diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/webrtc_ice_server.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/webrtc_ice_server.go new file mode 100644 index 0000000000000000000000000000000000000000..68bff8670559580e17465d061cccd394cf698271 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/webrtc_ice_server.go @@ -0,0 +1,9 @@ +package conf + +// WebRTCICEServer is a WebRTC ICE Server. +type WebRTCICEServer struct { + URL string `json:"url"` + Username string `json:"username"` + Password string `json:"password"` + ClientOnly bool `json:"clientOnly"` +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/90b5d1b18dd9f8ac b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/90b5d1b18dd9f8ac new file mode 100644 index 0000000000000000000000000000000000000000..f1c2cd66347cd1ed6a97ca4dd8d568aabe6fb2be --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/90b5d1b18dd9f8ac @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("*0") diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/dc806ec658c460fc b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/dc806ec658c460fc new file mode 100644 index 0000000000000000000000000000000000000000..ab8f1ee7318a9e860b91d80c1ee1b73104aa04df --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/dc806ec658c460fc @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("...") diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal.go new file mode 100644 index 0000000000000000000000000000000000000000..26115b5ff4e34bb69c792e4112d5c4828ecab019 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal.go @@ -0,0 +1,106 @@ +// Package yamlwrapper contains a YAML unmarshaler. +package yamlwrapper + +import ( + "encoding/json" + "fmt" + + "github.com/bluenviron/mediamtx/internal/conf/jsonwrapper" + "github.com/goccy/go-yaml" + "github.com/goccy/go-yaml/ast" + "github.com/goccy/go-yaml/parser" + "github.com/goccy/go-yaml/token" +) + +// differences with respect to the standard package: +// - some legacy YAML 1.1 boolean values (yes, no) are supported +// - all differences of jsonwrapper are inherited + +func convertLegacyBools(node ast.Node) ast.Node { + if node != nil { + switch n := node.(type) { + case *ast.MappingNode: + for _, value := range n.Values { + convertLegacyBools(value) + } + + case *ast.MappingValueNode: + n.Key = convertLegacyBools(n.Key).(ast.MapKeyNode) + n.Value = convertLegacyBools(n.Value) + + case *ast.SequenceNode: + for i, value := range n.Values { + n.Values[i] = convertLegacyBools(value) + } + + case *ast.DocumentNode: + n.Body = convertLegacyBools(n.Body) + + case *ast.StringNode: + if n.Token.Type == token.StringType { + var boolVal bool + shouldConvert := false + + switch n.Token.Value { + case "yes", "Yes", "YES", "on", "On", "ON": + boolVal = true + shouldConvert = true + + case "no", "No", "NO", "off", "Off", "OFF": + boolVal = false + shouldConvert = true + } + + if shouldConvert { + newToken := &token.Token{ + Type: token.BoolType, + Value: n.Token.Value, + } + + if boolVal { + newToken.Value = "true" + } else { + newToken.Value = "false" + } + + boolNode := ast.Bool(newToken) + boolNode.Value = boolVal + return boolNode + } + } + } + } + + return node +} + +// Unmarshal loads the configuration from YAML. +func Unmarshal(buf []byte, dest any) error { + file, err := parser.ParseBytes(buf, parser.ParseComments) + if err != nil { + return err + } + + if len(file.Docs) != 1 { + return fmt.Errorf("invalid YAML") + } + + file.Docs[0] = convertLegacyBools(file.Docs[0]).(*ast.DocumentNode) + + var temp any + if file.Docs[0].Body != nil { + err = yaml.NodeToValue(file.Docs[0].Body, &temp) + if err != nil { + return err + } + } + + // convert the generic map into JSON + buf, err = json.Marshal(temp) + if err != nil { + return err + } + + // load JSON into destination + return jsonwrapper.Unmarshal(buf, dest) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2990c5fc268482e2d30d3b3e7043432856d943f7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal_test.go @@ -0,0 +1,80 @@ +package yamlwrapper + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestUnmarshalIntegerMapKey(t *testing.T) { + buf := []byte(` +1: value +test: value2 +`) + + var dest any + err := Unmarshal(buf, &dest) + require.NoError(t, err) + + require.Equal(t, map[string]any{ + "1": "value", + "test": "value2", + }, dest) +} + +func TestUnmarshalDuplicateKey(t *testing.T) { + buf := []byte(` +key: value1 +key: value2 +`) + + err := Unmarshal(buf, &map[string]string{}) + require.EqualError(t, err, "[3:1] mapping key \"key\" already defined at [2:1]"+ + "\n 2 | key: value1\n> 3 | key: value2\n ^\n") +} + +func TestUnmarshalUnknownFields(t *testing.T) { + type testStruct struct { + Field1 string `json:"field1"` + Field2 int `json:"field2"` + } + + input := []byte(`field1: test +unknownField: value +field2: 456`) + + var result testStruct + err := Unmarshal(input, &result) + require.Error(t, err) + require.EqualError(t, err, "json: unknown field \"unknownField\"") +} + +func TestUnmarshalLegacyBools(t *testing.T) { + type testStruct struct { + Field1 bool `json:"field1"` + Field2 string `json:"field2"` + } + + input := []byte("field1: yes\n" + + "field2: \"yes\"\n") + + var result testStruct + err := Unmarshal(input, &result) + require.NoError(t, err) + require.Equal(t, true, result.Field1) +} + +func TestUnmarshalEmpty(t *testing.T) { + input := []byte(``) + + var result any + err := Unmarshal(input, &result) + require.NoError(t, err) +} + +func FuzzUnmarshal(f *testing.F) { + f.Fuzz(func(_ *testing.T, buf []byte) { + var dest any + Unmarshal(buf, &dest) //nolint:errcheck + }) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher.go new file mode 100644 index 0000000000000000000000000000000000000000..2a586f68cf30943e22e54157f0f5fc2d2e1c0344 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher.go @@ -0,0 +1,122 @@ +// Package confwatcher contains a configuration watcher. +package confwatcher + +import ( + "os" + "path/filepath" + "time" + + "github.com/fsnotify/fsnotify" +) + +const ( + minInterval = 1 * time.Second + additionalWait = 10 * time.Millisecond +) + +// ConfWatcher is a configuration file watcher. +type ConfWatcher struct { + FilePath string + + inner *fsnotify.Watcher + absolutePath string + + // in + terminate chan struct{} + + // out + signal chan struct{} + done chan struct{} +} + +// Initialize initializes a ConfWatcher. +func (w *ConfWatcher) Initialize() error { + if _, err := os.Stat(w.FilePath); err != nil { + return err + } + + var err error + w.inner, err = fsnotify.NewWatcher() + if err != nil { + return err + } + + // use absolute paths to support Darwin + w.absolutePath, _ = filepath.Abs(w.FilePath) + parentPath := filepath.Dir(w.absolutePath) + + err = w.inner.Add(parentPath) + if err != nil { + w.inner.Close() //nolint:errcheck + return err + } + + w.terminate = make(chan struct{}) + w.signal = make(chan struct{}) + w.done = make(chan struct{}) + + go w.run() + + return nil +} + +// Close closes a ConfWatcher. +func (w *ConfWatcher) Close() { + close(w.terminate) + <-w.done +} + +func (w *ConfWatcher) run() { + defer close(w.done) + + var lastCalled time.Time + previousWatchedPath, _ := filepath.EvalSymlinks(w.absolutePath) + +outer: + for { + select { + case event := <-w.inner.Events: + if time.Since(lastCalled) < minInterval { + continue + } + + currentWatchedPath, _ := filepath.EvalSymlinks(w.absolutePath) + eventPath, _ := filepath.Abs(event.Name) + eventPath, _ = filepath.EvalSymlinks(eventPath) + + if currentWatchedPath == "" { + // watched file was removed; wait for write event to trigger reload + previousWatchedPath = "" + } else if currentWatchedPath != previousWatchedPath || + (eventPath == currentWatchedPath && + ((event.Op&fsnotify.Write) == fsnotify.Write || + (event.Op&fsnotify.Create) == fsnotify.Create)) { + // wait some additional time to allow the writer to complete its job + time.Sleep(additionalWait) + previousWatchedPath = currentWatchedPath + + lastCalled = time.Now() + + select { + case w.signal <- struct{}{}: + case <-w.terminate: + break outer + } + } + + case <-w.inner.Errors: + break outer + + case <-w.terminate: + break outer + } + } + + close(w.signal) + w.inner.Close() //nolint:errcheck +} + +// Watch returns a channel that is called after the configuration file has changed. +func (w *ConfWatcher) Watch() chan struct{} { + return w.signal +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher_test.go new file mode 100644 index 0000000000000000000000000000000000000000..797fdd3d8601690906cccd7debbf4e3a27bdf62d --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher_test.go @@ -0,0 +1,145 @@ +package confwatcher + +import ( + "os" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestNoFile(t *testing.T) { + w := &ConfWatcher{FilePath: "/nonexistent"} + err := w.Initialize() + require.Error(t, err) +} + +func TestWrite(t *testing.T) { + fpath := test.CreateTempFile(t, []byte("{}")) + + w := &ConfWatcher{FilePath: fpath} + err := w.Initialize() + require.NoError(t, err) + defer w.Close() + + func() { + var f *os.File + f, err = os.Create(fpath) + require.NoError(t, err) + defer f.Close() + + _, err = f.Write([]byte("{}")) + require.NoError(t, err) + }() + + select { + case <-w.Watch(): + case <-time.After(500 * time.Millisecond): + t.Errorf("timed out") + return + } +} + +func TestWriteMultipleTimes(t *testing.T) { + fpath := test.CreateTempFile(t, []byte("{}")) + + w := &ConfWatcher{FilePath: fpath} + err := w.Initialize() + require.NoError(t, err) + defer w.Close() + + func() { + f, err2 := os.Create(fpath) + require.NoError(t, err2) + defer f.Close() + + _, err2 = f.Write([]byte("{}")) + require.NoError(t, err2) + }() + + time.Sleep(10 * time.Millisecond) + + func() { + f, err2 := os.Create(fpath) + require.NoError(t, err2) + defer f.Close() + + _, err2 = f.Write([]byte("{}")) + require.NoError(t, err2) + }() + + select { + case <-w.Watch(): + case <-time.After(500 * time.Millisecond): + t.Errorf("timed out") + return + } + + select { + case <-time.After(500 * time.Millisecond): + case <-w.Watch(): + t.Errorf("should not happen") + return + } +} + +func TestDeleteCreate(t *testing.T) { + fpath := test.CreateTempFile(t, []byte("{}")) + + w := &ConfWatcher{FilePath: fpath} + err := w.Initialize() + require.NoError(t, err) + defer w.Close() + + os.Remove(fpath) + + time.Sleep(10 * time.Millisecond) + + func() { + var f *os.File + f, err = os.Create(fpath) + require.NoError(t, err) + defer f.Close() + + _, err = f.Write([]byte("{}")) + require.NoError(t, err) + }() + + select { + case <-w.Watch(): + case <-time.After(500 * time.Millisecond): + t.Errorf("timed out") + return + } +} + +func TestSymlinkDeleteCreate(t *testing.T) { + fpath := test.CreateTempFile(t, []byte("{}")) + + err := os.Symlink(fpath, fpath+"-sym") + require.NoError(t, err) + + w := &ConfWatcher{FilePath: fpath + "-sym"} + err = w.Initialize() + require.NoError(t, err) + defer w.Close() + + os.Remove(fpath) + + func() { + f, err2 := os.Create(fpath) + require.NoError(t, err2) + defer f.Close() + + _, err2 = f.Write([]byte("{}")) + require.NoError(t, err2) + }() + + select { + case <-w.Watch(): + case <-time.After(500 * time.Millisecond): + t.Errorf("timed out") + return + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/api_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/api_test.go new file mode 100644 index 0000000000000000000000000000000000000000..24ba65d14e9d5589eefa88916367a6b4644dd30e --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/api_test.go @@ -0,0 +1,1412 @@ +//nolint:dupl,lll +package core + +import ( + "bufio" + "bytes" + "context" + "crypto/tls" + "encoding/json" + "io" + "net/http" + "net/url" + "testing" + "time" + + "github.com/bluenviron/gohlslib/v2" + "github.com/bluenviron/gortmplib" + rtmpcodecs "github.com/bluenviron/gortmplib/pkg/codecs" + "github.com/bluenviron/gortsplib/v5" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/gortsplib/v5/pkg/format/rtph264" + "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts" + tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs" + srt "github.com/datarhei/gosrt" + "github.com/google/uuid" + "github.com/pion/rtp" + pwebrtc "github.com/pion/webrtc/v4" + "github.com/stretchr/testify/require" + + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/formatlabel" + "github.com/bluenviron/mediamtx/internal/protocols/webrtc" + "github.com/bluenviron/mediamtx/internal/protocols/whip" + "github.com/bluenviron/mediamtx/internal/test" +) + +func checkClose(t *testing.T, closeFunc func() error) { + require.NoError(t, closeFunc()) +} + +func httpRequest(t *testing.T, hc *http.Client, method string, ur string, in any, out any) { + buf := func() io.Reader { + if in == nil { + return nil + } + + byts, err := json.Marshal(in) + require.NoError(t, err) + + return bytes.NewBuffer(byts) + }() + + req, err := http.NewRequest(method, ur, buf) + require.NoError(t, err) + + res, err := hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + t.Errorf("bad status code: %d", res.StatusCode) + } + + if out == nil { + return + } + + err = json.NewDecoder(res.Body).Decode(out) + require.NoError(t, err) +} + +func checkError(t *testing.T, msg string, body io.Reader) { + var resErr map[string]any + err := json.NewDecoder(body).Decode(&resErr) + require.NoError(t, err) + require.Equal(t, map[string]any{"status": "error", "error": msg}, resErr) +} + +func TestAPIPathsList(t *testing.T) { + type pathSource struct { + Type string `json:"type"` + } + + type path struct { + Name string `json:"name"` + Source pathSource `json:"source"` + Ready bool `json:"ready"` + Tracks []defs.APIPathTrackCodec `json:"tracks"` + InboundBytes uint64 `json:"inboundBytes"` + OutboundBytes uint64 `json:"outboundBytes"` + InboundFramesInError uint64 `json:"inboundFramesInError"` + BytesReceived uint64 `json:"bytesReceived"` + BytesSent uint64 `json:"bytesSent"` + } + + type pathList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []path `json:"items"` + } + + t.Run("rtsp session", func(t *testing.T) { + p, ok := newInstance(t, "api: yes\n"+ + "paths:\n"+ + " mypath:\n") + require.Equal(t, true, ok) + defer p.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + media0 := test.UniqueMediaH264() + + source := gortsplib.Client{} + err := source.StartRecording( + "rtsp://localhost:8554/mypath", + &description.Session{Medias: []*description.Media{ + media0, + test.MediaMPEG4Audio, + }}) + require.NoError(t, err) + defer source.Close() + + err = source.WritePacketRTP(media0, &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + PayloadType: 96, + }, + Payload: []byte{5, 1, 2, 3, 4}, + }) + require.NoError(t, err) + + var out pathList + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out) + require.Equal(t, pathList{ + ItemCount: 1, + PageCount: 1, + Items: []path{{ + Name: "mypath", + Source: pathSource{ + Type: "rtspSession", + }, + Ready: true, + Tracks: []defs.APIPathTrackCodec{formatlabel.H264, formatlabel.MPEG4Audio}, + InboundBytes: 17, + InboundFramesInError: 0, + BytesReceived: 17, + }}, + }, out) + }) + + t.Run("rtsps session", func(t *testing.T) { + serverCertFpath := test.CreateTempFile(t, test.TLSCertPub) + serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey) + + p, ok := newInstance(t, "api: yes\n"+ + "rtspEncryption: optional\n"+ + "rtspServerCert: "+serverCertFpath+"\n"+ + "rtspServerKey: "+serverKeyFpath+"\n"+ + "paths:\n"+ + " mypath:\n") + require.Equal(t, true, ok) + defer p.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + source := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}} + err := source.StartRecording("rtsps://localhost:8322/mypath", + &description.Session{Medias: []*description.Media{ + test.UniqueMediaH264(), + test.UniqueMediaMPEG4Audio(), + }}) + require.NoError(t, err) + defer source.Close() + + var out pathList + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out) + require.Equal(t, pathList{ + ItemCount: 1, + PageCount: 1, + Items: []path{{ + Name: "mypath", + Source: pathSource{ + Type: "rtspsSession", + }, + Ready: true, + Tracks: []defs.APIPathTrackCodec{formatlabel.H264, formatlabel.MPEG4Audio}, + }}, + }, out) + }) + + t.Run("rtsp source", func(t *testing.T) { + p, ok := newInstance(t, "api: yes\n"+ + "paths:\n"+ + " mypath:\n"+ + " source: rtsp://127.0.0.1:1234/mypath\n"+ + " sourceOnDemand: yes\n") + require.Equal(t, true, ok) + defer p.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + var out pathList + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out) + require.Equal(t, pathList{ + ItemCount: 1, + PageCount: 1, + Items: []path{{ + Name: "mypath", + Source: pathSource{ + Type: "rtspSource", + }, + Ready: false, + Tracks: []defs.APIPathTrackCodec{}, + }}, + }, out) + }) + + t.Run("rtmp source", func(t *testing.T) { + p, ok := newInstance(t, "api: yes\n"+ + "paths:\n"+ + " mypath:\n"+ + " source: rtmp://127.0.0.1:1234/mypath\n"+ + " sourceOnDemand: yes\n") + require.Equal(t, true, ok) + defer p.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + var out pathList + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out) + require.Equal(t, pathList{ + ItemCount: 1, + PageCount: 1, + Items: []path{{ + Name: "mypath", + Source: pathSource{ + Type: "rtmpSource", + }, + Ready: false, + Tracks: []defs.APIPathTrackCodec{}, + }}, + }, out) + }) + + t.Run("hls source", func(t *testing.T) { + p, ok := newInstance(t, "api: yes\n"+ + "paths:\n"+ + " mypath:\n"+ + " source: http://127.0.0.1:1234/mypath\n"+ + " sourceOnDemand: yes\n") + require.Equal(t, true, ok) + defer p.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + var out pathList + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out) + require.Equal(t, pathList{ + ItemCount: 1, + PageCount: 1, + Items: []path{{ + Name: "mypath", + Source: pathSource{ + Type: "hlsSource", + }, + Ready: false, + Tracks: []defs.APIPathTrackCodec{}, + }}, + }, out) + }) +} + +func TestAPIPathsGet(t *testing.T) { + p, ok := newInstance(t, "api: yes\n"+ + "paths:\n"+ + " all_others:\n") + require.Equal(t, true, ok) + defer p.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + for _, ca := range []string{"ok", "ok-nested", "not found"} { + t.Run(ca, func(t *testing.T) { + type pathSource struct { + Type string `json:"type"` + } + + type path struct { + Name string `json:"name"` + Source pathSource `json:"source"` + Ready bool `json:"Ready"` + Tracks []defs.APIPathTrackCodec `json:"tracks"` + InboundBytes uint64 `json:"inboundBytes"` + OutboundBytes uint64 `json:"outboundBytes"` + InboundFramesInError uint64 `json:"inboundFramesInError"` + BytesReceived uint64 `json:"bytesReceived"` + BytesSent uint64 `json:"bytesSent"` + } + + var pathName string + + switch ca { + case "ok": + pathName = "mypath" + case "ok-nested": + pathName = "my/nested/path" + case "not found": + pathName = "nonexisting" + } + + if ca == "ok" || ca == "ok-nested" { + source := gortsplib.Client{} + err := source.StartRecording("rtsp://localhost:8554/"+pathName, + &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}}) + require.NoError(t, err) + defer source.Close() + + var out path + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/get/"+pathName, nil, &out) + require.Equal(t, path{ + Name: pathName, + Source: pathSource{ + Type: "rtspSession", + }, + Ready: true, + Tracks: []defs.APIPathTrackCodec{formatlabel.H264}, + }, out) + } else { + res, err := hc.Get("http://localhost:9997/v3/paths/get/" + pathName) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusNotFound, res.StatusCode) + checkError(t, "path not found", res.Body) + } + }) + } +} + +func TestAPIProtocolListGet(t *testing.T) { + serverCertFpath := test.CreateTempFile(t, test.TLSCertPub) + serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey) + + for _, ca := range []string{ + "rtsp conns", + "rtsp sessions", + "rtsps conns", + "rtsps sessions", + "rtmp", + "rtmps", + "hls sessions", + "hls muxers", + "webrtc", + "srt", + } { + t.Run(ca, func(t *testing.T) { + cnf := "api: yes\n" + + switch ca { + case "rtsps conns", "rtsps sessions": + cnf += "rtspEncryption: strict\n" + + "rtspServerCert: " + serverCertFpath + "\n" + + "rtspServerKey: " + serverKeyFpath + "\n" + + case "rtmps": + cnf += "rtmpEncryption: strict\n" + + "rtmpServerCert: " + serverCertFpath + "\n" + + "rtmpServerKey: " + serverKeyFpath + "\n" + } + + cnf += "paths:\n" + + " all_others:\n" + + p, ok := newInstance(t, cnf) + require.Equal(t, true, ok) + defer p.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + medi := test.UniqueMediaH264() + + switch ca { //nolint:dupl + case "rtsp conns", "rtsp sessions": + source := gortsplib.Client{} + + err := source.StartRecording("rtsp://localhost:8554/mypath?key=val", + &description.Session{Medias: []*description.Media{medi}}) + require.NoError(t, err) + defer source.Close() + + case "rtsps conns", "rtsps sessions": + source := gortsplib.Client{ + TLSConfig: &tls.Config{InsecureSkipVerify: true}, + } + + err := source.StartRecording("rtsps://localhost:8322/mypath?key=val", + &description.Session{Medias: []*description.Media{medi}}) + require.NoError(t, err) + defer source.Close() + + case "rtmp", "rtmps": + var port string + if ca == "rtmp" { + port = "1935" + } else { + port = "1936" + } + + var rawURL string + + if ca == "rtmps" { + rawURL = "rtmps://" + } else { + rawURL = "rtmp://" + } + + rawURL += "127.0.0.1:" + port + "/mypath?key=val" + + var u *url.URL + u, err := url.Parse(rawURL) + require.NoError(t, err) + + conn := &gortmplib.Client{ + URL: u, + TLSConfig: &tls.Config{InsecureSkipVerify: true}, + Publish: true, + } + err = conn.Initialize(context.Background()) + require.NoError(t, err) + defer conn.Close() + + track := &gortmplib.Track{ + Codec: &rtmpcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + } + + w := &gortmplib.Writer{ + Conn: conn, + Tracks: []*gortmplib.Track{track}, + } + err = w.Initialize() + require.NoError(t, err) + + err = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}}) + require.NoError(t, err) + + time.Sleep(500 * time.Millisecond) + + case "hls sessions", "hls muxers": + source := gortsplib.Client{} + err := source.StartRecording("rtsp://localhost:8554/mypath", + &description.Session{Medias: []*description.Media{medi}}) + require.NoError(t, err) + defer source.Close() + + go func() { + time.Sleep(500 * time.Millisecond) + + for i := range 3 { + /*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{ + testSPS, + 0x05, + }, + }) + + []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, + },*/ + + err2 := 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{ + // testSPS, + 0x05, + }, + }) + require.NoError(t, err2) + } + }() + + func() { + res, err2 := hc.Get("http://localhost:8888/mypath/index.m3u8") + require.NoError(t, err2) + defer res.Body.Close() + require.Equal(t, 200, res.StatusCode) + }() + + case "webrtc": + source := gortsplib.Client{} + err := source.StartRecording("rtsp://localhost:8554/mypath", + &description.Session{Medias: []*description.Media{medi}}) + require.NoError(t, err) + defer source.Close() + + var u *url.URL + u, err = url.Parse("http://localhost:8889/mypath/whep?key=val") + require.NoError(t, err) + + go func() { + time.Sleep(500 * time.Millisecond) + + err2 := source.WritePacketRTP(medi, &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 96, + SequenceNumber: 123, + Timestamp: 45343, + SSRC: 563423, + }, + Payload: []byte{5, 1, 2, 3, 4}, + }) + require.NoError(t, err2) + }() + + c := &whip.Client{ + HTTPClient: hc, + URL: u, + Log: test.NilLogger, + } + + err = c.Initialize(context.Background()) + require.NoError(t, err) + defer checkClose(t, c.Close) + + case "srt": + conf := srt.DefaultConfig() + conf.StreamId = "publish:mypath:::key=val" + + var conn srt.Conn + conn, err := srt.Dial("srt", "localhost:8890", conf) + require.NoError(t, err) + defer conn.Close() + + track := &mpegts.Track{ + Codec: &tscodecs.H264{}, + } + + bw := bufio.NewWriter(conn) + w := &mpegts.Writer{W: bw, Tracks: []*mpegts.Track{track}} + err = w.Initialize() + require.NoError(t, err) + + err = w.WriteH264(track, 0, 0, [][]byte{{1}}) + require.NoError(t, err) + + err = bw.Flush() + require.NoError(t, err) + + time.Sleep(500 * time.Millisecond) + } + + var pa string + switch ca { + case "rtsp conns": + pa = "rtspconns" + + case "rtsp sessions": + pa = "rtspsessions" + + case "rtsps conns": + pa = "rtspsconns" + + case "rtsps sessions": + pa = "rtspssessions" + + case "rtmp": + pa = "rtmpconns" + + case "rtmps": + pa = "rtmpsconns" + + case "hls sessions": + pa = "hlssessions" + + case "hls muxers": + pa = "hlsmuxers" + + case "webrtc": + pa = "webrtcsessions" + + case "srt": + pa = "srtconns" + } + + var out1 any + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/list", nil, &out1) + + switch ca { + case "rtsp conns": + require.Equal(t, map[string]any{ + "pageCount": float64(1), + "itemCount": float64(1), + "items": []any{ + map[string]any{ + "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"], + "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"], + "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"], + "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"], + "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"], + "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"], + "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"], + "session": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["session"], + "tunnel": "none", + }, + }, + }, out1) + + case "rtsp sessions": + require.Equal(t, map[string]any{ + "pageCount": float64(1), + "itemCount": float64(1), + "items": []any{ + map[string]any{ + "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"], + "inboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"], + "inboundRTPPacketsLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"], + "inboundRTPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsInError"], + "inboundRTPPacketsJitter": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"], + "inboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"], + "inboundRTCPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPacketsInError"], + "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"], + "outboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"], + "outboundRTPPacketsReportedLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsReportedLost"], + "outboundRTPPacketsDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsDiscarded"], + "outboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"], + "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"], + "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"], + "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"], + "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"], + "path": "mypath", + "query": "key=val", + "user": "", + "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"], + "state": "publish", + "transport": "UDP", + "profile": "AVP", + "rtpPacketsReceived": float64(0), + "rtpPacketsSent": float64(0), + "rtpPacketsLost": float64(0), + "rtpPacketsInError": float64(0), + "rtpPacketsJitter": float64(0), + "rtcpPacketsReceived": float64(0), + "rtcpPacketsSent": float64(0), + "rtcpPacketsInError": float64(0), + "conns": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["conns"], + "userAgent": "gortsplib", + }, + }, + }, out1) + + case "rtsps conns": + require.Equal(t, map[string]any{ + "pageCount": float64(1), + "itemCount": float64(1), + "items": []any{ + map[string]any{ + "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"], + "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"], + "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"], + "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"], + "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"], + "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"], + "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"], + "session": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["session"], + "tunnel": "none", + }, + }, + }, out1) + + case "rtsps sessions": + require.Equal(t, map[string]any{ + "pageCount": float64(1), + "itemCount": float64(1), + "items": []any{ + map[string]any{ + "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"], + "inboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"], + "inboundRTPPacketsLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"], + "inboundRTPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsInError"], + "inboundRTPPacketsJitter": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"], + "inboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"], + "inboundRTCPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPacketsInError"], + "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"], + "outboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"], + "outboundRTPPacketsReportedLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsReportedLost"], + "outboundRTPPacketsDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsDiscarded"], + "outboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"], + "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"], + "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"], + "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"], + "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"], + "path": "mypath", + "query": "key=val", + "user": "", + "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"], + "state": "publish", + "transport": "UDP", + "profile": "SAVP", + "rtpPacketsReceived": float64(0), + "rtpPacketsSent": float64(0), + "rtpPacketsLost": float64(0), + "rtpPacketsInError": float64(0), + "rtpPacketsJitter": float64(0), + "rtcpPacketsReceived": float64(0), + "rtcpPacketsSent": float64(0), + "rtcpPacketsInError": float64(0), + "conns": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["conns"], + "userAgent": "gortsplib", + }, + }, + }, out1) + + case "rtmp": + require.Equal(t, map[string]any{ + "pageCount": float64(1), + "itemCount": float64(1), + "items": []any{ + map[string]any{ + "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"], + "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"], + "outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"], + "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"], + "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"], + "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"], + "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"], + "path": "mypath", + "query": "key=val", + "user": "", + "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"], + "state": "publish", + "userAgent": "LNX 9,0,124,2", + }, + }, + }, out1) + + case "rtmps": + require.Equal(t, map[string]any{ + "pageCount": float64(1), + "itemCount": float64(1), + "items": []any{ + map[string]any{ + "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"], + "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"], + "outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"], + "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"], + "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"], + "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"], + "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"], + "path": "mypath", + "query": "key=val", + "user": "", + "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"], + "state": "publish", + "userAgent": "LNX 9,0,124,2", + }, + }, + }, out1) + + case "hls sessions": + require.Equal(t, map[string]any{ + "itemCount": float64(1), + "pageCount": float64(1), + "items": []any{ + map[string]any{ + "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"], + "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"], + "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"], + "path": "mypath", + "query": "", + "user": "", + "isCDN": false, + "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"], + "userAgent": "Go-http-client/1.1", + }, + }, + }, out1) + + case "hls muxers": + require.Equal(t, map[string]any{ + "itemCount": float64(1), + "pageCount": float64(1), + "items": []any{ + map[string]any{ + "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"], + "outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"], + "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"], + "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"], + "lastRequest": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["lastRequest"], + "path": "mypath", + }, + }, + }, out1) + + case "webrtc": + require.Equal(t, map[string]any{ + "itemCount": float64(1), + "pageCount": float64(1), + "items": []any{ + map[string]any{ + "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"], + "inboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"], + "inboundRTPPacketsLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"], + "inboundRTPPacketsJitter": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"], + "inboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"], + "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"], + "outboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"], + "outboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"], + "outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"], + "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"], + "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"], + "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"], + "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"], + "localCandidate": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["localCandidate"], + "path": "mypath", + "peerConnectionEstablished": true, + "query": "key=val", + "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"], + "remoteCandidate": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteCandidate"], + "state": "read", + "user": "", + "rtcpPacketsReceived": float64(0), + "rtcpPacketsSent": float64(2), + "rtpPacketsJitter": float64(0), + "rtpPacketsLost": float64(0), + "rtpPacketsReceived": float64(0), + "rtpPacketsSent": float64(1), + "userAgent": "Go-http-client/1.1", + }, + }, + }, out1) + + case "srt": + require.Equal(t, map[string]any{ + "itemCount": float64(1), + "pageCount": float64(1), + "items": []any{ + map[string]any{ + "byteMSS": float64(1500), + "bytesAvailReceiveBuf": float64(0), + "bytesAvailSendBuf": float64(0), + "bytesReceiveBuf": float64(0), + "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"], + "bytesReceivedBelated": float64(0), + "bytesReceivedDrop": float64(0), + "bytesReceivedLoss": float64(0), + "bytesReceivedRetrans": float64(0), + "bytesReceivedUndecrypt": float64(0), + "outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"], + "bytesReceivedUnique": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceivedUnique"], + "bytesRetrans": float64(0), + "bytesSendBuf": float64(0), + "bytesSendDrop": float64(0), + "bytesSent": float64(0), + "bytesSentUnique": float64(0), + "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"], + "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"], + "mbpsLinkCapacity": float64(0), + "mbpsMaxBW": float64(-1), + "mbpsReceiveRate": float64(0), + "mbpsSendRate": float64(0), + "msRTT": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["msRTT"], + "msReceiveBuf": float64(0), + "msReceiveTsbPdDelay": float64(120), + "msSendBuf": float64(0), + "msSendTsbPdDelay": float64(120), + "packetsFlightSize": float64(0), + "packetsFlowWindow": float64(25600), + "packetsReceiveBuf": float64(0), + "packetsReceived": float64(1), + "packetsReceivedACK": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsReceivedACK"], + "packetsReceivedAvgBelatedTime": float64(0), + "packetsReceivedBelated": float64(0), + "packetsReceivedDrop": float64(0), + "packetsReceivedKM": float64(0), + "packetsReceivedLoss": float64(0), + "packetsReceivedLossRate": float64(0), + "packetsReceivedNAK": float64(0), + "packetsReceivedRetrans": float64(0), + "packetsReceivedUndecrypt": float64(0), + "packetsReceivedUnique": float64(1), + "packetsReorderTolerance": float64(0), + "packetsRetrans": float64(0), + "packetsSendBuf": float64(0), + "packetsSendDrop": float64(0), + "packetsSendLoss": float64(0), + "packetsSendLossRate": float64(0), + "packetsSent": float64(0), + "packetsSentACK": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsSentACK"], + "packetsSentKM": float64(0), + "packetsSentNAK": float64(0), + "packetsSentUnique": float64(0), + "path": "mypath", + "query": "key=val", + "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"], + "state": "publish", + "user": "", + "usPacketsSendPeriod": float64(10.967254638671875), + "usSndDuration": float64(0), + }, + }, + }, out1) + } + + var out2 any + + if ca == "hls muxers" { + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/get/"+ + out1.(map[string]any)["items"].([]any)[0].(map[string]any)["path"].(string), + nil, &out2) + } else { + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/get/"+ + out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"].(string), + nil, &out2) + } + + switch ca { + case "rtsp conns", "rtsps conns": + out2.(map[string]any)["inboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"] + out2.(map[string]any)["outboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"] + out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"] + out2.(map[string]any)["bytesSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"] + + case "rtsp sessions", "rtsps sessions": + out2.(map[string]any)["inboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"] + out2.(map[string]any)["inboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"] + out2.(map[string]any)["inboundRTPPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"] + out2.(map[string]any)["inboundRTPPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsInError"] + out2.(map[string]any)["inboundRTPPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"] + out2.(map[string]any)["inboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"] + out2.(map[string]any)["inboundRTCPPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPacketsInError"] + out2.(map[string]any)["outboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"] + out2.(map[string]any)["outboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"] + out2.(map[string]any)["outboundRTPPacketsReportedLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsReportedLost"] + out2.(map[string]any)["outboundRTPPacketsDiscarded"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsDiscarded"] + out2.(map[string]any)["outboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"] + out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"] + out2.(map[string]any)["bytesSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"] + out2.(map[string]any)["rtpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsReceived"] + out2.(map[string]any)["rtpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsSent"] + out2.(map[string]any)["rtpPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsLost"] + out2.(map[string]any)["rtpPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsInError"] + out2.(map[string]any)["rtpPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsJitter"] + out2.(map[string]any)["rtcpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsReceived"] + out2.(map[string]any)["rtcpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsSent"] + out2.(map[string]any)["rtcpPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsInError"] + + case "webrtc": + out2.(map[string]any)["inboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"] + out2.(map[string]any)["inboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"] + out2.(map[string]any)["inboundRTPPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"] + out2.(map[string]any)["inboundRTPPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"] + out2.(map[string]any)["inboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"] + out2.(map[string]any)["outboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"] + out2.(map[string]any)["outboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"] + out2.(map[string]any)["outboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"] + out2.(map[string]any)["outboundFramesDiscarded"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"] + out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"] + out2.(map[string]any)["bytesSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"] + out2.(map[string]any)["rtpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsReceived"] + out2.(map[string]any)["rtpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsSent"] + out2.(map[string]any)["rtpPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsLost"] + out2.(map[string]any)["rtpPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsJitter"] + out2.(map[string]any)["rtcpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsReceived"] + out2.(map[string]any)["rtcpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsSent"] + + case "hls muxers": + out2.(map[string]any)["lastRequest"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["lastRequest"] + + case "srt": + out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"] + out2.(map[string]any)["bytesReceivedUnique"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceivedUnique"] + out2.(map[string]any)["packetsReceivedACK"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsReceivedACK"] + out2.(map[string]any)["packetsSentACK"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsSentACK"] + out2.(map[string]any)["msRTT"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["msRTT"] + } + + require.Equal(t, out1.(map[string]any)["items"].([]any)[0], out2) + }) + } +} + +func TestAPIProtocolGetNotFound(t *testing.T) { + serverCertFpath := test.CreateTempFile(t, test.TLSCertPub) + serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey) + + for _, ca := range []string{ + "rtsp conns", + "rtsp sessions", + "rtsps conns", + "rtsps sessions", + "rtmp", + "rtmps", + "hls sessions", + "hls muxers", + "webrtc", + "srt", + } { + t.Run(ca, func(t *testing.T) { + cnf := "api: yes\n" + + switch ca { + case "rtsps conns", "rtsps sessions": + cnf += "rtspTransports: [tcp]\n" + + "rtspEncryption: strict\n" + + "rtspServerCert: " + serverCertFpath + "\n" + + "rtspServerKey: " + serverKeyFpath + "\n" + + case "rtmps": + cnf += "rtmpEncryption: strict\n" + + "rtmpServerCert: " + serverCertFpath + "\n" + + "rtmpServerKey: " + serverKeyFpath + "\n" + } + + cnf += "paths:\n" + + " all_others:\n" + + p, ok := newInstance(t, cnf) + require.Equal(t, true, ok) + defer p.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + var pa string + switch ca { + case "rtsp conns": + pa = "rtspconns" + + case "rtsp sessions": + pa = "rtspsessions" + + case "rtsps conns": + pa = "rtspsconns" + + case "rtsps sessions": + pa = "rtspssessions" + + case "rtmp": + pa = "rtmpconns" + + case "rtmps": + pa = "rtmpsconns" + + case "hls sessions": + pa = "hlssessions" + + case "hls muxers": + pa = "hlsmuxers" + + case "webrtc": + pa = "webrtcsessions" + + case "srt": + pa = "srtconns" + } + + func() { + var req *http.Request + req, err := http.NewRequest(http.MethodGet, "http://localhost:9997/v3/"+pa+"/get/"+uuid.New().String(), nil) + require.NoError(t, err) + + var res *http.Response + res, err = hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusNotFound, res.StatusCode) + + switch ca { + case "rtsp conns", "rtsps conns", "rtmp", "rtmps", "srt": + checkError(t, "connection not found", res.Body) + + case "rtsp sessions", "rtsps sessions", "hls sessions", "webrtc": + checkError(t, "session not found", res.Body) + + case "hls muxers": + checkError(t, "muxer not found", res.Body) + } + }() + }) + } +} + +func TestAPIProtocolKick(t *testing.T) { + serverCertFpath := test.CreateTempFile(t, test.TLSCertPub) + serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey) + + for _, ca := range []string{ + "rtsp", + "rtsps", + "rtmp", + "hls", + "webrtc", + "srt", + } { + t.Run(ca, func(t *testing.T) { + cnf := "api: yes\n" + + if ca == "rtsps" { + cnf += "rtspTransports: [tcp]\n" + + "rtspEncryption: strict\n" + + "rtspServerCert: " + serverCertFpath + "\n" + + "rtspServerKey: " + serverKeyFpath + "\n" + } + + cnf += "paths:\n" + + " all_others:\n" + + p, ok := newInstance(t, cnf) + require.Equal(t, true, ok) + defer p.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + medi := test.MediaH264 + + switch ca { + case "rtsp": + source := gortsplib.Client{} + err := source.StartRecording("rtsp://localhost:8554/mypath", + &description.Session{Medias: []*description.Media{medi}}) + require.NoError(t, err) + defer source.Close() + + case "rtsps": + source := gortsplib.Client{ + TLSConfig: &tls.Config{InsecureSkipVerify: true}, + } + err := source.StartRecording("rtsps://localhost:8322/mypath", + &description.Session{Medias: []*description.Media{medi}}) + require.NoError(t, err) + defer source.Close() + + case "rtmp": + var u *url.URL + u, err := url.Parse("rtmp://localhost:1935/mypath") + require.NoError(t, err) + + conn := &gortmplib.Client{ + URL: u, + Publish: true, + } + err = conn.Initialize(context.Background()) + require.NoError(t, err) + defer conn.Close() + + track := &gortmplib.Track{ + Codec: &rtmpcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + } + + w := &gortmplib.Writer{ + Conn: conn, + Tracks: []*gortmplib.Track{track}, + } + err = w.Initialize() + require.NoError(t, err) + + err = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}}) + require.NoError(t, err) + + case "hls": + source := gortsplib.Client{} + err := source.StartRecording("rtsp://localhost:8554/mypath", + &description.Session{Medias: []*description.Media{medi}}) + require.NoError(t, err) + defer source.Close() + + var enc *rtph264.Encoder + enc, err = medi.Formats[0].(*format.H264).CreateEncoder() + require.NoError(t, err) + + tracksReceived := make(chan struct{}) + + client := &gohlslib.Client{ + URI: "http://localhost:8888/mypath/index.m3u8", + OnTracks: func(_ []*gohlslib.Track) error { + close(tracksReceived) + return nil + }, + } + err = client.Start() + require.NoError(t, err) + defer client.Close() + + time.Sleep(500 * time.Millisecond) + + for i := range 2 { + var pkts []*rtp.Packet + pkts, err = enc.Encode([][]byte{{5, 2, 3, 4}}) + require.NoError(t, err) + + pkts[0].Timestamp = uint32(i * 90000) + + err = source.WritePacketRTP(medi, pkts[0]) + require.NoError(t, err) + } + + <-tracksReceived + + case "webrtc": + var u *url.URL + u, err := url.Parse("http://localhost:8889/mypath/whip") + require.NoError(t, err) + + track := &webrtc.OutboundTrack{ + Caps: pwebrtc.RTPCodecCapability{ + MimeType: pwebrtc.MimeTypeH264, + ClockRate: 90000, + SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f", + }, + } + + c := &whip.Client{ + HTTPClient: hc, + URL: u, + Log: test.NilLogger, + Publish: true, + OutboundTracks: []*webrtc.OutboundTrack{track}, + } + + err = c.Initialize(context.Background()) + require.NoError(t, err) + defer func() { + require.Error(t, c.Close()) + }() + + case "srt": + conf := srt.DefaultConfig() + conf.StreamId = "publish:mypath" + + var conn srt.Conn + conn, err := srt.Dial("srt", "localhost:8890", conf) + require.NoError(t, err) + defer conn.Close() + + track := &mpegts.Track{ + Codec: &tscodecs.H264{}, + } + + bw := bufio.NewWriter(conn) + w := &mpegts.Writer{W: bw, Tracks: []*mpegts.Track{track}} + err = w.Initialize() + require.NoError(t, err) + + err = w.WriteH264(track, 0, 0, [][]byte{{1}}) + require.NoError(t, err) + + err = bw.Flush() + require.NoError(t, err) + } + + var pa string + switch ca { + case "rtsp": + pa = "rtspsessions" + + case "rtsps": + pa = "rtspssessions" + + case "rtmp": + pa = "rtmpconns" + + case "hls": + pa = "hlssessions" + + case "webrtc": + pa = "webrtcsessions" + + case "srt": + pa = "srtconns" + } + + var out1 struct { + Items []struct { + ID string `json:"id"` + } `json:"items"` + } + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/list", nil, &out1) + require.NotEmpty(t, out1.Items) + + httpRequest(t, hc, http.MethodPost, "http://localhost:9997/v3/"+pa+"/kick/"+out1.Items[0].ID, nil, nil) + + var out2 struct { + Items []struct { + ID string `json:"id"` + } `json:"items"` + } + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/list", nil, &out2) + require.Empty(t, out2.Items) + }) + } +} + +func TestAPIProtocolKickNotFound(t *testing.T) { + serverCertFpath := test.CreateTempFile(t, test.TLSCertPub) + serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey) + + for _, ca := range []string{ + "rtsp", + "rtsps", + "rtmp", + "hls", + "webrtc", + "srt", + } { + t.Run(ca, func(t *testing.T) { + cnf := "api: yes\n" + + if ca == "rtsps" { + cnf += "rtspTransports: [tcp]\n" + + "rtspEncryption: strict\n" + + "rtspServerCert: " + serverCertFpath + "\n" + + "rtspServerKey: " + serverKeyFpath + "\n" + } + + cnf += "paths:\n" + + " all_others:\n" + + p, ok := newInstance(t, cnf) + require.Equal(t, true, ok) + defer p.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + var pa string + switch ca { + case "rtsp": + pa = "rtspsessions" + + case "rtsps": + pa = "rtspssessions" + + case "rtmp": + pa = "rtmpconns" + + case "hls": + pa = "hlssessions" + + case "webrtc": + pa = "webrtcsessions" + + case "srt": + pa = "srtconns" + } + + func() { + var req *http.Request + req, err := http.NewRequest(http.MethodPost, "http://localhost:9997/v3/"+pa+"/kick/"+uuid.New().String(), nil) + require.NoError(t, err) + + var res *http.Response + res, err = hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusNotFound, res.StatusCode) + + switch ca { + case "rtsp conns", "rtsps conns", "rtmp", "rtmps", "srt": + checkError(t, "connection not found", res.Body) + + case "rtsp sessions", "rtsps sessions", "hls", "webrtc": + checkError(t, "session not found", res.Body) + } + }() + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core.go new file mode 100644 index 0000000000000000000000000000000000000000..6c59e3ed3c5be4f6406f52970c9c8f6a9a04df8a --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core.go @@ -0,0 +1,1171 @@ +// Package core contains the main struct of the software. +package core + +import ( + "context" + _ "embed" + "fmt" + "os" + "os/signal" + "path/filepath" + "reflect" + "runtime" + "runtime/debug" + "slices" + "strings" + "syscall" + "time" + + "github.com/alecthomas/kong" + "github.com/gin-gonic/gin" + + "github.com/bluenviron/mediamtx/internal/api" + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/confwatcher" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/metrics" + "github.com/bluenviron/mediamtx/internal/playback" + "github.com/bluenviron/mediamtx/internal/pprof" + "github.com/bluenviron/mediamtx/internal/recordcleaner" + "github.com/bluenviron/mediamtx/internal/rlimit" + "github.com/bluenviron/mediamtx/internal/servers/hls" + "github.com/bluenviron/mediamtx/internal/servers/moq" + "github.com/bluenviron/mediamtx/internal/servers/rtmp" + "github.com/bluenviron/mediamtx/internal/servers/rtsp" + "github.com/bluenviron/mediamtx/internal/servers/srt" + "github.com/bluenviron/mediamtx/internal/servers/webrtc" + "github.com/bluenviron/mediamtx/internal/upgrade" +) + +//go:generate go run ./versiongetter + +//go:embed VERSION +var version []byte + +var started = time.Now() + +var defaultConfPaths = []string{ + "rtsp-simple-server.yml", + "mediamtx.yml", +} + +var defaultConfPathsNotWin = []string{ + "/usr/local/etc/mediamtx.yml", + "/usr/etc/mediamtx.yml", + "/etc/mediamtx/mediamtx.yml", +} + +func goArm() string { + bi, _ := debug.ReadBuildInfo() + for _, bs := range bi.Settings { + if bs.Key == "GOARM" { + return bs.Value + } + } + return "" +} + +func getArch() string { + var arch string + if runtime.GOARCH == "arm" { + arch = "armv" + goArm() + } else { + arch = runtime.GOARCH + } + return arch +} + +func atLeastOneRecordDeleteAfter(pathConfs map[string]*conf.Path) bool { + for _, e := range pathConfs { + if e.RecordDeleteAfter != 0 { + return true + } + } + return false +} + +func getRTPMaxPayloadSize(udpMaxPayloadSize int, rtspEncryption conf.Encryption) int { + // UDP max payload size - 12 (RTP header) + v := udpMaxPayloadSize - 12 + + // 10 (SRTP HMAC SHA1 authentication tag) + if rtspEncryption == conf.EncryptionOptional || rtspEncryption == conf.EncryptionStrict { + v -= 10 + } + + return v +} + +var cli struct { + Confpath string `arg:"" default:""` + Version bool `help:"print version"` + CheckVersion bool `help:"check whether a new version is available"` + Upgrade bool `help:"upgrade executable to the latest version"` +} + +// Core is an instance of MediaMTX. +type Core struct { + ctx context.Context + ctxCancel func() + confPath string + conf *conf.Conf + logger *logger.Logger + externalCmdPool *externalcmd.Pool + authManager *auth.Manager + metrics *metrics.Metrics + pprof *pprof.PPROF + recordCleaner *recordcleaner.Cleaner + playbackServer *playback.Server + pathManager *pathManager + rtspServer *rtsp.Server + rtspsServer *rtsp.Server + rtmpServer *rtmp.Server + rtmpsServer *rtmp.Server + hlsServer *hls.Server + webRTCServer *webrtc.Server + srtServer *srt.Server + moqServer *moq.Server + api *api.API + confWatcher *confwatcher.ConfWatcher + + // in + chAPIConfigSet chan *conf.Conf + + // out + done chan struct{} +} + +// New allocates a Core. +func New(args []string) (*Core, bool) { + parser, err := kong.New(&cli, + kong.Description("MediaMTX "+string(version)+", "+runtime.GOOS+", "+getArch()), + kong.UsageOnError(), + kong.ValueFormatter(func(value *kong.Value) string { + switch value.Name { + case "confpath": + return "path to a config file. The default is mediamtx.yml." + + default: + return kong.DefaultHelpValueFormatter(value) + } + })) + if err != nil { + panic(err) + } + + _, err = parser.Parse(args) + parser.FatalIfErrorf(err) + + if cli.Version { + fmt.Println(string(version)) + os.Exit(0) + } + + if cli.CheckVersion { + var newVersionAvailable bool + newVersionAvailable, err = upgrade.CheckVersion(string(version), getArch()) + if err != nil { + fmt.Printf("ERR: %v\n", err) + os.Exit(1) + } + if newVersionAvailable { + os.Exit(2) + } + os.Exit(0) + } + + if cli.Upgrade { + err = upgrade.Upgrade(string(version), getArch()) + if err != nil { + fmt.Printf("ERR: %v\n", err) + os.Exit(1) + } + os.Exit(0) + } + + ctx, ctxCancel := context.WithCancel(context.Background()) + + p := &Core{ + ctx: ctx, + ctxCancel: ctxCancel, + chAPIConfigSet: make(chan *conf.Conf), + done: make(chan struct{}), + } + + tempLogger := &logger.Logger{ + Level: logger.Warn, + Destinations: []logger.Destination{logger.DestinationStdout}, + Structured: false, + File: "", + SysLogPrefix: "", + } + tempLogger.Initialize() //nolint:errcheck + + confPaths := append([]string(nil), defaultConfPaths...) + if runtime.GOOS != "windows" { + confPaths = append(confPaths, defaultConfPathsNotWin...) + } + + p.conf, p.confPath, err = conf.Load(cli.Confpath, confPaths, tempLogger) + if err != nil { + fmt.Printf("ERR: %s\n", err) + return nil, false + } + + err = p.createResources(true) + if err != nil { + if p.logger != nil { + p.Log(logger.Error, "%s", err) + } else { + fmt.Printf("ERR: %s\n", err) + } + p.closeResources(nil, false) + return nil, false + } + + go p.run() + + return p, true +} + +// Close closes Core and waits for all goroutines to return. +func (p *Core) Close() { + p.ctxCancel() + <-p.done +} + +// Wait waits for the Core to exit. +func (p *Core) Wait() { + <-p.done +} + +// Log implements logger.Writer. +func (p *Core) Log(level logger.Level, format string, args ...any) { + p.logger.Log(level, format, args...) +} + +func (p *Core) run() { + defer close(p.done) + + confChanged := func() chan struct{} { + if p.confWatcher != nil { + return p.confWatcher.Watch() + } + return make(chan struct{}) + }() + + interrupt := make(chan os.Signal, 1) + signal.Notify(interrupt, os.Interrupt) + if runtime.GOOS == "linux" { + signal.Notify(interrupt, syscall.SIGTERM) + } + +outer: + for { + select { + case <-confChanged: + p.Log(logger.Info, "reloading configuration (file changed)") + + newConf, _, err := conf.Load(p.confPath, nil, p.logger) + if err != nil { + p.Log(logger.Error, "%s", err) + break outer + } + + err = p.reloadConf(newConf, false) + if err != nil { + p.Log(logger.Error, "%s", err) + break outer + } + + case newConf := <-p.chAPIConfigSet: + p.Log(logger.Info, "reloading configuration (API request)") + + err := p.reloadConf(newConf, true) + if err != nil { + p.Log(logger.Error, "%s", err) + break outer + } + + case <-interrupt: + p.Log(logger.Info, "shutting down gracefully") + break outer + + case <-p.ctx.Done(): + break outer + } + } + + p.ctxCancel() + + p.closeResources(nil, false) +} + +func (p *Core) createResources(initial bool) error { + var err error + + if p.logger == nil { + i := &logger.Logger{ + Level: logger.Level(p.conf.LogLevel), + Destinations: p.conf.LogDestinations.ToDestinations(), + Structured: p.conf.LogStructured, + File: p.conf.LogFile, + SysLogPrefix: p.conf.SysLogPrefix, + } + err = i.Initialize() + if err != nil { + return err + } + p.logger = i + } + + if initial { + p.Log(logger.Info, "MediaMTX %s, %s, %s", string(version), runtime.GOOS, getArch()) + + if p.confPath != "" { + a, _ := filepath.Abs(p.confPath) + p.Log(logger.Info, "configuration loaded from %s", a) + } else { + list := make([]string, len(defaultConfPaths)) + for i, pa := range defaultConfPaths { + a, _ := filepath.Abs(pa) + list[i] = a + } + + p.Log(logger.Warn, + "configuration file not found (looked in %s), using an empty configuration", + strings.Join(list, ", ")) + } + + // on Linux, try to raise the number of file descriptors that can be opened + // to allow the maximum possible number of clients. + rlimit.Raise() //nolint:errcheck + + gin.SetMode(gin.ReleaseMode) + + p.externalCmdPool = &externalcmd.Pool{} + p.externalCmdPool.Initialize() + } + + if p.authManager == nil { + p.authManager = &auth.Manager{ + Method: p.conf.AuthMethod, + InternalUsers: p.conf.AuthInternalUsers, + HTTPAddress: p.conf.AuthHTTPAddress, + HTTPFingerprint: p.conf.AuthHTTPFingerprint, + HTTPExclude: p.conf.AuthHTTPExclude, + JWTJWKS: p.conf.AuthJWTJWKS, + JWTJWKSFingerprint: p.conf.AuthJWTJWKSFingerprint, + JWTClaimKey: p.conf.AuthJWTClaimKey, + JWTExclude: p.conf.AuthJWTExclude, + JWTInHTTPQuery: p.conf.AuthJWTInHTTPQuery, + JWTIssuer: p.conf.AuthJWTIssuer, + JWTAudience: p.conf.AuthJWTAudience, + ReadTimeout: time.Duration(p.conf.ReadTimeout), + } + } + + if p.conf.Metrics && + p.metrics == nil { + i := &metrics.Metrics{ + Address: p.conf.MetricsAddress, + DumpPackets: p.conf.DumpPackets, + Encryption: p.conf.MetricsEncryption, + ServerKey: p.conf.MetricsServerKey, + ServerCert: p.conf.MetricsServerCert, + AllowOrigins: p.conf.MetricsAllowOrigins, + TrustedProxies: p.conf.MetricsTrustedProxies, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + AuthManager: p.authManager, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.metrics = i + } + + if p.conf.PPROF && + p.pprof == nil { + i := &pprof.PPROF{ + Address: p.conf.PPROFAddress, + DumpPackets: p.conf.DumpPackets, + Encryption: p.conf.PPROFEncryption, + ServerKey: p.conf.PPROFServerKey, + ServerCert: p.conf.PPROFServerCert, + AllowOrigins: p.conf.PPROFAllowOrigins, + TrustedProxies: p.conf.PPROFTrustedProxies, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + AuthManager: p.authManager, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.pprof = i + } + + if p.recordCleaner == nil && + atLeastOneRecordDeleteAfter(p.conf.Paths) { + p.recordCleaner = &recordcleaner.Cleaner{ + PathConfs: p.conf.Paths, + Parent: p, + } + p.recordCleaner.Initialize() + } + + if p.conf.Playback && + p.playbackServer == nil { + i := &playback.Server{ + Address: p.conf.PlaybackAddress, + DumpPackets: p.conf.DumpPackets, + Encryption: p.conf.PlaybackEncryption, + ServerKey: p.conf.PlaybackServerKey, + ServerCert: p.conf.PlaybackServerCert, + AllowOrigins: p.conf.PlaybackAllowOrigins, + TrustedProxies: p.conf.PlaybackTrustedProxies, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + PathConfs: p.conf.Paths, + AuthManager: p.authManager, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.playbackServer = i + } + + if p.pathManager == nil { + rtpMaxPayloadSize := getRTPMaxPayloadSize(p.conf.UDPMaxPayloadSize, p.conf.RTSPEncryption) + + p.pathManager = &pathManager{ + logLevel: p.conf.LogLevel, + dumpPackets: p.conf.DumpPackets, + rtspAddress: p.conf.RTSPAddress, + readTimeout: p.conf.ReadTimeout, + writeTimeout: p.conf.WriteTimeout, + writeQueueSize: p.conf.WriteQueueSize, + udpReadBufferSize: p.conf.UDPReadBufferSize, + rtpMaxPayloadSize: rtpMaxPayloadSize, + pathConfs: p.conf.Paths, + authManager: p.authManager, + externalCmdPool: p.externalCmdPool, + metrics: p.metrics, + parent: p, + } + p.pathManager.initialize() + } + + if p.conf.RTSP && + (p.conf.RTSPEncryption == conf.EncryptionNo || + p.conf.RTSPEncryption == conf.EncryptionOptional) && + p.rtspServer == nil { + udpReadBufferSize := p.conf.UDPReadBufferSize + if p.conf.RTSPUDPReadBufferSize != nil { + udpReadBufferSize = *p.conf.RTSPUDPReadBufferSize + } + + i := &rtsp.Server{ + Address: p.conf.RTSPAddress, + AuthMethods: p.conf.RTSPAuthMethods.ToAuthMethods(), + DumpPackets: p.conf.DumpPackets, + UDPReadBufferSize: udpReadBufferSize, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + WriteQueueSize: p.conf.WriteQueueSize, + RTSPTransports: p.conf.RTSPTransports, + RTPAddress: p.conf.RTPAddress, + RTCPAddress: p.conf.RTCPAddress, + MulticastIPRange: p.conf.MulticastIPRange, + MulticastRTPPort: p.conf.MulticastRTPPort, + MulticastRTCPPort: p.conf.MulticastRTCPPort, + Encryption: false, + ServerCert: "", + ServerKey: "", + RTSPAddress: p.conf.RTSPAddress, + TrustedProxies: p.conf.RTSPTrustedProxies, + Transports: p.conf.RTSPTransports, + RunOnConnect: p.conf.RunOnConnect, + RunOnConnectRestart: p.conf.RunOnConnectRestart, + RunOnDisconnect: p.conf.RunOnDisconnect, + ExternalCmdPool: p.externalCmdPool, + Metrics: p.metrics, + PathManager: p.pathManager, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.rtspServer = i + } + + if p.conf.RTSP && + (p.conf.RTSPEncryption == conf.EncryptionStrict || + p.conf.RTSPEncryption == conf.EncryptionOptional) && + p.rtspsServer == nil { + udpReadBufferSize := p.conf.UDPReadBufferSize + if p.conf.RTSPUDPReadBufferSize != nil { + udpReadBufferSize = *p.conf.RTSPUDPReadBufferSize + } + + i := &rtsp.Server{ + Address: p.conf.RTSPSAddress, + AuthMethods: p.conf.RTSPAuthMethods.ToAuthMethods(), + DumpPackets: p.conf.DumpPackets, + UDPReadBufferSize: udpReadBufferSize, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + WriteQueueSize: p.conf.WriteQueueSize, + RTSPTransports: p.conf.RTSPTransports, + RTPAddress: p.conf.SRTPAddress, + RTCPAddress: p.conf.SRTCPAddress, + MulticastIPRange: p.conf.MulticastIPRange, + MulticastRTPPort: p.conf.MulticastSRTPPort, + MulticastRTCPPort: p.conf.MulticastSRTCPPort, + Encryption: true, + ServerCert: p.conf.RTSPServerCert, + ServerKey: p.conf.RTSPServerKey, + RTSPAddress: p.conf.RTSPAddress, + TrustedProxies: p.conf.RTSPTrustedProxies, + Transports: p.conf.RTSPTransports, + RunOnConnect: p.conf.RunOnConnect, + RunOnConnectRestart: p.conf.RunOnConnectRestart, + RunOnDisconnect: p.conf.RunOnDisconnect, + ExternalCmdPool: p.externalCmdPool, + Metrics: p.metrics, + PathManager: p.pathManager, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.rtspsServer = i + } + + if p.conf.RTMP && + (p.conf.RTMPEncryption == conf.EncryptionNo || + p.conf.RTMPEncryption == conf.EncryptionOptional) && + p.rtmpServer == nil { + i := &rtmp.Server{ + Address: p.conf.RTMPAddress, + DumpPackets: p.conf.DumpPackets, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + Encryption: false, + ServerCert: "", + ServerKey: "", + RTSPAddress: p.conf.RTSPAddress, + TrustedProxies: p.conf.RTMPTrustedProxies, + RunOnConnect: p.conf.RunOnConnect, + RunOnConnectRestart: p.conf.RunOnConnectRestart, + RunOnDisconnect: p.conf.RunOnDisconnect, + ExternalCmdPool: p.externalCmdPool, + Metrics: p.metrics, + PathManager: p.pathManager, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.rtmpServer = i + } + + if p.conf.RTMP && + (p.conf.RTMPEncryption == conf.EncryptionStrict || + p.conf.RTMPEncryption == conf.EncryptionOptional) && + p.rtmpsServer == nil { + i := &rtmp.Server{ + Address: p.conf.RTMPSAddress, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + Encryption: true, + ServerCert: p.conf.RTMPServerCert, + ServerKey: p.conf.RTMPServerKey, + DumpPackets: p.conf.DumpPackets, + RTSPAddress: p.conf.RTSPAddress, + TrustedProxies: p.conf.RTMPTrustedProxies, + RunOnConnect: p.conf.RunOnConnect, + RunOnConnectRestart: p.conf.RunOnConnectRestart, + RunOnDisconnect: p.conf.RunOnDisconnect, + ExternalCmdPool: p.externalCmdPool, + Metrics: p.metrics, + PathManager: p.pathManager, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.rtmpsServer = i + } + + if p.conf.HLS && + p.hlsServer == nil { + i := &hls.Server{ + Address: p.conf.HLSAddress, + DumpPackets: p.conf.DumpPackets, + Encryption: p.conf.HLSEncryption, + ServerKey: p.conf.HLSServerKey, + ServerCert: p.conf.HLSServerCert, + AllowOrigins: p.conf.HLSAllowOrigins, + TrustedProxies: p.conf.HLSTrustedProxies, + AlwaysRemux: p.conf.HLSAlwaysRemux, + Variant: p.conf.HLSVariant, + SegmentCount: p.conf.HLSSegmentCount, + SegmentDuration: p.conf.HLSSegmentDuration, + PartDuration: p.conf.HLSPartDuration, + SegmentMaxSize: p.conf.HLSSegmentMaxSize, + Directory: p.conf.HLSDirectory, + CDNSecret: p.conf.HLSCDNSecret, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + MuxerCloseAfter: p.conf.HLSMuxerCloseAfter, + ExternalCmdPool: p.externalCmdPool, + Metrics: p.metrics, + PathManager: p.pathManager, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.hlsServer = i + } + + if p.conf.WebRTC && + p.webRTCServer == nil { + i := &webrtc.Server{ + Address: p.conf.WebRTCAddress, + DumpPackets: p.conf.DumpPackets, + Encryption: p.conf.WebRTCEncryption, + ServerKey: p.conf.WebRTCServerKey, + ServerCert: p.conf.WebRTCServerCert, + AllowOrigins: p.conf.WebRTCAllowOrigins, + TrustedProxies: p.conf.WebRTCTrustedProxies, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + UDPReadBufferSize: p.conf.UDPReadBufferSize, + LocalUDPAddress: p.conf.WebRTCLocalUDPAddress, + LocalTCPAddress: p.conf.WebRTCLocalTCPAddress, + IPsFromInterfaces: p.conf.WebRTCIPsFromInterfaces, + IPsFromInterfacesList: p.conf.WebRTCIPsFromInterfacesList, + AdditionalHosts: p.conf.WebRTCAdditionalHosts, + ICEServers: p.conf.WebRTCICEServers2, + STUNGatherTimeout: p.conf.WebRTCSTUNGatherTimeout, + HandshakeTimeout: p.conf.WebRTCHandshakeTimeout, + TrackGatherTimeout: p.conf.WebRTCTrackGatherTimeout, + ExternalCmdPool: p.externalCmdPool, + Metrics: p.metrics, + PathManager: p.pathManager, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.webRTCServer = i + } + + if p.conf.SRT && + p.srtServer == nil { + i := &srt.Server{ + Address: p.conf.SRTAddress, + RTSPAddress: p.conf.RTSPAddress, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + UDPMaxPayloadSize: p.conf.UDPMaxPayloadSize, + RunOnConnect: p.conf.RunOnConnect, + RunOnConnectRestart: p.conf.RunOnConnectRestart, + RunOnDisconnect: p.conf.RunOnDisconnect, + ExternalCmdPool: p.externalCmdPool, + Metrics: p.metrics, + PathManager: p.pathManager, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.srtServer = i + } + + if p.conf.MoQ && + p.moqServer == nil { + i := &moq.Server{ + HTTP2Address: p.conf.MoQHTTP2Address, + HTTP3Address: p.conf.MoQHTTP3Address, + ServerKey: p.conf.MoQServerKey, + ServerCert: p.conf.MoQServerCert, + AllowOrigins: p.conf.MoQAllowOrigins, + TrustedProxies: p.conf.MoQTrustedProxies, + UDPReadBufferSize: p.conf.UDPReadBufferSize, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + PathManager: p.pathManager, + Metrics: p.metrics, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.moqServer = i + } + + if p.conf.API && + p.api == nil { + i := &api.API{ + Version: string(version), + Started: started, + Address: p.conf.APIAddress, + DumpPackets: p.conf.DumpPackets, + Encryption: p.conf.APIEncryption, + ServerKey: p.conf.APIServerKey, + ServerCert: p.conf.APIServerCert, + AllowOrigins: p.conf.APIAllowOrigins, + TrustedProxies: p.conf.APITrustedProxies, + ReadTimeout: p.conf.ReadTimeout, + WriteTimeout: p.conf.WriteTimeout, + Conf: p.conf, + AuthManager: p.authManager, + PathManager: p.pathManager, + RTSPServer: p.rtspServer, + RTSPSServer: p.rtspsServer, + RTMPServer: p.rtmpServer, + RTMPSServer: p.rtmpsServer, + HLSServer: p.hlsServer, + WebRTCServer: p.webRTCServer, + SRTServer: p.srtServer, + MoQServer: p.moqServer, + Parent: p, + } + err = i.Initialize() + if err != nil { + return err + } + p.api = i + } + + if initial && p.confPath != "" { + cf := &confwatcher.ConfWatcher{FilePath: p.confPath} + err = cf.Initialize() + if err != nil { + return err + } + p.confWatcher = cf + } + + return nil +} + +func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) { + closeLogger := newConf == nil || + newConf.LogLevel != p.conf.LogLevel || + !reflect.DeepEqual(newConf.LogDestinations, p.conf.LogDestinations) || + newConf.LogFile != p.conf.LogFile || + newConf.SysLogPrefix != p.conf.SysLogPrefix || + newConf.LogStructured != p.conf.LogStructured + + closeAuthManager := newConf == nil || + newConf.AuthMethod != p.conf.AuthMethod || + newConf.AuthHTTPAddress != p.conf.AuthHTTPAddress || + newConf.AuthHTTPFingerprint != p.conf.AuthHTTPFingerprint || + !reflect.DeepEqual(newConf.AuthHTTPExclude, p.conf.AuthHTTPExclude) || + newConf.AuthJWTJWKS != p.conf.AuthJWTJWKS || + newConf.AuthJWTJWKSFingerprint != p.conf.AuthJWTJWKSFingerprint || + newConf.AuthJWTClaimKey != p.conf.AuthJWTClaimKey || + !reflect.DeepEqual(newConf.AuthJWTExclude, p.conf.AuthJWTExclude) || + !reflect.DeepEqual(newConf.AuthJWTInHTTPQuery, p.conf.AuthJWTInHTTPQuery) || + newConf.AuthJWTIssuer != p.conf.AuthJWTIssuer || + newConf.AuthJWTAudience != p.conf.AuthJWTAudience || + newConf.ReadTimeout != p.conf.ReadTimeout + if !closeAuthManager && !reflect.DeepEqual(newConf.AuthInternalUsers, p.conf.AuthInternalUsers) { + p.authManager.ReloadInternalUsers(newConf.AuthInternalUsers) + } + + closeMetrics := newConf == nil || + newConf.Metrics != p.conf.Metrics || + newConf.MetricsAddress != p.conf.MetricsAddress || + newConf.MetricsEncryption != p.conf.MetricsEncryption || + newConf.MetricsServerKey != p.conf.MetricsServerKey || + newConf.MetricsServerCert != p.conf.MetricsServerCert || + !slices.Equal(newConf.MetricsAllowOrigins, p.conf.MetricsAllowOrigins) || + !reflect.DeepEqual(newConf.MetricsTrustedProxies, p.conf.MetricsTrustedProxies) || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.DumpPackets != p.conf.DumpPackets || + closeAuthManager || + closeLogger + + closePPROF := newConf == nil || + newConf.PPROF != p.conf.PPROF || + newConf.PPROFAddress != p.conf.PPROFAddress || + newConf.PPROFEncryption != p.conf.PPROFEncryption || + newConf.PPROFServerKey != p.conf.PPROFServerKey || + newConf.PPROFServerCert != p.conf.PPROFServerCert || + !slices.Equal(newConf.PPROFAllowOrigins, p.conf.PPROFAllowOrigins) || + !reflect.DeepEqual(newConf.PPROFTrustedProxies, p.conf.PPROFTrustedProxies) || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.DumpPackets != p.conf.DumpPackets || + closeAuthManager || + closeLogger + + closeRecorderCleaner := newConf == nil || + atLeastOneRecordDeleteAfter(newConf.Paths) != atLeastOneRecordDeleteAfter(p.conf.Paths) || + closeLogger + if !closeRecorderCleaner && p.recordCleaner != nil && !reflect.DeepEqual(newConf.Paths, p.conf.Paths) { + p.recordCleaner.ReloadPathConfs(newConf.Paths) + } + + closePlaybackServer := newConf == nil || + newConf.Playback != p.conf.Playback || + newConf.PlaybackAddress != p.conf.PlaybackAddress || + newConf.PlaybackEncryption != p.conf.PlaybackEncryption || + newConf.PlaybackServerKey != p.conf.PlaybackServerKey || + newConf.PlaybackServerCert != p.conf.PlaybackServerCert || + !slices.Equal(newConf.PlaybackAllowOrigins, p.conf.PlaybackAllowOrigins) || + !reflect.DeepEqual(newConf.PlaybackTrustedProxies, p.conf.PlaybackTrustedProxies) || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.DumpPackets != p.conf.DumpPackets || + closeAuthManager || + closeLogger + if !closePlaybackServer && p.playbackServer != nil && !reflect.DeepEqual(newConf.Paths, p.conf.Paths) { + p.playbackServer.ReloadPathConfs(newConf.Paths) + } + + closePathManager := newConf == nil || + newConf.LogLevel != p.conf.LogLevel || + newConf.DumpPackets != p.conf.DumpPackets || + newConf.RTSPAddress != p.conf.RTSPAddress || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.WriteQueueSize != p.conf.WriteQueueSize || + newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize || + newConf.UDPMaxPayloadSize != p.conf.UDPMaxPayloadSize || + newConf.RTSPEncryption != p.conf.RTSPEncryption || + closeMetrics || + closeAuthManager || + closeLogger + if !closePathManager && !reflect.DeepEqual(newConf.Paths, p.conf.Paths) { + p.pathManager.ReloadPathConfs(newConf.Paths) + } + + closeRTSPServer := newConf == nil || + newConf.RTSP != p.conf.RTSP || + newConf.RTSPEncryption != p.conf.RTSPEncryption || + newConf.RTSPAddress != p.conf.RTSPAddress || + !reflect.DeepEqual(newConf.RTSPAuthMethods, p.conf.RTSPAuthMethods) || + newConf.RTSPUDPReadBufferSize != p.conf.RTSPUDPReadBufferSize || + newConf.DumpPackets != p.conf.DumpPackets || + newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.WriteQueueSize != p.conf.WriteQueueSize || + newConf.RTPAddress != p.conf.RTPAddress || + newConf.RTCPAddress != p.conf.RTCPAddress || + newConf.MulticastIPRange != p.conf.MulticastIPRange || + newConf.MulticastRTPPort != p.conf.MulticastRTPPort || + newConf.MulticastRTCPPort != p.conf.MulticastRTCPPort || + !reflect.DeepEqual(newConf.RTSPTransports, p.conf.RTSPTransports) || + !reflect.DeepEqual(newConf.RTSPTrustedProxies, p.conf.RTSPTrustedProxies) || + newConf.RunOnConnect != p.conf.RunOnConnect || + newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart || + newConf.RunOnDisconnect != p.conf.RunOnDisconnect || + closeMetrics || + closePathManager || + closeLogger + + closeRTSPSServer := newConf == nil || + newConf.RTSP != p.conf.RTSP || + newConf.RTSPEncryption != p.conf.RTSPEncryption || + newConf.RTSPSAddress != p.conf.RTSPSAddress || + !reflect.DeepEqual(newConf.RTSPAuthMethods, p.conf.RTSPAuthMethods) || + newConf.RTSPUDPReadBufferSize != p.conf.RTSPUDPReadBufferSize || + newConf.DumpPackets != p.conf.DumpPackets || + newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.WriteQueueSize != p.conf.WriteQueueSize || + newConf.RTSPServerCert != p.conf.RTSPServerCert || + newConf.RTSPServerKey != p.conf.RTSPServerKey || + newConf.RTSPAddress != p.conf.RTSPAddress || + !reflect.DeepEqual(newConf.RTSPTransports, p.conf.RTSPTransports) || + !reflect.DeepEqual(newConf.RTSPTrustedProxies, p.conf.RTSPTrustedProxies) || + newConf.RunOnConnect != p.conf.RunOnConnect || + newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart || + newConf.RunOnDisconnect != p.conf.RunOnDisconnect || + closeMetrics || + closePathManager || + closeLogger + + closeRTMPServer := newConf == nil || + newConf.RTMP != p.conf.RTMP || + newConf.RTMPEncryption != p.conf.RTMPEncryption || + newConf.RTMPAddress != p.conf.RTMPAddress || + newConf.DumpPackets != p.conf.DumpPackets || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.RTSPAddress != p.conf.RTSPAddress || + !reflect.DeepEqual(newConf.RTMPTrustedProxies, p.conf.RTMPTrustedProxies) || + newConf.RunOnConnect != p.conf.RunOnConnect || + newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart || + newConf.RunOnDisconnect != p.conf.RunOnDisconnect || + closeMetrics || + closePathManager || + closeLogger + + closeRTMPSServer := newConf == nil || + newConf.RTMP != p.conf.RTMP || + newConf.RTMPEncryption != p.conf.RTMPEncryption || + newConf.RTMPSAddress != p.conf.RTMPSAddress || + newConf.DumpPackets != p.conf.DumpPackets || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.RTMPServerCert != p.conf.RTMPServerCert || + newConf.RTMPServerKey != p.conf.RTMPServerKey || + newConf.RTSPAddress != p.conf.RTSPAddress || + !reflect.DeepEqual(newConf.RTMPTrustedProxies, p.conf.RTMPTrustedProxies) || + newConf.RunOnConnect != p.conf.RunOnConnect || + newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart || + newConf.RunOnDisconnect != p.conf.RunOnDisconnect || + closeMetrics || + closePathManager || + closeLogger + + closeHLSServer := newConf == nil || + newConf.HLS != p.conf.HLS || + newConf.HLSAddress != p.conf.HLSAddress || + newConf.HLSEncryption != p.conf.HLSEncryption || + newConf.HLSServerKey != p.conf.HLSServerKey || + newConf.HLSServerCert != p.conf.HLSServerCert || + !slices.Equal(newConf.HLSAllowOrigins, p.conf.HLSAllowOrigins) || + !reflect.DeepEqual(newConf.HLSTrustedProxies, p.conf.HLSTrustedProxies) || + newConf.HLSAlwaysRemux != p.conf.HLSAlwaysRemux || + newConf.HLSVariant != p.conf.HLSVariant || + newConf.HLSSegmentCount != p.conf.HLSSegmentCount || + newConf.HLSSegmentDuration != p.conf.HLSSegmentDuration || + newConf.HLSPartDuration != p.conf.HLSPartDuration || + newConf.HLSSegmentMaxSize != p.conf.HLSSegmentMaxSize || + newConf.HLSDirectory != p.conf.HLSDirectory || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.HLSMuxerCloseAfter != p.conf.HLSMuxerCloseAfter || + newConf.HLSCDNSecret != p.conf.HLSCDNSecret || + newConf.DumpPackets != p.conf.DumpPackets || + closePathManager || + closeMetrics || + closeLogger + + closeWebRTCServer := newConf == nil || + newConf.WebRTC != p.conf.WebRTC || + newConf.WebRTCAddress != p.conf.WebRTCAddress || + newConf.WebRTCEncryption != p.conf.WebRTCEncryption || + newConf.WebRTCServerKey != p.conf.WebRTCServerKey || + newConf.WebRTCServerCert != p.conf.WebRTCServerCert || + !slices.Equal(newConf.WebRTCAllowOrigins, p.conf.WebRTCAllowOrigins) || + !reflect.DeepEqual(newConf.WebRTCTrustedProxies, p.conf.WebRTCTrustedProxies) || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize || + newConf.WebRTCLocalUDPAddress != p.conf.WebRTCLocalUDPAddress || + newConf.WebRTCLocalTCPAddress != p.conf.WebRTCLocalTCPAddress || + newConf.WebRTCIPsFromInterfaces != p.conf.WebRTCIPsFromInterfaces || + !reflect.DeepEqual(newConf.WebRTCIPsFromInterfacesList, p.conf.WebRTCIPsFromInterfacesList) || + !reflect.DeepEqual(newConf.WebRTCAdditionalHosts, p.conf.WebRTCAdditionalHosts) || + !reflect.DeepEqual(newConf.WebRTCICEServers2, p.conf.WebRTCICEServers2) || + newConf.WebRTCSTUNGatherTimeout != p.conf.WebRTCSTUNGatherTimeout || + newConf.WebRTCHandshakeTimeout != p.conf.WebRTCHandshakeTimeout || + newConf.WebRTCTrackGatherTimeout != p.conf.WebRTCTrackGatherTimeout || + newConf.DumpPackets != p.conf.DumpPackets || + closeMetrics || + closePathManager || + closeLogger + + closeSRTServer := newConf == nil || + newConf.SRT != p.conf.SRT || + newConf.SRTAddress != p.conf.SRTAddress || + newConf.RTSPAddress != p.conf.RTSPAddress || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.UDPMaxPayloadSize != p.conf.UDPMaxPayloadSize || + newConf.RunOnConnect != p.conf.RunOnConnect || + newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart || + newConf.RunOnDisconnect != p.conf.RunOnDisconnect || + closeMetrics || + closePathManager || + closeLogger + + closeMoQServer := newConf == nil || + newConf.MoQ != p.conf.MoQ || + newConf.MoQHTTP2Address != p.conf.MoQHTTP2Address || + newConf.MoQHTTP3Address != p.conf.MoQHTTP3Address || + newConf.MoQServerKey != p.conf.MoQServerKey || + newConf.MoQServerCert != p.conf.MoQServerCert || + !slices.Equal(newConf.MoQAllowOrigins, p.conf.MoQAllowOrigins) || + !reflect.DeepEqual(newConf.MoQTrustedProxies, p.conf.MoQTrustedProxies) || + newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + closeMetrics || + closePathManager || + closeLogger + + closeAPI := newConf == nil || + newConf.API != p.conf.API || + newConf.APIAddress != p.conf.APIAddress || + newConf.APIEncryption != p.conf.APIEncryption || + newConf.APIServerKey != p.conf.APIServerKey || + newConf.APIServerCert != p.conf.APIServerCert || + !slices.Equal(newConf.APIAllowOrigins, p.conf.APIAllowOrigins) || + !reflect.DeepEqual(newConf.APITrustedProxies, p.conf.APITrustedProxies) || + newConf.ReadTimeout != p.conf.ReadTimeout || + newConf.WriteTimeout != p.conf.WriteTimeout || + newConf.DumpPackets != p.conf.DumpPackets || + closeAuthManager || + closePathManager || + closeRTSPServer || + closeRTSPSServer || + closeRTMPServer || + closeRTMPSServer || + closeHLSServer || + closeWebRTCServer || + closeSRTServer || + closeMoQServer || + closeLogger + + if newConf == nil && p.confWatcher != nil { + p.confWatcher.Close() + p.confWatcher = nil + } + + if p.api != nil { + if closeAPI { + p.api.Close() + p.api = nil + } else if !calledByAPI { // avoid a loop + p.api.ReloadConf(newConf) + } + } + + if closeSRTServer && p.srtServer != nil { + p.srtServer.Close() + p.srtServer = nil + } + + if closeMoQServer && p.moqServer != nil { + p.moqServer.Close() + p.moqServer = nil + } + + if closeWebRTCServer && p.webRTCServer != nil { + p.webRTCServer.Close() + p.webRTCServer = nil + } + + if closeHLSServer && p.hlsServer != nil { + p.hlsServer.Close() + p.hlsServer = nil + } + + if closeRTMPSServer && p.rtmpsServer != nil { + p.rtmpsServer.Close() + p.rtmpsServer = nil + } + + if closeRTMPServer && p.rtmpServer != nil { + p.rtmpServer.Close() + p.rtmpServer = nil + } + + if closeRTSPSServer && p.rtspsServer != nil { + p.rtspsServer.Close() + p.rtspsServer = nil + } + + if closeRTSPServer && p.rtspServer != nil { + p.rtspServer.Close() + p.rtspServer = nil + } + + if closePathManager && p.pathManager != nil { + p.pathManager.close() + p.pathManager = nil + } + + if closePlaybackServer && p.playbackServer != nil { + p.playbackServer.Close() + p.playbackServer = nil + } + + if closeRecorderCleaner && p.recordCleaner != nil { + p.recordCleaner.Close() + p.recordCleaner = nil + } + + if closePPROF && p.pprof != nil { + p.pprof.Close() + p.pprof = nil + } + + if closeMetrics && p.metrics != nil { + p.metrics.Close() + p.metrics = nil + } + + if closeAuthManager && p.authManager != nil { + p.authManager = nil + } + + if newConf == nil && p.externalCmdPool != nil { + p.Log(logger.Info, "waiting for running hooks") + p.externalCmdPool.Close() + } + + if closeLogger && p.logger != nil { + if newConf == nil { + p.logger.Close() + } + p.logger = nil + } +} + +func (p *Core) reloadConf(newConf *conf.Conf, calledByAPI bool) error { + oldLogger := p.logger + + p.closeResources(newConf, calledByAPI) + + p.conf = newConf + + err := p.createResources(false) + if err != nil { + p.logger = oldLogger + return err + } + + if p.logger != oldLogger { + oldLogger.Close() + } + + return nil +} + +// APIConfigSet implements apiParent. +func (p *Core) APIConfigSet(conf *conf.Conf) { + select { + case p.chAPIConfigSet <- conf: + case <-p.ctx.Done(): + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3ab14fbad0012440a8fddee8ec107db2e3b3b8b6 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core_test.go @@ -0,0 +1,148 @@ +package core + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/bluenviron/gortsplib/v5" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func newInstance(t *testing.T, conf string) (*Core, bool) { + if conf == "" { + return New([]string{}) + } + + tmpf := test.CreateTempFile(t, []byte(conf)) + + return New([]string{tmpf}) +} + +func TestCoreErrors(t *testing.T) { + for _, ca := range []struct { + name string + conf string + }{ + { + "logger", + "logDestinations: [file]\n" + + "logFile: /nonexisting/nonexist\n" + + "sysLogPrefix: /mediamtx\n", + }, + { + "metrics", + "metrics: yes\n" + + "metricsAddress: invalid\n", + }, + { + "pprof", + "pprof: yes\n" + + "pprofAddress: invalid\n", + }, + { + "playback", + "playback: yes\n" + + "playbackAddress: invalid\n", + }, + { + "rtsp", + "rtspAddress: invalid\n", + }, + { + "rtsps", + "rtspEncryption: strict\n" + + "rtspAddress: invalid\n", + }, + { + "rtmp", + "rtmpAddress: invalid\n", + }, + { + "rtmps", + "rtmpEncryption: strict\n" + + "rtmpAddress: invalid\n", + }, + { + "hls", + "hlsAddress: invalid\n", + }, + { + "webrtc", + "webrtcAddress: invalid\n", + }, + { + "srt", + "srtAddress: invalid\n", + }, + { + "api", + "api: yes\n" + + "apiAddress: invalid\n", + }, + } { + t.Run(ca.name, func(t *testing.T) { + _, ok := newInstance(t, ca.conf) + require.Equal(t, false, ok) + }) + } +} + +func TestCoreHotReloading(t *testing.T) { + confPath := filepath.Join(t.TempDir(), "rtsp-conf") + + err := os.WriteFile(confPath, []byte("paths:\n"+ + " test1:\n"+ + " publishUser: myuser\n"+ + " publishPass: mypass\n"), + 0o644) + require.NoError(t, err) + + p, ok := New([]string{confPath}) + require.Equal(t, true, ok) + defer p.Close() + + func() { + c := gortsplib.Client{} + err = c.StartRecording("rtsp://localhost:8554/test1", + &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}}) + require.EqualError(t, err, "bad status code: 401 (Unauthorized)") + }() + + err = os.WriteFile(confPath, []byte("paths:\n"+ + " test1:\n"), + 0o644) + require.NoError(t, err) + + time.Sleep(1 * time.Second) + + func() { + conn := gortsplib.Client{} + err = conn.StartRecording("rtsp://localhost:8554/test1", + &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}}) + require.NoError(t, err) + defer conn.Close() + }() +} + +func TestCoreHotReloadingAndLoggerError(t *testing.T) { + confPath := filepath.Join(t.TempDir(), "rtsp-conf") + + err := os.WriteFile(confPath, []byte(""), + 0o644) + require.NoError(t, err) + + p, ok := New([]string{confPath}) + require.Equal(t, true, ok) + defer p.Close() + + err = os.WriteFile(confPath, []byte("logDestinations: [file]\n"+ + "logFile: /nonexisting/nonexist\n"), + 0o644) + require.NoError(t, err) + + p.Wait() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/metrics_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/metrics_test.go new file mode 100644 index 0000000000000000000000000000000000000000..53f096d63db5f80f463709b7caab3cae4e925695 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/metrics_test.go @@ -0,0 +1,513 @@ +package core + +import ( + "bufio" + "context" + "crypto/tls" + "io" + "net/http" + "net/url" + "sync" + "testing" + "time" + + "github.com/bluenviron/gortmplib" + rtmpcodecs "github.com/bluenviron/gortmplib/pkg/codecs" + "github.com/bluenviron/gortsplib/v5" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts" + tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs" + srt "github.com/datarhei/gosrt" + "github.com/pion/rtp" + pwebrtc "github.com/pion/webrtc/v4" + "github.com/stretchr/testify/require" + + "github.com/bluenviron/mediamtx/internal/protocols/webrtc" + "github.com/bluenviron/mediamtx/internal/protocols/whip" + "github.com/bluenviron/mediamtx/internal/test" +) + +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 TestMetrics(t *testing.T) { + serverCertFpath := test.CreateTempFile(t, test.TLSCertPub) + serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey) + + p, ok := newInstance(t, "api: yes\n"+ + "hlsAlwaysRemux: yes\n"+ + "metrics: yes\n"+ + "webrtcServerCert: "+serverCertFpath+"\n"+ + "webrtcServerKey: "+serverKeyFpath+"\n"+ + "rtspEncryption: optional\n"+ + "rtspServerCert: "+serverCertFpath+"\n"+ + "rtspServerKey: "+serverKeyFpath+"\n"+ + "rtmpEncryption: optional\n"+ + "rtmpServerCert: "+serverCertFpath+"\n"+ + "rtmpServerKey: "+serverKeyFpath+"\n"+ + "paths:\n"+ + " all_others:\n") + require.Equal(t, true, ok) + defer p.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + t.Run("initial", func(t *testing.T) { + bo := httpPullFile(t, hc, "http://localhost:9998/metrics") + + require.Equal(t, `# Paths +paths 0 +paths_inbound_bytes 0 +paths_outbound_bytes 0 +paths_inbound_frames_in_error 0 + +# Paths (deprecated) +paths_bytes_received 0 +paths_bytes_sent 0 +paths_readers 0 + +# HLS sessions +hls_sessions 0 +hls_sessions_outbound_bytes 0 + +# HLS muxers +hls_muxers 0 +hls_muxers_outbound_bytes 0 +hls_muxers_outbound_frames_discarded 0 + +# HLS muxers (deprecated) +hls_muxers_bytes_sent 0 + +# RTSP connections +rtsp_conns 0 +rtsp_conns_inbound_bytes 0 +rtsp_conns_outbound_bytes 0 + +# RTSP connections (deprecated) +rtsp_conns_bytes_received 0 +rtsp_conns_bytes_sent 0 + +# RTSP sessions +rtsp_sessions 0 +rtsp_sessions_inbound_bytes 0 +rtsp_sessions_inbound_rtp_packets 0 +rtsp_sessions_inbound_rtp_packets_lost 0 +rtsp_sessions_inbound_rtp_packets_in_error 0 +rtsp_sessions_inbound_rtp_packets_jitter 0 +rtsp_sessions_inbound_rtcp_packets 0 +rtsp_sessions_inbound_rtcp_packets_in_error 0 +rtsp_sessions_outbound_bytes 0 +rtsp_sessions_outbound_rtp_packets 0 +rtsp_sessions_outbound_rtp_packets_reported_lost 0 +rtsp_sessions_outbound_rtp_packets_discarded 0 +rtsp_sessions_outbound_rtcp_packets 0 + +# RTSP sessions (deprecated) +rtsp_sessions_bytes_received 0 +rtsp_sessions_bytes_sent 0 +rtsp_sessions_rtp_packets_received 0 +rtsp_sessions_rtp_packets_sent 0 +rtsp_sessions_rtp_packets_lost 0 +rtsp_sessions_rtp_packets_in_error 0 +rtsp_sessions_rtp_packets_jitter 0 +rtsp_sessions_rtcp_packets_received 0 +rtsp_sessions_rtcp_packets_sent 0 +rtsp_sessions_rtcp_packets_in_error 0 + +# RTSPS connections +rtsps_conns 0 +rtsps_conns_inbound_bytes 0 +rtsps_conns_outbound_bytes 0 + +# RTSPS connections (deprecated) +rtsps_conns_bytes_received 0 +rtsps_conns_bytes_sent 0 + +# RTSPS sessions +rtsps_sessions 0 +rtsps_sessions_inbound_bytes 0 +rtsps_sessions_inbound_rtp_packets 0 +rtsps_sessions_inbound_rtp_packets_lost 0 +rtsps_sessions_inbound_rtp_packets_in_error 0 +rtsps_sessions_inbound_rtp_packets_jitter 0 +rtsps_sessions_inbound_rtcp_packets 0 +rtsps_sessions_inbound_rtcp_packets_in_error 0 +rtsps_sessions_outbound_bytes 0 +rtsps_sessions_outbound_rtp_packets 0 +rtsps_sessions_outbound_rtp_packets_reported_lost 0 +rtsps_sessions_outbound_rtp_packets_discarded 0 +rtsps_sessions_outbound_rtcp_packets 0 + +# RTSPS sessions (deprecated) +rtsps_sessions_bytes_received 0 +rtsps_sessions_bytes_sent 0 +rtsps_sessions_rtp_packets_received 0 +rtsps_sessions_rtp_packets_sent 0 +rtsps_sessions_rtp_packets_lost 0 +rtsps_sessions_rtp_packets_in_error 0 +rtsps_sessions_rtp_packets_jitter 0 +rtsps_sessions_rtcp_packets_received 0 +rtsps_sessions_rtcp_packets_sent 0 +rtsps_sessions_rtcp_packets_in_error 0 + +# RTMP connections +rtmp_conns 0 +rtmp_conns_inbound_bytes 0 +rtmp_conns_outbound_bytes 0 +rtmp_conns_outbound_frames_discarded 0 + +# RTMP connections (deprecated) +rtmp_conns_bytes_received 0 +rtmp_conns_bytes_sent 0 + +# RTMPS connections +rtmps_conns 0 +rtmps_conns_inbound_bytes 0 +rtmps_conns_outbound_bytes 0 +rtmps_conns_outbound_frames_discarded 0 + +# RTMPS connections (deprecated) +rtmps_conns_bytes_received 0 +rtmps_conns_bytes_sent 0 + +# SRT connections +srt_conns 0 +srt_conns_packets_sent 0 +srt_conns_packets_received 0 +srt_conns_packets_sent_unique 0 +srt_conns_packets_received_unique 0 +srt_conns_packets_send_loss 0 +srt_conns_packets_received_loss 0 +srt_conns_packets_retrans 0 +srt_conns_packets_received_retrans 0 +srt_conns_packets_sent_ack 0 +srt_conns_packets_received_ack 0 +srt_conns_packets_sent_nak 0 +srt_conns_packets_received_nak 0 +srt_conns_packets_sent_km 0 +srt_conns_packets_received_km 0 +srt_conns_us_snd_duration 0 +srt_conns_packets_received_belated 0 +srt_conns_packets_send_drop 0 +srt_conns_packets_received_drop 0 +srt_conns_packets_received_undecrypt 0 +srt_conns_bytes_sent 0 +srt_conns_bytes_received 0 +srt_conns_bytes_sent_unique 0 +srt_conns_bytes_received_unique 0 +srt_conns_bytes_received_loss 0 +srt_conns_bytes_retrans 0 +srt_conns_bytes_received_retrans 0 +srt_conns_bytes_received_belated 0 +srt_conns_bytes_send_drop 0 +srt_conns_bytes_received_drop 0 +srt_conns_bytes_received_undecrypt 0 +srt_conns_us_packets_send_period 0 +srt_conns_packets_flow_window 0 +srt_conns_packets_flight_size 0 +srt_conns_ms_rtt 0 +srt_conns_mbps_send_rate 0 +srt_conns_mbps_receive_rate 0 +srt_conns_mbps_link_capacity 0 +srt_conns_bytes_avail_send_buf 0 +srt_conns_bytes_avail_receive_buf 0 +srt_conns_mbps_max_bw 0 +srt_conns_bytes_mss 0 +srt_conns_packets_send_buf 0 +srt_conns_bytes_send_buf 0 +srt_conns_ms_send_buf 0 +srt_conns_ms_send_tsb_pd_delay 0 +srt_conns_packets_receive_buf 0 +srt_conns_bytes_receive_buf 0 +srt_conns_ms_receive_buf 0 +srt_conns_ms_receive_tsb_pd_delay 0 +srt_conns_packets_reorder_tolerance 0 +srt_conns_packets_received_avg_belated_time 0 +srt_conns_packets_send_loss_rate 0 +srt_conns_packets_received_loss_rate 0 +srt_conns_outbound_frames_discarded 0 + +# WebRTC sessions +webrtc_sessions 0 +webrtc_sessions_inbound_bytes 0 +webrtc_sessions_inbound_rtp_packets 0 +webrtc_sessions_inbound_rtp_packets_lost 0 +webrtc_sessions_inbound_rtp_packets_jitter 0 +webrtc_sessions_inbound_rtcp_packets 0 +webrtc_sessions_outbound_bytes 0 +webrtc_sessions_outbound_rtp_packets 0 +webrtc_sessions_outbound_rtcp_packets 0 +webrtc_sessions_outbound_frames_discarded 0 + +# WebRTC sessions (deprecated) +webrtc_sessions_bytes_received 0 +webrtc_sessions_bytes_sent 0 +webrtc_sessions_rtp_packets_received 0 +webrtc_sessions_rtp_packets_sent 0 +webrtc_sessions_rtp_packets_lost 0 +webrtc_sessions_rtp_packets_jitter 0 +webrtc_sessions_rtcp_packets_received 0 +webrtc_sessions_rtcp_packets_sent 0 + +# MoQ sessions +moq_sessions 0 +moq_sessions_inbound_bytes 0 +moq_sessions_outbound_bytes 0 + +`, string(bo)) + }) + + t.Run("with data", func(t *testing.T) { + terminate := make(chan struct{}) + var wg sync.WaitGroup + wg.Add(6) + + go func() { + defer wg.Done() + source := gortsplib.Client{} + err2 := source.StartRecording("rtsp://localhost:8554/rtsp_path", + &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}}) + require.NoError(t, err2) + defer source.Close() + <-terminate + }() + + go func() { + defer wg.Done() + source2 := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}} + err2 := source2.StartRecording("rtsps://localhost:8322/rtsps_path", + &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}}) + require.NoError(t, err2) + defer source2.Close() + <-terminate + }() + + go func() { + defer wg.Done() + + u, err2 := url.Parse("rtmp://localhost:1935/rtmp_path") + require.NoError(t, err2) + + conn := &gortmplib.Client{ + URL: u, + Publish: true, + } + err2 = conn.Initialize(context.Background()) + require.NoError(t, err2) + defer conn.Close() + + track := &gortmplib.Track{ + Codec: &rtmpcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + } + + w := &gortmplib.Writer{ + Conn: conn, + Tracks: []*gortmplib.Track{track}, + } + err2 = w.Initialize() + require.NoError(t, err2) + + err2 = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}}) + require.NoError(t, err2) + + <-terminate + }() + + go func() { + defer wg.Done() + + u, err2 := url.Parse("rtmps://localhost:1936/rtmps_path") + require.NoError(t, err2) + + conn := &gortmplib.Client{ + URL: u, + TLSConfig: &tls.Config{InsecureSkipVerify: true}, + Publish: true, + } + err2 = conn.Initialize(context.Background()) + require.NoError(t, err2) + defer conn.Close() + + track := &gortmplib.Track{ + Codec: &rtmpcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + } + + w := &gortmplib.Writer{ + Conn: conn, + Tracks: []*gortmplib.Track{track}, + } + err2 = w.Initialize() + require.NoError(t, err2) + + err2 = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}}) + require.NoError(t, err2) + + <-terminate + }() + + go func() { + defer wg.Done() + + su, err2 := url.Parse("http://localhost:8889/webrtc_path/whip") + require.NoError(t, err2) + + tr2 := &http.Transport{} + defer tr2.CloseIdleConnections() + hc2 := &http.Client{Transport: tr2} + + track := &webrtc.OutboundTrack{ + Caps: pwebrtc.RTPCodecCapability{ + MimeType: pwebrtc.MimeTypeH264, + ClockRate: 90000, + SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f", + }, + } + + s := &whip.Client{ + HTTPClient: hc2, + URL: su, + Log: test.NilLogger, + Publish: true, + OutboundTracks: []*webrtc.OutboundTrack{track}, + } + + err2 = s.Initialize(context.Background()) + require.NoError(t, err2) + defer checkClose(t, s.Close) + + err2 = track.WriteRTP(&rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 96, + SequenceNumber: 123, + Timestamp: 45343, + SSRC: 563423, + }, + Payload: []byte{1}, + }) + require.NoError(t, err2) + <-terminate + }() + + go func() { + defer wg.Done() + + srtConf := srt.DefaultConfig() + address, err2 := srtConf.UnmarshalURL("srt://localhost:8890?streamid=publish:srt_path") + require.NoError(t, err2) + + err2 = srtConf.Validate() + require.NoError(t, err2) + + publisher, err2 := srt.Dial("srt", address, srtConf) + require.NoError(t, err2) + defer publisher.Close() + + track := &mpegts.Track{ + Codec: &tscodecs.H264{}, + } + + bw := bufio.NewWriter(publisher) + w := &mpegts.Writer{W: bw, Tracks: []*mpegts.Track{track}} + err2 = w.Initialize() + require.NoError(t, err2) + + err2 = w.WriteH264(track, 0, 0, [][]byte{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {0x05, 1}, // IDR + }) + require.NoError(t, err2) + + err2 = bw.Flush() + require.NoError(t, err2) + <-terminate + }() + + time.Sleep(500*time.Millisecond + 2*time.Second) + + bo := httpPullFile(t, hc, "http://localhost:9998/metrics") + + boStr := string(bo) + require.Contains(t, boStr, "paths{name=\"rtmp_path\",state=\"ready\"} 1\n") + require.Contains(t, boStr, "paths{name=\"rtmps_path\",state=\"ready\"} 1\n") + require.Contains(t, boStr, "paths{name=\"rtsp_path\",state=\"ready\"} 1\n") + require.Contains(t, boStr, "paths{name=\"rtsps_path\",state=\"ready\"} 1\n") + require.Contains(t, boStr, "paths{name=\"srt_path\",state=\"ready\"} 1\n") + require.Contains(t, boStr, "paths{name=\"webrtc_path\",state=\"ready\"} 1\n") + require.Contains(t, boStr, "hls_muxers{name=\"rtmp_path\"} 1\n") + require.Contains(t, boStr, "hls_muxers{name=\"rtmps_path\"} 1\n") + require.Contains(t, boStr, "hls_muxers{name=\"rtsp_path\"} 1\n") + require.Contains(t, boStr, "hls_muxers{name=\"rtsps_path\"} 1\n") + require.Contains(t, boStr, "hls_muxers{name=\"srt_path\"} 1\n") + require.Contains(t, boStr, "hls_muxers{name=\"webrtc_path\"} 1\n") + require.Regexp(t, `(?m)^rtsp_conns\{id=".*?"\} 1$`, boStr) + require.Regexp(t, `(?m)^rtsp_sessions\{id=".*?",path="rtsp_path",remoteAddr=".*?",state="publish"\} 1$`, boStr) + require.Regexp(t, `(?m)^rtsps_conns\{id=".*?"\} 1$`, boStr) + require.Regexp(t, `(?m)^rtsps_sessions\{id=".*?",path="rtsps_path",remoteAddr=".*?",state="publish"\} 1$`, boStr) + require.Regexp(t, `(?m)^rtmp_conns\{id=".*?",path="rtmp_path",remoteAddr=".*?",state="publish"\} 1$`, boStr) + require.Regexp(t, `(?m)^rtmps_conns\{id=".*?",path="rtmps_path",remoteAddr=".*?",state="publish"\} 1$`, boStr) + require.Regexp(t, `(?m)^srt_conns\{id=".*?",path="srt_path",remoteAddr=".*?",state="publish"\} 1$`, boStr) + require.Regexp(t, `(?m)^srt_conns_ms_rtt\{id=".*?",path="srt_path",`+ + `remoteAddr=".*?",state="publish"\} [0-9.]+$`, boStr) + require.Regexp(t, `(?m)^webrtc_sessions\{id=".*?",path="webrtc_path",remoteAddr=".*?",state="publish"\} 1$`, boStr) + require.Regexp(t, `(?m)^webrtc_sessions_rtcp_packets_received\{id=".*?",path="webrtc_path",`+ + `remoteAddr=".*?",state="publish"\} [0-9]+$`, boStr) + + close(terminate) + wg.Wait() + }) + + t.Run("servers disabled", func(t *testing.T) { + httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/global/patch", map[string]any{ + "rtsp": false, + "rtmp": false, + "srt": false, + "hls": false, + "webrtc": false, + }, nil) + + time.Sleep(500 * time.Millisecond) + + bo := httpPullFile(t, hc, "http://localhost:9998/metrics") + + require.Equal(t, "# Paths\n"+ + "paths 0\n"+ + "paths_inbound_bytes 0\n"+ + "paths_outbound_bytes 0\n"+ + "paths_inbound_frames_in_error 0\n"+ + "\n"+ + "# Paths (deprecated)\n"+ + "paths_bytes_received 0\n"+ + "paths_bytes_sent 0\n"+ + "paths_readers 0\n"+ + "\n"+ + "# MoQ sessions\n"+ + "moq_sessions 0\n"+ + "moq_sessions_inbound_bytes 0\n"+ + "moq_sessions_outbound_bytes 0\n"+ + "\n", + string(bo)) + }) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path.go new file mode 100644 index 0000000000000000000000000000000000000000..7a5e7ea01d3af9d27ff7b76f39792680f3372e3d --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path.go @@ -0,0 +1,1116 @@ +package core + +import ( + "context" + "fmt" + "net" + "sort" + "strconv" + "sync" + "sync/atomic" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/formatlabel" + "github.com/bluenviron/mediamtx/internal/hooks" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/recorder" + "github.com/bluenviron/mediamtx/internal/staticsources" + "github.com/bluenviron/mediamtx/internal/stream" +) + +func emptyTimer() *time.Timer { + t := time.NewTimer(0) + <-t.C + return t +} + +type pathParent interface { + logger.Writer + setPathReady(*path) + setPathNotReady(*path) + closePathIfIdle(*path) + removePath(*path) + AddReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) +} + +type pathOnDemandState int + +const ( + pathOnDemandStateInitial pathOnDemandState = iota + pathOnDemandStateWaitingReady + pathOnDemandStateReady + pathOnDemandStateClosing +) + +type pathAPIPathsListRes struct { + data *defs.APIPathList + paths map[string]*path +} + +type pathAPIPathsListReq struct { + res chan pathAPIPathsListRes +} + +type pathAPIPathsGetRes struct { + path *path + data *defs.APIPath + err error +} + +type pathAPIPathsGetReq struct { + name string + res chan pathAPIPathsGetRes +} + +type path struct { + parentCtx context.Context + logLevel conf.LogLevel + dumpPackets bool + rtspAddress string + readTimeout conf.Duration + writeTimeout conf.Duration + writeQueueSize int + udpReadBufferSize uint + rtpMaxPayloadSize int + conf *conf.Path + name string + matches []string + wg *sync.WaitGroup + externalCmdPool *externalcmd.Pool + parent pathParent + + // accessed by pathManager only + ready bool + confName string + + ctx context.Context + ctxCancel func() + pendingRequests atomic.Int64 + confMutex sync.RWMutex + source defs.Source + stream *stream.Stream + recorder *recorder.Recorder + availableTime time.Time + onlineTime time.Time + onUnDemandHook func(string) + onNotReadyHook func() + readers map[defs.Reader]struct{} + describeRequestsOnHold []defs.PathDescribeReq + readerAddRequestsOnHold []defs.PathAddReaderReq + onDemandStaticSourceState pathOnDemandState + onDemandStaticSourceReadyTimer *time.Timer + onDemandStaticSourceCloseTimer *time.Timer + onDemandPublisherState pathOnDemandState + onDemandPublisherReadyTimer *time.Timer + onDemandPublisherCloseTimer *time.Timer + + // in + chReloadConf chan *conf.Path + chStaticSourceSetReady chan defs.PathSourceStaticSetReadyReq + chStaticSourceSetNotReady chan defs.PathSourceStaticSetNotReadyReq + chDescribe chan defs.PathDescribeReq + chAddPublisher chan defs.PathAddPublisherReq + chRemovePublisher chan defs.PathRemovePublisherReq + chAddReader chan defs.PathAddReaderReq + chRemoveReader chan defs.PathRemoveReaderReq + chAPIPathsGet chan pathAPIPathsGetReq + + // out + done chan struct{} +} + +func (pa *path) initialize() { + ctx, ctxCancel := context.WithCancel(pa.parentCtx) + + pa.confName = pa.conf.Name + pa.ctx = ctx + pa.ctxCancel = ctxCancel + pa.readers = make(map[defs.Reader]struct{}) + pa.onDemandStaticSourceReadyTimer = emptyTimer() + pa.onDemandStaticSourceCloseTimer = emptyTimer() + pa.onDemandPublisherReadyTimer = emptyTimer() + pa.onDemandPublisherCloseTimer = emptyTimer() + pa.chReloadConf = make(chan *conf.Path) + pa.chStaticSourceSetReady = make(chan defs.PathSourceStaticSetReadyReq) + pa.chStaticSourceSetNotReady = make(chan defs.PathSourceStaticSetNotReadyReq) + pa.chDescribe = make(chan defs.PathDescribeReq) + pa.chAddPublisher = make(chan defs.PathAddPublisherReq) + pa.chRemovePublisher = make(chan defs.PathRemovePublisherReq) + pa.chAddReader = make(chan defs.PathAddReaderReq) + pa.chRemoveReader = make(chan defs.PathRemoveReaderReq) + pa.chAPIPathsGet = make(chan pathAPIPathsGetReq) + pa.done = make(chan struct{}) + + pa.Log(logger.Debug, "created") + + pa.wg.Add(1) + go pa.run() +} + +func (pa *path) close() { + pa.ctxCancel() +} + +func (pa *path) wait() { + <-pa.done +} + +// Log implements logger.Writer. +func (pa *path) Log(level logger.Level, format string, args ...any) { + pa.parent.Log(level, "[path "+pa.name+"] "+format, args...) +} + +func (pa *path) Name() string { + return pa.name +} + +func (pa *path) isAvailable() bool { + return pa.stream != nil +} + +func (pa *path) isOnline() bool { + return pa.source != nil +} + +func (pa *path) run() { + defer close(pa.done) + defer pa.wg.Done() + + if pa.conf.AlwaysAvailable { + err := pa.setAvailable(nil, "", nil, true) + if err != nil { + panic(err) + } + } + + if pa.conf.Source == "redirect" { + pa.source = &sourceRedirect{} + } else if pa.conf.HasStaticSource() { + pa.source = &staticsources.Handler{ + Conf: pa.conf, + LogLevel: pa.logLevel, + DumpPackets: pa.dumpPackets, + ReadTimeout: pa.readTimeout, + WriteTimeout: pa.writeTimeout, + WriteQueueSize: pa.writeQueueSize, + UDPReadBufferSize: pa.udpReadBufferSize, + RTPMaxPayloadSize: pa.rtpMaxPayloadSize, + Matches: pa.matches, + PathManager: pa.parent, + Parent: pa, + } + pa.source.(*staticsources.Handler).Initialize() + + if !pa.conf.SourceOnDemand { + pa.source.(*staticsources.Handler).Start(false, "") + } + } + + onUnInitHook := hooks.OnInit(hooks.OnInitParams{ + Logger: pa, + ExternalCmdPool: pa.externalCmdPool, + Conf: pa.conf, + ExternalCmdEnv: pa.ExternalCmdEnv(), + }) + + err := pa.runInner() + + // call before destroying context + pa.parent.removePath(pa) + + pa.ctxCancel() + + pa.onDemandStaticSourceReadyTimer.Stop() + pa.onDemandStaticSourceCloseTimer.Stop() + pa.onDemandPublisherReadyTimer.Stop() + pa.onDemandPublisherCloseTimer.Stop() + + onUnInitHook() + + for _, req := range pa.describeRequestsOnHold { + req.Res <- defs.PathDescribeRes{Err: fmt.Errorf("terminated")} + } + + for _, req := range pa.readerAddRequestsOnHold { + req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("terminated")} + } + + if pa.stream != nil { + pa.setNotAvailable() + } + + if pa.source != nil { + if source, ok := pa.source.(*staticsources.Handler); ok { + if !pa.conf.SourceOnDemand || pa.onDemandStaticSourceState != pathOnDemandStateInitial { + source.Close("path is closing") + } + } else if source, ok2 := pa.source.(defs.Publisher); ok2 { + source.Close() + } + } + + if pa.onUnDemandHook != nil { + pa.onUnDemandHook("path destroyed") + } + + pa.Log(logger.Debug, "destroyed: %v", err) +} + +func (pa *path) runInner() error { + for { + select { + case <-pa.onDemandStaticSourceReadyTimer.C: + pa.doOnDemandStaticSourceReadyTimer() + + if pa.shouldClose() { + pa.parent.closePathIfIdle(pa) + } + + case <-pa.onDemandStaticSourceCloseTimer.C: + pa.doOnDemandStaticSourceCloseTimer() + + if pa.shouldClose() { + pa.parent.closePathIfIdle(pa) + } + + case <-pa.onDemandPublisherReadyTimer.C: + pa.doOnDemandPublisherReadyTimer() + + if pa.shouldClose() { + pa.parent.closePathIfIdle(pa) + } + + case <-pa.onDemandPublisherCloseTimer.C: + pa.doOnDemandPublisherCloseTimer() + + case newConf := <-pa.chReloadConf: + pa.doReloadConf(newConf) + + case req := <-pa.chStaticSourceSetReady: + pa.doSourceStaticSetReady(req) + + case req := <-pa.chStaticSourceSetNotReady: + pa.doSourceStaticSetNotReady(req) + + if pa.shouldClose() { + pa.parent.closePathIfIdle(pa) + } + + case req := <-pa.chDescribe: + pa.doDescribe(req) + + pa.pendingRequests.Add(-1) + + if pa.shouldClose() { + pa.parent.closePathIfIdle(pa) + } + + case req := <-pa.chAddPublisher: + pa.doAddPublisher(req) + + pa.pendingRequests.Add(-1) + + if pa.shouldClose() { + pa.parent.closePathIfIdle(pa) + } + + case req := <-pa.chRemovePublisher: + pa.doRemovePublisher(req) + + if pa.shouldClose() { + pa.parent.closePathIfIdle(pa) + } + + case req := <-pa.chAddReader: + pa.doAddReader(req) + + pa.pendingRequests.Add(-1) + + if pa.shouldClose() { + pa.parent.closePathIfIdle(pa) + } + + case req := <-pa.chRemoveReader: + pa.doRemoveReader(req) + + case req := <-pa.chAPIPathsGet: + pa.doAPIPathsGet(req) + + case <-pa.ctx.Done(): + return fmt.Errorf("terminated") + } + } +} + +func (pa *path) doOnDemandStaticSourceReadyTimer() { + for _, req := range pa.describeRequestsOnHold { + req.Res <- defs.PathDescribeRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)} + } + pa.describeRequestsOnHold = nil + + for _, req := range pa.readerAddRequestsOnHold { + req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)} + } + pa.readerAddRequestsOnHold = nil + + pa.onDemandStaticSourceStop("timed out") +} + +func (pa *path) doOnDemandStaticSourceCloseTimer() { + if pa.conf.AlwaysAvailable { + panic("should not happen") + } + pa.setNotAvailable() + pa.onDemandStaticSourceStop("not needed by anyone") +} + +func (pa *path) doOnDemandPublisherReadyTimer() { + for _, req := range pa.describeRequestsOnHold { + req.Res <- defs.PathDescribeRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)} + } + pa.describeRequestsOnHold = nil + + for _, req := range pa.readerAddRequestsOnHold { + req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)} + } + pa.readerAddRequestsOnHold = nil + + pa.onDemandPublisherStop("timed out") +} + +func (pa *path) doOnDemandPublisherCloseTimer() { + pa.onDemandPublisherStop("not needed by anyone") +} + +func (pa *path) doReloadConf(newConf *conf.Path) { + pa.confMutex.Lock() + oldConf := pa.conf + pa.conf = newConf + pa.confMutex.Unlock() + + if pa.conf.HasStaticSource() { + pa.source.(*staticsources.Handler).ReloadConf(newConf) + } + + if pa.recorder != nil && + (newConf.Record != oldConf.Record || + newConf.RecordPath != oldConf.RecordPath || + newConf.RecordFormat != oldConf.RecordFormat || + newConf.RecordPartDuration != oldConf.RecordPartDuration || + newConf.RecordMaxPartSize != oldConf.RecordMaxPartSize || + newConf.RecordSegmentDuration != oldConf.RecordSegmentDuration || + newConf.RecordDeleteAfter != oldConf.RecordDeleteAfter) { + pa.recorder.Close() + pa.recorder = nil + } + + if newConf.Record && pa.stream != nil && pa.recorder == nil { + pa.startRecording() + } +} + +func (pa *path) doSourceStaticSetReady(req defs.PathSourceStaticSetReadyReq) { + if !pa.conf.AlwaysAvailable { + err := pa.setAvailable(pa.source, "", req.Desc, req.ReplaceNTP) + if err != nil { + req.Res <- defs.PathSourceStaticSetReadyRes{Err: err} + return + } + } + + subStream := &stream.SubStream{ + Stream: pa.stream, + UseRTPPackets: req.UseRTPPackets, + } + + if pa.conf.AlwaysAvailable { + subStream.InDesc = req.Desc + } + + err := subStream.Initialize() + if err != nil { + req.Res <- defs.PathSourceStaticSetReadyRes{Err: err} + return + } + + if pa.conf.AlwaysAvailable { + pa.onlineTime = time.Now() + } + + if pa.conf.HasOnDemandStaticSource() { + pa.onDemandStaticSourceReadyTimer.Stop() + pa.onDemandStaticSourceReadyTimer = emptyTimer() + pa.onDemandStaticSourceScheduleClose() + } + + pa.consumeOnHoldRequests() + + req.Res <- defs.PathSourceStaticSetReadyRes{SubStream: subStream} +} + +func (pa *path) doSourceStaticSetNotReady(req defs.PathSourceStaticSetNotReadyReq) { + if !pa.conf.AlwaysAvailable { + pa.setNotAvailable() + } else { + err := pa.stream.StartOfflineSubStream() + if err != nil { + panic("should not happen") + } + } + + // send response before calling onDemandStaticSourceStop() + // in order to avoid a deadlock due to staticsources.Handler.stop() + close(req.Res) + + if pa.conf.HasOnDemandStaticSource() && pa.onDemandStaticSourceState != pathOnDemandStateInitial { + pa.onDemandStaticSourceStop("an error occurred") + } +} + +func (pa *path) doDescribe(req defs.PathDescribeReq) { + if _, ok := pa.source.(*sourceRedirect); ok { + req.Res <- defs.PathDescribeRes{ + Redirect: pa.conf.SourceRedirect, + } + return + } + + if pa.stream != nil { + req.Res <- defs.PathDescribeRes{ + Stream: pa.stream, + } + return + } + + if pa.conf.HasOnDemandStaticSource() { + if pa.onDemandStaticSourceState == pathOnDemandStateInitial { + pa.onDemandStaticSourceStart(req.AccessRequest.Query) + } + pa.describeRequestsOnHold = append(pa.describeRequestsOnHold, req) + return + } + + if pa.conf.HasOnDemandPublisher() { + if pa.onDemandPublisherState == pathOnDemandStateInitial { + pa.onDemandPublisherStart(req.AccessRequest.Query) + } + pa.describeRequestsOnHold = append(pa.describeRequestsOnHold, req) + return + } + + if pa.conf.Fallback != nil { + req.Res <- defs.PathDescribeRes{Redirect: *pa.conf.Fallback} + return + } + + req.Res <- defs.PathDescribeRes{Err: &defs.PathNoStreamAvailableError{PathName: pa.name}} +} + +func (pa *path) doRemovePublisher(req defs.PathRemovePublisherReq) { + if pa.source == req.Author { + pa.executeRemovePublisher() + } + close(req.Res) +} + +func (pa *path) doAddPublisher(req defs.PathAddPublisherReq) { + if pa.conf.Source != "publisher" { + req.Res <- defs.PathAddPublisherRes{ + Err: fmt.Errorf("can't publish to path '%s' since 'source' is not 'publisher'", pa.name), + } + return + } + + if pa.source != nil { + if !pa.conf.OverridePublisher { + req.Res <- defs.PathAddPublisherRes{Err: fmt.Errorf("someone is already publishing to path '%s'", pa.name)} + return + } + + pa.Log(logger.Info, "closing existing publisher") + pa.source.(defs.Publisher).Close() + pa.executeRemovePublisher() + } + + if !pa.conf.AlwaysAvailable { + err := pa.setAvailable(req.Author, req.AccessRequest.Query, req.Desc, req.ReplaceNTP) + if err != nil { + req.Res <- defs.PathAddPublisherRes{Err: err} + return + } + } + + subStream := &stream.SubStream{ + Stream: pa.stream, + UseRTPPackets: req.UseRTPPackets, + } + + if pa.conf.AlwaysAvailable { + subStream.InDesc = req.Desc + } + + err := subStream.Initialize() + if err != nil { + req.Res <- defs.PathAddPublisherRes{Err: err} + return + } + + pa.source = req.Author + + req.Author.Log(logger.Info, "is publishing to path '%s'", + pa.name) + + if pa.conf.AlwaysAvailable { + pa.onlineTime = time.Now() + } + + if pa.conf.HasOnDemandPublisher() && pa.onDemandPublisherState != pathOnDemandStateInitial { + pa.onDemandPublisherReadyTimer.Stop() + pa.onDemandPublisherReadyTimer = emptyTimer() + pa.onDemandPublisherScheduleClose() + } + + pa.consumeOnHoldRequests() + + req.Res <- defs.PathAddPublisherRes{SubStream: subStream} +} + +func (pa *path) doAddReader(req defs.PathAddReaderReq) { + if pa.stream != nil { + pa.addReaderPost(req) + return + } + + if pa.conf.HasOnDemandStaticSource() { + if pa.onDemandStaticSourceState == pathOnDemandStateInitial { + pa.onDemandStaticSourceStart(req.AccessRequest.Query) + } + pa.readerAddRequestsOnHold = append(pa.readerAddRequestsOnHold, req) + return + } + + if pa.conf.HasOnDemandPublisher() { + if pa.onDemandPublisherState == pathOnDemandStateInitial { + pa.onDemandPublisherStart(req.AccessRequest.Query) + } + pa.readerAddRequestsOnHold = append(pa.readerAddRequestsOnHold, req) + return + } + + req.Res <- defs.PathAddReaderRes{Err: &defs.PathNoStreamAvailableError{PathName: pa.name}} +} + +func (pa *path) doRemoveReader(req defs.PathRemoveReaderReq) { + if _, ok := pa.readers[req.Author]; ok { + pa.executeRemoveReader(req.Author) + } + close(req.Res) + + if len(pa.readers) == 0 { + if pa.conf.HasOnDemandStaticSource() { + if pa.onDemandStaticSourceState == pathOnDemandStateReady { + pa.onDemandStaticSourceScheduleClose() + } + } else if pa.conf.HasOnDemandPublisher() { + if pa.onDemandPublisherState == pathOnDemandStateReady { + pa.onDemandPublisherScheduleClose() + } + } + } +} + +func (pa *path) doAPIPathsGet(req pathAPIPathsGetReq) { + var outDesc *description.Session + if pa.isAvailable() { + outDesc = pa.stream.OutDescCopy() + } + + req.res <- pathAPIPathsGetRes{ + data: &defs.APIPath{ + Name: pa.name, + ConfName: pa.conf.Name, + Ready: pa.isAvailable(), + ReadyTime: func() *time.Time { + if !pa.isAvailable() { + return nil + } + v := pa.availableTime + return &v + }(), + Available: pa.isAvailable(), + AvailableTime: func() *time.Time { + if !pa.isAvailable() { + return nil + } + v := pa.availableTime + return &v + }(), + Online: pa.isOnline(), + OnlineTime: func() *time.Time { + if !pa.isOnline() { + return nil + } + v := pa.onlineTime + return &v + }(), + Source: func() *defs.APIPathSource { + if pa.source == nil { + return nil + } + v := pa.source.APISourceDescribe() + return v + }(), + Tracks: func() []defs.APIPathTrackCodec { + if !pa.isAvailable() { + return []defs.APIPathTrackCodec{} + } + return formatlabel.MediasToLabels(outDesc.Medias) + }(), + Tracks2: func() []defs.APIPathTrack { + if !pa.isAvailable() { + return []defs.APIPathTrack{} + } + return defs.MediasToTracks(outDesc.Medias) + }(), + InboundBytes: func() uint64 { + if !pa.isAvailable() { + return 0 + } + return pa.stream.InboundBytes() + }(), + OutboundBytes: func() uint64 { + if !pa.isAvailable() { + return 0 + } + return pa.stream.OutboundBytes() + }(), + InboundFramesInError: func() uint64 { + if !pa.isAvailable() { + return 0 + } + return pa.stream.InboundFramesInError() + }(), + BytesReceived: func() uint64 { + if !pa.isAvailable() { + return 0 + } + return pa.stream.InboundBytes() + }(), + BytesSent: func() uint64 { + if !pa.isAvailable() { + return 0 + } + return pa.stream.OutboundBytes() + }(), + Readers: func() []defs.APIPathReader { + ret := make([]defs.APIPathReader, 0, len(pa.readers)) + + for r := range pa.readers { + desc := *r.APIReaderDescribe() + if desc.Type != defs.APIPathReaderTypeHidden { + ret = append(ret, desc) + } + } + + sort.Slice(ret, func(i, j int) bool { + if ret[i].Type != ret[j].Type { + return ret[i].Type < ret[j].Type + } + return ret[i].ID < ret[j].ID + }) + + return ret + }(), + }, + } +} + +func (pa *path) SafeConf() *conf.Path { + pa.confMutex.RLock() + defer pa.confMutex.RUnlock() + return pa.conf +} + +func (pa *path) ExternalCmdEnv() externalcmd.Environment { + _, port, _ := net.SplitHostPort(pa.rtspAddress) + env := externalcmd.Environment{ + "MTX_PATH": pa.name, + "RTSP_PATH": pa.name, // deprecated + "RTSP_PORT": port, + } + + if len(pa.matches) > 1 { + for i, ma := range pa.matches[1:] { + env["G"+strconv.FormatInt(int64(i+1), 10)] = ma + } + } + + return env +} + +func (pa *path) shouldClose() bool { + return pa.conf.Regexp != nil && + pa.source == nil && + len(pa.readers) == 0 && + len(pa.describeRequestsOnHold) == 0 && + len(pa.readerAddRequestsOnHold) == 0 +} + +func (pa *path) onDemandStaticSourceStart(query string) { + pa.source.(*staticsources.Handler).Start(true, query) + + pa.onDemandStaticSourceReadyTimer.Stop() + pa.onDemandStaticSourceReadyTimer = time.NewTimer(time.Duration(pa.conf.SourceOnDemandStartTimeout)) + + pa.onDemandStaticSourceState = pathOnDemandStateWaitingReady +} + +func (pa *path) onDemandStaticSourceScheduleClose() { + pa.onDemandStaticSourceCloseTimer.Stop() + pa.onDemandStaticSourceCloseTimer = time.NewTimer(time.Duration(pa.conf.SourceOnDemandCloseAfter)) + + pa.onDemandStaticSourceState = pathOnDemandStateClosing +} + +func (pa *path) onDemandStaticSourceStop(reason string) { + if pa.onDemandStaticSourceState == pathOnDemandStateClosing { + pa.onDemandStaticSourceCloseTimer.Stop() + pa.onDemandStaticSourceCloseTimer = emptyTimer() + } + + pa.onDemandStaticSourceState = pathOnDemandStateInitial + + pa.source.(*staticsources.Handler).Stop(reason) +} + +func (pa *path) onDemandPublisherStart(query string) { + pa.onUnDemandHook = hooks.OnDemand(hooks.OnDemandParams{ + Logger: pa, + ExternalCmdPool: pa.externalCmdPool, + Conf: pa.conf, + ExternalCmdEnv: pa.ExternalCmdEnv(), + Query: query, + }) + + pa.onDemandPublisherReadyTimer.Stop() + pa.onDemandPublisherReadyTimer = time.NewTimer(time.Duration(pa.conf.RunOnDemandStartTimeout)) + + pa.onDemandPublisherState = pathOnDemandStateWaitingReady +} + +func (pa *path) onDemandPublisherScheduleClose() { + pa.onDemandPublisherCloseTimer.Stop() + pa.onDemandPublisherCloseTimer = time.NewTimer(time.Duration(pa.conf.RunOnDemandCloseAfter)) + + pa.onDemandPublisherState = pathOnDemandStateClosing +} + +func (pa *path) onDemandPublisherStop(reason string) { + if pa.onDemandPublisherState == pathOnDemandStateClosing { + pa.onDemandPublisherCloseTimer.Stop() + pa.onDemandPublisherCloseTimer = emptyTimer() + } + + pa.onUnDemandHook(reason) + pa.onUnDemandHook = nil + + pa.onDemandPublisherState = pathOnDemandStateInitial +} + +func (pa *path) setAvailable( + source defs.Source, + publisherQuery string, + desc *description.Session, + replaceNTP bool, +) error { + pa.stream = &stream.Stream{ + OrigDesc: desc, + AlwaysAvailable: pa.conf.AlwaysAvailable, + AlwaysAvailableTracks: pa.conf.AlwaysAvailableTracks, + AlwaysAvailableFile: pa.conf.AlwaysAvailableFile, + WriteQueueSize: pa.writeQueueSize, + RTPMaxPayloadSize: pa.rtpMaxPayloadSize, + ReplaceNTP: replaceNTP, + Parent: pa, + } + err := pa.stream.Initialize() + if err != nil { + return err + } + + pa.availableTime = time.Now() + + if !pa.conf.AlwaysAvailable { + pa.onlineTime = time.Now() + } + + if pa.conf.Record { + pa.startRecording() + } + + var sourceDesc *defs.APIPathSource + if source != nil { + sourceDesc = source.APISourceDescribe() + } + + pa.onNotReadyHook = hooks.OnReady(hooks.OnReadyParams{ + Logger: pa, + ExternalCmdPool: pa.externalCmdPool, + Conf: pa.conf, + ExternalCmdEnv: pa.ExternalCmdEnv(), + Desc: sourceDesc, + Query: publisherQuery, + }) + + if pa.conf.AlwaysAvailable { + pa.Log(logger.Info, "stream is available, %s", defs.MediasInfo(pa.stream.OrigDesc.Medias)) + } else { + pa.Log(logger.Info, "stream is available and online, %s", defs.MediasInfo(pa.stream.OrigDesc.Medias)) + } + + pa.parent.setPathReady(pa) + + return nil +} + +func (pa *path) consumeOnHoldRequests() { + for _, req := range pa.describeRequestsOnHold { + req.Res <- defs.PathDescribeRes{ + Stream: pa.stream, + } + } + pa.describeRequestsOnHold = nil + + for _, req := range pa.readerAddRequestsOnHold { + pa.addReaderPost(req) + } + pa.readerAddRequestsOnHold = nil +} + +func (pa *path) setNotAvailable() { + pa.parent.setPathNotReady(pa) + + for r := range pa.readers { + pa.executeRemoveReader(r) + r.Close() + } + + pa.onNotReadyHook() + + if pa.recorder != nil { + pa.recorder.Close() + pa.recorder = nil + } + + if pa.stream != nil { + pa.stream.Close() + pa.stream = nil + } +} + +func (pa *path) startRecording() { + pa.recorder = &recorder.Recorder{ + PathFormat: pa.conf.RecordPath, + Format: pa.conf.RecordFormat, + PartDuration: time.Duration(pa.conf.RecordPartDuration), + MaxPartSize: pa.conf.RecordMaxPartSize, + SegmentDuration: time.Duration(pa.conf.RecordSegmentDuration), + PathName: pa.name, + Stream: pa.stream, + OnSegmentCreate: func(segmentPath string) { + if pa.conf.RunOnRecordSegmentCreate != "" { + env := pa.ExternalCmdEnv() + env["MTX_SEGMENT_PATH"] = segmentPath + + pa.Log(logger.Info, "runOnRecordSegmentCreate command launched") + cmd := &externalcmd.Cmd{ + Pool: pa.externalCmdPool, + Cmdstr: pa.conf.RunOnRecordSegmentCreate, + Restart: false, + Env: env, + } + cmd.Start() + } + }, + OnSegmentComplete: func(segmentPath string, segmentDuration time.Duration) { + if pa.conf.RunOnRecordSegmentComplete != "" { + env := pa.ExternalCmdEnv() + env["MTX_SEGMENT_PATH"] = segmentPath + env["MTX_SEGMENT_DURATION"] = strconv.FormatFloat(segmentDuration.Seconds(), 'f', -1, 64) + + pa.Log(logger.Info, "runOnRecordSegmentComplete command launched") + cmd := &externalcmd.Cmd{ + Pool: pa.externalCmdPool, + Cmdstr: pa.conf.RunOnRecordSegmentComplete, + Restart: false, + Env: env, + } + cmd.Start() + } + }, + Parent: pa, + } + pa.recorder.Initialize() +} + +func (pa *path) executeRemoveReader(r defs.Reader) { + delete(pa.readers, r) +} + +func (pa *path) executeRemovePublisher() { + if !pa.conf.AlwaysAvailable { + pa.setNotAvailable() + } else { + err := pa.stream.StartOfflineSubStream() + if err != nil { + panic("should not happen") + } + } + pa.source = nil +} + +func (pa *path) addReaderPost(req defs.PathAddReaderReq) { + if _, ok := pa.readers[req.Author]; ok { + req.Res <- defs.PathAddReaderRes{Stream: pa.stream} + return + } + + if pa.conf.MaxReaders != 0 && len(pa.readers) >= pa.conf.MaxReaders { + req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("maximum reader count reached")} + return + } + + pa.readers[req.Author] = struct{}{} + + if pa.conf.HasOnDemandStaticSource() { + if pa.onDemandStaticSourceState == pathOnDemandStateClosing { + pa.onDemandStaticSourceState = pathOnDemandStateReady + pa.onDemandStaticSourceCloseTimer.Stop() + pa.onDemandStaticSourceCloseTimer = emptyTimer() + } + } else if pa.conf.HasOnDemandPublisher() { + if pa.onDemandPublisherState == pathOnDemandStateClosing { + pa.onDemandPublisherState = pathOnDemandStateReady + pa.onDemandPublisherCloseTimer.Stop() + pa.onDemandPublisherCloseTimer = emptyTimer() + } + } + + req.Res <- defs.PathAddReaderRes{Stream: pa.stream} +} + +// reloadConf is called by pathManager. +func (pa *path) reloadConf(newConf *conf.Path) { + select { + case pa.chReloadConf <- newConf: + case <-pa.ctx.Done(): + } +} + +// StaticSourceHandlerSetReady is called by staticsources.Handler. +func (pa *path) StaticSourceHandlerSetReady( + ctx context.Context, req defs.PathSourceStaticSetReadyReq, +) { + select { + case pa.chStaticSourceSetReady <- req: + + case <-pa.ctx.Done(): + req.Res <- defs.PathSourceStaticSetReadyRes{Err: fmt.Errorf("terminated")} + + // this avoids: + // - invalid requests sent after the source has been terminated + // - deadlocks caused by <-done inside stop() + case <-ctx.Done(): + req.Res <- defs.PathSourceStaticSetReadyRes{Err: fmt.Errorf("terminated")} + } +} + +// StaticSourceHandlerSetNotReady is called by staticsources.Handler. +func (pa *path) StaticSourceHandlerSetNotReady( + ctx context.Context, req defs.PathSourceStaticSetNotReadyReq, +) { + select { + case pa.chStaticSourceSetNotReady <- req: + + case <-pa.ctx.Done(): + close(req.Res) + + // this avoids: + // - invalid requests sent after the source has been terminated + // - deadlocks caused by <-done inside stop() + case <-ctx.Done(): + close(req.Res) + } +} + +// describe is called by a reader or publisher through pathManager. +func (pa *path) describe(req defs.PathDescribeReq) (*defs.PathDescribeRes, error) { + select { + case pa.chDescribe <- req: + res := <-req.Res + return &res, res.Err + + case <-pa.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// addPublisher is called by a publisher through pathManager. +func (pa *path) addPublisher(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) { + select { + case pa.chAddPublisher <- req: + res := <-req.Res + return &res, res.Err + case <-pa.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// RemovePublisher is called by a publisher. +func (pa *path) RemovePublisher(req defs.PathRemovePublisherReq) { + req.Res = make(chan struct{}) + select { + case pa.chRemovePublisher <- req: + <-req.Res + case <-pa.ctx.Done(): + } +} + +// addReader is called by a reader through pathManager. +func (pa *path) addReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + select { + case pa.chAddReader <- req: + res := <-req.Res + return &res, res.Err + case <-pa.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// RemoveReader is called by a reader. +func (pa *path) RemoveReader(req defs.PathRemoveReaderReq) { + req.Res = make(chan struct{}) + select { + case pa.chRemoveReader <- req: + <-req.Res + case <-pa.ctx.Done(): + } +} + +// APIPathsGet implements defs.APIPathManager. +func (pa *path) APIPathsGet(req pathAPIPathsGetReq) (*defs.APIPath, error) { + req.res = make(chan pathAPIPathsGetRes) + select { + case pa.chAPIPathsGet <- req: + res := <-req.res + return res.data, res.err + + case <-pa.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager.go new file mode 100644 index 0000000000000000000000000000000000000000..fcd13b1ba970c7b4b400f158f7916d7690ad386f --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager.go @@ -0,0 +1,690 @@ +package core + +import ( + "context" + "fmt" + "maps" + "sort" + "sync" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/metrics" + "github.com/bluenviron/mediamtx/internal/servers/hls" +) + +func pathConfCanBeUpdated(oldPathConf *conf.Path, newPathConf *conf.Path) bool { + clone := oldPathConf.Clone() + + clone.Name = newPathConf.Name + clone.Regexp = newPathConf.Regexp + + clone.Record = newPathConf.Record + clone.RecordPath = newPathConf.RecordPath + clone.RecordFormat = newPathConf.RecordFormat + clone.RecordPartDuration = newPathConf.RecordPartDuration + clone.RecordMaxPartSize = newPathConf.RecordMaxPartSize + clone.RecordSegmentDuration = newPathConf.RecordSegmentDuration + clone.RecordDeleteAfter = newPathConf.RecordDeleteAfter + + clone.RPICameraBrightness = newPathConf.RPICameraBrightness + clone.RPICameraContrast = newPathConf.RPICameraContrast + clone.RPICameraSaturation = newPathConf.RPICameraSaturation + clone.RPICameraSharpness = newPathConf.RPICameraSharpness + clone.RPICameraExposure = newPathConf.RPICameraExposure + clone.RPICameraFlickerPeriod = newPathConf.RPICameraFlickerPeriod + clone.RPICameraAWB = newPathConf.RPICameraAWB + clone.RPICameraAWBGains = newPathConf.RPICameraAWBGains + clone.RPICameraDenoise = newPathConf.RPICameraDenoise + clone.RPICameraShutter = newPathConf.RPICameraShutter + clone.RPICameraMetering = newPathConf.RPICameraMetering + clone.RPICameraGain = newPathConf.RPICameraGain + clone.RPICameraEV = newPathConf.RPICameraEV + clone.RPICameraFPS = newPathConf.RPICameraFPS + clone.RPICameraTextOverlayEnable = newPathConf.RPICameraTextOverlayEnable + clone.RPICameraTextOverlay = newPathConf.RPICameraTextOverlay + clone.RPICameraIDRPeriod = newPathConf.RPICameraIDRPeriod + clone.RPICameraBitrate = newPathConf.RPICameraBitrate + + return newPathConf.Equal(clone) +} + +type pathSetHLSServerRes struct { + readyPaths []defs.Path +} + +type pathSetHLSServerReq struct { + s *hls.Server + res chan pathSetHLSServerRes +} + +type pathManagerAuthManager interface { + Authenticate(req *auth.Request) (string, *auth.Error) +} + +type pathManagerParent interface { + logger.Writer +} + +type pathManager struct { + logLevel conf.LogLevel + rtspAddress string + dumpPackets bool + readTimeout conf.Duration + writeTimeout conf.Duration + writeQueueSize int + udpReadBufferSize uint + rtpMaxPayloadSize int + pathConfs map[string]*conf.Path + authManager pathManagerAuthManager + externalCmdPool *externalcmd.Pool + metrics *metrics.Metrics + parent pathManagerParent + + ctx context.Context + ctxCancel func() + wg sync.WaitGroup + hlsServer *hls.Server + paths map[string]*path + + // in + chReloadConf chan map[string]*conf.Path + chSetHLSServer chan pathSetHLSServerReq + chRemovePath chan *path + chClosePathIfIdle chan *path + chSetPathReady chan *path + chSetPathNotReady chan *path + chFindPathConf chan defs.PathFindPathConfReq + chDescribe chan defs.PathDescribeReq + chAddReader chan defs.PathAddReaderReq + chAddPublisher chan defs.PathAddPublisherReq + chAPIPathsList chan pathAPIPathsListReq + chAPIPathsGet chan pathAPIPathsGetReq +} + +func (pm *pathManager) initialize() { + ctx, ctxCancel := context.WithCancel(context.Background()) + + pm.ctx = ctx + pm.ctxCancel = ctxCancel + pm.paths = make(map[string]*path) + pm.chReloadConf = make(chan map[string]*conf.Path) + pm.chSetHLSServer = make(chan pathSetHLSServerReq) + pm.chRemovePath = make(chan *path) + pm.chClosePathIfIdle = make(chan *path) + pm.chSetPathReady = make(chan *path) + pm.chSetPathNotReady = make(chan *path) + pm.chFindPathConf = make(chan defs.PathFindPathConfReq) + pm.chDescribe = make(chan defs.PathDescribeReq) + pm.chAddReader = make(chan defs.PathAddReaderReq) + pm.chAddPublisher = make(chan defs.PathAddPublisherReq) + pm.chAPIPathsList = make(chan pathAPIPathsListReq) + pm.chAPIPathsGet = make(chan pathAPIPathsGetReq) + + for _, pathConf := range pm.pathConfs { + if pathConf.Regexp == nil { + pm.createPath(pathConf, pathConf.Name, nil) + } + } + + pm.Log(logger.Debug, "path manager created") + + pm.wg.Add(1) + go pm.run() + + if pm.metrics != nil { + pm.metrics.SetPathManager(pm) + } +} + +func (pm *pathManager) close() { + pm.Log(logger.Debug, "path manager is shutting down") + + if pm.metrics != nil { + pm.metrics.SetPathManager(nil) + } + + pm.ctxCancel() + pm.wg.Wait() +} + +// Log implements logger.Writer. +func (pm *pathManager) Log(level logger.Level, format string, args ...any) { + pm.parent.Log(level, format, args...) +} + +func (pm *pathManager) run() { + defer pm.wg.Done() + +outer: + for { + select { + case newPaths := <-pm.chReloadConf: + pm.doReloadConf(newPaths) + + case req := <-pm.chSetHLSServer: + readyPaths := pm.doSetHLSServer(req.s) + req.res <- pathSetHLSServerRes{readyPaths: readyPaths} + + case pa := <-pm.chRemovePath: + if pa2, ok := pm.paths[pa.name]; ok && pa2 == pa { + delete(pm.paths, pa.name) + } + + case pa := <-pm.chClosePathIfIdle: + if pa.pendingRequests.Load() == 0 { + pm.doClosePath(pa) + } + + case pa := <-pm.chSetPathReady: + pm.doSetPathReady(pa) + + case pa := <-pm.chSetPathNotReady: + pm.doSetPathNotReady(pa) + + case req := <-pm.chFindPathConf: + pm.doFindPathConf(req) + + case req := <-pm.chDescribe: + pm.doDescribe(req) + + case req := <-pm.chAddReader: + pm.doAddReader(req) + + case req := <-pm.chAddPublisher: + pm.doAddPublisher(req) + + case req := <-pm.chAPIPathsList: + pm.doAPIPathsList(req) + + case req := <-pm.chAPIPathsGet: + pm.doAPIPathsGet(req) + + case <-pm.ctx.Done(): + break outer + } + } + + pm.ctxCancel() +} + +func (pm *pathManager) doReloadConf(newPaths map[string]*conf.Path) { + confsToRecreate := make(map[string]struct{}) + confsToReload := make(map[string]struct{}) + + for confName, pathConf := range pm.pathConfs { + if newPath, ok := newPaths[confName]; ok { + if !newPath.Equal(pathConf) { + if pathConfCanBeUpdated(pathConf, newPath) { + confsToReload[confName] = struct{}{} + } else { + confsToRecreate[confName] = struct{}{} + } + } + } + } + + // process existing paths + for pathName, pa := range pm.paths { + newPathConf, _, err := conf.FindPathConf(newPaths, pathName) + // path does not have a config anymore: delete it + if err != nil { + pm.doClosePath(pa) + continue + } + + // path now belongs to a different config + if newPathConf.Name != pa.confName { + // path config can be hot reloaded + oldPathConf := pm.pathConfs[pa.confName] + if pathConfCanBeUpdated(oldPathConf, newPathConf) { + pa.confName = newPathConf.Name + go pa.reloadConf(newPathConf) + continue + } + + // Configuration cannot be hot reloaded: delete the path + pm.doClosePath(pa) + continue + } + + // path configuration has changed and cannot be hot reloaded: delete path + if _, ok := confsToRecreate[newPathConf.Name]; ok { + pm.doClosePath(pa) + continue + } + + // path configuration has changed but can be hot reloaded: reload it + if _, ok := confsToReload[newPathConf.Name]; ok { + go pa.reloadConf(newPathConf) + } + } + + pm.pathConfs = newPaths + + // create new static paths + for pathConfName, pathConf := range newPaths { + if pathConf.Regexp == nil { + if _, ok := pm.paths[pathConfName]; !ok { + pm.createPath(pathConf, pathConfName, nil) + } + } + } +} + +func (pm *pathManager) doClosePath(pa *path) { + delete(pm.paths, pa.name) + pa.close() + pa.wait() // avoid conflicts between sources +} + +func (pm *pathManager) doSetHLSServer(m *hls.Server) []defs.Path { + pm.hlsServer = m + + var ret []defs.Path + + for _, pa := range pm.paths { + if pa.ready { + ret = append(ret, pa) + } + } + + return ret +} + +func (pm *pathManager) doSetPathReady(pa *path) { + if pa2, ok := pm.paths[pa.name]; !ok || pa2 != pa { + return + } + + pm.paths[pa.name].ready = true + + if pm.hlsServer != nil { + pm.hlsServer.PathReady(pa) + } +} + +func (pm *pathManager) doSetPathNotReady(pa *path) { + if pa2, ok := pm.paths[pa.name]; !ok || pa2 != pa { + return + } + + pm.paths[pa.name].ready = false + + if pm.hlsServer != nil { + pm.hlsServer.PathNotReady(pa) + } +} + +func (pm *pathManager) doFindPathConf(req defs.PathFindPathConfReq) { + pathConf, _, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name) + if err != nil { + req.Res <- defs.PathFindPathConfRes{Err: err} + return + } + + user, err2 := pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest()) + if err2 != nil { + req.Res <- defs.PathFindPathConfRes{Err: err2} + return + } + + req.Res <- defs.PathFindPathConfRes{ + Conf: pathConf, + User: user, + } +} + +func (pm *pathManager) doDescribe(req defs.PathDescribeReq) { + pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name) + if err != nil { + req.Res <- defs.PathDescribeRes{Err: err} + return + } + + if !req.AccessRequest.SkipAuth { + _, err2 := pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest()) + if err2 != nil { + req.Res <- defs.PathDescribeRes{Err: err2} + return + } + } + + // create path if it doesn't exist + if _, ok := pm.paths[req.AccessRequest.Name]; !ok { + pm.createPath(pathConf, req.AccessRequest.Name, pathMatches) + } + + pa := pm.paths[req.AccessRequest.Name] + + pa.pendingRequests.Add(1) + + req.Res <- defs.PathDescribeRes{Path: pa} +} + +func (pm *pathManager) doAddReader(req defs.PathAddReaderReq) { + pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name) + if err != nil { + req.Res <- defs.PathAddReaderRes{Err: err} + return + } + + var user string + + if !req.AccessRequest.SkipAuth { + var authErr *auth.Error + user, authErr = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest()) + if authErr != nil { + req.Res <- defs.PathAddReaderRes{Err: authErr} + return + } + } + + // create path if it doesn't exist + if _, ok := pm.paths[req.AccessRequest.Name]; !ok { + pm.createPath(pathConf, req.AccessRequest.Name, pathMatches) + } + + pa := pm.paths[req.AccessRequest.Name] + + pa.pendingRequests.Add(1) + + req.Res <- defs.PathAddReaderRes{ + Path: pa, + User: user, + } +} + +func (pm *pathManager) doAddPublisher(req defs.PathAddPublisherReq) { + pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name) + if err != nil { + req.Res <- defs.PathAddPublisherRes{Err: err} + return + } + + if req.ConfToCompare != nil && !pathConf.Equal(req.ConfToCompare) { + req.Res <- defs.PathAddPublisherRes{Err: fmt.Errorf("configuration has changed")} + return + } + + var user string + + if !req.AccessRequest.SkipAuth { + var authErr *auth.Error + user, authErr = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest()) + if authErr != nil { + req.Res <- defs.PathAddPublisherRes{Err: authErr} + return + } + } + + // create path if it doesn't exist + if _, ok := pm.paths[req.AccessRequest.Name]; !ok { + pm.createPath(pathConf, req.AccessRequest.Name, pathMatches) + } + + pa := pm.paths[req.AccessRequest.Name] + + pa.pendingRequests.Add(1) + + req.Res <- defs.PathAddPublisherRes{ + Path: pa, + User: user, + } +} + +func (pm *pathManager) doAPIPathsList(req pathAPIPathsListReq) { + paths := make(map[string]*path) + maps.Copy(paths, pm.paths) + + req.res <- pathAPIPathsListRes{paths: paths} +} + +func (pm *pathManager) doAPIPathsGet(req pathAPIPathsGetReq) { + pa, ok := pm.paths[req.name] + if !ok { + req.res <- pathAPIPathsGetRes{err: conf.ErrPathNotFound} + return + } + + req.res <- pathAPIPathsGetRes{path: pa} +} + +func (pm *pathManager) createPath( + pathConf *conf.Path, + name string, + matches []string, +) { + pa := &path{ + parentCtx: pm.ctx, + logLevel: pm.logLevel, + dumpPackets: pm.dumpPackets, + rtspAddress: pm.rtspAddress, + readTimeout: pm.readTimeout, + writeTimeout: pm.writeTimeout, + writeQueueSize: pm.writeQueueSize, + udpReadBufferSize: pm.udpReadBufferSize, + rtpMaxPayloadSize: pm.rtpMaxPayloadSize, + conf: pathConf, + name: name, + matches: matches, + wg: &pm.wg, + externalCmdPool: pm.externalCmdPool, + parent: pm, + } + pa.initialize() + pm.paths[name] = pa +} + +// ReloadPathConfs is called by core. +func (pm *pathManager) ReloadPathConfs(pathConfs map[string]*conf.Path) { + select { + case pm.chReloadConf <- pathConfs: + case <-pm.ctx.Done(): + } +} + +// setPathReady is called by path. +func (pm *pathManager) setPathReady(pa *path) { + select { + case pm.chSetPathReady <- pa: + case <-pm.ctx.Done(): + case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait() + } +} + +// setPathNotReady is called by path. +func (pm *pathManager) setPathNotReady(pa *path) { + select { + case pm.chSetPathNotReady <- pa: + case <-pm.ctx.Done(): + case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait() + } +} + +// removePath is called by path. +func (pm *pathManager) removePath(pa *path) { + select { + case pm.chRemovePath <- pa: + case <-pm.ctx.Done(): + case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait() + } +} + +// closePath is called by path. +func (pm *pathManager) closePathIfIdle(pa *path) { + select { + case pm.chClosePathIfIdle <- pa: + case <-pm.ctx.Done(): + case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait() + } +} + +// FindPathConf is called by a reader or publisher. +func (pm *pathManager) FindPathConf(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) { + req.Res = make(chan defs.PathFindPathConfRes) + select { + case pm.chFindPathConf <- req: + res := <-req.Res + + if res.Err != nil { + auth.DelayBruteForce(res.Err) + return nil, res.Err + } + + return &res, nil + + case <-pm.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// Describe is called by a reader or publisher. +func (pm *pathManager) Describe(req defs.PathDescribeReq) (*defs.PathDescribeRes, error) { + req.Res = make(chan defs.PathDescribeRes) + select { + case pm.chDescribe <- req: + res1 := <-req.Res + if res1.Err != nil { + auth.DelayBruteForce(res1.Err) + return nil, res1.Err + } + + res2, err := res1.Path.(*path).describe(req) + if err != nil { + return nil, err + } + + res2.Path = res1.Path + return res2, nil + + case <-pm.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// AddPublisher is called by a publisher. +func (pm *pathManager) AddPublisher(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) { + req.Res = make(chan defs.PathAddPublisherRes) + select { + case pm.chAddPublisher <- req: + res1 := <-req.Res + if res1.Err != nil { + auth.DelayBruteForce(res1.Err) + return nil, res1.Err + } + + res2, err := res1.Path.(*path).addPublisher(req) + if err != nil { + return nil, err + } + + res2.Path = res1.Path + res2.User = res1.User + + return res2, nil + + case <-pm.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// AddReader is called by a reader. +func (pm *pathManager) AddReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + req.Res = make(chan defs.PathAddReaderRes) + select { + case pm.chAddReader <- req: + res1 := <-req.Res + if res1.Err != nil { + auth.DelayBruteForce(res1.Err) + return nil, res1.Err + } + + res2, err := res1.Path.(*path).addReader(req) + if err != nil { + return nil, err + } + + res2.Path = res1.Path + res2.User = res1.User + + return res2, nil + + case <-pm.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// SetHLSServer is called by hls.Server. +func (pm *pathManager) SetHLSServer(s *hls.Server) []defs.Path { + req := pathSetHLSServerReq{ + s: s, + res: make(chan pathSetHLSServerRes), + } + + select { + case pm.chSetHLSServer <- req: + res := <-req.res + return res.readyPaths + + case <-pm.ctx.Done(): + return nil + } +} + +// APIPathsList implements defs.APIPathManager. +func (pm *pathManager) APIPathsList() (*defs.APIPathList, error) { + req := pathAPIPathsListReq{ + res: make(chan pathAPIPathsListRes), + } + + select { + case pm.chAPIPathsList <- req: + res := <-req.res + + res.data = &defs.APIPathList{ + Items: []defs.APIPath{}, + } + + for _, pa := range res.paths { + item, err := pa.APIPathsGet(pathAPIPathsGetReq{}) + if err == nil { + res.data.Items = append(res.data.Items, *item) + } + } + + sort.Slice(res.data.Items, func(i, j int) bool { + return res.data.Items[i].Name < res.data.Items[j].Name + }) + + return res.data, nil + + case <-pm.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// APIPathsGet implements defs.APIPathManager. +func (pm *pathManager) APIPathsGet(name string) (*defs.APIPath, error) { + req := pathAPIPathsGetReq{ + name: name, + res: make(chan pathAPIPathsGetRes), + } + + select { + case pm.chAPIPathsGet <- req: + res := <-req.res + if res.err != nil { + return nil, res.err + } + + data, err := res.path.APIPathsGet(req) + return data, err + + case <-pm.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager_test.go new file mode 100644 index 0000000000000000000000000000000000000000..31a82c2dc04ce08c811c6b0485ab4840d2e6b6af --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager_test.go @@ -0,0 +1,217 @@ +package core + +import ( + "net/http" + "regexp" + "testing" + "time" + + "github.com/bluenviron/gortsplib/v5" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/pion/rtp" + "github.com/stretchr/testify/require" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/test" +) + +type dummyPublisher struct{} + +func (d *dummyPublisher) Close() {} + +func (d *dummyPublisher) Log(_ logger.Level, _ string, _ ...any) {} + +func (d *dummyPublisher) APISourceDescribe() *defs.APIPathSource { + return nil +} + +type dummyReader struct{} + +func (d *dummyReader) Close() {} + +func (d *dummyReader) Log(_ logger.Level, _ string, _ ...any) {} + +func (d *dummyReader) APIReaderDescribe() *defs.APIPathReader { + return nil +} + +func TestPathManagerDynamicPathAutoDeletion(t *testing.T) { + for _, ca := range []string{"describe", "add reader"} { + t.Run(ca, func(t *testing.T) { + pathConfs := map[string]*conf.Path{ + "all_others": { + Regexp: regexp.MustCompile("^.*$"), + Name: "all_others", + Source: "publisher", + }, + } + + pm := &pathManager{ + authManager: test.NilAuthManager, + pathConfs: pathConfs, + parent: test.NilLogger, + } + pm.initialize() + defer pm.close() + + func() { + if ca == "describe" { + _, err := pm.Describe(defs.PathDescribeReq{ + AccessRequest: defs.PathAccessRequest{ + Name: "mypath", + }, + }) + require.EqualError(t, err, "no stream is available on path 'mypath'") + } else { + _, err := pm.AddReader(defs.PathAddReaderReq{ + Author: &dummyReader{}, + AccessRequest: defs.PathAccessRequest{ + Name: "mypath", + }, + }) + require.EqualError(t, err, "no stream is available on path 'mypath'") + } + }() + + time.Sleep(100 * time.Millisecond) + + data, err := pm.APIPathsList() + require.NoError(t, err) + + require.Empty(t, data.Items) + }) + } +} + +func TestPathManagerDynamicPathDescribeAndPublish(t *testing.T) { + pathConfs := map[string]*conf.Path{ + "all_others": { + Regexp: regexp.MustCompile("^.*$"), + Name: "all_others", + Source: "publisher", + }, + } + + pm := &pathManager{ + authManager: test.NilAuthManager, + pathConfs: pathConfs, + parent: test.NilLogger, + } + pm.initialize() + defer pm.close() + + go func() { + for range 10 { + pm.Describe(defs.PathDescribeReq{ //nolint:errcheck + AccessRequest: defs.PathAccessRequest{ + Name: "mypath", + }, + }) + } + }() + + _, err := pm.AddPublisher(defs.PathAddPublisherReq{ + Author: &dummyPublisher{}, + Desc: &description.Session{}, + AccessRequest: defs.PathAccessRequest{ + Name: "mypath", + }, + }) + require.NoError(t, err) +} + +func TestPathManagerConfigHotReload(t *testing.T) { + // Start MediaMTX with basic configuration + p, ok := newInstance(t, "api: yes\n"+ + "paths:\n"+ + " all:\n"+ + " record: no\n") + require.Equal(t, true, ok) + defer p.Close() + + // Set up HTTP client for API calls + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + // Create a publisher that will use the "all" configuration + media0 := test.UniqueMediaH264() + source := gortsplib.Client{} + err := source.StartRecording( + "rtsp://localhost:8554/undefined_stream", + &description.Session{Medias: []*description.Media{media0}}) + require.NoError(t, err) + defer source.Close() + + // Send some data to establish the stream + err = source.WritePacketRTP(media0, &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + PayloadType: 96, + }, + Payload: []byte{5, 1, 2, 3, 4}, + }) + require.NoError(t, err) + + time.Sleep(100 * time.Millisecond) + + // Verify the path exists and is using the "all" configuration + pathData, err := p.pathManager.APIPathsGet("undefined_stream") + require.NoError(t, err) + require.Equal(t, "undefined_stream", pathData.Name) + require.Equal(t, "all", pathData.ConfName) + + // Check the current configuration via API + var allConfig map[string]any + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/config/paths/get/all", nil, &allConfig) + require.Equal(t, false, allConfig["record"]) // Should be false from "all" config + + // Add a new specific configuration for "undefined_stream" with record enabled + httpRequest(t, hc, http.MethodPost, "http://localhost:9997/v3/config/paths/add/undefined_stream", + map[string]any{ + "record": true, + }, nil) + + // Give the system time to process the configuration change + time.Sleep(200 * time.Millisecond) + + // Verify the path now uses the new specific configuration + pathData, err = p.pathManager.APIPathsGet("undefined_stream") + require.NoError(t, err) + require.Equal(t, "undefined_stream", pathData.Name) + require.Equal(t, "undefined_stream", pathData.ConfName) // Should now use the specific config + + // Check the new configuration via API + var newConfig map[string]any + httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/config/paths/get/undefined_stream", nil, &newConfig) + require.Equal(t, true, newConfig["record"]) // Should be true from new config + + // Verify the stream is still active and working + err = source.WritePacketRTP(media0, &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + PayloadType: 96, + SequenceNumber: 2, + }, + Payload: []byte{5, 1, 2, 3, 4}, + }) + require.NoError(t, err) + + // Verify the path is still ready and functional + require.Equal(t, true, pathData.Ready) + + // revert configuration + httpRequest(t, hc, http.MethodDelete, "http://localhost:9997/v3/config/paths/delete/undefined_stream", + nil, nil) + + // Give the system time to process the configuration change + time.Sleep(200 * time.Millisecond) + + // Verify the path now uses the old configuration + pathData, err = p.pathManager.APIPathsGet("undefined_stream") + require.NoError(t, err) + require.Equal(t, "undefined_stream", pathData.Name) + require.Equal(t, "all", pathData.ConfName) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9d5a856ad00c38204b722e0bba933746339bf91c --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_test.go @@ -0,0 +1,1035 @@ +package core + +import ( + "bufio" + "context" + "crypto/tls" + "fmt" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/bluenviron/gortmplib" + "github.com/bluenviron/gortsplib/v5" + "github.com/bluenviron/gortsplib/v5/pkg/base" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/headers" + "github.com/bluenviron/gortsplib/v5/pkg/sdp" + srt "github.com/datarhei/gosrt" + "github.com/pion/rtp" + "github.com/stretchr/testify/require" + + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/protocols/whip" + "github.com/bluenviron/mediamtx/internal/test" +) + +type testServer struct { + onDescribe func(*gortsplib.ServerHandlerOnDescribeCtx) (*base.Response, *gortsplib.ServerStream, error) + onSetup func(*gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) + onPlay func(*gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) +} + +func (sh *testServer) OnDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx, +) (*base.Response, *gortsplib.ServerStream, error) { + return sh.onDescribe(ctx) +} + +func (sh *testServer) OnSetup(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) { + return sh.onSetup(ctx) +} + +func (sh *testServer) OnPlay(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) { + return sh.onPlay(ctx) +} + +var _ defs.Path = &path{} + +func TestPathRunOnDemand(t *testing.T) { + for _, ca := range []string{"describe", "setup", "describe and setup"} { + t.Run(ca, func(t *testing.T) { + onDemand := filepath.Join(t.TempDir(), "on_demand") + onUnDemand := filepath.Join(t.TempDir(), "on_undemand") + + p1, ok := newInstance(t, fmt.Sprintf("rtmp: no\n"+ + "hls: no\n"+ + "webrtc: no\n"+ + "paths:\n"+ + " '~^(on)demand$':\n"+ + " runOnDemand: sh -c \"ON_DEMAND=%s go run ./test_on_demand/main.go\"\n"+ + " runOnDemandCloseAfter: 1s\n"+ + " runOnUnDemand: touch %s\n", onDemand, onUnDemand)) + require.Equal(t, true, ok) + defer p1.Close() + + var control string + + func() { + conn, err := net.Dial("tcp", "localhost:8554") + require.NoError(t, err) + defer conn.Close() + br := bufio.NewReader(conn) + + if ca == "describe" || ca == "describe and setup" { + var u *base.URL + u, err = base.ParseURL("rtsp://localhost:8554/ondemand?key1=val1&key2=val2") + require.NoError(t, err) + + byts, _ := base.Request{ + Method: base.Describe, + URL: u, + Header: base.Header{ + "CSeq": base.HeaderValue{"1"}, + }, + }.Marshal() + _, err = conn.Write(byts) + require.NoError(t, err) + + var res base.Response + err = res.Unmarshal(br) + require.NoError(t, err) + require.Equal(t, base.StatusOK, res.StatusCode) + + var desc sdp.SessionDescription + err = desc.Unmarshal(res.Body) + require.NoError(t, err) + control, _ = desc.MediaDescriptions[0].Attribute("control") + control = "rtsp://localhost:8554/ondemand?key1=val1&key2=val2/" + control + } else { + control = "rtsp://localhost:8554/ondemand?key1=val1&key2=val2/" + } + + if ca == "setup" || ca == "describe and setup" { + var u *base.URL + u, err = base.ParseURL(control) + require.NoError(t, err) + + byts, _ := base.Request{ + Method: base.Setup, + URL: u, + Header: base.Header{ + "CSeq": base.HeaderValue{"2"}, + "Transport": headers.Transport{ + Mode: func() *headers.TransportMode { + v := headers.TransportModePlay + return &v + }(), + Protocol: headers.TransportProtocolTCP, + InterleavedIDs: &[2]int{0, 1}, + }.Marshal(), + }, + }.Marshal() + _, err = conn.Write(byts) + require.NoError(t, err) + + var res base.Response + err = res.Unmarshal(br) + require.NoError(t, err) + require.Equal(t, base.StatusOK, res.StatusCode) + } + }() + + for { + _, err := os.Stat(onUnDemand) + if err == nil { + break + } + time.Sleep(100 * time.Millisecond) + } + + _, err := os.Stat(onDemand) + require.NoError(t, err) + }) + } +} + +func TestPathRunOnConnect(t *testing.T) { + serverCertFpath := test.CreateTempFile(t, test.TLSCertPub) + serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey) + + for _, ca := range []string{"rtsp", "rtsps", "rtmp", "rtmps", "srt"} { + t.Run(ca, func(t *testing.T) { + onConnect := filepath.Join(t.TempDir(), "on_connect") + onDisconnect := filepath.Join(t.TempDir(), "on_disconnect") + + connType := "" + + func() { + p, ok := newInstance(t, fmt.Sprintf( + "rtspEncryption: optional\n"+ + "rtspServerCert: "+serverCertFpath+"\n"+ + "rtspServerKey: "+serverKeyFpath+"\n"+ + "rtmpEncryption: optional\n"+ + "rtmpServerCert: "+serverCertFpath+"\n"+ + "rtmpServerKey: "+serverKeyFpath+"\n"+ + "paths:\n"+ + " test:\n"+ + "runOnConnect: sh -c 'echo \"$MTX_CONN_TYPE $MTX_CONN_ID $RTSP_PORT\" > %s'\n"+ + "runOnDisconnect: sh -c 'echo \"$MTX_CONN_TYPE $MTX_CONN_ID $RTSP_PORT\" > %s'\n", + onConnect, onDisconnect)) + require.Equal(t, true, ok) + defer p.Close() + + switch ca { + case "rtsp": + connType = "rtspConn" + + c := gortsplib.Client{} + + err := c.StartRecording( + "rtsp://localhost:8554/test", + &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}}) + require.NoError(t, err) + defer c.Close() + + case "rtsps": + connType = "rtspsConn" + + c := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}} + + err := c.StartRecording( + "rtsps://localhost:8322/test", + &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}}) + require.NoError(t, err) + defer c.Close() + + case "rtmp": + connType = "rtmpConn" + + var u *url.URL + u, err := url.Parse("rtmp://127.0.0.1:1935/test") + require.NoError(t, err) + + conn := &gortmplib.Client{ + URL: u, + Publish: true, + } + err = conn.Initialize(context.Background()) + require.NoError(t, err) + defer conn.Close() + + case "rtmps": + connType = "rtmpsConn" + + var u *url.URL + u, err := url.Parse("rtmps://127.0.0.1:1936/test") + require.NoError(t, err) + + conn := &gortmplib.Client{ + URL: u, + Publish: true, + TLSConfig: &tls.Config{InsecureSkipVerify: true}, + } + err = conn.Initialize(context.Background()) + require.NoError(t, err) + defer conn.Close() + + case "srt": + connType = "srtConn" + + conf := srt.DefaultConfig() + var address string + address, err := conf.UnmarshalURL("srt://localhost:8890?streamid=publish:test") + require.NoError(t, err) + + err = conf.Validate() + require.NoError(t, err) + + var c srt.Conn + c, err = srt.Dial("srt", address, conf) + require.NoError(t, err) + defer c.Close() + } + + time.Sleep(500 * time.Millisecond) + }() + + var byts []byte + byts, err := os.ReadFile(onConnect) + require.NoError(t, err) + fields := strings.Split(string(byts[:len(byts)-1]), " ") + require.Equal(t, connType, fields[0]) + require.NotEmpty(t, fields[1]) + require.Equal(t, "8554", fields[2]) + + byts, err = os.ReadFile(onDisconnect) + require.NoError(t, err) + fields = strings.Split(string(byts[:len(byts)-1]), " ") + require.Equal(t, connType, fields[0]) + require.NotEmpty(t, fields[1]) + require.Equal(t, "8554", fields[2]) + }) + } +} + +func TestPathRunOnReady(t *testing.T) { + onReady := filepath.Join(t.TempDir(), "on_ready") + onNotReady := filepath.Join(t.TempDir(), "on_unready") + + func() { + p, ok := newInstance(t, fmt.Sprintf("rtmp: no\n"+ + "hls: no\n"+ + "webrtc: no\n"+ + "paths:\n"+ + " ~te(st):\n"+ + " runOnReady: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_SOURCE_TYPE $MTX_SOURCE_ID $RTSP_PORT $G1\" > %s'\n"+ + " runOnNotReady: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_SOURCE_TYPE $MTX_SOURCE_ID $RTSP_PORT $G1\" > %s'\n", + onReady, onNotReady)) + require.Equal(t, true, ok) + defer p.Close() + + c := gortsplib.Client{} + + err := c.StartRecording( + "rtsp://localhost:8554/test?query=value", + &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}}) + require.NoError(t, err) + defer c.Close() + + time.Sleep(500 * time.Millisecond) + }() + + byts, err := os.ReadFile(onReady) + require.NoError(t, err) + fields := strings.Split(string(byts[:len(byts)-1]), " ") + require.Equal(t, "test", fields[0]) + require.Equal(t, "query%3Dvalue", fields[1]) + require.Equal(t, "rtspSession", fields[2]) + require.NotEmpty(t, fields[3]) + require.Equal(t, "8554", fields[4]) + require.Equal(t, "st", fields[5]) + + byts, err = os.ReadFile(onNotReady) + require.NoError(t, err) + fields = strings.Split(string(byts[:len(byts)-1]), " ") + require.Equal(t, "test", fields[0]) + require.Equal(t, "query%3Dvalue", fields[1]) + require.Equal(t, "rtspSession", fields[2]) + require.NotEmpty(t, fields[3]) + require.Equal(t, "8554", fields[4]) + require.Equal(t, "st", fields[5]) +} + +func TestPathRunOnReadyQueryInjection(t *testing.T) { + sentinel := filepath.Join(t.TempDir(), "mediamtx_test_query_injection_sentinel") + + for _, ca := range []struct { + name string + cmdstr string + query string + }{ + { + // $(…) inside double quotes still triggers command substitution. + // ${IFS} expands to a space, avoiding a literal space in the query string. + name: "command substitution dollar", + cmdstr: "sh -c 'echo \"$MTX_QUERY\"'", + query: "$(touch${IFS}" + sentinel + "1)", + }, + { + // > in an unquoted expansion redirects echo's output, creating the file. + name: "redirect", + cmdstr: "sh -c 'echo $MTX_QUERY'", + query: ">" + sentinel + "2", + }, + { + // & in an unquoted expansion backgrounds echo and runs touch directly. + // ${IFS} expands to a space, avoiding a literal space in the query string. + name: "and operator", + cmdstr: "sh -c 'echo $MTX_QUERY'", + query: "&touch${IFS}" + sentinel + "3", + }, + } { + t.Run(ca.name, func(t *testing.T) { + p, ok := newInstance(t, fmt.Sprintf( + "rtmp: no\nhls: no\nwebrtc: no\npaths:\n test:\n runOnReady: %s\n", + ca.cmdstr)) + require.Equal(t, true, ok) + defer p.Close() + + c := gortsplib.Client{} + err := c.StartRecording( + "rtsp://localhost:8554/test?"+ca.query, + &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}}) + require.NoError(t, err) + defer c.Close() + + time.Sleep(500 * time.Millisecond) + + _, statErr := os.Stat(sentinel) + require.ErrorIs(t, statErr, os.ErrNotExist) + }) + } +} + +func TestPathRunOnRead(t *testing.T) { + serverCertFpath := test.CreateTempFile(t, test.TLSCertPub) + serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey) + + for _, ca := range []string{"rtsp", "rtsps", "rtmp", "rtmps", "srt", "webrtc"} { + t.Run(ca, func(t *testing.T) { + onRead := filepath.Join(t.TempDir(), "on_read") + onUnread := filepath.Join(t.TempDir(), "on_unread") + + func() { + p, ok := newInstance(t, fmt.Sprintf( + "rtspEncryption: optional\n"+ + "rtspServerCert: "+serverCertFpath+"\n"+ + "rtspServerKey: "+serverKeyFpath+"\n"+ + "rtmpEncryption: optional\n"+ + "rtmpServerCert: "+serverCertFpath+"\n"+ + "rtmpServerKey: "+serverKeyFpath+"\n"+ + "paths:\n"+ + " ~te(st):\n"+ + " runOnRead: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_READER_TYPE $MTX_READER_ID $RTSP_PORT $G1\" > %s'\n"+ + " runOnUnread: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_READER_TYPE $MTX_READER_ID $RTSP_PORT $G1\" > %s'\n", + onRead, onUnread)) + require.Equal(t, true, ok) + defer p.Close() + + media0 := test.UniqueMediaH264() + + source := gortsplib.Client{} + + err := source.StartRecording( + "rtsp://localhost:8554/test", + &description.Session{Medias: []*description.Media{media0}}) + require.NoError(t, err) + defer source.Close() + + writerDone := make(chan struct{}) + defer func() { <-writerDone }() + + writerTerminate := make(chan struct{}) + defer close(writerTerminate) + + go func() { + defer close(writerDone) + i := 0 + for { + select { + case <-time.After(100 * time.Millisecond): + case <-writerTerminate: + return + } + err2 := source.WritePacketRTP(media0, &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 96, + SequenceNumber: uint16(123 + i), + Timestamp: uint32(45343 + i*90000), + SSRC: 563423, + }, + Payload: []byte{5}, + }) + require.NoError(t, err2) + i++ + } + }() + + switch ca { + case "rtsp": + var u *base.URL + u, err = base.ParseURL("rtsp://127.0.0.1:8554/test?query=value") + require.NoError(t, err) + + reader := gortsplib.Client{ + Scheme: u.Scheme, + Host: u.Host, + } + + err = reader.Start() + require.NoError(t, err) + defer reader.Close() + + var desc *description.Session + 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) + + case "rtsps": + var u *base.URL + u, err = base.ParseURL("rtsps://127.0.0.1:8322/test?query=value") + require.NoError(t, err) + + reader := gortsplib.Client{ + Scheme: u.Scheme, + Host: u.Host, + TLSConfig: &tls.Config{InsecureSkipVerify: true}, + } + + err = reader.Start() + require.NoError(t, err) + defer reader.Close() + + var desc *description.Session + 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) + + case "rtmp": + var u *url.URL + u, err = url.Parse("rtmp://127.0.0.1:1935/test?query=value") + require.NoError(t, err) + + conn := &gortmplib.Client{ + URL: u, + Publish: false, + } + err = conn.Initialize(context.Background()) + require.NoError(t, err) + defer conn.Close() + + r := &gortmplib.Reader{ + Conn: conn, + } + err = r.Initialize() + require.NoError(t, err) + + case "rtmps": + var u *url.URL + u, err = url.Parse("rtmps://127.0.0.1:1936/test?query=value") + require.NoError(t, err) + + conn := &gortmplib.Client{ + URL: u, + Publish: false, + TLSConfig: &tls.Config{InsecureSkipVerify: true}, + } + err = conn.Initialize(context.Background()) + require.NoError(t, err) + defer conn.Close() + + go func() { + for i := range uint16(3) { + err2 := source.WritePacketRTP(media0, &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 96, + SequenceNumber: 123 + i, + Timestamp: 45343 + uint32(i)*2*90000, + SSRC: 563423, + }, + Payload: []byte{5}, + }) + require.NoError(t, err2) + } + }() + + r := &gortmplib.Reader{ + Conn: conn, + } + err = r.Initialize() + require.NoError(t, err) + + case "srt": + conf := srt.DefaultConfig() + var address string + address, err = conf.UnmarshalURL("srt://localhost:8890?streamid=read:test:query=value") + require.NoError(t, err) + + err = conf.Validate() + require.NoError(t, err) + + var reader srt.Conn + reader, err = srt.Dial("srt", address, conf) + require.NoError(t, err) + defer reader.Close() + + case "webrtc": + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + var u *url.URL + u, err = url.Parse("http://localhost:8889/test/whep?query=value") + require.NoError(t, err) + + c := &whip.Client{ + HTTPClient: hc, + URL: u, + Log: test.NilLogger, + } + + err = c.Initialize(context.Background()) + require.NoError(t, err) + defer checkClose(t, c.Close) + } + + time.Sleep(500 * time.Millisecond) + }() + + var readerType string + + switch ca { + case "rtsp": + readerType = "rtspSession" + case "rtsps": + readerType = "rtspsSession" + case "rtmp": + readerType = "rtmpConn" + case "rtmps": + readerType = "rtmpsConn" + case "srt": + readerType = "srtConn" + case "webrtc": + readerType = "webRTCSession" + } + + var byts []byte + byts, err := os.ReadFile(onRead) + require.NoError(t, err) + fields := strings.Split(string(byts[:len(byts)-1]), " ") + require.Equal(t, "test", fields[0]) + require.Equal(t, "query%3Dvalue", fields[1]) + require.Equal(t, readerType, fields[2]) + require.NotEmpty(t, fields[3]) + require.Equal(t, "8554", fields[4]) + require.Equal(t, "st", fields[5]) + + byts, err = os.ReadFile(onUnread) + require.NoError(t, err) + fields = strings.Split(string(byts[:len(byts)-1]), " ") + require.Equal(t, "test", fields[0]) + require.Equal(t, "query%3Dvalue", fields[1]) + require.Equal(t, readerType, fields[2]) + require.NotEmpty(t, fields[3]) + require.Equal(t, "8554", fields[4]) + require.Equal(t, "st", fields[5]) + }) + } +} + +func TestPathRunOnRecordSegment(t *testing.T) { + onRecordSegmentCreate := filepath.Join(t.TempDir(), "on_record_segment_create") + onRecordSegmentComplete := filepath.Join(t.TempDir(), "on_record_segment_complete") + + recordDir := t.TempDir() + var err error + + func() { + p, ok := newInstance(t, fmt.Sprintf("record: yes\n"+ + "recordPath: %s\n"+ + "paths:\n"+ + " test:\n"+ + " runOnRecordSegmentCreate: sh -c 'echo \"$MTX_SEGMENT_PATH $RTSP_PORT\" > %s'\n"+ + " runOnRecordSegmentComplete: sh -c 'echo \"$MTX_SEGMENT_PATH $MTX_SEGMENT_DURATION $RTSP_PORT\" > %s'\n", + filepath.Join(recordDir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + onRecordSegmentCreate, + onRecordSegmentComplete, + )) + require.Equal(t, true, ok) + defer p.Close() + + media0 := test.UniqueMediaH264() + + source := gortsplib.Client{} + + err = source.StartRecording( + "rtsp://localhost:8554/test", + &description.Session{Medias: []*description.Media{media0}}) + require.NoError(t, err) + defer source.Close() + + for i := range 4 { + err = source.WritePacketRTP(media0, &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 96, + SequenceNumber: 1123 + uint16(i), + Timestamp: 45343 + 90000*uint32(i), + SSRC: 563423, + }, + Payload: []byte{5}, + }) + require.NoError(t, err) + } + + time.Sleep(500 * time.Millisecond) + }() + + byts, err := os.ReadFile(onRecordSegmentCreate) + require.NoError(t, err) + fields := strings.Split(string(byts[:len(byts)-1]), " ") + require.True(t, strings.HasPrefix(fields[0], recordDir)) + require.Equal(t, "8554", fields[1]) + + byts, err = os.ReadFile(onRecordSegmentComplete) + require.NoError(t, err) + fields = strings.Split(string(byts[:len(byts)-1]), " ") + require.True(t, strings.HasPrefix(fields[0], recordDir)) + require.Equal(t, "3", fields[1]) + require.Equal(t, "8554", fields[2]) +} + +func TestPathMaxReaders(t *testing.T) { + p, ok := newInstance(t, "paths:\n"+ + " all_others:\n"+ + " maxReaders: 1\n") + require.Equal(t, true, ok) + defer p.Close() + + source := gortsplib.Client{} + + err := source.StartRecording( + "rtsp://localhost:8554/mystream", + &description.Session{Medias: []*description.Media{ + test.UniqueMediaH264(), + test.UniqueMediaMPEG4Audio(), + }}) + require.NoError(t, err) + defer source.Close() + + for i := range 2 { + var u *base.URL + u, err = base.ParseURL("rtsp://127.0.0.1:8554/mystream") + require.NoError(t, err) + + reader := gortsplib.Client{ + Scheme: u.Scheme, + Host: u.Host, + } + + err = reader.Start() + require.NoError(t, err) + defer reader.Close() + + var desc *description.Session + desc, _, err = reader.Describe(u) + require.NoError(t, err) + + err = reader.SetupAll(desc.BaseURL, desc.Medias) + if i != 1 { + require.NoError(t, err) + } else { + require.Error(t, err) + } + } +} + +func TestPathRecord(t *testing.T) { + dir := t.TempDir() + + p, ok := newInstance(t, "api: yes\n"+ + "record: yes\n"+ + "recordPath: "+filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f")+"\n"+ + "paths:\n"+ + " all_others:\n"+ + " record: yes\n") + require.Equal(t, true, ok) + defer p.Close() + + media0 := test.UniqueMediaH264() + + source := gortsplib.Client{} + + err := source.StartRecording( + "rtsp://localhost:8554/mystream", + &description.Session{Medias: []*description.Media{media0}}) + require.NoError(t, err) + defer source.Close() + + for i := range 4 { + err = source.WritePacketRTP(media0, &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 96, + SequenceNumber: 1123 + uint16(i), + Timestamp: 45343 + 90000*uint32(i), + SSRC: 563423, + }, + Payload: []byte{5}, + }) + require.NoError(t, err) + } + + time.Sleep(500 * time.Millisecond) + + files, err := os.ReadDir(filepath.Join(dir, "mystream")) + require.NoError(t, err) + require.Equal(t, 1, len(files)) + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/paths/patch/all_others", map[string]any{ + "record": false, + }, nil) + + time.Sleep(500 * time.Millisecond) + + httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/paths/patch/all_others", map[string]any{ + "record": true, + }, nil) + + time.Sleep(500 * time.Millisecond) + + for i := 4; i < 8; i++ { + err = source.WritePacketRTP(media0, &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 96, + SequenceNumber: 1123 + uint16(i), + Timestamp: 45343 + 90000*uint32(i), + SSRC: 563423, + }, + Payload: []byte{5}, + }) + require.NoError(t, err) + } + + time.Sleep(500 * time.Millisecond) + + files, err = os.ReadDir(filepath.Join(dir, "mystream")) + require.NoError(t, err) + require.Equal(t, 2, len(files)) +} + +func TestPathFallback(t *testing.T) { + for _, ca := range []string{ + "absolute", + "relative", + "source", + } { + t.Run(ca, func(t *testing.T) { + var cnf string + + switch ca { + case "absolute": + cnf = "paths:\n" + + " path1:\n" + + " fallback: rtsp://localhost:8554/path2\n" + + " path2:\n" + + case "relative": + cnf = "paths:\n" + + " path1:\n" + + " fallback: /path2\n" + + " path2:\n" + + case "source": + cnf = "paths:\n" + + " path1:\n" + + " fallback: /path2\n" + + " source: rtsp://localhost:3333/nonexistent\n" + + " path2:\n" + } + + p1, ok := newInstance(t, cnf) + require.Equal(t, true, ok) + defer p1.Close() + + source := gortsplib.Client{} + err := source.StartRecording("rtsp://localhost:8554/path2", + &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}}) + require.NoError(t, err) + defer source.Close() + + u, err := base.ParseURL("rtsp://localhost:8554/path1") + require.NoError(t, err) + + dest := gortsplib.Client{ + Scheme: u.Scheme, + Host: u.Host, + } + + err = dest.Start() + require.NoError(t, err) + defer dest.Close() + + desc, _, err := dest.Describe(u) + require.NoError(t, err) + require.Equal(t, 1, len(desc.Medias)) + }) + } +} + +func TestPathResolveSource(t *testing.T) { + var strm *gortsplib.ServerStream + + s := gortsplib.Server{ + Handler: &testServer{ + onDescribe: func(ctx *gortsplib.ServerHandlerOnDescribeCtx, + ) (*base.Response, *gortsplib.ServerStream, error) { + require.Equal(t, "key=val", ctx.Query) + require.Equal(t, "/a", ctx.Path) + return &base.Response{ + StatusCode: base.StatusOK, + }, strm, nil + }, + onSetup: func(_ *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) { + return &base.Response{ + StatusCode: base.StatusOK, + }, strm, nil + }, + onPlay: func(_ *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) { + return &base.Response{ + StatusCode: base.StatusOK, + }, nil + }, + }, + RTSPAddress: "127.0.0.1:8555", + } + + err := s.Start() + require.NoError(t, err) + defer s.Close() + + strm = &gortsplib.ServerStream{ + Server: &s, + Desc: &description.Session{Medias: []*description.Media{test.MediaH264}}, + } + err = strm.Initialize() + require.NoError(t, err) + defer strm.Close() + + p, ok := newInstance(t, + "paths:\n"+ + " '~^test_(.+)$':\n"+ + " source: rtsp://127.0.0.1:8555/$G1?$MTX_QUERY\n"+ + " sourceOnDemand: yes\n"+ + " 'all':\n") + require.Equal(t, true, ok) + defer p.Close() + + u, err := base.ParseURL("rtsp://127.0.0.1:8554/test_a?key=val") + require.NoError(t, err) + + reader := gortsplib.Client{ + Scheme: u.Scheme, + Host: u.Host, + } + + err = reader.Start() + require.NoError(t, err) + defer reader.Close() + + _, _, err = reader.Describe(u) + require.NoError(t, err) +} + +func TestPathOverridePublisher(t *testing.T) { + for _, ca := range []string{ + "enabled", + "disabled", + } { + t.Run(ca, func(t *testing.T) { + cnf := "rtmp: no\n" + + "paths:\n" + + " all_others:\n" + + if ca == "disabled" { + cnf += " overridePublisher: no\n" + } + + p, ok := newInstance(t, cnf) + require.Equal(t, true, ok) + defer p.Close() + + medi := test.UniqueMediaH264() + + 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{}) + + u, err := base.ParseURL("rtsp://localhost:8554/teststream") + require.NoError(t, err) + + c := gortsplib.Client{ + Scheme: u.Scheme, + Host: u.Host, + } + + err = c.Start() + 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 + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/source_redirect.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/source_redirect.go new file mode 100644 index 0000000000000000000000000000000000000000..445b12229deec0ec9e9b81def8e76c6e22f68160 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/source_redirect.go @@ -0,0 +1,20 @@ +package core + +import ( + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/logger" +) + +// sourceRedirect is a source that redirects to another one. +type sourceRedirect struct{} + +func (*sourceRedirect) Log(logger.Level, string, ...any) { +} + +// APISourceDescribe implements source. +func (*sourceRedirect) APISourceDescribe() *defs.APIPathSource { + return &defs.APIPathSource{ + Type: defs.APIPathSourceTypeRedirect, + ID: "", + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/test_on_demand/main.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/test_on_demand/main.go new file mode 100644 index 0000000000000000000000000000000000000000..a695163e568e460e6b37d4800a9b20336de495bc --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/test_on_demand/main.go @@ -0,0 +1,54 @@ +// This is used for testing purposes. +package main + +import ( + "os" + "os/signal" + "syscall" + + "github.com/bluenviron/gortsplib/v5" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" +) + +func main() { + if os.Getenv("MTX_QUERY") != "key1%3Dval1%26key2%3Dval2" { + panic("unexpected MTX_QUERY: " + os.Getenv("MTX_QUERY")) + } + if os.Getenv("G1") != "on" { + panic("unexpected G1: " + os.Getenv("G1")) + } + + medi := &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H264{ + PayloadTyp: 96, + SPS: []byte{ + 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{0x01, 0x02, 0x03, 0x04}, + PacketizationMode: 1, + }}, + } + + source := gortsplib.Client{} + + err := source.StartRecording( + "rtsp://localhost:"+os.Getenv("RTSP_PORT")+"/"+os.Getenv("MTX_PATH"), + &description.Session{Medias: []*description.Media{medi}}) + if err != nil { + panic(err) + } + defer source.Close() + + c := make(chan os.Signal, 1) + signal.Notify(c, syscall.SIGINT) + <-c + + err = os.WriteFile(os.Getenv("ON_DEMAND"), []byte(""), 0o644) + if err != nil { + panic(err) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/versiongetter/main.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/versiongetter/main.go new file mode 100644 index 0000000000000000000000000000000000000000..60efa567eba54a505acddc04bc505bce38230183 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/versiongetter/main.go @@ -0,0 +1,143 @@ +// Package main contains an utility to get the server version +package main + +import ( + "fmt" + "log" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/go-git/go-billy/v5/osfs" + "github.com/go-git/go-git/v5" + "github.com/go-git/go-git/v5/plumbing" + "github.com/go-git/go-git/v5/plumbing/cache" + "github.com/go-git/go-git/v5/plumbing/object" + "github.com/go-git/go-git/v5/storage/filesystem" +) + +// Golang version of git describe --tags +func gitDescribeTags(repo *git.Repository) (string, error) { + head, err := repo.Head() + if err != nil { + return "", fmt.Errorf("failed to get HEAD: %w", err) + } + + tagIterator, err := repo.Tags() + if err != nil { + return "", fmt.Errorf("failed to get tags: %w", err) + } + defer tagIterator.Close() + + tags := make(map[plumbing.Hash]*plumbing.Reference) + + err = tagIterator.ForEach(func(t *plumbing.Reference) error { + if to, err2 := repo.TagObject(t.Hash()); err2 == nil { + tags[to.Target] = t + } else { + tags[t.Hash()] = t + } + return nil + }) + if err != nil { + return "", fmt.Errorf("failed to iterate tags: %w", err) + } + + cIter, err := repo.Log(&git.LogOptions{From: head.Hash()}) + if err != nil { + return "", fmt.Errorf("failed to get log: %w", err) + } + + i := 0 + + for { + var commit *object.Commit + commit, err = cIter.Next() + if err != nil { + return "", fmt.Errorf("failed to get next commit: %w", err) + } + + if str, ok := tags[commit.Hash]; ok { + label := strings.TrimPrefix(string(str.Name()), "refs/tags/") + + if i != 0 { + label += "-" + strconv.FormatInt(int64(i), 10) + "-" + head.Hash().String()[:8] + } + + return label, nil + } + + i++ + } +} + +func tagFromGit() error { + // [git.PlainOpen] uses a ChrootOS that limits filesystem access to the .git directory only. + // + // Unfortunately, this can cause issues with package build environments such as Arch Linux's, + // where .git/objects/info/alternates points to a directory outside of the .git directory. + // + // To work around this, specify an AlternatesFS that allows access to the entire filesystem. + dotGitAbs, _ := filepath.Abs("../../.git") + storerFs := osfs.New(dotGitAbs, osfs.WithBoundOS()) + storer := filesystem.NewStorageWithOptions(storerFs, cache.NewObjectLRUDefault(), filesystem.Options{ + AlternatesFS: osfs.New("/", osfs.WithBoundOS()), + }) + workTreeAbs, _ := filepath.Abs("../../") + worktreeFs := osfs.New(workTreeAbs, osfs.WithBoundOS()) + repo, err := git.Open(storer, worktreeFs) + if err != nil { + return fmt.Errorf("failed to open repository: %w", err) + } + + version, err := gitDescribeTags(repo) + if err != nil { + return fmt.Errorf("failed to get version: %w", err) + } + + wt, err := repo.Worktree() + if err != nil { + return fmt.Errorf("failed to get worktree: %w", err) + } + + status, err := wt.Status() + if err != nil { + return fmt.Errorf("failed to get status: %w", err) + } + + if !status.IsClean() { + version += "-dirty" + } + + err = os.WriteFile("VERSION", []byte(version), 0o644) + if err != nil { + return fmt.Errorf("failed to write version file: %w", err) + } + + log.Printf("ok (%s)", version) + return nil +} + +func do() error { + log.Println("getting mediamtx version...") + + err := tagFromGit() + if err != nil { + log.Println("WARN: cannot get tag from .git folder, using v0.0.0 as version") + err = os.WriteFile("VERSION", []byte("v0.0.0"), 0o644) + if err != nil { + return fmt.Errorf("failed to write version file: %w", err) + } + } + + return nil +} + +func main() { + err := do() + if err != nil { + log.Printf("ERR: %v", err) + os.Exit(1) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper.go new file mode 100644 index 0000000000000000000000000000000000000000..7ad87edf496d36c3683b86defe8f78e220d41a09 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper.go @@ -0,0 +1,84 @@ +// Package counterdumper contains a counter that that periodically invokes a callback if the counter is not zero. +package counterdumper + +import ( + "sync" + "time" +) + +const ( + callbackPeriod = 1 * time.Second +) + +// Dumper is a counter that periodically invokes a callback if the counter is not zero. +type Dumper struct { + OnReport func(v uint64) + + mutex sync.Mutex + counter uint64 + absCounter uint64 + + terminate chan struct{} + done chan struct{} +} + +// Start starts the counter. +func (c *Dumper) Start() { + c.terminate = make(chan struct{}) + c.done = make(chan struct{}) + + go c.run() +} + +// Stop stops the counter. +func (c *Dumper) Stop() { + close(c.terminate) + <-c.done +} + +// Increase increases the counter value by 1. +func (c *Dumper) Increase() { + c.mutex.Lock() + defer c.mutex.Unlock() + c.counter++ + c.absCounter++ +} + +// Add adds value to the counter. +func (c *Dumper) Add(v uint64) { + c.mutex.Lock() + defer c.mutex.Unlock() + c.counter += v + c.absCounter += v +} + +// Get returns the counter value. +func (c *Dumper) Get() uint64 { + c.mutex.Lock() + defer c.mutex.Unlock() + return c.absCounter +} + +func (c *Dumper) run() { + defer close(c.done) + + t := time.NewTicker(callbackPeriod) + defer t.Stop() + + for { + select { + case <-c.terminate: + return + + case <-t.C: + c.mutex.Lock() + var v uint64 + v, c.counter = c.counter, 0 + c.mutex.Unlock() + + if v != 0 { + c.OnReport(v) + } + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper_test.go new file mode 100644 index 0000000000000000000000000000000000000000..889e6db6bc0fd7a88a619eb2426b1c1f9909ff29 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper_test.go @@ -0,0 +1,42 @@ +package counterdumper + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestDumperReport(t *testing.T) { + done := make(chan struct{}) + + c := &Dumper{ + OnReport: func(v uint64) { + require.Equal(t, uint64(3), v) + close(done) + }, + } + c.Start() + defer c.Stop() + + c.Add(2) + c.Increase() + + select { + case <-done: + case <-time.After(2 * time.Second): + t.Errorf("should not happen") + } +} + +func TestDumperDoNotReport(t *testing.T) { + c := &Dumper{ + OnReport: func(_ uint64) { + t.Errorf("should not happen") + }, + } + c.Start() + defer c.Stop() + + <-time.After(2 * time.Second) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api.go new file mode 100644 index 0000000000000000000000000000000000000000..43043ab602f7ad5b6ddbdb696e4dd6a024a3d5b6 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api.go @@ -0,0 +1,47 @@ +package defs + +import ( + "time" + + "github.com/bluenviron/mediamtx/internal/conf" +) + +// APIOKStatus is the status of a successful response. +type APIOKStatus string + +// statuses. +const ( + APIOKStatusOK APIOKStatus = "ok" +) + +// APIErrorStatus is the status of an error response. +type APIErrorStatus string + +// statuses. +const ( + APIErrorStatusError APIErrorStatus = "error" +) + +// APIOK is returned on success. +type APIOK struct { + Status APIOKStatus `json:"status"` +} + +// APIError is a generic error. +type APIError struct { + Status APIErrorStatus `json:"status"` + Error string `json:"error"` +} + +// APIInfo is a info response. +type APIInfo struct { + Version string `json:"version"` + Started time.Time `json:"started"` +} + +// APIPathConfList is a list of path configurations. +type APIPathConfList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []conf.Path `json:"items"` +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_hls.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_hls.go new file mode 100644 index 0000000000000000000000000000000000000000..20ad0a17316c2030349bfc7726de9e00be62c2d2 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_hls.go @@ -0,0 +1,54 @@ +package defs + +import ( + "time" + + "github.com/google/uuid" +) + +// APIHLSServer contains methods used by the API and Metrics server. +type APIHLSServer interface { + APISessionsList() (*APIHLSSessionList, error) + APISessionsGet(uuid.UUID) (*APIHLSSession, error) + APISessionsKick(uuid.UUID) error + APIMuxersList() (*APIHLSMuxerList, error) + APIMuxersGet(string) (*APIHLSMuxer, error) +} + +// APIHLSSessionList is a list of HLS sessions. +type APIHLSSessionList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []APIHLSSession `json:"items"` +} + +// APIHLSSession is an HLS session. +type APIHLSSession struct { + ID uuid.UUID `json:"id"` + Created time.Time `json:"created"` + RemoteAddr string `json:"remoteAddr"` + Path string `json:"path"` + Query string `json:"query"` + User string `json:"user"` + UserAgent string `json:"userAgent"` + IsCDN bool `json:"isCDN"` + OutboundBytes uint64 `json:"outboundBytes"` +} + +// APIHLSMuxerList is a list of HLS muxers. +type APIHLSMuxerList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []APIHLSMuxer `json:"items"` +} + +// APIHLSMuxer is an HLS muxer. +type APIHLSMuxer struct { + Path string `json:"path"` + Created time.Time `json:"created"` + LastRequest time.Time `json:"lastRequest"` + OutboundBytes uint64 `json:"outboundBytes"` + OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"` + // deprecated + BytesSent uint64 `json:"bytesSent" deprecated:"true"` +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_moq.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_moq.go new file mode 100644 index 0000000000000000000000000000000000000000..b3f897ab530dfb3c565e74be5ae54571ae3b4877 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_moq.go @@ -0,0 +1,44 @@ +package defs + +import ( + "time" + + "github.com/google/uuid" +) + +// APIMoQServer contains methods used by the API server. +type APIMoQServer interface { + APISessionsList() (*APIMoQSessionList, error) + APISessionsGet(uuid.UUID) (*APIMoQSession, error) + APISessionsKick(uuid.UUID) error +} + +// APIMoQSessionState is the state of a MoQ session. +type APIMoQSessionState string + +// states. +const ( + APIMoQSessionStateIdle APIMoQSessionState = "idle" + APIMoQSessionStateRead APIMoQSessionState = "read" + APIMoQSessionStatePublish APIMoQSessionState = "publish" +) + +// APIMoQSessionList is a list of MoQ sessions. +type APIMoQSessionList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []APIMoQSession `json:"items"` +} + +// APIMoQSession is a MoQ session. +type APIMoQSession struct { + ID uuid.UUID `json:"id"` + Created time.Time `json:"created"` + RemoteAddr string `json:"remoteAddr"` + State APIMoQSessionState `json:"state"` + Path string `json:"path"` + Query string `json:"query"` + UserAgent string `json:"userAgent"` + InboundBytes uint64 `json:"inboundBytes"` + OutboundBytes uint64 `json:"outboundBytes"` +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path.go new file mode 100644 index 0000000000000000000000000000000000000000..17b65a51005172d68a22f1a6defcbbeee4c09367 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path.go @@ -0,0 +1,93 @@ +package defs + +import ( + "time" +) + +// APIPathManager contains methods used by the API and Metrics server. +type APIPathManager interface { + APIPathsList() (*APIPathList, error) + APIPathsGet(string) (*APIPath, error) +} + +// APIPathSourceType is the type of a path source. +type APIPathSourceType string + +// source types. +const ( + APIPathSourceTypeHLSSource APIPathSourceType = "hlsSource" + APIPathSourceTypeRedirect APIPathSourceType = "redirect" + APIPathSourceTypeRPICameraSource APIPathSourceType = "rpiCameraSource" + APIPathSourceTypeRTMPConn APIPathSourceType = "rtmpConn" + APIPathSourceTypeRTMPSConn APIPathSourceType = "rtmpsConn" + APIPathSourceTypeRTMPSource APIPathSourceType = "rtmpSource" + APIPathSourceTypeRTSPSession APIPathSourceType = "rtspSession" + APIPathSourceTypeRTSPSource APIPathSourceType = "rtspSource" + APIPathSourceTypeRTSPSSession APIPathSourceType = "rtspsSession" + APIPathSourceTypeSRTConn APIPathSourceType = "srtConn" + APIPathSourceTypeSRTSource APIPathSourceType = "srtSource" + APIPathSourceTypeMPEGTSSource APIPathSourceType = "mpegtsSource" + APIPathSourceTypeRTPSource APIPathSourceType = "rtpSource" + APIPathSourceTypeWebRTCSession APIPathSourceType = "webRTCSession" + APIPathSourceTypeWebRTCSource APIPathSourceType = "webRTCSource" + APIPathSourceTypeMoQSession APIPathSourceType = "moqSession" +) + +// APIPathSource is a source. +type APIPathSource struct { + Type APIPathSourceType `json:"type"` + ID string `json:"id"` +} + +// APIPathReaderType is the type of a path reader. +type APIPathReaderType string + +// reader types. +const ( + APIPathReaderTypeHLSSession APIPathReaderType = "hlsSession" + APIPathReaderTypeRTMPConn APIPathReaderType = "rtmpConn" + APIPathReaderTypeRTMPSConn APIPathReaderType = "rtmpsConn" + APIPathReaderTypeRTSPConn APIPathReaderType = "rtspConn" + APIPathReaderTypeRTSPSession APIPathReaderType = "rtspSession" + APIPathReaderTypeRTSPSConn APIPathReaderType = "rtspsConn" + APIPathReaderTypeRTSPSSession APIPathReaderType = "rtspsSession" + APIPathReaderTypeSRTConn APIPathReaderType = "srtConn" + APIPathReaderTypeWebRTCSession APIPathReaderType = "webRTCSession" + APIPathReaderTypeMoQSession APIPathReaderType = "moqSession" + APIPathReaderTypeHidden APIPathReaderType = "hidden" +) + +// APIPathReader is a reader. +type APIPathReader struct { + Type APIPathReaderType `json:"type"` + ID string `json:"id"` +} + +// APIPath is a path. +type APIPath struct { + Name string `json:"name"` + ConfName string `json:"confName"` + Ready bool `json:"ready" deprecated:"true"` + ReadyTime *time.Time `json:"readyTime" deprecated:"true"` + Available bool `json:"available"` + AvailableTime *time.Time `json:"availableTime"` + Online bool `json:"online"` + OnlineTime *time.Time `json:"onlineTime"` + Source *APIPathSource `json:"source"` + Tracks []APIPathTrackCodec `json:"tracks" deprecated:"true"` + Tracks2 []APIPathTrack `json:"tracks2"` + Readers []APIPathReader `json:"readers"` + InboundBytes uint64 `json:"inboundBytes"` + OutboundBytes uint64 `json:"outboundBytes"` + InboundFramesInError uint64 `json:"inboundFramesInError"` + // deprecated + BytesReceived uint64 `json:"bytesReceived" deprecated:"true"` + BytesSent uint64 `json:"bytesSent" deprecated:"true"` +} + +// APIPathList is a list of paths. +type APIPathList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []APIPath `json:"items"` +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track.go new file mode 100644 index 0000000000000000000000000000000000000000..d50635cc5fd6667fe8b434068b9983d769877634 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track.go @@ -0,0 +1,55 @@ +package defs + +import ( + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediamtx/internal/formatlabel" +) + +// APIPathTrack is a track. +type APIPathTrack struct { + Codec APIPathTrackCodec `json:"codec"` + CodecProps APIPathTrackCodecProps `json:"codecProps"` +} + +func formatToTrack(outFormat format.Format) APIPathTrack { + return APIPathTrack{ + Codec: formatlabel.FormatToLabel(outFormat), + CodecProps: formatToTrackCodecProps(outFormat), + } +} + +func gatherFormats(medias []*description.Media) []format.Format { + n := 0 + for _, media := range medias { + n += len(media.Formats) + } + + if n == 0 { + return nil + } + + formats := make([]format.Format, n) + n = 0 + + for _, media := range medias { + n += copy(formats[n:], media.Formats) + } + + return formats +} + +func formatsToTracks(outFormats []format.Format) []APIPathTrack { + ret := make([]APIPathTrack, len(outFormats)) + + for i, outFormat := range outFormats { + ret[i] = formatToTrack(outFormat) + } + + return ret +} + +// MediasToTracks returns tracks of given medias. +func MediasToTracks(outMedias []*description.Media) []APIPathTrack { + return formatsToTracks(gatherFormats(outMedias)) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec.go new file mode 100644 index 0000000000000000000000000000000000000000..67c4e03678e967b27ffc9158e44fd238e9be4c07 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec.go @@ -0,0 +1,6 @@ +package defs + +import "github.com/bluenviron/mediamtx/internal/formatlabel" + +// APIPathTrackCodec is a track codec. +type APIPathTrackCodec = formatlabel.Label diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec_props.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec_props.go new file mode 100644 index 0000000000000000000000000000000000000000..25e4cdd4c4195207a72a2e9a9fea07d9b3dd2bc1 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec_props.go @@ -0,0 +1,257 @@ +package defs + +import ( + "fmt" + "strconv" + + "github.com/bluenviron/gortsplib/v5/pkg/format" + codecsh264 "github.com/bluenviron/mediacommon/v2/pkg/codecs/h264" + codecsh265 "github.com/bluenviron/mediacommon/v2/pkg/codecs/h265" +) + +// APIPathTrackCodecProps contains codec-specific properties. +type APIPathTrackCodecProps interface { + apiPathTrackCodecProps() +} + +// APIPathTrackCodecPropsAV1 contains codec-specific properties of AV1. +type APIPathTrackCodecPropsAV1 struct { + Width int `json:"width"` + Height int `json:"height"` + Profile int `json:"profile"` + Level int `json:"level"` + Tier int `json:"tier"` +} + +func (*APIPathTrackCodecPropsAV1) apiPathTrackCodecProps() {} + +// APIPathTrackCodecPropsVP9 contains codec-specific properties of VP9. +type APIPathTrackCodecPropsVP9 struct { + Profile int `json:"profile"` +} + +func (*APIPathTrackCodecPropsVP9) apiPathTrackCodecProps() {} + +// APIPathTrackCodecPropsH265 contains codec-specific properties of H265. +type APIPathTrackCodecPropsH265 struct { + Width int `json:"width"` + Height int `json:"height"` + Profile string `json:"profile"` + Level string `json:"level"` +} + +func (*APIPathTrackCodecPropsH265) apiPathTrackCodecProps() {} + +// APIPathTrackCodecPropsH264 contains codec-specific properties of H264. +type APIPathTrackCodecPropsH264 struct { + Width int `json:"width"` + Height int `json:"height"` + Profile string `json:"profile"` + Level string `json:"level"` +} + +func (*APIPathTrackCodecPropsH264) apiPathTrackCodecProps() {} + +// APIPathTrackCodecPropsOpus contains codec-specific properties of Opus. +type APIPathTrackCodecPropsOpus struct { + ChannelCount int `json:"channelCount"` +} + +func (*APIPathTrackCodecPropsOpus) apiPathTrackCodecProps() {} + +// APIPathTrackCodecPropsMPEG4Audio contains codec-specific properties of MPEG4Audio. +type APIPathTrackCodecPropsMPEG4Audio struct { + SampleRate int `json:"sampleRate"` + ChannelCount int `json:"channelCount"` +} + +func (*APIPathTrackCodecPropsMPEG4Audio) apiPathTrackCodecProps() {} + +// APIPathTrackCodecPropsAC3 contains codec-specific properties of AC3. +type APIPathTrackCodecPropsAC3 struct { + SampleRate int `json:"sampleRate"` + ChannelCount int `json:"channelCount"` +} + +func (*APIPathTrackCodecPropsAC3) apiPathTrackCodecProps() {} + +// APIPathTrackCodecPropsG711 contains codec-specific properties of G711. +type APIPathTrackCodecPropsG711 struct { + MULaw bool `json:"muLaw"` + SampleRate int `json:"sampleRate"` + ChannelCount int `json:"channelCount"` +} + +func (*APIPathTrackCodecPropsG711) apiPathTrackCodecProps() {} + +// APIPathTrackCodecPropsLPCM contains codec-specific properties of LPCM. +type APIPathTrackCodecPropsLPCM struct { + BitDepth int `json:"bitDepth"` + SampleRate int `json:"sampleRate"` + ChannelCount int `json:"channelCount"` +} + +func (*APIPathTrackCodecPropsLPCM) apiPathTrackCodecProps() {} + +func h264ProfileString(profileIdc uint8) string { + switch profileIdc { + case 66: + return "Baseline" + case 77: + return "Main" + case 88: + return "Extended" + case 100: + return "High" + case 110: + return "High 10" + case 122: + return "High 4:2:2" + case 244: + return "High 4:4:4 Predictive" + default: + return strconv.Itoa(int(profileIdc)) + } +} + +func h264LevelString(levelIdc uint8) string { + major := levelIdc / 10 + minor := levelIdc % 10 + if minor == 0 { + return fmt.Sprintf("%d", major) + } + return fmt.Sprintf("%d.%d", major, minor) +} + +func h265ProfileString(profileIdc uint8) string { + switch profileIdc { + case 1: + return "Main" + case 2: + return "Main 10" + case 3: + return "Main Still Picture" + case 4: + return "Range Extensions" + case 5: + return "High Throughput" + case 6: + return "Multiview Main" + case 7: + return "Scalable Main" + case 8: + return "3D Main" + case 9: + return "Screen Content Coding Extensions" + case 10: + return "Scalable Range Extensions" + default: + return strconv.Itoa(int(profileIdc)) + } +} + +func h265LevelString(levelIdc uint8) string { + // H.265 level_idc = 30 * level, so 3.0 = 90, 4.0 = 120, 4.1 = 123 + level := float64(levelIdc) / 30.0 + // Check if it's a clean level like 3.0, 4.0 + if levelIdc%30 == 0 { + return fmt.Sprintf("%.0f", level) + } + return fmt.Sprintf("%.1f", level) +} + +func formatToTrackCodecProps(outFormat format.Format) APIPathTrackCodecProps { + switch outFormat := outFormat.(type) { + case *format.AV1: + props := &APIPathTrackCodecPropsAV1{} + + if outFormat.Profile != nil { + props.Profile = *outFormat.Profile + } + if outFormat.LevelIdx != nil { + props.Level = *outFormat.LevelIdx + } + if outFormat.Tier != nil { + props.Tier = *outFormat.Tier + } + + return props + + case *format.VP9: + props := &APIPathTrackCodecPropsVP9{} + + if outFormat.ProfileID != nil { + props.Profile = *outFormat.ProfileID + } + + return props + + case *format.H265: + props := &APIPathTrackCodecPropsH265{} + + if outFormat.SPS != nil { + var s codecsh265.SPS + if err := s.Unmarshal(outFormat.SPS); err == nil { + props.Width = s.Width() + props.Height = s.Height() + props.Profile = h265ProfileString(s.ProfileTierLevel.GeneralProfileIdc) + props.Level = h265LevelString(s.ProfileTierLevel.GeneralLevelIdc) + } + } + + return props + + case *format.H264: + props := &APIPathTrackCodecPropsH264{} + + if outFormat.SPS != nil { + var s codecsh264.SPS + if err := s.Unmarshal(outFormat.SPS); err == nil { + props.Width = s.Width() + props.Height = s.Height() + props.Profile = h264ProfileString(s.ProfileIdc) + props.Level = h264LevelString(s.LevelIdc) + } + } + + return props + + case *format.Opus: + return &APIPathTrackCodecPropsOpus{ + ChannelCount: outFormat.ChannelCount, + } + + case *format.MPEG4Audio: + props := &APIPathTrackCodecPropsMPEG4Audio{} + + if outFormat.Config != nil { + props.SampleRate = outFormat.Config.SampleRate + props.ChannelCount = int(outFormat.Config.ChannelConfig) + } + + return props + + case *format.AC3: + return &APIPathTrackCodecPropsAC3{ + SampleRate: outFormat.SampleRate, + ChannelCount: outFormat.ChannelCount, + } + + case *format.G711: + return &APIPathTrackCodecPropsG711{ + MULaw: outFormat.MULaw, + SampleRate: outFormat.SampleRate, + ChannelCount: outFormat.ChannelCount, + } + + case *format.LPCM: + return &APIPathTrackCodecPropsLPCM{ + BitDepth: outFormat.BitDepth, + SampleRate: outFormat.SampleRate, + ChannelCount: outFormat.ChannelCount, + } + + default: + return nil + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_recording.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_recording.go new file mode 100644 index 0000000000000000000000000000000000000000..e0cee8cb71daebc0f4aafeaf1e178bb53dd857de --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_recording.go @@ -0,0 +1,21 @@ +package defs + +import "time" + +// APIRecordingSegment is a recording segment. +type APIRecordingSegment struct { + Start time.Time `json:"start"` +} + +// APIRecording is a recording. +type APIRecording struct { + Name string `json:"name"` + Segments []APIRecordingSegment `json:"segments"` +} + +// APIRecordingList is a list of recordings. +type APIRecordingList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []APIRecording `json:"items"` +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtmp.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtmp.go new file mode 100644 index 0000000000000000000000000000000000000000..ee313efc7e82cd88d8d0ae87b31fd2a1ee2f9ad9 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtmp.go @@ -0,0 +1,49 @@ +package defs + +import ( + "time" + + "github.com/google/uuid" +) + +// APIRTMPServer contains methods used by the API and Metrics server. +type APIRTMPServer interface { + APIConnsList() (*APIRTMPConnList, error) + APIConnsGet(uuid.UUID) (*APIRTMPConn, error) + APIConnsKick(uuid.UUID) error +} + +// APIRTMPConnState is the state of a RTMP connection. +type APIRTMPConnState string + +// states. +const ( + APIRTMPConnStateIdle APIRTMPConnState = "idle" + APIRTMPConnStateRead APIRTMPConnState = "read" + APIRTMPConnStatePublish APIRTMPConnState = "publish" +) + +// APIRTMPConn is a RTMP connection. +type APIRTMPConn struct { + ID uuid.UUID `json:"id"` + Created time.Time `json:"created"` + RemoteAddr string `json:"remoteAddr"` + State APIRTMPConnState `json:"state"` + Path string `json:"path"` + Query string `json:"query"` + User string `json:"user"` + UserAgent string `json:"userAgent"` + InboundBytes uint64 `json:"inboundBytes"` + OutboundBytes uint64 `json:"outboundBytes"` + OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"` + // deprecated + BytesReceived uint64 `json:"bytesReceived" deprecated:"true"` + BytesSent uint64 `json:"bytesSent" deprecated:"true"` +} + +// APIRTMPConnList is a list of RTMP connections. +type APIRTMPConnList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []APIRTMPConn `json:"items"` +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtsp.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtsp.go new file mode 100644 index 0000000000000000000000000000000000000000..1b6cc830c5b4036c5c4b698a7636ac4ca1882e61 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtsp.go @@ -0,0 +1,91 @@ +package defs + +import ( + "time" + + "github.com/google/uuid" +) + +// APIRTSPServer contains methods used by the API and Metrics server. +type APIRTSPServer interface { + APIConnsList() (*APIRTSPConnsList, error) + APIConnsGet(uuid.UUID) (*APIRTSPConn, error) + APISessionsList() (*APIRTSPSessionList, error) + APISessionsGet(uuid.UUID) (*APIRTSPSession, error) + APISessionsKick(uuid.UUID) error +} + +// APIRTSPConn is a RTSP connection. +type APIRTSPConn struct { + ID uuid.UUID `json:"id"` + Created time.Time `json:"created"` + RemoteAddr string `json:"remoteAddr"` + Session *uuid.UUID `json:"session"` + Tunnel string `json:"tunnel"` + InboundBytes uint64 `json:"inboundBytes"` + OutboundBytes uint64 `json:"outboundBytes"` + BytesReceived uint64 `json:"bytesReceived" deprecated:"true"` + BytesSent uint64 `json:"bytesSent" deprecated:"true"` +} + +// APIRTSPConnsList is a list of RTSP connections. +type APIRTSPConnsList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []APIRTSPConn `json:"items"` +} + +// APIRTSPSessionState is the state of a RTSP session. +type APIRTSPSessionState string + +// states. +const ( + APIRTSPSessionStateIdle APIRTSPSessionState = "idle" + APIRTSPSessionStateRead APIRTSPSessionState = "read" + APIRTSPSessionStatePublish APIRTSPSessionState = "publish" +) + +// APIRTSPSession is a RTSP session. +type APIRTSPSession struct { + ID uuid.UUID `json:"id"` + Created time.Time `json:"created"` + RemoteAddr string `json:"remoteAddr"` + State APIRTSPSessionState `json:"state"` + Path string `json:"path"` + Query string `json:"query"` + User string `json:"user"` + UserAgent string `json:"userAgent"` + Transport *string `json:"transport"` + Profile *string `json:"profile"` + Conns []uuid.UUID `json:"conns"` + InboundBytes uint64 `json:"inboundBytes"` + InboundRTPPackets uint64 `json:"inboundRTPPackets"` + InboundRTPPacketsLost uint64 `json:"inboundRTPPacketsLost"` + InboundRTPPacketsInError uint64 `json:"inboundRTPPacketsInError"` + InboundRTPPacketsJitter float64 `json:"inboundRTPPacketsJitter"` + InboundRTCPPackets uint64 `json:"inboundRTCPPackets"` + InboundRTCPPacketsInError uint64 `json:"inboundRTCPPacketsInError"` + OutboundBytes uint64 `json:"outboundBytes"` + OutboundRTPPackets uint64 `json:"outboundRTPPackets"` + OutboundRTPPacketsReportedLost uint64 `json:"outboundRTPPacketsReportedLost"` + OutboundRTPPacketsDiscarded uint64 `json:"outboundRTPPacketsDiscarded"` + OutboundRTCPPackets uint64 `json:"outboundRTCPPackets"` + // deprecated + BytesReceived uint64 `json:"bytesReceived" deprecated:"true"` + BytesSent uint64 `json:"bytesSent" deprecated:"true"` + RTPPacketsReceived uint64 `json:"rtpPacketsReceived" deprecated:"true"` + RTPPacketsSent uint64 `json:"rtpPacketsSent" deprecated:"true"` + RTPPacketsLost uint64 `json:"rtpPacketsLost" deprecated:"true"` + RTPPacketsInError uint64 `json:"rtpPacketsInError" deprecated:"true"` + RTPPacketsJitter float64 `json:"rtpPacketsJitter" deprecated:"true"` + RTCPPacketsReceived uint64 `json:"rtcpPacketsReceived" deprecated:"true"` + RTCPPacketsSent uint64 `json:"rtcpPacketsSent" deprecated:"true"` + RTCPPacketsInError uint64 `json:"rtcpPacketsInError" deprecated:"true"` +} + +// APIRTSPSessionList is a list of RTSP sessions. +type APIRTSPSessionList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []APIRTSPSession `json:"items"` +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_srt.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_srt.go new file mode 100644 index 0000000000000000000000000000000000000000..21c5a2e0d150cd62c0849385c3488f49ac174ce1 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_srt.go @@ -0,0 +1,165 @@ +package defs + +import ( + "time" + + "github.com/google/uuid" +) + +// APISRTServer contains methods used by the API and Metrics server. +type APISRTServer interface { + APIConnsList() (*APISRTConnList, error) + APIConnsGet(uuid.UUID) (*APISRTConn, error) + APIConnsKick(uuid.UUID) error +} + +// APISRTConnState is the state of a SRT connection. +type APISRTConnState string + +// states. +const ( + APISRTConnStateIdle APISRTConnState = "idle" + APISRTConnStateRead APISRTConnState = "read" + APISRTConnStatePublish APISRTConnState = "publish" +) + +// APISRTConn is a SRT connection. +type APISRTConn struct { + ID uuid.UUID `json:"id"` + Created time.Time `json:"created"` + RemoteAddr string `json:"remoteAddr"` + State APISRTConnState `json:"state"` + Path string `json:"path"` + Query string `json:"query"` + User string `json:"user"` + + // The metric names/comments are pulled from GoSRT + + // The total number of sent DATA packets, including retransmitted packets + PacketsSent uint64 `json:"packetsSent"` + // The total number of received DATA packets, including retransmitted packets + PacketsReceived uint64 `json:"packetsReceived"` + // The total number of unique DATA packets sent by the SRT sender + PacketsSentUnique uint64 `json:"packetsSentUnique"` + // The total number of unique original, retransmitted or recovered by the packet filter DATA packets + // received in time, decrypted without errors and, as a result, scheduled for delivery to the + // upstream application by the SRT receiver. + PacketsReceivedUnique uint64 `json:"packetsReceivedUnique"` + // The total number of data packets considered or reported as lost at the sender side. + // Does not correspond to the packets detected as lost at the receiver side. + PacketsSendLoss uint64 `json:"packetsSendLoss"` + // The total number of SRT DATA packets detected as presently missing (either reordered or lost) at the receiver side + PacketsReceivedLoss uint64 `json:"packetsReceivedLoss"` + // The total number of retransmitted packets sent by the SRT sender + PacketsRetrans uint64 `json:"packetsRetrans"` + // The total number of retransmitted packets registered at the receiver side + PacketsReceivedRetrans uint64 `json:"packetsReceivedRetrans"` + // The total number of sent ACK (Acknowledgement) control packets + PacketsSentACK uint64 `json:"packetsSentACK"` + // The total number of received ACK (Acknowledgement) control packets + PacketsReceivedACK uint64 `json:"packetsReceivedACK"` + // The total number of sent NAK (Negative Acknowledgement) control packets + PacketsSentNAK uint64 `json:"packetsSentNAK"` + // The total number of received NAK (Negative Acknowledgement) control packets + PacketsReceivedNAK uint64 `json:"packetsReceivedNAK"` + // The total number of sent KM (Key Material) control packets + PacketsSentKM uint64 `json:"packetsSentKM"` + // The total number of received KM (Key Material) control packets + PacketsReceivedKM uint64 `json:"packetsReceivedKM"` + // The total accumulated time in microseconds, during which the SRT sender has some data to transmit, + // including packets that have been sent, but not yet acknowledged + UsSndDuration uint64 `json:"usSndDuration"` + // ?? + PacketsReceivedBelated uint64 `json:"packetsReceivedBelated"` + // The total number of dropped by the SRT sender DATA packets that have no chance to be delivered in time + PacketsSendDrop uint64 `json:"packetsSendDrop"` + // The total number of dropped by the SRT receiver and, as a result, + // not delivered to the upstream application DATA packets + PacketsReceivedDrop uint64 `json:"packetsReceivedDrop"` + // The total number of packets that failed to be decrypted at the receiver side + PacketsReceivedUndecrypt uint64 `json:"packetsReceivedUndecrypt"` + + // Same as packetsReceived, but expressed in bytes, including payload and all the headers (IP, TCP, SRT) + BytesReceived uint64 `json:"bytesReceived"` + // Same as packetsSent, but expressed in bytes, including payload and all the headers (IP, TCP, SRT) + BytesSent uint64 `json:"bytesSent"` + // Same as packetsSentUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT) + BytesSentUnique uint64 `json:"bytesSentUnique"` + // Same as packetsReceivedUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT) + BytesReceivedUnique uint64 `json:"bytesReceivedUnique"` + // Same as packetsReceivedLoss, but expressed in bytes, including payload and all the headers (IP, TCP, SRT), + // bytes for the presently missing (either reordered or lost) packets' payloads are estimated + // based on the average packet size + BytesReceivedLoss uint64 `json:"bytesReceivedLoss"` + // Same as packetsRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT) + BytesRetrans uint64 `json:"bytesRetrans"` + // Same as packetsReceivedRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT) + BytesReceivedRetrans uint64 `json:"bytesReceivedRetrans"` + // Same as PacketsReceivedBelated, but expressed in bytes, including payload and all the headers (IP, TCP, SRT) + BytesReceivedBelated uint64 `json:"bytesReceivedBelated"` + // Same as packetsSendDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT) + BytesSendDrop uint64 `json:"bytesSendDrop"` + // Same as packetsReceivedDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT) + BytesReceivedDrop uint64 `json:"bytesReceivedDrop"` + // Same as packetsReceivedUndecrypt, but expressed in bytes, including payload and all the headers (IP, TCP, SRT) + BytesReceivedUndecrypt uint64 `json:"bytesReceivedUndecrypt"` + + // Current minimum time interval between which consecutive packets are sent, in microseconds + UsPacketsSendPeriod float64 `json:"usPacketsSendPeriod"` + // The maximum number of packets that can be "in flight" + PacketsFlowWindow uint64 `json:"packetsFlowWindow"` + // The number of packets in flight + PacketsFlightSize uint64 `json:"packetsFlightSize"` + // Smoothed round-trip time (SRTT), an exponentially-weighted moving average (EWMA) + // of an endpoint's RTT samples, in milliseconds + MsRTT float64 `json:"msRTT"` + // Current transmission bandwidth, in Mbps + MbpsSendRate float64 `json:"mbpsSendRate"` + // Current receiving bandwidth, in Mbps + MbpsReceiveRate float64 `json:"mbpsReceiveRate"` + // Estimated capacity of the network link, in Mbps + MbpsLinkCapacity float64 `json:"mbpsLinkCapacity"` + // The available space in the sender's buffer, in bytes + BytesAvailSendBuf uint64 `json:"bytesAvailSendBuf"` + // The available space in the receiver's buffer, in bytes + BytesAvailReceiveBuf uint64 `json:"bytesAvailReceiveBuf"` + // Transmission bandwidth limit, in Mbps + MbpsMaxBW float64 `json:"mbpsMaxBW"` + // Maximum Segment Size (MSS), in bytes + ByteMSS uint64 `json:"byteMSS"` + // The number of packets in the sender's buffer that are already scheduled + // for sending or even possibly sent, but not yet acknowledged + PacketsSendBuf uint64 `json:"packetsSendBuf"` + // Instantaneous (current) value of packetsSndBuf, but expressed in bytes, + // including payload and all headers (IP, TCP, SRT) + BytesSendBuf uint64 `json:"bytesSendBuf"` + // The timespan (msec) of packets in the sender's buffer (unacknowledged packets) + MsSendBuf uint64 `json:"msSendBuf"` + // Timestamp-based Packet Delivery Delay value of the peer + MsSendTsbPdDelay uint64 `json:"msSendTsbPdDelay"` + // The number of acknowledged packets in receiver's buffer + PacketsReceiveBuf uint64 `json:"packetsReceiveBuf"` + // Instantaneous (current) value of packetsRcvBuf, expressed in bytes, including payload and all headers (IP, TCP, SRT) + BytesReceiveBuf uint64 `json:"bytesReceiveBuf"` + // The timespan (msec) of acknowledged packets in the receiver's buffer + MsReceiveBuf uint64 `json:"msReceiveBuf"` + // Timestamp-based Packet Delivery Delay value set on the socket via SRTO_RCVLATENCY or SRTO_LATENCY + MsReceiveTsbPdDelay uint64 `json:"msReceiveTsbPdDelay"` + // Instant value of the packet reorder tolerance + PacketsReorderTolerance uint64 `json:"packetsReorderTolerance"` + // Accumulated difference between the current time and the time-to-play of a packet that is received late + PacketsReceivedAvgBelatedTime uint64 `json:"packetsReceivedAvgBelatedTime"` + // Percentage of resent data vs. sent data + PacketsSendLossRate float64 `json:"packetsSendLossRate"` + // Percentage of retransmitted data vs. received data + PacketsReceivedLossRate float64 `json:"packetsReceivedLossRate"` + + OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"` +} + +// APISRTConnList is a list of SRT connections. +type APISRTConnList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []APISRTConn `json:"items"` +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_webrtc.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_webrtc.go new file mode 100644 index 0000000000000000000000000000000000000000..1d6e7fe9c52cf1c2afeba13287162af85e24d04a --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_webrtc.go @@ -0,0 +1,63 @@ +package defs + +import ( + "time" + + "github.com/google/uuid" +) + +// APIWebRTCServer contains methods used by the API and Metrics server. +type APIWebRTCServer interface { + APISessionsList() (*APIWebRTCSessionList, error) + APISessionsGet(uuid.UUID) (*APIWebRTCSession, error) + APISessionsKick(uuid.UUID) error +} + +// APIWebRTCSessionState is the state of a WebRTC connection. +type APIWebRTCSessionState string + +// states. +const ( + APIWebRTCSessionStateRead APIWebRTCSessionState = "read" + APIWebRTCSessionStatePublish APIWebRTCSessionState = "publish" +) + +// APIWebRTCSession is a WebRTC session. +type APIWebRTCSession struct { + ID uuid.UUID `json:"id"` + Created time.Time `json:"created"` + RemoteAddr string `json:"remoteAddr"` + PeerConnectionEstablished bool `json:"peerConnectionEstablished"` + LocalCandidate string `json:"localCandidate"` + RemoteCandidate string `json:"remoteCandidate"` + State APIWebRTCSessionState `json:"state"` + Path string `json:"path"` + Query string `json:"query"` + User string `json:"user"` + UserAgent string `json:"userAgent"` + InboundBytes uint64 `json:"inboundBytes"` + InboundRTPPackets uint64 `json:"inboundRTPPackets"` + InboundRTPPacketsLost uint64 `json:"inboundRTPPacketsLost"` + InboundRTPPacketsJitter float64 `json:"inboundRTPPacketsJitter"` + InboundRTCPPackets uint64 `json:"inboundRTCPPackets"` + OutboundBytes uint64 `json:"outboundBytes"` + OutboundRTPPackets uint64 `json:"outboundRTPPackets"` + OutboundRTCPPackets uint64 `json:"outboundRTCPPackets"` + OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"` + // deprecated + BytesReceived uint64 `json:"bytesReceived" deprecated:"true"` + BytesSent uint64 `json:"bytesSent" deprecated:"true"` + RTPPacketsReceived uint64 `json:"rtpPacketsReceived" deprecated:"true"` + RTPPacketsSent uint64 `json:"rtpPacketsSent" deprecated:"true"` + RTPPacketsLost uint64 `json:"rtpPacketsLost" deprecated:"true"` + RTPPacketsJitter float64 `json:"rtpPacketsJitter" deprecated:"true"` + RTCPPacketsReceived uint64 `json:"rtcpPacketsReceived" deprecated:"true"` + RTCPPacketsSent uint64 `json:"rtcpPacketsSent" deprecated:"true"` +} + +// APIWebRTCSessionList is a list of WebRTC sessions. +type APIWebRTCSessionList struct { + ItemCount int `json:"itemCount"` + PageCount int `json:"pageCount"` + Items []APIWebRTCSession `json:"items"` +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/defs.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/defs.go new file mode 100644 index 0000000000000000000000000000000000000000..21f64a5c53def711567ebdb8144fca6ba55ddb46 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/defs.go @@ -0,0 +1,2 @@ +// Package defs contains shared definitions. +package defs diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path.go new file mode 100644 index 0000000000000000000000000000000000000000..f14d11ca17aa0ecc352109de64ee60fe721800e8 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path.go @@ -0,0 +1,122 @@ +package defs + +import ( + "fmt" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/stream" +) + +// PathNoStreamAvailableError is returned when no one is publishing. +type PathNoStreamAvailableError struct { + PathName string +} + +// Error implements the error interface. +func (e *PathNoStreamAvailableError) Error() string { + return fmt.Sprintf("no stream is available on path '%s'", e.PathName) +} + +// Path is a path. +type Path interface { + Name() string + SafeConf() *conf.Path + ExternalCmdEnv() externalcmd.Environment + RemovePublisher(req PathRemovePublisherReq) + RemoveReader(req PathRemoveReaderReq) +} + +// PathFindPathConfRes contains the response of FindPathConf(). +type PathFindPathConfRes struct { + Conf *conf.Path + User string + Err error +} + +// PathFindPathConfReq contains arguments of FindPathConf(). +type PathFindPathConfReq struct { + AccessRequest PathAccessRequest + Res chan PathFindPathConfRes +} + +// PathDescribeRes contains the response of Describe(). +type PathDescribeRes struct { + Path Path + Stream *stream.Stream + Redirect string + Err error +} + +// PathDescribeReq contains arguments of Describe(). +type PathDescribeReq struct { + AccessRequest PathAccessRequest + Res chan PathDescribeRes +} + +// PathAddPublisherRes contains the response of AddPublisher(). +type PathAddPublisherRes struct { + Path Path + User string + SubStream *stream.SubStream + Err error +} + +// PathAddPublisherReq contains arguments of AddPublisher(). +type PathAddPublisherReq struct { + Author Publisher + Desc *description.Session + UseRTPPackets bool + ReplaceNTP bool + ConfToCompare *conf.Path + AccessRequest PathAccessRequest + Res chan PathAddPublisherRes +} + +// PathRemovePublisherReq contains arguments of RemovePublisher(). +type PathRemovePublisherReq struct { + Author Publisher + Res chan struct{} +} + +// PathAddReaderRes contains the response of AddReader(). +type PathAddReaderRes struct { + Path Path + User string + Stream *stream.Stream + Err error +} + +// PathAddReaderReq contains arguments of AddReader(). +type PathAddReaderReq struct { + Author Reader + AccessRequest PathAccessRequest + Res chan PathAddReaderRes +} + +// PathRemoveReaderReq contains arguments of RemoveReader(). +type PathRemoveReaderReq struct { + Author Reader + Res chan struct{} +} + +// PathSourceStaticSetReadyRes contains the response of SetReady(). +type PathSourceStaticSetReadyRes struct { + SubStream *stream.SubStream + Err error +} + +// PathSourceStaticSetReadyReq contains arguments of SetReady(). +type PathSourceStaticSetReadyReq struct { + Desc *description.Session + UseRTPPackets bool + ReplaceNTP bool + Res chan PathSourceStaticSetReadyRes +} + +// PathSourceStaticSetNotReadyReq contains arguments of SetNotReady(). +type PathSourceStaticSetNotReadyReq struct { + Res chan struct{} +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path_access_request.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path_access_request.go new file mode 100644 index 0000000000000000000000000000000000000000..b44695cb3ba30fe86b63b54af357013ec22bca8f --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path_access_request.go @@ -0,0 +1,45 @@ +package defs + +import ( + "net" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/google/uuid" +) + +// PathAccessRequest is a path access request. +type PathAccessRequest struct { + Name string + Query string + UserAgent string + Publish bool + SkipAuth bool + + // only if skipAuth = false + Proto auth.Protocol + ID *uuid.UUID + Credentials *auth.Credentials + IP net.IP + CustomVerifyFunc func(expectedUser string, expectedPass string) bool +} + +// ToAuthRequest converts a path access request into an authentication request. +func (r *PathAccessRequest) ToAuthRequest() *auth.Request { + return &auth.Request{ + Action: func() conf.AuthAction { + if r.Publish { + return conf.AuthActionPublish + } + return conf.AuthActionRead + }(), + Path: r.Name, + Query: r.Query, + Protocol: r.Proto, + ID: r.ID, + UserAgent: r.UserAgent, + Credentials: r.Credentials, + IP: r.IP, + CustomVerifyFunc: r.CustomVerifyFunc, + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/publisher.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/publisher.go new file mode 100644 index 0000000000000000000000000000000000000000..6eecad47365060a838ba85ee06e850b15c1a5a1f --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/publisher.go @@ -0,0 +1,7 @@ +package defs + +// Publisher is an entity that can publish a stream. +type Publisher interface { + Source + Close() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/reader.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/reader.go new file mode 100644 index 0000000000000000000000000000000000000000..544d2ace195d46beba48ca95c8af7ac7a3676f65 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/reader.go @@ -0,0 +1,7 @@ +package defs + +// Reader is an entity that can read a stream. +type Reader interface { + Close() + APIReaderDescribe() *APIPathReader +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/source.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/source.go new file mode 100644 index 0000000000000000000000000000000000000000..ff89b644e2a07de75fdca351ba9cad0cf7b161df --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/source.go @@ -0,0 +1,46 @@ +package defs + +import ( + "fmt" + "strings" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + + "github.com/bluenviron/mediamtx/internal/formatlabel" + "github.com/bluenviron/mediamtx/internal/logger" +) + +// Source is an entity that can provide a stream. +// it can be: +// - Publisher +// - staticsources.Handler +// - core.sourceRedirect +type Source interface { + logger.Writer + APISourceDescribe() *APIPathSource +} + +// FormatsInfo returns a description of formats. +func FormatsInfo(formats []format.Format) string { + labels := formatlabel.FormatsToLabels(formats) + codecNames := make([]string, len(labels)) + for i, label := range labels { + codecNames[i] = string(label) + } + + return fmt.Sprintf("%d %s (%s)", + len(formats), + func() string { + if len(formats) == 1 { + return "track" + } + return "tracks" + }(), + strings.Join(codecNames, ", ")) +} + +// MediasInfo returns a description of medias. +func MediasInfo(medias []*description.Media) string { + return FormatsInfo(gatherFormats(medias)) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/static_source.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/static_source.go new file mode 100644 index 0000000000000000000000000000000000000000..7113a7de8308f2e3cae430af88ed169f3313a37b --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/static_source.go @@ -0,0 +1,15 @@ +package defs + +import ( + "context" + + "github.com/bluenviron/mediamtx/internal/conf" +) + +// StaticSourceRunParams is the set of params passed to Run(). +type StaticSourceRunParams struct { + Context context.Context + ResolvedSource string + Conf *conf.Path + ReloadConf chan *conf.Path +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper.go new file mode 100644 index 0000000000000000000000000000000000000000..aa4d5018306bee1f788b8088f6163ddd63fd6bdf --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper.go @@ -0,0 +1,79 @@ +// Package errordumper contains a counter that that periodically invokes a callback if the counter is not zero. +package errordumper + +import ( + "sync" + "time" +) + +const ( + callbackPeriod = 1 * time.Second +) + +// Dumper is a counter that periodically invokes a callback if errors were added. +type Dumper struct { + OnReport func(v uint64, last error) + + mutex sync.Mutex + counter uint64 + absCounter uint64 + last error + + terminate chan struct{} + done chan struct{} +} + +// Start starts the counter. +func (c *Dumper) Start() { + c.terminate = make(chan struct{}) + c.done = make(chan struct{}) + + go c.run() +} + +// Stop stops the counter. +func (c *Dumper) Stop() { + close(c.terminate) + <-c.done +} + +// Add adds an error to the counter. +func (c *Dumper) Add(err error) { + c.mutex.Lock() + defer c.mutex.Unlock() + c.counter++ + c.absCounter++ + c.last = err +} + +// Get returns the total number of errors. +func (c *Dumper) Get() uint64 { + c.mutex.Lock() + defer c.mutex.Unlock() + return c.absCounter +} + +func (c *Dumper) run() { + defer close(c.done) + + t := time.NewTicker(callbackPeriod) + defer t.Stop() + + for { + select { + case <-c.terminate: + return + + case <-t.C: + c.mutex.Lock() + var counter uint64 + counter, c.counter = c.counter, 0 + last := c.last + c.mutex.Unlock() + + if counter != 0 { + c.OnReport(counter, last) + } + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c6f2fd38208f6fc6ab5460864bc3c642fa96672e --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper_test.go @@ -0,0 +1,43 @@ +package errordumper + +import ( + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestDumperReport(t *testing.T) { + done := make(chan struct{}) + + c := &Dumper{ + OnReport: func(v uint64, last error) { + require.Equal(t, uint64(1), v) + require.EqualError(t, last, "test error") + close(done) + }, + } + c.Start() + defer c.Stop() + + c.Add(fmt.Errorf("test error")) + + select { + case <-done: + case <-time.After(2 * time.Second): + t.Errorf("should not happen") + } +} + +func TestDumperDoNotReport(t *testing.T) { + c := &Dumper{ + OnReport: func(_ uint64, _ error) { + t.Errorf("should not happen") + }, + } + c.Start() + defer c.Stop() + + <-time.After(2 * time.Second) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd.go new file mode 100644 index 0000000000000000000000000000000000000000..0cc374ea38fcf7fe7d954eecc1e3adbc5cdf60b6 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd.go @@ -0,0 +1,95 @@ +// Package externalcmd allows to launch external commands. +package externalcmd + +import ( + "errors" + "fmt" + "os" + "time" +) + +const ( + restartPause = 5 * time.Second +) + +var errTerminated = errors.New("terminated") + +// OnExitFunc is the prototype of onExit. +type OnExitFunc func(error) + +// Environment is a Cmd environment. +type Environment map[string]string + +// Cmd is an external command. +type Cmd struct { + Pool *Pool + Cmdstr string + Restart bool + Env Environment + OnExit OnExitFunc + + // in + terminate chan struct{} +} + +// Start starts the command. +func (c *Cmd) Start() { + if c.OnExit == nil { + c.OnExit = func(_ error) {} + } + + c.terminate = make(chan struct{}) + + c.Pool.wg.Add(1) + + go c.run() +} + +// Close closes the command. It doesn't wait for the command to exit. +func (c *Cmd) Close() { + close(c.terminate) +} + +func expandEnv(s string, env Environment) string { + return os.Expand(s, func(variable string) string { + if value, ok := env[variable]; ok { + return value + } + return os.Getenv(variable) + }) +} + +func (c *Cmd) run() { + defer c.Pool.wg.Done() + + env := append([]string(nil), os.Environ()...) + for key, val := range c.Env { + env = append(env, key+"="+val) + } + + for { + err := c.runOSSpecific(c.Cmdstr, env) + if errors.Is(err, errTerminated) { + return + } + + if !c.Restart { + if err != nil { + c.OnExit(err) + } + return + } + + if err != nil { + c.OnExit(err) + } else { + c.OnExit(fmt.Errorf("command exited with code 0")) + } + + select { + case <-time.After(restartPause): + case <-c.terminate: + return + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os.go new file mode 100644 index 0000000000000000000000000000000000000000..29d14a797e07a78badd4bd3f8ff8802fdfbc18ea --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os.go @@ -0,0 +1,66 @@ +//go:build !windows + +package externalcmd + +import ( + "errors" + "fmt" + "os" + "os/exec" + "syscall" + + "github.com/kballard/go-shellquote" +) + +func (c *Cmd) runOSSpecific(cmdstr string, env []string) error { + cmdParts, err := shellquote.Split(cmdstr) + if err != nil { + return err + } + + for i, part := range cmdParts { + cmdParts[i] = expandEnv(part, c.Env) + } + + cmd := exec.Command(cmdParts[0], cmdParts[1:]...) + + cmd.Env = env + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + + // set process group in order to allow killing subprocesses + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + + err = cmd.Start() + if err != nil { + return err + } + + cmdDone := make(chan int) + go func() { + cmdDone <- func() int { + err2 := cmd.Wait() + if err2 == nil { + return 0 + } + if ee, ok := errors.AsType[*exec.ExitError](err2); ok { + ee.ExitCode() + } + return 0 + }() + }() + + select { + case <-c.terminate: + // the minus is needed to kill all subprocesses + syscall.Kill(-cmd.Process.Pid, syscall.SIGINT) //nolint:errcheck + <-cmdDone + return errTerminated + + case c := <-cmdDone: + if c != 0 { + return fmt.Errorf("command exited with code %d", c) + } + return nil + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os_windows.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..5f5f2c9e9b3c7f47ebb2f919ba496278462036af --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os_windows.go @@ -0,0 +1,141 @@ +package externalcmd + +import ( + "fmt" + "os" + "os/exec" + "strings" + "syscall" + "unsafe" + + "github.com/kballard/go-shellquote" + "golang.org/x/sys/windows" +) + +// taken from +// https://gist.github.com/hallazzang/76f3970bfc949831808bbebc8ca15209 +func createProcessGroup() (windows.Handle, error) { + h, err := windows.CreateJobObject(nil, nil) + if err != nil { + return 0, err + } + + info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{ + BasicLimitInformation: windows.JOBOBJECT_BASIC_LIMIT_INFORMATION{ + LimitFlags: windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + }, + } + _, err = windows.SetInformationJobObject( + h, + windows.JobObjectExtendedLimitInformation, + uintptr(unsafe.Pointer(&info)), + uint32(unsafe.Sizeof(info))) + if err != nil { + return 0, err + } + + return h, nil +} + +func closeProcessGroup(h windows.Handle) error { + return windows.CloseHandle(h) +} + +func addProcessToGroup(h windows.Handle, p *os.Process) error { + // Combine the required access rights + access := uint32(windows.PROCESS_SET_QUOTA | windows.PROCESS_TERMINATE) + + processHandle, err := windows.OpenProcess(access, false, uint32(p.Pid)) + if err != nil { + return fmt.Errorf("failed to open process: %v", err) + } + defer windows.CloseHandle(processHandle) + + err = windows.AssignProcessToJobObject(h, processHandle) + if err != nil { + return fmt.Errorf("failed to assign process to job object: %v", err) + } + + return nil +} + +func (c *Cmd) runOSSpecific(cmdstr string, env []string) error { + var cmd *exec.Cmd + + // from Golang documentation: + // On Windows, processes receive the whole command line as a single string and do their own parsing. + // Command combines and quotes Args into a command line string with an algorithm compatible with + // applications using CommandLineToArgvW (which is the most common way). Notable exceptions are + // msiexec.exe and cmd.exe (and thus, all batch files), which have a different unquoting algorithm. + // In these or other similar cases, you can do the quoting yourself and provide the full command + // line in SysProcAttr.CmdLine, leaving Args empty. + if strings.HasPrefix(cmdstr, "cmd ") || strings.HasPrefix(cmdstr, "cmd.exe ") { + args := strings.TrimPrefix(strings.TrimPrefix(cmdstr, "cmd "), "cmd.exe ") + args = expandEnv(args, c.Env) + + cmd = exec.Command("cmd.exe") + cmd.SysProcAttr = &syscall.SysProcAttr{ + CmdLine: args, + } + } else { + cmdParts, err := shellquote.Split(cmdstr) + if err != nil { + return err + } + + for i, part := range cmdParts { + cmdParts[i] = expandEnv(part, c.Env) + } + + cmd = exec.Command(cmdParts[0], cmdParts[1:]...) + } + + cmd.Env = env + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + + // create a process group to kill all subprocesses + g, err := createProcessGroup() + if err != nil { + return err + } + + err = cmd.Start() + if err != nil { + return err + } + + err = addProcessToGroup(g, cmd.Process) + if err != nil { + return err + } + + cmdDone := make(chan int) + go func() { + cmdDone <- func() int { + err := cmd.Wait() + if err == nil { + return 0 + } + ee, ok := err.(*exec.ExitError) + if !ok { + return 0 + } + return ee.ExitCode() + }() + }() + + select { + case <-c.terminate: + closeProcessGroup(g) + <-cmdDone + return errTerminated + + case code := <-cmdDone: + closeProcessGroup(g) + if code != 0 { + return fmt.Errorf("command exited with code %d", code) + } + return nil + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_test.go new file mode 100644 index 0000000000000000000000000000000000000000..cc50a4360a379375ee5883a06561701302df2ad4 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_test.go @@ -0,0 +1,44 @@ +package externalcmd + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestCmdRunExpandAfterSplit(t *testing.T) { + // if os.Expand runs before shellquote.Split, a variable value containing a + // single quote produces unbalanced quotes that cause shellquote.Split to fail. + p := &Pool{} + p.Initialize() + + out := filepath.Join(t.TempDir(), "out") + + cmd := &Cmd{ + Pool: p, + Cmdstr: "sh -c 'echo \"$MY_VAR\" > " + out + "'", + Env: Environment{ + "MY_VAR": "it's", + }, + } + cmd.Start() + + poolClosed := make(chan struct{}) + go func() { + p.Close() + close(poolClosed) + }() + + select { + case <-poolClosed: + case <-time.After(10 * time.Second): + t.Fatal("timeout") + } + + byts, err := os.ReadFile(out) + require.NoError(t, err) + require.Equal(t, "it's\n", string(byts)) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/pool.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/pool.go new file mode 100644 index 0000000000000000000000000000000000000000..11852812077a50e023d2c10a45b12e0579cb83a1 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/pool.go @@ -0,0 +1,19 @@ +package externalcmd + +import ( + "sync" +) + +// Pool is a pool of external commands. +type Pool struct { + wg sync.WaitGroup +} + +// Initialize initializes a Pool. +func (p *Pool) Initialize() { +} + +// Close waits for all external commands to exit. +func (p *Pool) Close() { + p.wg.Wait() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label.go new file mode 100644 index 0000000000000000000000000000000000000000..f8f62617ec1e75b2027980f4326368f463305c8f --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label.go @@ -0,0 +1,133 @@ +// Package formatlabel contains format label definitions. +package formatlabel + +import ( + "strings" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" +) + +// Label is a format label. +type Label string + +// labels. +const ( + // video + AV1 Label = "AV1" + VP9 Label = "VP9" + VP8 Label = "VP8" + H265 Label = "H265" + H264 Label = "H264" + MPEG4Video Label = "MPEG-4 Video" + MPEG1Video Label = "MPEG-1/2 Video" + MJPEG Label = "M-JPEG" + // audio + Opus Label = "Opus" + FLAC Label = "FLAC" + Vorbis Label = "Vorbis" + MPEG4Audio Label = "MPEG-4 Audio" + MPEG4AudioLATM Label = "MPEG-4 Audio LATM" + MPEG1Audio Label = "MPEG-1/2 Audio" + AC3 Label = "AC3" + Speex Label = "Speex" + G726 Label = "G726" + G722 Label = "G722" + G711 Label = "G711" + LPCM Label = "LPCM" + // other + MPEGTS Label = "MPEG-TS" + KLV Label = "KLV" + Generic Label = "Generic" +) + +// FormatToLabel returns the label associated with a format. +func FormatToLabel(forma format.Format) Label { + switch forma.(type) { + // video + case *format.AV1: + return AV1 + case *format.VP9: + return VP9 + case *format.VP8: + return VP8 + case *format.H265: + return H265 + case *format.H264: + return H264 + case *format.MPEG4Video: + return MPEG4Video + case *format.MPEG1Video: + return MPEG1Video + case *format.MJPEG: + return MJPEG + // audio + case *format.Opus: + return Opus + case *format.Vorbis: + return Vorbis + case *format.MPEG4Audio: + return MPEG4Audio + case *format.MPEG4AudioLATM: + return MPEG4AudioLATM + case *format.MPEG1Audio: + return MPEG1Audio + case *format.AC3: + return AC3 + case *format.Speex: + return Speex + case *format.G726: + return G726 + case *format.G722: + return G722 + case *format.G711: + return G711 + case *format.LPCM: + return LPCM + // other + case *format.MPEGTS: + return MPEGTS + case *format.KLV: + return KLV + case *format.Generic: + if strings.HasPrefix(strings.ToLower(forma.RTPMap()), "flac/") { + return FLAC + } + } + + return Generic +} + +func gatherFormats(medias []*description.Media) []format.Format { + n := 0 + for _, media := range medias { + n += len(media.Formats) + } + + if n == 0 { + return nil + } + + formats := make([]format.Format, n) + n = 0 + + for _, media := range medias { + n += copy(formats[n:], media.Formats) + } + + return formats +} + +// FormatsToLabels returns labels of given formats. +func FormatsToLabels(formats []format.Format) []Label { + ret := make([]Label, len(formats)) + for i, forma := range formats { + ret[i] = FormatToLabel(forma) + } + return ret +} + +// MediasToLabels returns labels of given medias. +func MediasToLabels(medias []*description.Media) []Label { + return FormatsToLabels(gatherFormats(medias)) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5b46f46bfb4369d328c1456a97046d046b27383a --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label_test.go @@ -0,0 +1,90 @@ +package formatlabel + +import ( + "testing" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/stretchr/testify/require" +) + +func TestFormatToLabel(t *testing.T) { + codecs := []Label{ + FormatToLabel(&format.AV1{}), + FormatToLabel(&format.VP9{}), + FormatToLabel(&format.VP8{}), + FormatToLabel(&format.H265{}), + FormatToLabel(&format.H264{}), + FormatToLabel(&format.MPEG4Video{}), + FormatToLabel(&format.MPEG1Video{}), + FormatToLabel(&format.MJPEG{}), + FormatToLabel(&format.Opus{}), + FormatToLabel(&format.Generic{RTPMa: "FLAC/44100/2"}), + FormatToLabel(&format.Vorbis{}), + FormatToLabel(&format.MPEG4Audio{}), + FormatToLabel(&format.MPEG4AudioLATM{}), + FormatToLabel(&format.MPEG1Audio{}), + FormatToLabel(&format.AC3{}), + FormatToLabel(&format.Speex{}), + FormatToLabel(&format.G726{}), + FormatToLabel(&format.G722{}), + FormatToLabel(&format.G711{}), + FormatToLabel(&format.LPCM{}), + FormatToLabel(&format.MPEGTS{}), + FormatToLabel(&format.KLV{}), + FormatToLabel(&format.Generic{}), + } + + require.Equal(t, []Label{ + AV1, + VP9, + VP8, + H265, + H264, + MPEG4Video, + MPEG1Video, + MJPEG, + Opus, + FLAC, + Vorbis, + MPEG4Audio, + MPEG4AudioLATM, + MPEG1Audio, + AC3, + Speex, + G726, + G722, + G711, + LPCM, + MPEGTS, + KLV, + Generic, + }, codecs) +} + +func TestFormatsToLabels(t *testing.T) { + require.Equal(t, []Label{ + H264, + Opus, + KLV, + Generic, + }, FormatsToLabels([]format.Format{ + &format.H264{}, + &format.Opus{}, + &format.KLV{}, + &format.Generic{}, + })) +} + +func TestMediasToLabels(t *testing.T) { + require.Equal(t, []Label{ + H264, + Opus, + G711, + KLV, + }, MediasToLabels([]*description.Media{ + {Formats: []format.Format{&format.H264{}}}, + {Formats: []format.Format{&format.Opus{}, &format.G711{}}}, + {Formats: []format.Format{&format.KLV{}}}, + })) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/hooks.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/hooks.go new file mode 100644 index 0000000000000000000000000000000000000000..be2a346a12d365b335d7cc90b60a779230cfb2ea --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/hooks.go @@ -0,0 +1,2 @@ +// Package hooks contains hook implementations. +package hooks diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_connect.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_connect.go new file mode 100644 index 0000000000000000000000000000000000000000..0e7e6c2773afd81dc64842db3216a8d3ea21fcf7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_connect.go @@ -0,0 +1,68 @@ +package hooks + +import ( + "net" + + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" +) + +// OnConnectParams are the parameters of OnConnect. +type OnConnectParams struct { + Logger logger.Writer + ExternalCmdPool *externalcmd.Pool + RunOnConnect string + RunOnConnectRestart bool + RunOnDisconnect string + RTSPAddress string + Desc defs.APIPathReader +} + +// OnConnect is the OnConnect hook. +func OnConnect(params OnConnectParams) func() { + var env externalcmd.Environment + var onConnectCmd *externalcmd.Cmd + + if params.RunOnConnect != "" || params.RunOnDisconnect != "" { + _, port, _ := net.SplitHostPort(params.RTSPAddress) + env = externalcmd.Environment{ + "RTSP_PORT": port, + "MTX_CONN_TYPE": string(params.Desc.Type), + "MTX_CONN_ID": params.Desc.ID, + } + } + + if params.RunOnConnect != "" { + params.Logger.Log(logger.Info, "runOnConnect command started") + + onConnectCmd = &externalcmd.Cmd{ + Pool: params.ExternalCmdPool, + Cmdstr: params.RunOnConnect, + Restart: params.RunOnConnectRestart, + Env: env, + OnExit: func(err error) { + params.Logger.Log(logger.Info, "runOnConnect command exited: %v", err) + }, + } + onConnectCmd.Start() + } + + return func() { + if onConnectCmd != nil { + onConnectCmd.Close() + params.Logger.Log(logger.Info, "runOnConnect command stopped") + } + + if params.RunOnDisconnect != "" { + params.Logger.Log(logger.Info, "runOnDisconnect command launched") + cmd := &externalcmd.Cmd{ + Pool: params.ExternalCmdPool, + Cmdstr: params.RunOnDisconnect, + Restart: false, + Env: env, + } + cmd.Start() + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_demand.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_demand.go new file mode 100644 index 0000000000000000000000000000000000000000..516d511204d4a847763a33c7a4f2598082878936 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_demand.go @@ -0,0 +1,62 @@ +package hooks + +import ( + "net/url" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" +) + +// OnDemandParams are the parameters of OnDemand. +type OnDemandParams struct { + Logger logger.Writer + ExternalCmdPool *externalcmd.Pool + Conf *conf.Path + ExternalCmdEnv externalcmd.Environment + Query string +} + +// OnDemand is the OnDemand hook. +func OnDemand(params OnDemandParams) func(string) { + var env externalcmd.Environment + var onDemandCmd *externalcmd.Cmd + + if params.Conf.RunOnDemand != "" || params.Conf.RunOnUnDemand != "" { + env = params.ExternalCmdEnv + env["MTX_QUERY"] = url.QueryEscape(params.Query) + } + + if params.Conf.RunOnDemand != "" { + params.Logger.Log(logger.Info, "runOnDemand command started") + + onDemandCmd = &externalcmd.Cmd{ + Pool: params.ExternalCmdPool, + Cmdstr: params.Conf.RunOnDemand, + Restart: params.Conf.RunOnDemandRestart, + Env: env, + OnExit: func(err error) { + params.Logger.Log(logger.Info, "runOnDemand command exited: %v", err) + }, + } + onDemandCmd.Start() + } + + return func(reason string) { + if onDemandCmd != nil { + onDemandCmd.Close() + params.Logger.Log(logger.Info, "runOnDemand command stopped: %v", reason) + } + + if params.Conf.RunOnUnDemand != "" { + params.Logger.Log(logger.Info, "runOnUnDemand command launched") + cmd := &externalcmd.Cmd{ + Pool: params.ExternalCmdPool, + Cmdstr: params.Conf.RunOnUnDemand, + Restart: false, + Env: env, + } + cmd.Start() + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_init.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_init.go new file mode 100644 index 0000000000000000000000000000000000000000..b88c114834a5afd882553be62e33eaf4ce8e1904 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_init.go @@ -0,0 +1,41 @@ +package hooks + +import ( + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" +) + +// OnInitParams are the parameters of OnInit. +type OnInitParams struct { + Logger logger.Writer + ExternalCmdPool *externalcmd.Pool + Conf *conf.Path + ExternalCmdEnv externalcmd.Environment +} + +// OnInit is the OnInit hook. +func OnInit(params OnInitParams) func() { + var onInitCmd *externalcmd.Cmd + + if params.Conf.RunOnInit != "" { + params.Logger.Log(logger.Info, "runOnInit command started") + onInitCmd = &externalcmd.Cmd{ + Pool: params.ExternalCmdPool, + Cmdstr: params.Conf.RunOnInit, + Restart: params.Conf.RunOnInitRestart, + Env: params.ExternalCmdEnv, + OnExit: func(err error) { + params.Logger.Log(logger.Info, "runOnInit command exited: %v", err) + }, + } + onInitCmd.Start() + } + + return func() { + if onInitCmd != nil { + onInitCmd.Close() + params.Logger.Log(logger.Info, "runOnInit command stopped") + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_read.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_read.go new file mode 100644 index 0000000000000000000000000000000000000000..a221295d042c8baa6e6791cf37c35f5d7bc54c48 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_read.go @@ -0,0 +1,66 @@ +package hooks + +import ( + "net/url" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" +) + +// OnReadParams are the parameters of OnRead. +type OnReadParams struct { + Logger logger.Writer + ExternalCmdPool *externalcmd.Pool + Conf *conf.Path + ExternalCmdEnv externalcmd.Environment + Reader defs.APIPathReader + Query string +} + +// OnRead is the OnRead hook. +func OnRead(params OnReadParams) func() { + var env externalcmd.Environment + var onReadCmd *externalcmd.Cmd + + if params.Conf.RunOnRead != "" || params.Conf.RunOnUnread != "" { + env = params.ExternalCmdEnv + desc := params.Reader + env["MTX_QUERY"] = url.QueryEscape(params.Query) + env["MTX_READER_TYPE"] = string(desc.Type) + env["MTX_READER_ID"] = desc.ID + } + + if params.Conf.RunOnRead != "" { + params.Logger.Log(logger.Info, "runOnRead command started") + onReadCmd = &externalcmd.Cmd{ + Pool: params.ExternalCmdPool, + Cmdstr: params.Conf.RunOnRead, + Restart: params.Conf.RunOnReadRestart, + Env: env, + OnExit: func(err error) { + params.Logger.Log(logger.Info, "runOnRead command exited: %v", err) + }, + } + onReadCmd.Start() + } + + return func() { + if onReadCmd != nil { + onReadCmd.Close() + params.Logger.Log(logger.Info, "runOnRead command stopped") + } + + if params.Conf.RunOnUnread != "" { + params.Logger.Log(logger.Info, "runOnUnread command launched") + cmd := &externalcmd.Cmd{ + Pool: params.ExternalCmdPool, + Cmdstr: params.Conf.RunOnUnread, + Restart: false, + Env: env, + } + cmd.Start() + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_ready.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_ready.go new file mode 100644 index 0000000000000000000000000000000000000000..35b45774a4ce2e20d0dcc0d591cd5fc4cdd94122 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_ready.go @@ -0,0 +1,67 @@ +package hooks + +import ( + "net/url" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" +) + +// OnReadyParams are the parameters of OnReady. +type OnReadyParams struct { + Logger logger.Writer + ExternalCmdPool *externalcmd.Pool + Conf *conf.Path + ExternalCmdEnv externalcmd.Environment + Desc *defs.APIPathSource + Query string +} + +// OnReady is the OnReady hook. +func OnReady(params OnReadyParams) func() { + var env externalcmd.Environment + var onReadyCmd *externalcmd.Cmd + + if params.Conf.RunOnReady != "" || params.Conf.RunOnNotReady != "" { + env = params.ExternalCmdEnv + env["MTX_QUERY"] = url.QueryEscape(params.Query) + if params.Desc != nil { + env["MTX_SOURCE_TYPE"] = string(params.Desc.Type) + env["MTX_SOURCE_ID"] = params.Desc.ID + } + } + + if params.Conf.RunOnReady != "" { + params.Logger.Log(logger.Info, "runOnReady command started") + onReadyCmd = &externalcmd.Cmd{ + Pool: params.ExternalCmdPool, + Cmdstr: params.Conf.RunOnReady, + Restart: params.Conf.RunOnReadyRestart, + Env: env, + OnExit: func(err error) { + params.Logger.Log(logger.Info, "runOnReady command exited: %v", err) + }, + } + onReadyCmd.Start() + } + + return func() { + if onReadyCmd != nil { + onReadyCmd.Close() + params.Logger.Log(logger.Info, "runOnReady command stopped") + } + + if params.Conf.RunOnNotReady != "" { + params.Logger.Log(logger.Info, "runOnNotReady command launched") + cmd := &externalcmd.Cmd{ + Pool: params.ExternalCmdPool, + Cmdstr: params.Conf.RunOnNotReady, + Restart: false, + Env: env, + } + cmd.Start() + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/conf/conf_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/conf/conf_test.go new file mode 100644 index 0000000000000000000000000000000000000000..8a8c51c1426d6de7282c97149da19992699acb95 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/conf/conf_test.go @@ -0,0 +1,41 @@ +//go:build enable_linters + +package conf + +import ( + "os" + "strings" + "testing" + + "github.com/goccy/go-yaml/ast" + "github.com/goccy/go-yaml/parser" + "github.com/goccy/go-yaml/token" + "github.com/stretchr/testify/require" +) + +func checkBooleans(t *testing.T, keys []string, node ast.Node) { + switch n := node.(type) { + case *ast.StringNode: + if n.Token.Type == token.StringType { + val := strings.ToLower(n.Token.Value) + if val == "yes" || val == "no" || val == "on" || val == "off" || val == "y" || val == "n" { + t.Errorf("deprecated bool value '%v: %v'", strings.Join(keys, "."), val) + } + } + + case *ast.MappingNode: + for _, value := range n.Values { + checkBooleans(t, append(keys, value.Key.(*ast.StringNode).Token.Value), value.Value) + } + } +} + +func TestConf(t *testing.T) { + buf, err := os.ReadFile("../../../mediamtx.yml") + require.NoError(t, err) + + file, err := parser.ParseBytes(buf, 0) + require.NoError(t, err) + + checkBooleans(t, nil, file.Docs[0].Body) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/docslinks/docslinks_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/docslinks/docslinks_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0d41c5215709bd70206e5bb73cdeabf85cbddda7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/docslinks/docslinks_test.go @@ -0,0 +1,288 @@ +//go:build enable_linters + +package docslinks + +import ( + "bufio" + "os" + "path" + "path/filepath" + "strconv" + "strings" + "testing" + "unicode" + "unicode/utf8" + + "github.com/stretchr/testify/require" +) + +const ( + repoPath = "../../.." + docsPath = "docs/**/*.md" + additionalDoc = "README.md" +) + +type docFile struct { + anchors map[string]struct{} +} + +type markdownLink struct { + line int + target string +} + +func collectDocFile(docPath string) (docFile, error) { + anchors := make(map[string]struct{}) + anchorCounts := make(map[string]int) + + _, err := scanMarkdown(docPath, func(lineNum int, line string) { + heading, ok := parseHeading(line) + if !ok { + return + } + + anchor := slugifyHeading(heading) + if anchor == "" { + return + } + + count := anchorCounts[anchor] + anchorCounts[anchor] = count + 1 + if count > 0 { + anchor = anchor + "-" + strconv.Itoa(count) + } + + anchors[anchor] = struct{}{} + }) + if err != nil { + return docFile{}, err + } + + return docFile{anchors: anchors}, nil +} + +func collectLinks(docPath string) ([]markdownLink, error) { + var links []markdownLink + + _, err := scanMarkdown(docPath, func(lineNum int, line string) { + for _, target := range extractInlineLinks(line) { + links = append(links, markdownLink{line: lineNum, target: target}) + } + }) + + return links, err +} + +func scanMarkdown(docPath string, cb func(lineNum int, line string)) (map[string]struct{}, error) { + file, err := os.Open(docPath) + if err != nil { + return nil, err + } + defer file.Close() + + activeFence := "" + lineNum := 0 + scanner := bufio.NewScanner(file) + for scanner.Scan() { + lineNum++ + line := scanner.Text() + + if fence, ok := fenceDelimiter(line); ok { + if activeFence == "" { + activeFence = fence + } else if activeFence == fence { + activeFence = "" + } + continue + } + if activeFence != "" { + continue + } + + cb(lineNum, line) + } + + return nil, scanner.Err() +} + +func fenceDelimiter(line string) (string, bool) { + trimmed := strings.TrimLeftFunc(line, unicode.IsSpace) + if trimmed == "" { + return "", false + } + + r, _ := utf8.DecodeRuneInString(trimmed) + if r != '`' && r != '~' { + return "", false + } + + count := 0 + for _, candidate := range trimmed { + if candidate != r { + break + } + count++ + } + if count < 3 { + return "", false + } + + return strings.Repeat(string(r), count), true +} + +func parseHeading(line string) (string, bool) { + trimmed := strings.TrimSpace(line) + if !strings.HasPrefix(trimmed, "#") { + return "", false + } + + level := 0 + for level < len(trimmed) && trimmed[level] == '#' { + level++ + } + if level == 0 || level == len(trimmed) || trimmed[level] != ' ' { + return "", false + } + + heading := strings.TrimSpace(trimmed[level:]) + heading = strings.TrimRight(heading, " #") + return heading, heading != "" +} + +func slugifyHeading(heading string) string { + var b strings.Builder + prevHyphen := false + + for _, r := range strings.ToLower(heading) { + switch { + case unicode.IsLetter(r) || unicode.IsNumber(r): + b.WriteRune(r) + prevHyphen = false + + case unicode.IsSpace(r) || r == '-': + if b.Len() > 0 && !prevHyphen { + b.WriteByte('-') + prevHyphen = true + } + + case r == '/': + if b.Len() > 0 && !prevHyphen { + b.WriteByte('-') + prevHyphen = true + } + + case unicode.IsPunct(r) || unicode.IsSymbol(r): + } + } + + return strings.Trim(b.String(), "-") +} + +func extractInlineLinks(line string) []string { + var out []string + + for i := 0; i < len(line); i++ { + if line[i] != '[' || isImageLink(line, i) { + continue + } + + closeLabel := strings.IndexByte(line[i:], ']') + if closeLabel < 0 { + continue + } + closeLabel += i + if closeLabel+1 >= len(line) || line[closeLabel+1] != '(' { + continue + } + + closeTarget := strings.IndexByte(line[closeLabel+2:], ')') + if closeTarget < 0 { + continue + } + closeTarget += closeLabel + 2 + + target := strings.TrimSpace(line[closeLabel+2 : closeTarget]) + if target != "" { + out = append(out, target) + } + + i = closeTarget + } + + return out +} + +func isImageLink(line string, i int) bool { + return i > 0 && line[i-1] == '!' +} + +func splitLinkTarget(target string) (string, string) { + file, anchor, _ := strings.Cut(target, "#") + return file, anchor +} + +func isInternalDocLink(targetFile string, targetAnchor string) bool { + if targetFile == "" { + return targetAnchor != "" + } + + lower := strings.ToLower(targetFile) + if strings.HasPrefix(lower, "http://") || + strings.HasPrefix(lower, "https://") || + strings.HasPrefix(lower, "mailto:") { + return false + } + + return strings.HasSuffix(lower, ".md") +} + +func toRepoPath(p string) string { + rel, err := filepath.Rel(repoPath, p) + if err != nil { + panic(err) + } + return path.Clean(filepath.ToSlash(rel)) +} + +func TestDocsLinks(t *testing.T) { + docPaths, err := filepath.Glob(repoPath + "/" + docsPath) + require.NoError(t, err) + docPaths = append(docPaths, repoPath+"/"+additionalDoc) + + docs := make(map[string]docFile) + for _, docPath := range docPaths { + doc, err := collectDocFile(docPath) + require.NoError(t, err) + docs[toRepoPath(docPath)] = doc + } + + for _, docPath := range docPaths { + links, err := collectLinks(docPath) + require.NoError(t, err) + + sourceDocPath := toRepoPath(docPath) + for _, link := range links { + targetFile, targetAnchor := splitLinkTarget(link.target) + if !isInternalDocLink(targetFile, targetAnchor) { + continue + } + + resolvedFile := sourceDocPath + if targetFile != "" { + resolvedFile = path.Clean(path.Join(path.Dir(sourceDocPath), targetFile)) + } + + targetDoc, ok := docs[resolvedFile] + if !ok { + t.Errorf("%s:%d: link target %q does not exist", sourceDocPath, link.line, link.target) + continue + } + + if targetAnchor != "" { + if _, ok := targetDoc.anchors[targetAnchor]; !ok { + t.Errorf("%s:%d: anchor %q in link target %q does not exist", sourceDocPath, link.line, targetAnchor, link.target) + } + } + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/docsorder/docsorder_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/docsorder/docsorder_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f74c17b0d09eb6c6b6c1ecf9f9d9c5bb153b23 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/docsorder/docsorder_test.go @@ -0,0 +1,84 @@ +//go:build enable_linters + +package docsorder + +import ( + "fmt" + "os" + "regexp" + "sort" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +const repoPath = "../../.." + +var numberedFileRe = regexp.MustCompile(`^(\d+)-`) + +type numberedFile struct { + name string + numStr string + num int +} + +func TestDocsOrder(t *testing.T) { + entries, err := os.ReadDir(repoPath + "/docs") + require.NoError(t, err) + + for _, entry := range entries { + if !entry.IsDir() { + continue + } + + dirPath := fmt.Sprintf("%s/docs/%s", repoPath, entry.Name()) + + files, err := os.ReadDir(dirPath) + require.NoError(t, err) + + var numbered []numberedFile + for _, f := range files { + if f.IsDir() { + continue + } + m := numberedFileRe.FindStringSubmatch(f.Name()) + if m == nil { + continue + } + num, err2 := strconv.Atoi(m[1]) + if err2 != nil { + t.Errorf("docs/%s/%s: cannot parse numeric prefix %q", entry.Name(), f.Name(), m[1]) + continue + } + numbered = append(numbered, numberedFile{ + name: f.Name(), + numStr: m[1], + num: num, + }) + } + + if len(numbered) == 0 { + continue + } + + sort.Slice(numbered, func(i, j int) bool { + return numbered[i].name < numbered[j].name + }) + + usesPadding := len(numbered) >= 10 + + for _, nf := range numbered { + if usesPadding { + if len(nf.numStr) != 2 { + t.Errorf("docs/%s/%s: expected zero-padded prefix, got %q", entry.Name(), nf.name, nf.numStr) + } + } else { + if strings.HasPrefix(nf.numStr, "0") { + t.Errorf("docs/%s/%s: unexpected zero-padded prefix %q (directory has fewer than 10 files)", entry.Name(), nf.name, nf.numStr) + } + } + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/go2api/go2api_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/go2api/go2api_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0aba3fb1445bde34ed6ff20744192bdca38f6c6a --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/linters/go2api/go2api_test.go @@ -0,0 +1,560 @@ +//go:build enable_linters + +package main + +import ( + "os" + "reflect" + "strings" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/goccy/go-yaml" + "github.com/google/uuid" + "github.com/stretchr/testify/require" +) + +type openAPIProperty struct { + Ref string `yaml:"$ref"` + Type string `yaml:"type"` + Format string `yaml:"format"` + AllOf []openAPIProperty `yaml:"allOf"` + Nullable bool `yaml:"nullable"` + Deprecated bool `yaml:"deprecated"` + Enum []string `yaml:"enum"` + Items *openAPIProperty `yaml:"items"` +} + +func wrapRef(rt reflect.Type, p openAPIProperty) openAPIProperty { + if p.Ref == "" { + return p + } + + if _, ok := goEnumToApi(rt); ok { + p.Type = "string" + } else if rt.Kind() == reflect.Struct { + p.Type = "object" + } + + p.AllOf = []openAPIProperty{{Ref: p.Ref}} + p.Ref = "" + return p +} + +type openAPISchema struct { + Type string `yaml:"type"` + Enum []string `yaml:"enum"` + OneOf []openAPIProperty `yaml:"oneOf"` + Properties map[string]openAPIProperty `yaml:"properties"` +} + +type openAPI struct { + Components struct { + Schemas map[string]openAPISchema `yaml:"schemas"` + } `yaml:"components"` +} + +func schemaName(rt reflect.Type) string { + name := strings.TrimPrefix(rt.Name(), "API") + + if rt.PkgPath() == "github.com/bluenviron/mediamtx/internal/conf" && name == "Path" { + return "PathConf" + } + + if rt == reflect.TypeOf(defs.APIPathTrackCodec("")) { + return "PathTrackCodec" + } + + return name +} + +func goStructToApi(t *testing.T, rt reflect.Type) openAPIProperty { + if rt.Kind() == reflect.Pointer { + prop := goStructToApi(t, rt.Elem()) + prop = wrapRef(rt.Elem(), prop) + prop.Nullable = true + return prop + } + + if _, ok := goEnumToApi(rt); ok { + return openAPIProperty{Ref: "#/components/schemas/" + schemaName(rt)} + } + + if rt == reflect.TypeOf((*defs.APIPathTrackCodecProps)(nil)).Elem() { + return openAPIProperty{ + Type: "object", + AllOf: []openAPIProperty{{Ref: "#/components/schemas/" + schemaName(rt)}}, + Nullable: true, + } + } + + switch { + case rt == reflect.TypeOf(""): + return openAPIProperty{Type: "string"} + + case rt == reflect.TypeOf(int(0)): + return openAPIProperty{Type: "integer", Format: "int64"} + + case rt == reflect.TypeOf(uint(0)): + return openAPIProperty{Type: "integer", Format: "uint64"} + + case rt == reflect.TypeOf(uint64(0)): + return openAPIProperty{Type: "integer", Format: "uint64"} + + case rt == reflect.TypeOf(float64(0)): + return openAPIProperty{Type: "number", Format: "double"} + + case rt == reflect.TypeOf(false): + return openAPIProperty{Type: "boolean"} + + case rt == reflect.TypeOf(uuid.UUID{}): + return openAPIProperty{Type: "string", Format: "uuid"} + + case rt == reflect.TypeOf(time.Time{}) || + rt == reflect.TypeOf(conf.Duration(0)) || + rt == reflect.TypeOf(conf.IPNetwork{}) || + rt == reflect.TypeOf(conf.Credential("")) || + rt == reflect.TypeOf(conf.StringSize(0)): + return openAPIProperty{Type: "string"} + + case rt == reflect.TypeOf(conf.RTSPTransports{}): + return openAPIProperty{ + Type: "array", + Items: &openAPIProperty{ + Type: "string", + Enum: []string{"udp", "multicast", "tcp"}, + }, + } + + case rt.Kind() == reflect.Struct: + return openAPIProperty{ + Ref: "#/components/schemas/" + schemaName(rt), + } + + case rt.Kind() == reflect.Slice: + items := goStructToApi(t, rt.Elem()) + return openAPIProperty{ + Type: "array", + Items: &items, + } + + default: + t.Errorf("unhandled type: %v", rt) + return openAPIProperty{} + } +} + +func goEnumToApi(rt reflect.Type) (openAPISchema, bool) { + switch rt { + case reflect.TypeOf(defs.APIOKStatus("")): + return openAPISchema{Type: "string", Enum: []string{"ok"}}, true + + case reflect.TypeOf(defs.APIErrorStatus("")): + return openAPISchema{Type: "string", Enum: []string{"error"}}, true + + case reflect.TypeOf(defs.APIPathSourceType("")): + return openAPISchema{Type: "string", Enum: []string{ + "hlsSource", + "redirect", + "rpiCameraSource", + "rtmpConn", + "rtmpsConn", + "rtmpSource", + "rtspSession", + "rtspSource", + "rtspsSession", + "srtConn", + "srtSource", + "mpegtsSource", + "rtpSource", + "webRTCSession", + "webRTCSource", + }}, true + + case reflect.TypeOf(defs.APIPathReaderType("")): + return openAPISchema{Type: "string", Enum: []string{ + "hlsSession", + "rtmpConn", + "rtmpsConn", + "rtspConn", + "rtspSession", + "rtspsConn", + "rtspsSession", + "srtConn", + "webRTCSession", + }}, true + + case reflect.TypeOf(defs.APIPathTrackCodec("")): + return openAPISchema{Type: "string", Enum: []string{ + "AV1", + "VP9", + "VP8", + "H265", + "H264", + "MPEG-4 Video", + "MPEG-1/2 Video", + "M-JPEG", + "Opus", + "Vorbis", + "MPEG-4 Audio", + "MPEG-4 Audio LATM", + "MPEG-1/2 Audio", + "AC3", + "Speex", + "G726", + "G722", + "G711", + "LPCM", + "MPEG-TS", + "KLV", + "Generic", + }}, true + + case reflect.TypeOf(conf.AlwaysAvailableTrackCodec("")): + return openAPISchema{Type: "string", Enum: []string{ + "AV1", + "VP9", + "H265", + "H264", + "MPEG4Audio", + "Opus", + "G711", + "LPCM", + }}, true + + case reflect.TypeOf(conf.AuthAction("")): + return openAPISchema{Type: "string", Enum: []string{ + "publish", + "read", + "playback", + "api", + "metrics", + "pprof", + }}, true + + case reflect.TypeOf(conf.AuthMethod("")): + return openAPISchema{Type: "string", Enum: []string{ + "internal", + "http", + "jwt", + }}, true + + case reflect.TypeOf(conf.Encryption("")): + return openAPISchema{Type: "string", Enum: []string{ + "no", + "optional", + "strict", + }}, true + + case reflect.TypeOf(conf.HLSVariant(0)): + return openAPISchema{Type: "string", Enum: []string{ + "mpegts", + "fmp4", + "lowLatency", + }}, true + + case reflect.TypeOf(conf.LogDestination(0)): + return openAPISchema{Type: "string", Enum: []string{ + "stdout", + "file", + "syslog", + }}, true + + case reflect.TypeOf(conf.LogLevel(0)): + return openAPISchema{Type: "string", Enum: []string{ + "error", + "warn", + "info", + "debug", + }}, true + + case reflect.TypeOf(conf.RecordFormat("")): + return openAPISchema{Type: "string", Enum: []string{ + "fmp4", + "mpegts", + }}, true + + case reflect.TypeOf(conf.RTSPAuthMethod(0)): + return openAPISchema{Type: "string", Enum: []string{ + "basic", + "digest", + }}, true + + case reflect.TypeOf(conf.RTSPRangeType("")): + return openAPISchema{Type: "string", Enum: []string{ + "", + "clock", + "npt", + "smpte", + }}, true + + case reflect.TypeOf(conf.RTSPTransport{}): + return openAPISchema{Type: "string", Enum: []string{ + "udp", + "multicast", + "tcp", + "automatic", + }}, true + + case reflect.TypeOf(defs.APIRTMPConnState("")): + return openAPISchema{Type: "string", Enum: []string{"idle", "read", "publish"}}, true + + case reflect.TypeOf(defs.APIWebRTCSessionState("")): + return openAPISchema{Type: "string", Enum: []string{"read", "publish"}}, true + + case reflect.TypeOf(defs.APISRTConnState("")): + return openAPISchema{Type: "string", Enum: []string{"idle", "read", "publish"}}, true + + case reflect.TypeOf(defs.APIRTSPSessionState("")): + return openAPISchema{Type: "string", Enum: []string{"idle", "read", "publish"}}, true + } + + return openAPISchema{}, false +} + +func TestGo2API(t *testing.T) { + byts, err := os.ReadFile("../../../api/openapi.yaml") + require.NoError(t, err) + + var doc openAPI + err = yaml.Unmarshal(byts, &doc) + require.NoError(t, err) + + t.Run("structs", func(t *testing.T) { + for _, ca := range []struct { + openAPIKey string + goStruct any + }{ + { + "AlwaysAvailableTrack", + conf.AlwaysAvailableTrack{}, + }, + { + "AuthInternalUser", + conf.AuthInternalUser{}, + }, + { + "AuthInternalUserPermission", + conf.AuthInternalUserPermission{}, + }, + { + "GlobalConf", + conf.Conf{}, + }, + { + "HLSMuxer", + defs.APIHLSMuxer{}, + }, + { + "HLSMuxerList", + defs.APIHLSMuxerList{}, + }, + { + "HLSSession", + defs.APIHLSSession{}, + }, + { + "HLSSessionList", + defs.APIHLSSessionList{}, + }, + { + "Info", + defs.APIInfo{}, + }, + { + "Path", + defs.APIPath{}, + }, + { + "PathConf", + conf.Path{}, + }, + { + "PathConfList", + defs.APIPathConfList{}, + }, + { + "PathList", + defs.APIPathList{}, + }, + { + "PathReader", + defs.APIPathReader{}, + }, + { + "PathSource", + defs.APIPathSource{}, + }, + { + "PathTrack", + defs.APIPathTrack{}, + }, + { + "PathTrackCodecPropsAV1", + defs.APIPathTrackCodecPropsAV1{}, + }, + { + "PathTrackCodecPropsVP9", + defs.APIPathTrackCodecPropsVP9{}, + }, + { + "PathTrackCodecPropsH265", + defs.APIPathTrackCodecPropsH265{}, + }, + { + "PathTrackCodecPropsH264", + defs.APIPathTrackCodecPropsH264{}, + }, + { + "PathTrackCodecPropsOpus", + defs.APIPathTrackCodecPropsOpus{}, + }, + { + "PathTrackCodecPropsMPEG4Audio", + defs.APIPathTrackCodecPropsMPEG4Audio{}, + }, + { + "PathTrackCodecPropsAC3", + defs.APIPathTrackCodecPropsAC3{}, + }, + { + "PathTrackCodecPropsG711", + defs.APIPathTrackCodecPropsG711{}, + }, + { + "PathTrackCodecPropsLPCM", + defs.APIPathTrackCodecPropsLPCM{}, + }, + { + "Recording", + defs.APIRecording{}, + }, + { + "RecordingList", + defs.APIRecordingList{}, + }, + { + "RecordingSegment", + defs.APIRecordingSegment{}, + }, + { + "RTMPConn", + defs.APIRTMPConn{}, + }, + { + "RTMPConnList", + defs.APIRTMPConnList{}, + }, + { + "RTSPConn", + defs.APIRTSPConn{}, + }, + { + "RTSPConnList", + defs.APIRTSPConnsList{}, + }, + { + "RTSPSession", + defs.APIRTSPSession{}, + }, + { + "RTSPSessionList", + defs.APIRTSPSessionList{}, + }, + { + "SRTConn", + defs.APISRTConn{}, + }, + { + "SRTConnList", + defs.APISRTConnList{}, + }, + { + "WebRTCSession", + defs.APIWebRTCSession{}, + }, + { + "WebRTCSessionList", + defs.APIWebRTCSessionList{}, + }, + } { + t.Run(ca.openAPIKey, func(t *testing.T) { + content1 := doc.Components.Schemas[ca.openAPIKey] + + content2 := openAPISchema{ + Type: "object", + Properties: make(map[string]openAPIProperty), + } + + ty := reflect.TypeOf(ca.goStruct) + + for i := range ty.NumField() { + sf := ty.Field(i) + js := sf.Tag.Get("json") + name, _, _ := strings.Cut(js, ",") + deprecated := sf.Tag.Get("deprecated") == "true" + + if name != "" && name != "-" && name != "paths" && name != "pathDefaults" && + (!strings.Contains(js, ",omitempty") || deprecated) { + prop := goStructToApi(t, sf.Type) + prop.Deprecated = deprecated + if deprecated { + prop = wrapRef(sf.Type, prop) + } + content2.Properties[name] = prop + } + } + + require.Equal(t, content2, content1) + }) + } + }) + + t.Run("oneOfs", func(t *testing.T) { + require.Equal(t, openAPISchema{OneOf: []openAPIProperty{ + {Ref: "#/components/schemas/PathTrackCodecPropsAV1"}, + {Ref: "#/components/schemas/PathTrackCodecPropsVP9"}, + {Ref: "#/components/schemas/PathTrackCodecPropsH265"}, + {Ref: "#/components/schemas/PathTrackCodecPropsH264"}, + {Ref: "#/components/schemas/PathTrackCodecPropsOpus"}, + {Ref: "#/components/schemas/PathTrackCodecPropsMPEG4Audio"}, + {Ref: "#/components/schemas/PathTrackCodecPropsAC3"}, + {Ref: "#/components/schemas/PathTrackCodecPropsG711"}, + {Ref: "#/components/schemas/PathTrackCodecPropsLPCM"}, + }}, doc.Components.Schemas["PathTrackCodecProps"]) + }) + + t.Run("enums", func(t *testing.T) { + for _, rt := range []reflect.Type{ + reflect.TypeOf(defs.APIOKStatus("")), + reflect.TypeOf(defs.APIErrorStatus("")), + reflect.TypeOf(defs.APIPathSourceType("")), + reflect.TypeOf(defs.APIPathReaderType("")), + reflect.TypeOf(defs.APIPathTrackCodec("")), + reflect.TypeOf(conf.AlwaysAvailableTrackCodec("")), + reflect.TypeOf(conf.AuthAction("")), + reflect.TypeOf(conf.AuthMethod("")), + reflect.TypeOf(conf.Encryption("")), + reflect.TypeOf(conf.HLSVariant(0)), + reflect.TypeOf(conf.LogDestination(0)), + reflect.TypeOf(conf.LogLevel(0)), + reflect.TypeOf(conf.RecordFormat("")), + reflect.TypeOf(conf.RTSPAuthMethod(0)), + reflect.TypeOf(conf.RTSPRangeType("")), + reflect.TypeOf(conf.RTSPTransport{}), + reflect.TypeOf(defs.APIRTMPConnState("")), + reflect.TypeOf(defs.APIRTSPSessionState("")), + reflect.TypeOf(defs.APISRTConnState("")), + reflect.TypeOf(defs.APIWebRTCSessionState("")), + } { + t.Run(rt.Name(), func(t *testing.T) { + content1 := doc.Components.Schemas[schemaName(rt)] + content2, ok := goEnumToApi(rt) + require.True(t, ok) + require.Equal(t, content2, content1) + }) + } + }) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination.go new file mode 100644 index 0000000000000000000000000000000000000000..9b3a68dad62aa488073ee32dc65d9be2e9e98ed3 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination.go @@ -0,0 +1,24 @@ +package logger + +import ( + "time" +) + +// Destination is a log destination. +type Destination int + +const ( + // DestinationStdout writes logs to the standard output. + DestinationStdout Destination = iota + + // DestinationFile writes logs to a file. + DestinationFile + + // DestinationSyslog writes logs to the system logger. + DestinationSyslog +) + +type destination interface { + log(time.Time, Level, string, ...any) + close() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_file.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_file.go new file mode 100644 index 0000000000000000000000000000000000000000..926cd860bd383790e310342dc515ffd82edad179 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_file.go @@ -0,0 +1,54 @@ +package logger + +import ( + "bytes" + "fmt" + "os" + "strconv" + "time" +) + +type destinationFile struct { + structured bool + file *os.File + buf bytes.Buffer +} + +func newDestinationFile(structured bool, filePath string) (destination, error) { + f, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + return nil, err + } + + return &destinationFile{ + structured: structured, + file: f, + }, nil +} + +func (d *destinationFile) log(t time.Time, level Level, format string, args ...any) { + d.buf.Reset() + + if d.structured { + d.buf.WriteString(`{"timestamp":"`) + d.buf.WriteString(t.Format(time.RFC3339Nano)) + d.buf.WriteString(`","level":"`) + writeLevel(&d.buf, level, false) + d.buf.WriteString(`","message":`) + d.buf.WriteString(strconv.Quote(fmt.Sprintf(format, args...))) + d.buf.WriteString(`}`) + d.buf.WriteByte('\n') + } else { + writePlainTime(&d.buf, t, false) + writeLevel(&d.buf, level, false) + d.buf.WriteByte(' ') + fmt.Fprintf(&d.buf, format, args...) + d.buf.WriteByte('\n') + } + + d.file.Write(d.buf.Bytes()) //nolint:errcheck +} + +func (d *destinationFile) close() { + d.file.Close() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_stdout.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_stdout.go new file mode 100644 index 0000000000000000000000000000000000000000..de9702a490ec18cd1ccf093f51ef68f69d354a84 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_stdout.go @@ -0,0 +1,53 @@ +package logger + +import ( + "bytes" + "fmt" + "io" + "os" + "strconv" + "time" + + "golang.org/x/term" +) + +type destinationStdout struct { + structured bool + stdout io.Writer + useColor bool + buf bytes.Buffer +} + +func newDestionationStdout(structured bool, stdout io.Writer) destination { + return &destinationStdout{ + structured: structured, + stdout: stdout, + useColor: term.IsTerminal(int(os.Stdout.Fd())), + } +} + +func (d *destinationStdout) log(t time.Time, level Level, format string, args ...any) { + d.buf.Reset() + + if d.structured { + d.buf.WriteString(`{"timestamp":"`) + d.buf.WriteString(t.Format(time.RFC3339Nano)) + d.buf.WriteString(`","level":"`) + writeLevel(&d.buf, level, false) + d.buf.WriteString(`","message":`) + d.buf.WriteString(strconv.Quote(fmt.Sprintf(format, args...))) + d.buf.WriteString(`}`) + d.buf.WriteByte('\n') + } else { + writePlainTime(&d.buf, t, d.useColor) + writeLevel(&d.buf, level, d.useColor) + d.buf.WriteByte(' ') + fmt.Fprintf(&d.buf, format, args...) + d.buf.WriteByte('\n') + } + + d.stdout.Write(d.buf.Bytes()) //nolint:errcheck +} + +func (d *destinationStdout) close() { +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_syslog.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_syslog.go new file mode 100644 index 0000000000000000000000000000000000000000..6d210bdaf9fe4a37fadf5042420b0a2fbdac6a58 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_syslog.go @@ -0,0 +1,47 @@ +//go:build !darwin && !windows + +package logger + +import ( + "bytes" + "fmt" + "log/syslog" + "time" +) + +type destinationSysLog struct { + syslog *syslog.Writer + buf bytes.Buffer +} + +func newDestinationSyslog(prefix string) (destination, error) { + syslog, err := syslog.New(syslog.LOG_DAEMON, prefix) + if err != nil { + return nil, err + } + + return &destinationSysLog{ + syslog: syslog, + }, nil +} + +func (d *destinationSysLog) log(_ time.Time, level Level, format string, args ...any) { + d.buf.Reset() + + fmt.Fprintf(&d.buf, format, args...) + + switch level { + case Debug: + d.syslog.Debug(d.buf.String()) //nolint:errcheck + case Info: + d.syslog.Info(d.buf.String()) //nolint:errcheck + case Warn: + d.syslog.Warning(d.buf.String()) //nolint:errcheck + case Error: + d.syslog.Err(d.buf.String()) //nolint:errcheck + } +} + +func (d *destinationSysLog) close() { + d.syslog.Close() //nolint:errcheck +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_syslog_darwin.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_syslog_darwin.go new file mode 100644 index 0000000000000000000000000000000000000000..16cd02b3fab4a60e9020b72262be7df5319627a7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_syslog_darwin.go @@ -0,0 +1,7 @@ +package logger + +import "fmt" + +func newDestinationSyslog(_ string) (destination, error) { + return nil, fmt.Errorf("syslog is not available on macOS and Windows") +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_syslog_windows.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_syslog_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..16cd02b3fab4a60e9020b72262be7df5319627a7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/destination_syslog_windows.go @@ -0,0 +1,7 @@ +package logger + +import "fmt" + +func newDestinationSyslog(_ string) (destination, error) { + return nil, fmt.Errorf("syslog is not available on macOS and Windows") +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/level.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/level.go new file mode 100644 index 0000000000000000000000000000000000000000..85249ab12cdb5178b15723980dcbd27de73a9a6d --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/level.go @@ -0,0 +1,12 @@ +package logger + +// Level is a log level. +type Level int + +// Log levels. +const ( + Debug Level = iota + 1 + Info + Warn + Error +) diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/logger.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..7a844754635c739173ef9f050049a1408d50abb4 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/logger.go @@ -0,0 +1,161 @@ +// Package logger contains a logger implementation. +package logger + +import ( + "bytes" + "io" + "os" + "sync" + "time" + + "github.com/gookit/color" +) + +// Logger is a log handler. +type Logger struct { + Level Level + Destinations []Destination + Structured bool + File string + SysLogPrefix string + + timeNow func() time.Time + stdout io.Writer + destinations []destination + mutex sync.Mutex +} + +// Initialize initializes Logger. +func (l *Logger) Initialize() error { + if l.timeNow == nil { + l.timeNow = time.Now + } + if l.stdout == nil { + l.stdout = os.Stdout + } + + for _, destType := range l.Destinations { + switch destType { + case DestinationStdout: + l.destinations = append(l.destinations, newDestionationStdout(l.Structured, l.stdout)) + + case DestinationFile: + dest, err := newDestinationFile(l.Structured, l.File) + if err != nil { + l.Close() + return err + } + l.destinations = append(l.destinations, dest) + + case DestinationSyslog: + dest, err := newDestinationSyslog(l.SysLogPrefix) + if err != nil { + l.Close() + return err + } + l.destinations = append(l.destinations, dest) + } + } + + return nil +} + +// Close closes a log handler. +func (l *Logger) Close() { + for _, dest := range l.destinations { + dest.close() + } +} + +// https://golang.org/src/log/log.go#L78 +func itoa(i int, wid int) []byte { + // Assemble decimal in reverse order. + var b [20]byte + bp := len(b) - 1 + for i >= 10 || wid > 1 { + wid-- + q := i / 10 + b[bp] = byte('0' + i - q*10) + bp-- + i = q + } + // i < 10 + b[bp] = byte('0' + i) + return b[bp:] +} + +func writePlainTime(buf *bytes.Buffer, t time.Time, useColor bool) { + var intbuf bytes.Buffer + + // date + year, month, day := t.Date() + intbuf.Write(itoa(year, 4)) + intbuf.WriteByte('/') + intbuf.Write(itoa(int(month), 2)) + intbuf.WriteByte('/') + intbuf.Write(itoa(day, 2)) + intbuf.WriteByte(' ') + + // time + hour, minute, sec := t.Clock() + intbuf.Write(itoa(hour, 2)) + intbuf.WriteByte(':') + intbuf.Write(itoa(minute, 2)) + intbuf.WriteByte(':') + intbuf.Write(itoa(sec, 2)) + intbuf.WriteByte(' ') + + if useColor { + buf.WriteString(color.RenderString(color.Gray.Code(), intbuf.String())) + } else { + buf.WriteString(intbuf.String()) + } +} + +func writeLevel(buf *bytes.Buffer, level Level, useColor bool) { + switch level { + case Debug: + if useColor { + buf.WriteString(color.RenderString(color.Debug.Code(), "DEB")) + } else { + buf.WriteString("DEB") + } + + case Info: + if useColor { + buf.WriteString(color.RenderString(color.Green.Code(), "INF")) + } else { + buf.WriteString("INF") + } + + case Warn: + if useColor { + buf.WriteString(color.RenderString(color.Warn.Code(), "WAR")) + } else { + buf.WriteString("WAR") + } + + case Error: + if useColor { + buf.WriteString(color.RenderString(color.Error.Code(), "ERR")) + } else { + buf.WriteString("ERR") + } + } +} + +// Log writes a log entry. +func (l *Logger) Log(level Level, format string, args ...any) { + if level < l.Level { + return + } + + l.mutex.Lock() + defer l.mutex.Unlock() + + t := l.timeNow() + + for _, dest := range l.destinations { + dest.log(t, level, format, args...) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/logger_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/logger_test.go new file mode 100644 index 0000000000000000000000000000000000000000..d542e294baee27304946351e03263f15eed737dd --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/logger_test.go @@ -0,0 +1,76 @@ +package logger + +import ( + "bytes" + "os" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestLoggerToStdout(t *testing.T) { + for _, ca := range []string{ + "plain", + "structured", + } { + t.Run(ca, func(t *testing.T) { + var buf bytes.Buffer + + l := &Logger{ + Destinations: []Destination{DestinationStdout}, + Structured: (ca == "structured"), + timeNow: func() time.Time { return time.Date(2003, 11, 4, 23, 15, 8, 431232, time.UTC) }, + stdout: &buf, + } + err := l.Initialize() + require.NoError(t, err) + defer l.Close() + + l.Log(Info, "test format %d", 123) + + if ca == "plain" { + require.Equal(t, "2003/11/04 23:15:08 INF test format 123\n", buf.String()) + } else { + require.Equal(t, `{"timestamp":"2003-11-04T23:15:08.000431232Z",`+ + `"level":"INF","message":"test format 123"}`+"\n", buf.String()) + } + }) + } +} + +func TestLoggerToFile(t *testing.T) { + for _, ca := range []string{ + "plain", + "structured", + } { + t.Run(ca, func(t *testing.T) { + tempFile, err := os.CreateTemp(t.TempDir(), "mtx-logger-") + require.NoError(t, err) + defer tempFile.Close() + + l := &Logger{ + Level: Debug, + Destinations: []Destination{DestinationFile}, + Structured: ca == "structured", + File: tempFile.Name(), + timeNow: func() time.Time { return time.Date(2003, 11, 4, 23, 15, 8, 0, time.UTC) }, + } + err = l.Initialize() + require.NoError(t, err) + defer l.Close() + + l.Log(Info, "test format %d", 123) + + buf, err := os.ReadFile(tempFile.Name()) + require.NoError(t, err) + + if ca == "plain" { + require.Equal(t, "2003/11/04 23:15:08 INF test format 123\n", string(buf)) + } else { + require.Equal(t, `{"timestamp":"2003-11-04T23:15:08Z",`+ + `"level":"INF","message":"test format 123"}`+"\n", string(buf)) + } + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/writer.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/writer.go new file mode 100644 index 0000000000000000000000000000000000000000..86cbd942aefb0f4a0305ec5dde54485797668171 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/logger/writer.go @@ -0,0 +1,6 @@ +package logger + +// Writer is an object that provides a log method. +type Writer interface { + Log(Level, string, ...any) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/metrics/metrics.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/metrics/metrics.go new file mode 100644 index 0000000000000000000000000000000000000000..0e42cfba132c3b1bb56d3fbe07121f383dbcf191 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/metrics/metrics.go @@ -0,0 +1,1095 @@ +// Package metrics contains the metrics provider. +package metrics //nolint:revive + +import ( + "fmt" + "net" + "net/http" + "reflect" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/gin-gonic/gin" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/httpp" +) + +func interfaceIsEmpty(i any) bool { + return reflect.ValueOf(i).Kind() != reflect.Pointer || reflect.ValueOf(i).IsNil() +} + +func sortedKeys[T any](paths map[string]T) []string { + ret := make([]string, len(paths)) + i := 0 + for name := range paths { + ret[i] = name + i++ + } + sort.Strings(ret) + return ret +} + +func tags(m map[string]string) string { + var b strings.Builder + b.WriteByte('{') + first := true + for _, k := range sortedKeys(m) { + if !first { + b.WriteByte(',') + } + first = false + b.WriteString(k) + b.WriteString("=\"") + b.WriteString(m[k]) + b.WriteByte('"') + } + b.WriteByte('}') + return b.String() +} + +func metric(out *strings.Builder, key string, tags string, value int64) { + out.WriteString(key) + out.WriteString(tags) + out.WriteByte(' ') + out.WriteString(strconv.FormatInt(value, 10)) + out.WriteByte('\n') +} + +func metricFloat(out *strings.Builder, key string, tags string, value float64) { + out.WriteString(key) + out.WriteString(tags) + out.WriteByte(' ') + out.WriteString(strconv.FormatFloat(value, 'f', -1, 64)) + out.WriteByte('\n') +} + +type metricsType string + +const ( + metricsTypePaths metricsType = "paths" + metricsTypeHLSSessions metricsType = "hls_sessions" + metricsTypeHLSMuxers metricsType = "hls_muxers" + metricsTypeRTSPConns metricsType = "rtsp_conns" + metricsTypeRTSPSessions metricsType = "rtsp_sessions" + metricsTypeRTSPSConns metricsType = "rtsps_conns" + metricsTypeRTSPSSessions metricsType = "rtsps_sessions" + metricsTypeRTMPConns metricsType = "rtmp_conns" + metricsTypeRTMPSConns metricsType = "rtmps_conns" + metricsTypeSRTConns metricsType = "srt_conns" + metricsTypeWebRTCSessions metricsType = "webrtc_sessions" + metricsTypeMoQSessions metricsType = "moq_sessions" +) + +type metricsAuthManager interface { + Authenticate(req *auth.Request) (string, *auth.Error) +} + +type metricsParent interface { + logger.Writer +} + +// Metrics is a metrics provider. +type Metrics struct { + Address string + DumpPackets bool + Encryption bool + ServerKey string + ServerCert string + AllowOrigins []string + TrustedProxies conf.IPNetworks + ReadTimeout conf.Duration + WriteTimeout conf.Duration + AuthManager metricsAuthManager + Parent metricsParent + + httpServer *httpp.Server + mutex sync.RWMutex + pathManager defs.APIPathManager + hlsServer defs.APIHLSServer + rtspServer defs.APIRTSPServer + rtspsServer defs.APIRTSPServer + rtmpServer defs.APIRTMPServer + rtmpsServer defs.APIRTMPServer + srtServer defs.APISRTServer + webRTCServer defs.APIWebRTCServer + moqServer defs.APIMoQServer +} + +// Initialize initializes metrics. +func (m *Metrics) Initialize() error { + router := gin.New() + router.SetTrustedProxies(m.TrustedProxies.ToTrustedProxies()) //nolint:errcheck + router.Use(m.middlewarePreflightRequests) + router.Use(m.middlewareAuth) + + router.GET("/metrics", m.onMetrics) + + m.httpServer = &httpp.Server{ + Address: m.Address, + AllowOrigins: m.AllowOrigins, + DumpPackets: m.DumpPackets, + DumpPacketsPrefix: "metrics_server_conn", + ReadTimeout: time.Duration(m.ReadTimeout), + WriteTimeout: time.Duration(m.WriteTimeout), + Encryption: m.Encryption, + ServerCert: m.ServerCert, + ServerKey: m.ServerKey, + Handler: router, + Parent: m, + } + err := m.httpServer.Initialize() + if err != nil { + return err + } + + str := "started with listener on " + m.Address + if !m.Encryption { + str += " (TCP/HTTP)" + } else { + str += " (TCP/HTTPS)" + } + m.Log(logger.Info, str) + + return nil +} + +// Close closes Metrics. +func (m *Metrics) Close() { + m.Log(logger.Info, "closing") + m.httpServer.Close() +} + +// Log implements logger.Writer. +func (m *Metrics) Log(level logger.Level, format string, args ...any) { + m.Parent.Log(level, "[metrics] "+format, args...) +} + +func (m *Metrics) middlewarePreflightRequests(ctx *gin.Context) { + if ctx.Request.Method == http.MethodOptions && + ctx.Request.Header.Get("Access-Control-Request-Method") != "" { + ctx.Header("Access-Control-Allow-Methods", "OPTIONS, GET") + ctx.Header("Access-Control-Allow-Headers", "Authorization") + ctx.AbortWithStatus(http.StatusNoContent) + return + } +} + +func (m *Metrics) writeErrorNoLog(ctx *gin.Context, status int, err error) { + ctx.AbortWithStatusJSON(status, &defs.APIError{ + Status: defs.APIErrorStatusError, + Error: err.Error(), + }) +} + +func (m *Metrics) middlewareAuth(ctx *gin.Context) { + req := &auth.Request{ + Action: conf.AuthActionMetrics, + Query: ctx.Request.URL.RawQuery, + Credentials: httpp.Credentials(ctx.Request), + IP: net.ParseIP(ctx.ClientIP()), + } + + _, err := m.AuthManager.Authenticate(req) + if err != nil { + auth.DelayBruteForce(err) + + if err.AskCredentials { + ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`) + m.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return + } + + m.Log(logger.Info, "connection %v failed to authenticate: %v", httpp.RemoteAddr(ctx), err.Wrapped) + + m.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return + } +} + +func (m *Metrics) onMetrics(ctx *gin.Context) { + m.mutex.RLock() + pathManager := m.pathManager + hlsServer := m.hlsServer + rtspServer := m.rtspServer + rtspsServer := m.rtspsServer + rtmpServer := m.rtmpServer + rtmpsServer := m.rtmpsServer + srtServer := m.srtServer + webRTCServer := m.webRTCServer + moqServer := m.moqServer + m.mutex.RUnlock() + + typ := metricsType(ctx.Query("type")) + pathFilter := ctx.Query("path") + hlsMuxerFilter := ctx.Query("hls_muxer") + hlsSessionFilter := ctx.Query("hls_session") + rtspConnFilter := ctx.Query("rtsp_conn") + rtspSessionFilter := ctx.Query("rtsp_session") + rtspsConnFilter := ctx.Query("rtsps_conn") + rtspsSessionFilter := ctx.Query("rtsps_session") + rtmpConnFilter := ctx.Query("rtmp_conn") + rtmpsConnFilter := ctx.Query("rtmps_conn") + srtConnFilter := ctx.Query("srt_conn") + webrtcSessionFilter := ctx.Query("webrtc_session") + moqSessionFilter := ctx.Query("moq_session") + + anyFilterActive := pathFilter != "" || + hlsMuxerFilter != "" || + hlsSessionFilter != "" || + rtspConnFilter != "" || + rtspSessionFilter != "" || + rtspsConnFilter != "" || + rtspsSessionFilter != "" || + rtmpConnFilter != "" || + rtmpsConnFilter != "" || + srtConnFilter != "" || + webrtcSessionFilter != "" || + moqSessionFilter != "" + + var out strings.Builder + + if (typ == "" || typ == metricsTypePaths) && (!anyFilterActive || pathFilter != "") { + data, err := pathManager.APIPathsList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# Paths\n") + for _, i := range data.Items { + if pathFilter == "" || pathFilter == i.Name { + var state string + if i.Ready { + state = "ready" + } else { + state = "notReady" + } + + ta := tags(map[string]string{ + "name": i.Name, + "state": state, + }) + + metric(&out, "paths", ta, 1) + + if len(i.Readers) != 0 { + readersByType := make(map[string]int) + for _, r := range i.Readers { + readersByType[string(r.Type)]++ + } + + for _, rt := range sortedKeys(readersByType) { + rta := tags(map[string]string{ + "name": i.Name, + "state": state, + "readerType": rt, + }) + metric(&out, "paths_readers", rta, int64(readersByType[rt])) + } + } else { + rta := tags(map[string]string{ + "name": i.Name, + "state": state, + "readerType": "", + }) + metric(&out, "paths_readers", rta, 0) + } + + metric(&out, "paths_inbound_bytes", ta, int64(i.InboundBytes)) + metric(&out, "paths_outbound_bytes", ta, int64(i.OutboundBytes)) + metric(&out, "paths_inbound_frames_in_error", ta, int64(i.InboundFramesInError)) + } + } + out.WriteString("\n") + + out.WriteString("# Paths (deprecated)\n") + for _, i := range data.Items { + if pathFilter == "" || pathFilter == i.Name { + var state string + if i.Ready { + state = "ready" + } else { + state = "notReady" + } + + ta := tags(map[string]string{ + "name": i.Name, + "state": state, + }) + + metric(&out, "paths_bytes_received", ta, int64(i.BytesReceived)) + metric(&out, "paths_bytes_sent", ta, int64(i.BytesSent)) + } + } + out.WriteString("\n") + } else if pathFilter == "" { + out.WriteString("# Paths\n") + metric(&out, "paths", "", 0) + metric(&out, "paths_inbound_bytes", "", 0) + metric(&out, "paths_outbound_bytes", "", 0) + metric(&out, "paths_inbound_frames_in_error", "", 0) + out.WriteString("\n") + + out.WriteString("# Paths (deprecated)\n") + metric(&out, "paths_bytes_received", "", 0) + metric(&out, "paths_bytes_sent", "", 0) + metric(&out, "paths_readers", "", 0) + out.WriteString("\n") + } + } + + if !interfaceIsEmpty(hlsServer) { + if (typ == "" || typ == metricsTypeHLSSessions) && (!anyFilterActive || hlsSessionFilter != "") { + var data *defs.APIHLSSessionList + data, err := hlsServer.APISessionsList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# HLS sessions\n") + for _, i := range data.Items { + if hlsSessionFilter == "" || hlsSessionFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "hls_sessions", ta, 1) + metric(&out, "hls_sessions_outbound_bytes", ta, int64(i.OutboundBytes)) + } + } + out.WriteString("\n") + } else if hlsSessionFilter == "" { + out.WriteString("# HLS sessions\n") + metric(&out, "hls_sessions", "", 0) + metric(&out, "hls_sessions_outbound_bytes", "", 0) + out.WriteString("\n") + } + } + + if (typ == "" || typ == metricsTypeHLSMuxers) && (!anyFilterActive || hlsMuxerFilter != "") { + var data *defs.APIHLSMuxerList + data, err := hlsServer.APIMuxersList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# HLS muxers\n") + for _, i := range data.Items { + if hlsMuxerFilter == "" || hlsMuxerFilter == i.Path { + ta := tags(map[string]string{ + "name": i.Path, + }) + + metric(&out, "hls_muxers", ta, 1) + metric(&out, "hls_muxers_outbound_bytes", ta, int64(i.OutboundBytes)) + metric(&out, "hls_muxers_outbound_frames_discarded", ta, int64(i.OutboundFramesDiscarded)) + } + } + out.WriteString("\n") + + out.WriteString("# HLS muxers (deprecated)\n") + for _, i := range data.Items { + if hlsMuxerFilter == "" || hlsMuxerFilter == i.Path { + ta := tags(map[string]string{ + "name": i.Path, + }) + + metric(&out, "hls_muxers_bytes_sent", ta, int64(i.BytesSent)) + } + } + out.WriteString("\n") + } else if hlsMuxerFilter == "" { + out.WriteString("# HLS muxers\n") + metric(&out, "hls_muxers", "", 0) + metric(&out, "hls_muxers_outbound_bytes", "", 0) + metric(&out, "hls_muxers_outbound_frames_discarded", "", 0) + out.WriteString("\n") + + out.WriteString("# HLS muxers (deprecated)\n") + metric(&out, "hls_muxers_bytes_sent", "", 0) + out.WriteString("\n") + } + } + } + + if !interfaceIsEmpty(rtspServer) { //nolint:dupl + if (typ == "" || typ == metricsTypeRTSPConns) && (!anyFilterActive || rtspConnFilter != "") { + var data *defs.APIRTSPConnsList + data, err := rtspServer.APIConnsList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# RTSP connections\n") + for _, i := range data.Items { + if rtspConnFilter == "" || rtspConnFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + }) + + metric(&out, "rtsp_conns", ta, 1) + metric(&out, "rtsp_conns_inbound_bytes", ta, int64(i.InboundBytes)) + metric(&out, "rtsp_conns_outbound_bytes", ta, int64(i.OutboundBytes)) + } + } + out.WriteString("\n") + + out.WriteString("# RTSP connections (deprecated)\n") + for _, i := range data.Items { + if rtspConnFilter == "" || rtspConnFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + }) + + metric(&out, "rtsp_conns_bytes_received", ta, int64(i.BytesReceived)) + metric(&out, "rtsp_conns_bytes_sent", ta, int64(i.BytesSent)) + } + } + out.WriteString("\n") + } else if rtspConnFilter == "" { + out.WriteString("# RTSP connections\n") + metric(&out, "rtsp_conns", "", 0) + metric(&out, "rtsp_conns_inbound_bytes", "", 0) + metric(&out, "rtsp_conns_outbound_bytes", "", 0) + out.WriteString("\n") + + out.WriteString("# RTSP connections (deprecated)\n") + metric(&out, "rtsp_conns_bytes_received", "", 0) + metric(&out, "rtsp_conns_bytes_sent", "", 0) + out.WriteString("\n") + } + } + + if (typ == "" || typ == metricsTypeRTSPSessions) && (!anyFilterActive || rtspSessionFilter != "") { + var data *defs.APIRTSPSessionList + data, err := rtspServer.APISessionsList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# RTSP sessions\n") + for _, i := range data.Items { + if rtspSessionFilter == "" || rtspSessionFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "rtsp_sessions", ta, 1) + metric(&out, "rtsp_sessions_inbound_bytes", ta, int64(i.InboundBytes)) + metric(&out, "rtsp_sessions_inbound_rtp_packets", ta, int64(i.InboundRTPPackets)) + metric(&out, "rtsp_sessions_inbound_rtp_packets_lost", ta, int64(i.InboundRTPPacketsLost)) + metric(&out, "rtsp_sessions_inbound_rtp_packets_in_error", ta, int64(i.InboundRTPPacketsInError)) + metricFloat(&out, "rtsp_sessions_inbound_rtp_packets_jitter", ta, i.InboundRTPPacketsJitter) + metric(&out, "rtsp_sessions_inbound_rtcp_packets", ta, int64(i.InboundRTCPPackets)) + metric(&out, "rtsp_sessions_inbound_rtcp_packets_in_error", ta, int64(i.InboundRTCPPacketsInError)) + metric(&out, "rtsp_sessions_outbound_bytes", ta, int64(i.OutboundBytes)) + metric(&out, "rtsp_sessions_outbound_rtp_packets", ta, int64(i.OutboundRTPPackets)) + metric(&out, "rtsp_sessions_outbound_rtp_packets_reported_lost", ta, int64(i.OutboundRTPPacketsReportedLost)) + metric(&out, "rtsp_sessions_outbound_rtp_packets_discarded", ta, int64(i.OutboundRTPPacketsDiscarded)) + metric(&out, "rtsp_sessions_outbound_rtcp_packets", ta, int64(i.OutboundRTCPPackets)) + } + } + out.WriteString("\n") + + out.WriteString("# RTSP sessions (deprecated)\n") + for _, i := range data.Items { + if rtspSessionFilter == "" || rtspSessionFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "rtsp_sessions_bytes_received", ta, int64(i.BytesReceived)) + metric(&out, "rtsp_sessions_bytes_sent", ta, int64(i.BytesSent)) + metric(&out, "rtsp_sessions_rtp_packets_received", ta, int64(i.RTPPacketsReceived)) + metric(&out, "rtsp_sessions_rtp_packets_sent", ta, int64(i.RTPPacketsSent)) + metric(&out, "rtsp_sessions_rtp_packets_lost", ta, int64(i.RTPPacketsLost)) + metric(&out, "rtsp_sessions_rtp_packets_in_error", ta, int64(i.RTPPacketsInError)) + metricFloat(&out, "rtsp_sessions_rtp_packets_jitter", ta, i.RTPPacketsJitter) + metric(&out, "rtsp_sessions_rtcp_packets_received", ta, int64(i.RTCPPacketsReceived)) + metric(&out, "rtsp_sessions_rtcp_packets_sent", ta, int64(i.RTCPPacketsSent)) + metric(&out, "rtsp_sessions_rtcp_packets_in_error", ta, int64(i.RTCPPacketsInError)) + } + } + out.WriteString("\n") + } else if rtspSessionFilter == "" { + out.WriteString("# RTSP sessions\n") + metric(&out, "rtsp_sessions", "", 0) + metric(&out, "rtsp_sessions_inbound_bytes", "", 0) + metric(&out, "rtsp_sessions_inbound_rtp_packets", "", 0) + metric(&out, "rtsp_sessions_inbound_rtp_packets_lost", "", 0) + metric(&out, "rtsp_sessions_inbound_rtp_packets_in_error", "", 0) + metricFloat(&out, "rtsp_sessions_inbound_rtp_packets_jitter", "", 0) + metric(&out, "rtsp_sessions_inbound_rtcp_packets", "", 0) + metric(&out, "rtsp_sessions_inbound_rtcp_packets_in_error", "", 0) + metric(&out, "rtsp_sessions_outbound_bytes", "", 0) + metric(&out, "rtsp_sessions_outbound_rtp_packets", "", 0) + metric(&out, "rtsp_sessions_outbound_rtp_packets_reported_lost", "", 0) + metric(&out, "rtsp_sessions_outbound_rtp_packets_discarded", "", 0) + metric(&out, "rtsp_sessions_outbound_rtcp_packets", "", 0) + out.WriteString("\n") + + out.WriteString("# RTSP sessions (deprecated)\n") + metric(&out, "rtsp_sessions_bytes_received", "", 0) + metric(&out, "rtsp_sessions_bytes_sent", "", 0) + metric(&out, "rtsp_sessions_rtp_packets_received", "", 0) + metric(&out, "rtsp_sessions_rtp_packets_sent", "", 0) + metric(&out, "rtsp_sessions_rtp_packets_lost", "", 0) + metric(&out, "rtsp_sessions_rtp_packets_in_error", "", 0) + metricFloat(&out, "rtsp_sessions_rtp_packets_jitter", "", 0) + metric(&out, "rtsp_sessions_rtcp_packets_received", "", 0) + metric(&out, "rtsp_sessions_rtcp_packets_sent", "", 0) + metric(&out, "rtsp_sessions_rtcp_packets_in_error", "", 0) + out.WriteString("\n") + } + } + } + + if !interfaceIsEmpty(rtspsServer) { //nolint:dupl + if (typ == "" || typ == metricsTypeRTSPSConns) && (!anyFilterActive || rtspsConnFilter != "") { + var data *defs.APIRTSPConnsList + data, err := rtspsServer.APIConnsList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# RTSPS connections\n") + for _, i := range data.Items { + if rtspsConnFilter == "" || rtspsConnFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + }) + + metric(&out, "rtsps_conns", ta, 1) + metric(&out, "rtsps_conns_inbound_bytes", ta, int64(i.InboundBytes)) + metric(&out, "rtsps_conns_outbound_bytes", ta, int64(i.OutboundBytes)) + } + } + out.WriteString("\n") + + out.WriteString("# RTSPS connections (deprecated)\n") + for _, i := range data.Items { + if rtspsConnFilter == "" || rtspsConnFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + }) + + metric(&out, "rtsps_conns_bytes_received", ta, int64(i.BytesReceived)) + metric(&out, "rtsps_conns_bytes_sent", ta, int64(i.BytesSent)) + } + } + out.WriteString("\n") + } else if rtspsConnFilter == "" { + out.WriteString("# RTSPS connections\n") + metric(&out, "rtsps_conns", "", 0) + metric(&out, "rtsps_conns_inbound_bytes", "", 0) + metric(&out, "rtsps_conns_outbound_bytes", "", 0) + out.WriteString("\n") + + out.WriteString("# RTSPS connections (deprecated)\n") + metric(&out, "rtsps_conns_bytes_received", "", 0) + metric(&out, "rtsps_conns_bytes_sent", "", 0) + out.WriteString("\n") + } + } + + if (typ == "" || typ == metricsTypeRTSPSSessions) && (!anyFilterActive || rtspsSessionFilter != "") { + var data *defs.APIRTSPSessionList + data, err := rtspsServer.APISessionsList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# RTSPS sessions\n") + for _, i := range data.Items { + if rtspsSessionFilter == "" || rtspsSessionFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "rtsps_sessions", ta, 1) + metric(&out, "rtsps_sessions_inbound_bytes", ta, int64(i.InboundBytes)) + metric(&out, "rtsps_sessions_inbound_rtp_packets", ta, int64(i.InboundRTPPackets)) + metric(&out, "rtsps_sessions_inbound_rtp_packets_lost", ta, int64(i.InboundRTPPacketsLost)) + metric(&out, "rtsps_sessions_inbound_rtp_packets_in_error", ta, int64(i.InboundRTPPacketsInError)) + metricFloat(&out, "rtsps_sessions_inbound_rtp_packets_jitter", ta, i.InboundRTPPacketsJitter) + metric(&out, "rtsps_sessions_inbound_rtcp_packets", ta, int64(i.InboundRTCPPackets)) + metric(&out, "rtsps_sessions_inbound_rtcp_packets_in_error", ta, int64(i.InboundRTCPPacketsInError)) + metric(&out, "rtsps_sessions_outbound_bytes", ta, int64(i.OutboundBytes)) + metric(&out, "rtsps_sessions_outbound_rtp_packets", ta, int64(i.OutboundRTPPackets)) + metric(&out, "rtsps_sessions_outbound_rtp_packets_reported_lost", ta, int64(i.OutboundRTPPacketsReportedLost)) + metric(&out, "rtsps_sessions_outbound_rtp_packets_discarded", ta, int64(i.OutboundRTPPacketsDiscarded)) + metric(&out, "rtsps_sessions_outbound_rtcp_packets", ta, int64(i.OutboundRTCPPackets)) + } + } + out.WriteString("\n") + + out.WriteString("# RTSPS sessions (deprecated)\n") + for _, i := range data.Items { + if rtspsSessionFilter == "" || rtspsSessionFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "rtsps_sessions_bytes_received", ta, int64(i.BytesReceived)) + metric(&out, "rtsps_sessions_bytes_sent", ta, int64(i.BytesSent)) + metric(&out, "rtsps_sessions_rtp_packets_received", ta, int64(i.RTPPacketsReceived)) + metric(&out, "rtsps_sessions_rtp_packets_sent", ta, int64(i.RTPPacketsSent)) + metric(&out, "rtsps_sessions_rtp_packets_lost", ta, int64(i.RTPPacketsLost)) + metric(&out, "rtsps_sessions_rtp_packets_in_error", ta, int64(i.RTPPacketsInError)) + metricFloat(&out, "rtsps_sessions_rtp_packets_jitter", ta, i.RTPPacketsJitter) + metric(&out, "rtsps_sessions_rtcp_packets_received", ta, int64(i.RTCPPacketsReceived)) + metric(&out, "rtsps_sessions_rtcp_packets_sent", ta, int64(i.RTCPPacketsSent)) + metric(&out, "rtsps_sessions_rtcp_packets_in_error", ta, int64(i.RTCPPacketsInError)) + } + } + out.WriteString("\n") + } else if rtspsSessionFilter == "" { + out.WriteString("# RTSPS sessions\n") + metric(&out, "rtsps_sessions", "", 0) + metric(&out, "rtsps_sessions_inbound_bytes", "", 0) + metric(&out, "rtsps_sessions_inbound_rtp_packets", "", 0) + metric(&out, "rtsps_sessions_inbound_rtp_packets_lost", "", 0) + metric(&out, "rtsps_sessions_inbound_rtp_packets_in_error", "", 0) + metricFloat(&out, "rtsps_sessions_inbound_rtp_packets_jitter", "", 0) + metric(&out, "rtsps_sessions_inbound_rtcp_packets", "", 0) + metric(&out, "rtsps_sessions_inbound_rtcp_packets_in_error", "", 0) + metric(&out, "rtsps_sessions_outbound_bytes", "", 0) + metric(&out, "rtsps_sessions_outbound_rtp_packets", "", 0) + metric(&out, "rtsps_sessions_outbound_rtp_packets_reported_lost", "", 0) + metric(&out, "rtsps_sessions_outbound_rtp_packets_discarded", "", 0) + metric(&out, "rtsps_sessions_outbound_rtcp_packets", "", 0) + out.WriteString("\n") + + out.WriteString("# RTSPS sessions (deprecated)\n") + metric(&out, "rtsps_sessions_bytes_received", "", 0) + metric(&out, "rtsps_sessions_bytes_sent", "", 0) + metric(&out, "rtsps_sessions_rtp_packets_received", "", 0) + metric(&out, "rtsps_sessions_rtp_packets_sent", "", 0) + metric(&out, "rtsps_sessions_rtp_packets_lost", "", 0) + metric(&out, "rtsps_sessions_rtp_packets_in_error", "", 0) + metricFloat(&out, "rtsps_sessions_rtp_packets_jitter", "", 0) + metric(&out, "rtsps_sessions_rtcp_packets_received", "", 0) + metric(&out, "rtsps_sessions_rtcp_packets_sent", "", 0) + metric(&out, "rtsps_sessions_rtcp_packets_in_error", "", 0) + out.WriteString("\n") + } + } + } + + if !interfaceIsEmpty(rtmpServer) && //nolint:dupl + (typ == "" || typ == metricsTypeRTMPConns) && + (!anyFilterActive || rtmpConnFilter != "") { + var data *defs.APIRTMPConnList + data, err := rtmpServer.APIConnsList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# RTMP connections\n") + for _, i := range data.Items { + if rtmpConnFilter == "" || rtmpConnFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "rtmp_conns", ta, 1) + metric(&out, "rtmp_conns_inbound_bytes", ta, int64(i.InboundBytes)) + metric(&out, "rtmp_conns_outbound_bytes", ta, int64(i.OutboundBytes)) + metric(&out, "rtmp_conns_outbound_frames_discarded", ta, int64(i.OutboundFramesDiscarded)) + } + } + out.WriteString("\n") + + out.WriteString("# RTMP connections (deprecated)\n") + for _, i := range data.Items { + if rtmpConnFilter == "" || rtmpConnFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "rtmp_conns_bytes_received", ta, int64(i.BytesReceived)) + metric(&out, "rtmp_conns_bytes_sent", ta, int64(i.BytesSent)) + } + } + out.WriteString("\n") + } else if rtmpConnFilter == "" { + out.WriteString("# RTMP connections\n") + metric(&out, "rtmp_conns", "", 0) + metric(&out, "rtmp_conns_inbound_bytes", "", 0) + metric(&out, "rtmp_conns_outbound_bytes", "", 0) + metric(&out, "rtmp_conns_outbound_frames_discarded", "", 0) + out.WriteString("\n") + + out.WriteString("# RTMP connections (deprecated)\n") + metric(&out, "rtmp_conns_bytes_received", "", 0) + metric(&out, "rtmp_conns_bytes_sent", "", 0) + out.WriteString("\n") + } + } + + if !interfaceIsEmpty(rtmpsServer) && //nolint:dupl + (typ == "" || typ == metricsTypeRTMPSConns) && + (!anyFilterActive || rtmpsConnFilter != "") { + var data *defs.APIRTMPConnList + data, err := rtmpsServer.APIConnsList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# RTMPS connections\n") + for _, i := range data.Items { + if rtmpsConnFilter == "" || rtmpsConnFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "rtmps_conns", ta, 1) + metric(&out, "rtmps_conns_inbound_bytes", ta, int64(i.InboundBytes)) + metric(&out, "rtmps_conns_outbound_bytes", ta, int64(i.OutboundBytes)) + metric(&out, "rtmps_conns_outbound_frames_discarded", ta, int64(i.OutboundFramesDiscarded)) + } + } + out.WriteString("\n") + + out.WriteString("# RTMPS connections (deprecated)\n") + for _, i := range data.Items { + if rtmpsConnFilter == "" || rtmpsConnFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "rtmps_conns_bytes_received", ta, int64(i.BytesReceived)) + metric(&out, "rtmps_conns_bytes_sent", ta, int64(i.BytesSent)) + } + } + out.WriteString("\n") + } else if rtmpsConnFilter == "" { + out.WriteString("# RTMPS connections\n") + metric(&out, "rtmps_conns", "", 0) + metric(&out, "rtmps_conns_inbound_bytes", "", 0) + metric(&out, "rtmps_conns_outbound_bytes", "", 0) + metric(&out, "rtmps_conns_outbound_frames_discarded", "", 0) + out.WriteString("\n") + + out.WriteString("# RTMPS connections (deprecated)\n") + metric(&out, "rtmps_conns_bytes_received", "", 0) + metric(&out, "rtmps_conns_bytes_sent", "", 0) + out.WriteString("\n") + } + } + + if !interfaceIsEmpty(srtServer) && + (typ == "" || typ == metricsTypeSRTConns) && + (!anyFilterActive || srtConnFilter != "") { + var data *defs.APISRTConnList + data, err := srtServer.APIConnsList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# SRT connections\n") + for _, i := range data.Items { + if srtConnFilter == "" || srtConnFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "srt_conns", ta, 1) + metric(&out, "srt_conns_packets_sent", ta, int64(i.PacketsSent)) + metric(&out, "srt_conns_packets_received", ta, int64(i.PacketsReceived)) + metric(&out, "srt_conns_packets_sent_unique", ta, int64(i.PacketsSentUnique)) + metric(&out, "srt_conns_packets_received_unique", ta, int64(i.PacketsReceivedUnique)) + metric(&out, "srt_conns_packets_send_loss", ta, int64(i.PacketsSendLoss)) + metric(&out, "srt_conns_packets_received_loss", ta, int64(i.PacketsReceivedLoss)) + metric(&out, "srt_conns_packets_retrans", ta, int64(i.PacketsRetrans)) + metric(&out, "srt_conns_packets_received_retrans", ta, int64(i.PacketsReceivedRetrans)) + metric(&out, "srt_conns_packets_sent_ack", ta, int64(i.PacketsSentACK)) + metric(&out, "srt_conns_packets_received_ack", ta, int64(i.PacketsReceivedACK)) + metric(&out, "srt_conns_packets_sent_nak", ta, int64(i.PacketsSentNAK)) + metric(&out, "srt_conns_packets_received_nak", ta, int64(i.PacketsReceivedNAK)) + metric(&out, "srt_conns_packets_sent_km", ta, int64(i.PacketsSentKM)) + metric(&out, "srt_conns_packets_received_km", ta, int64(i.PacketsReceivedKM)) + metric(&out, "srt_conns_us_snd_duration", ta, int64(i.UsSndDuration)) + metric(&out, "srt_conns_packets_received_belated", ta, int64(i.PacketsReceivedBelated)) + metric(&out, "srt_conns_packets_send_drop", ta, int64(i.PacketsSendDrop)) + metric(&out, "srt_conns_packets_received_drop", ta, int64(i.PacketsReceivedDrop)) + metric(&out, "srt_conns_packets_received_undecrypt", ta, int64(i.PacketsReceivedUndecrypt)) + metric(&out, "srt_conns_bytes_sent", ta, int64(i.BytesSent)) + metric(&out, "srt_conns_bytes_received", ta, int64(i.BytesReceived)) + metric(&out, "srt_conns_bytes_sent_unique", ta, int64(i.BytesSentUnique)) + metric(&out, "srt_conns_bytes_received_unique", ta, int64(i.BytesReceivedUnique)) + metric(&out, "srt_conns_bytes_received_loss", ta, int64(i.BytesReceivedLoss)) + metric(&out, "srt_conns_bytes_retrans", ta, int64(i.BytesRetrans)) + metric(&out, "srt_conns_bytes_received_retrans", ta, int64(i.BytesReceivedRetrans)) + metric(&out, "srt_conns_bytes_received_belated", ta, int64(i.BytesReceivedBelated)) + metric(&out, "srt_conns_bytes_send_drop", ta, int64(i.BytesSendDrop)) + metric(&out, "srt_conns_bytes_received_drop", ta, int64(i.BytesReceivedDrop)) + metric(&out, "srt_conns_bytes_received_undecrypt", ta, int64(i.BytesReceivedUndecrypt)) + metricFloat(&out, "srt_conns_us_packets_send_period", ta, i.UsPacketsSendPeriod) + metric(&out, "srt_conns_packets_flow_window", ta, int64(i.PacketsFlowWindow)) + metric(&out, "srt_conns_packets_flight_size", ta, int64(i.PacketsFlightSize)) + metricFloat(&out, "srt_conns_ms_rtt", ta, i.MsRTT) + metricFloat(&out, "srt_conns_mbps_send_rate", ta, i.MbpsSendRate) + metricFloat(&out, "srt_conns_mbps_receive_rate", ta, i.MbpsReceiveRate) + metricFloat(&out, "srt_conns_mbps_link_capacity", ta, i.MbpsLinkCapacity) + metric(&out, "srt_conns_bytes_avail_send_buf", ta, int64(i.BytesAvailSendBuf)) + metric(&out, "srt_conns_bytes_avail_receive_buf", ta, int64(i.BytesAvailReceiveBuf)) + metricFloat(&out, "srt_conns_mbps_max_bw", ta, i.MbpsMaxBW) + metric(&out, "srt_conns_bytes_mss", ta, int64(i.ByteMSS)) + metric(&out, "srt_conns_packets_send_buf", ta, int64(i.PacketsSendBuf)) + metric(&out, "srt_conns_bytes_send_buf", ta, int64(i.BytesSendBuf)) + metric(&out, "srt_conns_ms_send_buf", ta, int64(i.MsSendBuf)) + metric(&out, "srt_conns_ms_send_tsb_pd_delay", ta, int64(i.MsSendTsbPdDelay)) + metric(&out, "srt_conns_packets_receive_buf", ta, int64(i.PacketsReceiveBuf)) + metric(&out, "srt_conns_bytes_receive_buf", ta, int64(i.BytesReceiveBuf)) + metric(&out, "srt_conns_ms_receive_buf", ta, int64(i.MsReceiveBuf)) + metric(&out, "srt_conns_ms_receive_tsb_pd_delay", ta, int64(i.MsReceiveTsbPdDelay)) + metric(&out, "srt_conns_packets_reorder_tolerance", ta, int64(i.PacketsReorderTolerance)) + metric(&out, "srt_conns_packets_received_avg_belated_time", ta, int64(i.PacketsReceivedAvgBelatedTime)) + metricFloat(&out, "srt_conns_packets_send_loss_rate", ta, i.PacketsSendLossRate) + metricFloat(&out, "srt_conns_packets_received_loss_rate", ta, i.PacketsReceivedLossRate) + metric(&out, "srt_conns_outbound_frames_discarded", ta, int64(i.OutboundFramesDiscarded)) + } + } + out.WriteString("\n") + } else if srtConnFilter == "" { + out.WriteString("# SRT connections\n") + metric(&out, "srt_conns", "", 0) + metric(&out, "srt_conns_packets_sent", "", 0) + metric(&out, "srt_conns_packets_received", "", 0) + metric(&out, "srt_conns_packets_sent_unique", "", 0) + metric(&out, "srt_conns_packets_received_unique", "", 0) + metric(&out, "srt_conns_packets_send_loss", "", 0) + metric(&out, "srt_conns_packets_received_loss", "", 0) + metric(&out, "srt_conns_packets_retrans", "", 0) + metric(&out, "srt_conns_packets_received_retrans", "", 0) + metric(&out, "srt_conns_packets_sent_ack", "", 0) + metric(&out, "srt_conns_packets_received_ack", "", 0) + metric(&out, "srt_conns_packets_sent_nak", "", 0) + metric(&out, "srt_conns_packets_received_nak", "", 0) + metric(&out, "srt_conns_packets_sent_km", "", 0) + metric(&out, "srt_conns_packets_received_km", "", 0) + metric(&out, "srt_conns_us_snd_duration", "", 0) + metric(&out, "srt_conns_packets_received_belated", "", 0) + metric(&out, "srt_conns_packets_send_drop", "", 0) + metric(&out, "srt_conns_packets_received_drop", "", 0) + metric(&out, "srt_conns_packets_received_undecrypt", "", 0) + metric(&out, "srt_conns_bytes_sent", "", 0) + metric(&out, "srt_conns_bytes_received", "", 0) + metric(&out, "srt_conns_bytes_sent_unique", "", 0) + metric(&out, "srt_conns_bytes_received_unique", "", 0) + metric(&out, "srt_conns_bytes_received_loss", "", 0) + metric(&out, "srt_conns_bytes_retrans", "", 0) + metric(&out, "srt_conns_bytes_received_retrans", "", 0) + metric(&out, "srt_conns_bytes_received_belated", "", 0) + metric(&out, "srt_conns_bytes_send_drop", "", 0) + metric(&out, "srt_conns_bytes_received_drop", "", 0) + metric(&out, "srt_conns_bytes_received_undecrypt", "", 0) + metricFloat(&out, "srt_conns_us_packets_send_period", "", 0) + metric(&out, "srt_conns_packets_flow_window", "", 0) + metric(&out, "srt_conns_packets_flight_size", "", 0) + metricFloat(&out, "srt_conns_ms_rtt", "", 0) + metricFloat(&out, "srt_conns_mbps_send_rate", "", 0) + metricFloat(&out, "srt_conns_mbps_receive_rate", "", 0) + metricFloat(&out, "srt_conns_mbps_link_capacity", "", 0) + metric(&out, "srt_conns_bytes_avail_send_buf", "", 0) + metric(&out, "srt_conns_bytes_avail_receive_buf", "", 0) + metricFloat(&out, "srt_conns_mbps_max_bw", "", 0) + metric(&out, "srt_conns_bytes_mss", "", 0) + metric(&out, "srt_conns_packets_send_buf", "", 0) + metric(&out, "srt_conns_bytes_send_buf", "", 0) + metric(&out, "srt_conns_ms_send_buf", "", 0) + metric(&out, "srt_conns_ms_send_tsb_pd_delay", "", 0) + metric(&out, "srt_conns_packets_receive_buf", "", 0) + metric(&out, "srt_conns_bytes_receive_buf", "", 0) + metric(&out, "srt_conns_ms_receive_buf", "", 0) + metric(&out, "srt_conns_ms_receive_tsb_pd_delay", "", 0) + metric(&out, "srt_conns_packets_reorder_tolerance", "", 0) + metric(&out, "srt_conns_packets_received_avg_belated_time", "", 0) + metricFloat(&out, "srt_conns_packets_send_loss_rate", "", 0) + metricFloat(&out, "srt_conns_packets_received_loss_rate", "", 0) + metric(&out, "srt_conns_outbound_frames_discarded", "", 0) + out.WriteString("\n") + } + } + + if !interfaceIsEmpty(webRTCServer) && + (typ == "" || typ == metricsTypeWebRTCSessions) && + (!anyFilterActive || webrtcSessionFilter != "") { + var data *defs.APIWebRTCSessionList + data, err := webRTCServer.APISessionsList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# WebRTC sessions\n") + for _, i := range data.Items { + if webrtcSessionFilter == "" || webrtcSessionFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "webrtc_sessions", ta, 1) + metric(&out, "webrtc_sessions_inbound_bytes", ta, int64(i.InboundBytes)) + metric(&out, "webrtc_sessions_inbound_rtp_packets", ta, int64(i.InboundRTPPackets)) + metric(&out, "webrtc_sessions_inbound_rtp_packets_lost", ta, int64(i.InboundRTPPacketsLost)) + metricFloat(&out, "webrtc_sessions_inbound_rtp_packets_jitter", ta, i.InboundRTPPacketsJitter) + metric(&out, "webrtc_sessions_inbound_rtcp_packets", ta, int64(i.InboundRTCPPackets)) + metric(&out, "webrtc_sessions_outbound_bytes", ta, int64(i.OutboundBytes)) + metric(&out, "webrtc_sessions_outbound_rtp_packets", ta, int64(i.OutboundRTPPackets)) + metric(&out, "webrtc_sessions_outbound_rtcp_packets", ta, int64(i.OutboundRTCPPackets)) + metric(&out, "webrtc_sessions_outbound_frames_discarded", ta, int64(i.OutboundFramesDiscarded)) + } + } + out.WriteString("\n") + + out.WriteString("# WebRTC sessions (deprecated)\n") + for _, i := range data.Items { + if webrtcSessionFilter == "" || webrtcSessionFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "webrtc_sessions_bytes_received", ta, int64(i.BytesReceived)) + metric(&out, "webrtc_sessions_bytes_sent", ta, int64(i.BytesSent)) + metric(&out, "webrtc_sessions_rtp_packets_received", ta, int64(i.RTPPacketsReceived)) + metric(&out, "webrtc_sessions_rtp_packets_sent", ta, int64(i.RTPPacketsSent)) + metric(&out, "webrtc_sessions_rtp_packets_lost", ta, int64(i.RTPPacketsLost)) + metricFloat(&out, "webrtc_sessions_rtp_packets_jitter", ta, i.RTPPacketsJitter) + metric(&out, "webrtc_sessions_rtcp_packets_received", ta, int64(i.RTCPPacketsReceived)) + metric(&out, "webrtc_sessions_rtcp_packets_sent", ta, int64(i.RTCPPacketsSent)) + } + } + out.WriteString("\n") + } else if webrtcSessionFilter == "" { + out.WriteString("# WebRTC sessions\n") + metric(&out, "webrtc_sessions", "", 0) + metric(&out, "webrtc_sessions_inbound_bytes", "", 0) + metric(&out, "webrtc_sessions_inbound_rtp_packets", "", 0) + metric(&out, "webrtc_sessions_inbound_rtp_packets_lost", "", 0) + metricFloat(&out, "webrtc_sessions_inbound_rtp_packets_jitter", "", 0) + metric(&out, "webrtc_sessions_inbound_rtcp_packets", "", 0) + metric(&out, "webrtc_sessions_outbound_bytes", "", 0) + metric(&out, "webrtc_sessions_outbound_rtp_packets", "", 0) + metric(&out, "webrtc_sessions_outbound_rtcp_packets", "", 0) + metric(&out, "webrtc_sessions_outbound_frames_discarded", "", 0) + out.WriteString("\n") + + out.WriteString("# WebRTC sessions (deprecated)\n") + metric(&out, "webrtc_sessions_bytes_received", "", 0) + metric(&out, "webrtc_sessions_bytes_sent", "", 0) + metric(&out, "webrtc_sessions_rtp_packets_received", "", 0) + metric(&out, "webrtc_sessions_rtp_packets_sent", "", 0) + metric(&out, "webrtc_sessions_rtp_packets_lost", "", 0) + metricFloat(&out, "webrtc_sessions_rtp_packets_jitter", "", 0) + metric(&out, "webrtc_sessions_rtcp_packets_received", "", 0) + metric(&out, "webrtc_sessions_rtcp_packets_sent", "", 0) + out.WriteString("\n") + } + } + + if !interfaceIsEmpty(moqServer) && + (typ == "" || typ == metricsTypeMoQSessions) && + (!anyFilterActive || moqSessionFilter != "") { + var data *defs.APIMoQSessionList + data, err := moqServer.APISessionsList() + if err == nil && len(data.Items) != 0 { + out.WriteString("# MoQ sessions\n") + for _, i := range data.Items { + if moqSessionFilter == "" || moqSessionFilter == i.ID.String() { + ta := tags(map[string]string{ + "id": i.ID.String(), + "state": string(i.State), + "path": i.Path, + "remoteAddr": i.RemoteAddr, + }) + + metric(&out, "moq_sessions", ta, 1) + metric(&out, "moq_sessions_inbound_bytes", ta, int64(i.InboundBytes)) + metric(&out, "moq_sessions_outbound_bytes", ta, int64(i.OutboundBytes)) + } + } + out.WriteString("\n") + } else if moqSessionFilter == "" { + out.WriteString("# MoQ sessions\n") + metric(&out, "moq_sessions", "", 0) + metric(&out, "moq_sessions_inbound_bytes", "", 0) + metric(&out, "moq_sessions_outbound_bytes", "", 0) + out.WriteString("\n") + } + } + + ctx.Writer.WriteHeader(http.StatusOK) + ctx.Writer.WriteString(out.String()) //nolint:errcheck +} + +// SetPathManager is called by core. +func (m *Metrics) SetPathManager(s defs.APIPathManager) { + m.mutex.Lock() + defer m.mutex.Unlock() + m.pathManager = s +} + +// SetHLSServer is called by core. +func (m *Metrics) SetHLSServer(s defs.APIHLSServer) { + m.mutex.Lock() + defer m.mutex.Unlock() + m.hlsServer = s +} + +// SetRTSPServer is called by core. +func (m *Metrics) SetRTSPServer(s defs.APIRTSPServer) { + m.mutex.Lock() + defer m.mutex.Unlock() + m.rtspServer = s +} + +// SetRTSPSServer is called by core. +func (m *Metrics) SetRTSPSServer(s defs.APIRTSPServer) { + m.mutex.Lock() + defer m.mutex.Unlock() + m.rtspsServer = s +} + +// SetRTMPServer is called by core. +func (m *Metrics) SetRTMPServer(s defs.APIRTMPServer) { + m.mutex.Lock() + defer m.mutex.Unlock() + m.rtmpServer = s +} + +// SetRTMPSServer is called by core. +func (m *Metrics) SetRTMPSServer(s defs.APIRTMPServer) { + m.mutex.Lock() + defer m.mutex.Unlock() + m.rtmpsServer = s +} + +// SetSRTServer is called by core. +func (m *Metrics) SetSRTServer(s defs.APISRTServer) { + m.mutex.Lock() + defer m.mutex.Unlock() + m.srtServer = s +} + +// SetWebRTCServer is called by core. +func (m *Metrics) SetWebRTCServer(s defs.APIWebRTCServer) { + m.mutex.Lock() + defer m.mutex.Unlock() + m.webRTCServer = s +} + +// SetMoQServer is called by core. +func (m *Metrics) SetMoQServer(s defs.APIMoQServer) { + m.mutex.Lock() + defer m.mutex.Unlock() + m.moqServer = s +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/metrics/metrics_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/metrics/metrics_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3da52d468b97ae1676d09a7046b174a8267cb587 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/metrics/metrics_test.go @@ -0,0 +1,1845 @@ +package metrics //nolint:revive + +import ( + "fmt" + "io" + "net/http" + "strings" + "sync" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/formatlabel" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/google/uuid" + "github.com/stretchr/testify/require" +) + +type dummyPathManager struct{} + +func (dummyPathManager) APIPathsList() (*defs.APIPathList, error) { + return &defs.APIPathList{ + ItemCount: 1, + PageCount: 1, + Items: []defs.APIPath{{ + Name: "mypath", + ConfName: "mypathconf", + Source: &defs.APIPathSource{ + Type: defs.APIPathSourceTypeRTSPSession, + ID: "123324354", + }, + Ready: true, + ReadyTime: new(time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC)), + Tracks: []defs.APIPathTrackCodec{formatlabel.H264, formatlabel.H265}, + InboundBytes: 123, + OutboundBytes: 456, + InboundFramesInError: 7, + BytesReceived: 123, + BytesSent: 456, + Readers: []defs.APIPathReader{ + { + Type: defs.APIPathReaderTypeRTSPSession, + ID: "345234423", + }, + { + Type: defs.APIPathReaderTypeRTSPSession, + ID: "124123142", + }, + { + Type: defs.APIPathReaderTypeRTMPConn, + ID: "723141123", + }, + }, + }}, + }, nil +} + +func (dummyPathManager) APIPathsGet(string) (*defs.APIPath, error) { + panic("unused") +} + +type dummyHLSServer struct{} + +func (dummyHLSServer) APIMuxersList() (*defs.APIHLSMuxerList, error) { + return &defs.APIHLSMuxerList{ + ItemCount: 1, + PageCount: 1, + Items: []defs.APIHLSMuxer{{ + Path: "mypath", + Created: time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC), + LastRequest: time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC), + OutboundBytes: 789, + OutboundFramesDiscarded: 12, + BytesSent: 789, + }}, + }, nil +} + +func (dummyHLSServer) APIMuxersGet(string) (*defs.APIHLSMuxer, error) { + panic("unused") +} + +func (dummyHLSServer) APISessionsList() (*defs.APIHLSSessionList, error) { + return &defs.APIHLSSessionList{ + ItemCount: 1, + PageCount: 1, + Items: []defs.APIHLSSession{{ + ID: uuid.MustParse("18294761-f9d1-4ea9-9a35-fe265b62eb41"), + Created: time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC), + RemoteAddr: "124.5.5.5:34542", + Path: "mypath", + OutboundBytes: 187, + }}, + }, nil +} + +func (dummyHLSServer) APISessionsGet(uuid.UUID) (*defs.APIHLSSession, error) { + panic("unused") +} + +func (dummyHLSServer) APISessionsKick(uuid.UUID) error { + panic("unused") +} + +type dummyRTSPServer struct{} + +func (dummyRTSPServer) APIConnsList() (*defs.APIRTSPConnsList, error) { + return &defs.APIRTSPConnsList{ + ItemCount: 1, + PageCount: 1, + Items: []defs.APIRTSPConn{{ + ID: uuid.MustParse("18294761-f9d1-4ea9-9a35-fe265b62eb41"), + Created: time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC), + RemoteAddr: "124.5.5.5:34542", + InboundBytes: 123, + OutboundBytes: 456, + BytesReceived: 123, + BytesSent: 456, + Session: nil, + }}, + }, nil +} + +func (dummyRTSPServer) APIConnsGet(uuid.UUID) (*defs.APIRTSPConn, error) { + panic("unused") +} + +func (dummyRTSPServer) APISessionsList() (*defs.APIRTSPSessionList, error) { + return &defs.APIRTSPSessionList{ + ItemCount: 1, + PageCount: 1, + Items: []defs.APIRTSPSession{{ + ID: uuid.MustParse("124b22ce-9c34-4387-b045-44caf98049f7"), + Created: time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC), + RemoteAddr: "124.5.5.5:34542", + State: defs.APIRTSPSessionStatePublish, + Path: "mypath", + Query: "myquery", + Transport: nil, + InboundBytes: 123, + InboundRTPPackets: 789, + InboundRTPPacketsLost: 456, + InboundRTPPacketsInError: 789, + InboundRTPPacketsJitter: 123, + InboundRTCPPackets: 456, + InboundRTCPPacketsInError: 456, + OutboundBytes: 456, + OutboundRTPPackets: 123, + OutboundRTPPacketsReportedLost: 321, + OutboundRTPPacketsDiscarded: 111, + OutboundRTCPPackets: 789, + BytesReceived: 123, + BytesSent: 456, + RTPPacketsReceived: 789, + RTPPacketsSent: 123, + RTPPacketsLost: 456, + RTPPacketsInError: 789, + RTPPacketsJitter: 123, + RTCPPacketsReceived: 456, + RTCPPacketsSent: 789, + RTCPPacketsInError: 456, + }}, + }, nil +} + +func (dummyRTSPServer) APISessionsGet(uuid.UUID) (*defs.APIRTSPSession, error) { + panic("unused") +} + +func (dummyRTSPServer) APISessionsKick(uuid.UUID) error { + panic("unused") +} + +type dummyRTMPServer struct{} + +func (dummyRTMPServer) APIConnsList() (*defs.APIRTMPConnList, error) { + return &defs.APIRTMPConnList{ + ItemCount: 1, + PageCount: 1, + Items: []defs.APIRTMPConn{{ + ID: uuid.MustParse("9a07afe4-fc07-4c9b-be6e-6255720c36d0"), + Created: time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC), + RemoteAddr: "3.3.3.3:5678", + State: defs.APIRTMPConnStateRead, + Path: "mypath", + Query: "myquery", + InboundBytes: 123, + OutboundBytes: 456, + OutboundFramesDiscarded: 12, + BytesReceived: 123, + BytesSent: 456, + }}, + }, nil +} + +func (dummyRTMPServer) APIConnsGet(uuid.UUID) (*defs.APIRTMPConn, error) { + panic("unused") +} + +func (dummyRTMPServer) APIConnsKick(uuid.UUID) error { + panic("unused") +} + +type dummySRTServer struct{} + +func (dummySRTServer) APIConnsList() (*defs.APISRTConnList, error) { + return &defs.APISRTConnList{ + ItemCount: 1, + PageCount: 1, + Items: []defs.APISRTConn{{ + ID: uuid.MustParse("a0b1c2d3-e4f5-6789-abcd-ef0123456789"), + Created: time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC), + RemoteAddr: "5.5.5.5:4321", + State: defs.APISRTConnStatePublish, + Path: "mypath", + Query: "myquery", + PacketsSent: 100, + PacketsReceived: 200, + PacketsSentUnique: 90, + PacketsReceivedUnique: 180, + PacketsSendLoss: 10, + PacketsReceivedLoss: 20, + PacketsRetrans: 5, + PacketsReceivedRetrans: 3, + PacketsSentACK: 50, + PacketsReceivedACK: 40, + PacketsSentNAK: 2, + PacketsReceivedNAK: 1, + PacketsSentKM: 4, + PacketsReceivedKM: 3, + UsSndDuration: 1000000, + PacketsReceivedBelated: 7, + PacketsSendDrop: 8, + PacketsReceivedDrop: 6, + PacketsReceivedUndecrypt: 0, + BytesSent: 12345, + BytesReceived: 67890, + BytesSentUnique: 11000, + BytesReceivedUnique: 60000, + BytesReceivedLoss: 500, + BytesRetrans: 300, + BytesReceivedRetrans: 200, + BytesReceivedBelated: 100, + BytesSendDrop: 400, + BytesReceivedDrop: 350, + BytesReceivedUndecrypt: 0, + UsPacketsSendPeriod: 10.5, + PacketsFlowWindow: 8192, + PacketsFlightSize: 25, + MsRTT: 1.5, + MbpsSendRate: 50.0, + MbpsReceiveRate: 48.0, + MbpsLinkCapacity: 100.0, + BytesAvailSendBuf: 65536, + BytesAvailReceiveBuf: 65536, + MbpsMaxBW: 100.0, + ByteMSS: 1500, + PacketsSendBuf: 10, + BytesSendBuf: 15000, + MsSendBuf: 120, + MsSendTsbPdDelay: 120, + PacketsReceiveBuf: 15, + BytesReceiveBuf: 22500, + MsReceiveBuf: 120, + MsReceiveTsbPdDelay: 120, + PacketsReorderTolerance: 3, + PacketsReceivedAvgBelatedTime: 50, + PacketsSendLossRate: 0.01, + PacketsReceivedLossRate: 0.02, + OutboundFramesDiscarded: 5, + }}, + }, nil +} + +func (dummySRTServer) APIConnsGet(uuid.UUID) (*defs.APISRTConn, error) { + panic("unused") +} + +func (dummySRTServer) APIConnsKick(uuid.UUID) error { + panic("unused") +} + +type dummyWebRTCServer struct{} + +func (dummyWebRTCServer) APISessionsList() (*defs.APIWebRTCSessionList, error) { + return &defs.APIWebRTCSessionList{ + ItemCount: 1, + PageCount: 1, + Items: []defs.APIWebRTCSession{{ + ID: uuid.MustParse("f47ac10b-58cc-4372-a567-0e02b2c3d479"), + Created: time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC), + RemoteAddr: "127.0.0.1:3455", + PeerConnectionEstablished: true, + LocalCandidate: "local", + RemoteCandidate: "remote", + State: defs.APIWebRTCSessionStateRead, + Path: "mypath", + Query: "myquery", + InboundBytes: 123, + InboundRTPPackets: 789, + InboundRTPPacketsLost: 456, + InboundRTPPacketsJitter: 789, + InboundRTCPPackets: 123, + OutboundBytes: 456, + OutboundRTPPackets: 123, + OutboundRTCPPackets: 456, + OutboundFramesDiscarded: 12, + BytesReceived: 123, + BytesSent: 456, + RTPPacketsReceived: 789, + RTPPacketsSent: 123, + RTPPacketsLost: 456, + RTPPacketsJitter: 789, + RTCPPacketsReceived: 123, + RTCPPacketsSent: 456, + }}, + }, nil +} + +func (dummyWebRTCServer) APISessionsGet(uuid.UUID) (*defs.APIWebRTCSession, error) { + panic("unused") +} + +func (dummyWebRTCServer) APISessionsKick(uuid.UUID) error { + panic("unused") +} + +type dummyMoQServer struct{} + +func (dummyMoQServer) APISessionsList() (*defs.APIMoQSessionList, error) { + return &defs.APIMoQSessionList{ + ItemCount: 1, + PageCount: 1, + Items: []defs.APIMoQSession{{ + ID: uuid.MustParse("b47ac10b-58cc-4372-a567-0e02b2c3d479"), + Created: time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC), + RemoteAddr: "127.0.0.2:3456", + State: defs.APIMoQSessionStatePublish, + Path: "mypath", + InboundBytes: 321, + OutboundBytes: 654, + }}, + }, nil +} + +func (dummyMoQServer) APISessionsGet(uuid.UUID) (*defs.APIMoQSession, error) { + panic("unused") +} + +func (dummyMoQServer) APISessionsKick(uuid.UUID) error { + panic("unused") +} + +type emptyPathManager struct{} + +func (emptyPathManager) APIPathsList() (*defs.APIPathList, error) { + return &defs.APIPathList{}, nil +} + +func (emptyPathManager) APIPathsGet(string) (*defs.APIPath, error) { + panic("unused") +} + +type emptyHLSServer struct{} + +func (emptyHLSServer) APIMuxersList() (*defs.APIHLSMuxerList, error) { + return &defs.APIHLSMuxerList{}, nil +} + +func (emptyHLSServer) APIMuxersGet(string) (*defs.APIHLSMuxer, error) { + panic("unused") +} + +func (emptyHLSServer) APISessionsList() (*defs.APIHLSSessionList, error) { + return &defs.APIHLSSessionList{}, nil +} + +func (emptyHLSServer) APISessionsGet(uuid.UUID) (*defs.APIHLSSession, error) { + panic("unused") +} + +func (emptyHLSServer) APISessionsKick(uuid.UUID) error { + panic("unused") +} + +type emptyRTSPServer struct{} + +func (emptyRTSPServer) APIConnsList() (*defs.APIRTSPConnsList, error) { + return &defs.APIRTSPConnsList{}, nil +} + +func (emptyRTSPServer) APIConnsGet(uuid.UUID) (*defs.APIRTSPConn, error) { + panic("unused") +} + +func (emptyRTSPServer) APISessionsList() (*defs.APIRTSPSessionList, error) { + return &defs.APIRTSPSessionList{}, nil +} + +func (emptyRTSPServer) APISessionsGet(uuid.UUID) (*defs.APIRTSPSession, error) { + panic("unused") +} + +func (emptyRTSPServer) APISessionsKick(uuid.UUID) error { + panic("unused") +} + +type emptySRTServer struct{} + +func (emptySRTServer) APIConnsList() (*defs.APISRTConnList, error) { + return &defs.APISRTConnList{}, nil +} + +func (emptySRTServer) APIConnsGet(uuid.UUID) (*defs.APISRTConn, error) { + panic("unused") +} + +func (emptySRTServer) APIConnsKick(uuid.UUID) error { + panic("unused") +} + +type emptyWebRTCServer struct{} + +func (emptyWebRTCServer) APISessionsList() (*defs.APIWebRTCSessionList, error) { + return &defs.APIWebRTCSessionList{}, nil +} + +func (emptyWebRTCServer) APISessionsGet(uuid.UUID) (*defs.APIWebRTCSession, error) { + panic("unused") +} + +func (emptyWebRTCServer) APISessionsKick(uuid.UUID) error { + panic("unused") +} + +type emptyMoQServer struct{} + +func (emptyMoQServer) APISessionsList() (*defs.APIMoQSessionList, error) { + return &defs.APIMoQSessionList{}, nil +} + +func (emptyMoQServer) APISessionsGet(uuid.UUID) (*defs.APIMoQSession, error) { + panic("unused") +} + +func (emptyMoQServer) APISessionsKick(uuid.UUID) error { + panic("unused") +} + +func TestPreflightRequest(t *testing.T) { + m := Metrics{ + Address: "localhost:9998", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + AuthManager: test.NilAuthManager, + Parent: test.NilLogger, + } + err := m.Initialize() + require.NoError(t, err) + defer m.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + req, err := http.NewRequest(http.MethodOptions, "http://localhost:9998", nil) + require.NoError(t, err) + + req.Header.Add("Access-Control-Request-Method", "GET") + + res, err := hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusNoContent, res.StatusCode) + + byts, err := io.ReadAll(res.Body) + require.NoError(t, err) + + require.Equal(t, "*", res.Header.Get("Access-Control-Allow-Origin")) + require.Equal(t, "true", res.Header.Get("Access-Control-Allow-Credentials")) + require.Equal(t, "OPTIONS, GET", res.Header.Get("Access-Control-Allow-Methods")) + require.Equal(t, "Authorization", res.Header.Get("Access-Control-Allow-Headers")) + require.Equal(t, byts, []byte{}) +} + +func TestMetrics(t *testing.T) { + checked := false + + m := Metrics{ + Address: "localhost:9998", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + AuthManager: &test.AuthManager{ + AuthenticateImpl: func(req *auth.Request) (string, *auth.Error) { + require.Equal(t, conf.AuthActionMetrics, req.Action) + require.Equal(t, "myuser", req.Credentials.User) + require.Equal(t, "mypass", req.Credentials.Pass) + checked = true + return req.Credentials.User, nil + }, + }, + Parent: test.NilLogger, + } + err := m.Initialize() + require.NoError(t, err) + defer m.Close() + + m.SetPathManager(&dummyPathManager{}) + m.SetHLSServer(&dummyHLSServer{}) + m.SetRTSPServer(&dummyRTSPServer{}) + m.SetRTSPSServer(&dummyRTSPServer{}) + m.SetRTMPServer(&dummyRTMPServer{}) + m.SetRTMPSServer(&dummyRTMPServer{}) + m.SetSRTServer(&dummySRTServer{}) + m.SetWebRTCServer(&dummyWebRTCServer{}) + m.SetMoQServer(&dummyMoQServer{}) + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + res, err := hc.Get("http://myuser:mypass@localhost:9998/metrics") + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusOK, res.StatusCode) + + byts, err := io.ReadAll(res.Body) + require.NoError(t, err) + + require.Equal(t, + "# Paths\n"+ //nolint:dupl + "paths{name=\"mypath\",state=\"ready\"} 1\n"+ + "paths_readers{name=\"mypath\",readerType=\"rtmpConn\",state=\"ready\"} 1\n"+ + "paths_readers{name=\"mypath\",readerType=\"rtspSession\",state=\"ready\"} 2\n"+ + "paths_inbound_bytes{name=\"mypath\",state=\"ready\"} 123\n"+ + "paths_outbound_bytes{name=\"mypath\",state=\"ready\"} 456\n"+ + "paths_inbound_frames_in_error{name=\"mypath\",state=\"ready\"} 7\n"+ + "\n"+ + "# Paths (deprecated)\n"+ + "paths_bytes_received{name=\"mypath\",state=\"ready\"} 123\n"+ + "paths_bytes_sent{name=\"mypath\",state=\"ready\"} 456\n"+ + "\n"+ + "# HLS sessions\n"+ + "hls_sessions{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\"} 1\n"+ + "hls_sessions_outbound_bytes{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\"} 187\n"+ + "\n"+ + "# HLS muxers\n"+ + "hls_muxers{name=\"mypath\"} 1\n"+ + "hls_muxers_outbound_bytes{name=\"mypath\"} 789\n"+ + "hls_muxers_outbound_frames_discarded{name=\"mypath\"} 12\n"+ + "\n"+ + "# HLS muxers (deprecated)\n"+ + "hls_muxers_bytes_sent{name=\"mypath\"} 789\n"+ + "\n"+ + "# RTSP connections\n"+ + "rtsp_conns{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\"} 1\n"+ + "rtsp_conns_inbound_bytes{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\"} 123\n"+ + "rtsp_conns_outbound_bytes{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\"} 456\n"+ + "\n"+ + "# RTSP connections (deprecated)\n"+ + "rtsp_conns_bytes_received{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\"} 123\n"+ + "rtsp_conns_bytes_sent{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\"} 456\n"+ + "\n"+ + "# RTSP sessions\n"+ + "rtsp_sessions{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 1\n"+ + "rtsp_sessions_inbound_bytes{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsp_sessions_inbound_rtp_packets{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "rtsp_sessions_inbound_rtp_packets_lost{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsp_sessions_inbound_rtp_packets_in_error{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "rtsp_sessions_inbound_rtp_packets_jitter{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsp_sessions_inbound_rtcp_packets{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsp_sessions_inbound_rtcp_packets_in_error{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsp_sessions_outbound_bytes{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsp_sessions_outbound_rtp_packets{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsp_sessions_outbound_rtp_packets_reported_lost{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 321\n"+ + "rtsp_sessions_outbound_rtp_packets_discarded{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 111\n"+ + "rtsp_sessions_outbound_rtcp_packets{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "\n"+ + "# RTSP sessions (deprecated)\n"+ + "rtsp_sessions_bytes_received{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsp_sessions_bytes_sent{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsp_sessions_rtp_packets_received{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "rtsp_sessions_rtp_packets_sent{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsp_sessions_rtp_packets_lost{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsp_sessions_rtp_packets_in_error{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "rtsp_sessions_rtp_packets_jitter{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsp_sessions_rtcp_packets_received{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsp_sessions_rtcp_packets_sent{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "rtsp_sessions_rtcp_packets_in_error{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "\n"+ + "# RTSPS connections\n"+ + "rtsps_conns{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\"} 1\n"+ + "rtsps_conns_inbound_bytes{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\"} 123\n"+ + "rtsps_conns_outbound_bytes{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\"} 456\n"+ + "\n"+ + "# RTSPS connections (deprecated)\n"+ + "rtsps_conns_bytes_received{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\"} 123\n"+ + "rtsps_conns_bytes_sent{id=\"18294761-f9d1-4ea9-9a35-fe265b62eb41\"} 456\n"+ + "\n"+ + "# RTSPS sessions\n"+ + "rtsps_sessions{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 1\n"+ + "rtsps_sessions_inbound_bytes{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsps_sessions_inbound_rtp_packets{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "rtsps_sessions_inbound_rtp_packets_lost{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsps_sessions_inbound_rtp_packets_in_error{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "rtsps_sessions_inbound_rtp_packets_jitter{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsps_sessions_inbound_rtcp_packets{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsps_sessions_inbound_rtcp_packets_in_error{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsps_sessions_outbound_bytes{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsps_sessions_outbound_rtp_packets{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsps_sessions_outbound_rtp_packets_reported_lost{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 321\n"+ + "rtsps_sessions_outbound_rtp_packets_discarded{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 111\n"+ + "rtsps_sessions_outbound_rtcp_packets{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "\n"+ + "# RTSPS sessions (deprecated)\n"+ + "rtsps_sessions_bytes_received{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsps_sessions_bytes_sent{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsps_sessions_rtp_packets_received{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "rtsps_sessions_rtp_packets_sent{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsps_sessions_rtp_packets_lost{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsps_sessions_rtp_packets_in_error{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "rtsps_sessions_rtp_packets_jitter{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 123\n"+ + "rtsps_sessions_rtcp_packets_received{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "rtsps_sessions_rtcp_packets_sent{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 789\n"+ + "rtsps_sessions_rtcp_packets_in_error{id=\"124b22ce-9c34-4387-b045-44caf98049f7\",path=\"mypath\","+ + "remoteAddr=\"124.5.5.5:34542\",state=\"publish\"} 456\n"+ + "\n"+ + "# RTMP connections\n"+ + "rtmp_conns{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 1\n"+ + "rtmp_conns_inbound_bytes{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 123\n"+ + "rtmp_conns_outbound_bytes{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 456\n"+ + "rtmp_conns_outbound_frames_discarded{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 12\n"+ + "\n"+ + "# RTMP connections (deprecated)\n"+ + "rtmp_conns_bytes_received{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 123\n"+ + "rtmp_conns_bytes_sent{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 456\n"+ + "\n"+ + "# RTMPS connections\n"+ + "rtmps_conns{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 1\n"+ + "rtmps_conns_inbound_bytes{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 123\n"+ + "rtmps_conns_outbound_bytes{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 456\n"+ + "rtmps_conns_outbound_frames_discarded{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 12\n"+ + "\n"+ + "# RTMPS connections (deprecated)\n"+ + "rtmps_conns_bytes_received{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 123\n"+ + "rtmps_conns_bytes_sent{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 456\n"+ + "\n"+ + "# SRT connections\n"+ + "srt_conns{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 1\n"+ + "srt_conns_packets_sent{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 100\n"+ + "srt_conns_packets_received{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 200\n"+ + "srt_conns_packets_sent_unique{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 90\n"+ + "srt_conns_packets_received_unique{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 180\n"+ + "srt_conns_packets_send_loss{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 10\n"+ + "srt_conns_packets_received_loss{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 20\n"+ + "srt_conns_packets_retrans{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 5\n"+ + "srt_conns_packets_received_retrans{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 3\n"+ + "srt_conns_packets_sent_ack{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 50\n"+ + "srt_conns_packets_received_ack{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 40\n"+ + "srt_conns_packets_sent_nak{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 2\n"+ + "srt_conns_packets_received_nak{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 1\n"+ + "srt_conns_packets_sent_km{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 4\n"+ + "srt_conns_packets_received_km{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 3\n"+ + "srt_conns_us_snd_duration{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 1000000\n"+ + "srt_conns_packets_received_belated{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 7\n"+ + "srt_conns_packets_send_drop{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 8\n"+ + "srt_conns_packets_received_drop{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 6\n"+ + "srt_conns_packets_received_undecrypt{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 0\n"+ + "srt_conns_bytes_sent{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 12345\n"+ + "srt_conns_bytes_received{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 67890\n"+ + "srt_conns_bytes_sent_unique{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 11000\n"+ + "srt_conns_bytes_received_unique{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 60000\n"+ + "srt_conns_bytes_received_loss{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 500\n"+ + "srt_conns_bytes_retrans{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 300\n"+ + "srt_conns_bytes_received_retrans{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 200\n"+ + "srt_conns_bytes_received_belated{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 100\n"+ + "srt_conns_bytes_send_drop{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 400\n"+ + "srt_conns_bytes_received_drop{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 350\n"+ + "srt_conns_bytes_received_undecrypt{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 0\n"+ + "srt_conns_us_packets_send_period{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 10.5\n"+ + "srt_conns_packets_flow_window{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 8192\n"+ + "srt_conns_packets_flight_size{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 25\n"+ + "srt_conns_ms_rtt{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 1.5\n"+ + "srt_conns_mbps_send_rate{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 50\n"+ + "srt_conns_mbps_receive_rate{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 48\n"+ + "srt_conns_mbps_link_capacity{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 100\n"+ + "srt_conns_bytes_avail_send_buf{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 65536\n"+ + "srt_conns_bytes_avail_receive_buf{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 65536\n"+ + "srt_conns_mbps_max_bw{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 100\n"+ + "srt_conns_bytes_mss{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 1500\n"+ + "srt_conns_packets_send_buf{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 10\n"+ + "srt_conns_bytes_send_buf{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 15000\n"+ + "srt_conns_ms_send_buf{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 120\n"+ + "srt_conns_ms_send_tsb_pd_delay{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 120\n"+ + "srt_conns_packets_receive_buf{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 15\n"+ + "srt_conns_bytes_receive_buf{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 22500\n"+ + "srt_conns_ms_receive_buf{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 120\n"+ + "srt_conns_ms_receive_tsb_pd_delay{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 120\n"+ + "srt_conns_packets_reorder_tolerance{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 3\n"+ + "srt_conns_packets_received_avg_belated_time{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 50\n"+ + "srt_conns_packets_send_loss_rate{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 0.01\n"+ + "srt_conns_packets_received_loss_rate{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 0.02\n"+ + "srt_conns_outbound_frames_discarded{id=\"a0b1c2d3-e4f5-6789-abcd-ef0123456789\",path=\"mypath\","+ + "remoteAddr=\"5.5.5.5:4321\",state=\"publish\"} 5\n"+ + "\n"+ + "# WebRTC sessions\n"+ + "webrtc_sessions{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 1\n"+ + "webrtc_sessions_inbound_bytes{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_inbound_rtp_packets{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 789\n"+ + "webrtc_sessions_inbound_rtp_packets_lost{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n"+ + "webrtc_sessions_inbound_rtp_packets_jitter{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 789\n"+ + "webrtc_sessions_inbound_rtcp_packets{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_outbound_bytes{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n"+ + "webrtc_sessions_outbound_rtp_packets{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_outbound_rtcp_packets{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n"+ + "webrtc_sessions_outbound_frames_discarded{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 12\n"+ + "\n"+ + "# WebRTC sessions (deprecated)\n"+ + "webrtc_sessions_bytes_received{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_bytes_sent{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n"+ + "webrtc_sessions_rtp_packets_received{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 789\n"+ + "webrtc_sessions_rtp_packets_sent{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_rtp_packets_lost{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n"+ + "webrtc_sessions_rtp_packets_jitter{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 789\n"+ + "webrtc_sessions_rtcp_packets_received{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_rtcp_packets_sent{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n"+ + "\n"+ + "# MoQ sessions\n"+ + "moq_sessions{id=\"b47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.2:3456\",state=\"publish\"} 1\n"+ + "moq_sessions_inbound_bytes{id=\"b47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.2:3456\",state=\"publish\"} 321\n"+ + "moq_sessions_outbound_bytes{id=\"b47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.2:3456\",state=\"publish\"} 654\n"+ + "\n", + string(byts)) + + require.True(t, checked) +} + +func TestZeroMetricsFallback(t *testing.T) { + m := Metrics{ + Address: "localhost:9998", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + AuthManager: test.NilAuthManager, + Parent: test.NilLogger, + } + err := m.Initialize() + require.NoError(t, err) + defer m.Close() + + m.SetPathManager(&emptyPathManager{}) + m.SetHLSServer(&emptyHLSServer{}) + m.SetRTSPServer(&emptyRTSPServer{}) + m.SetSRTServer(&emptySRTServer{}) + m.SetWebRTCServer(&emptyWebRTCServer{}) + m.SetMoQServer(&emptyMoQServer{}) + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + res, err := hc.Get("http://localhost:9998/metrics") + require.NoError(t, err) + defer res.Body.Close() + + byts, err := io.ReadAll(res.Body) + require.NoError(t, err) + + require.Equal(t, + "# Paths\n"+ //nolint:dupl + "paths 0\n"+ + "paths_inbound_bytes 0\n"+ + "paths_outbound_bytes 0\n"+ + "paths_inbound_frames_in_error 0\n"+ + "\n"+ + "# Paths (deprecated)\n"+ + "paths_bytes_received 0\n"+ + "paths_bytes_sent 0\n"+ + "paths_readers 0\n"+ + "\n"+ + "# HLS sessions\n"+ + "hls_sessions 0\n"+ + `hls_sessions_outbound_bytes 0`+"\n"+ + "\n"+ + "# HLS muxers\n"+ + "hls_muxers 0\n"+ + "hls_muxers_outbound_bytes 0\n"+ + "hls_muxers_outbound_frames_discarded 0\n"+ + "\n"+ + "# HLS muxers (deprecated)\n"+ + "hls_muxers_bytes_sent 0\n"+ + "\n"+ + "# RTSP connections\n"+ + "rtsp_conns 0\n"+ + "rtsp_conns_inbound_bytes 0\n"+ + "rtsp_conns_outbound_bytes 0\n"+ + "\n"+ + "# RTSP connections (deprecated)\n"+ + "rtsp_conns_bytes_received 0\n"+ + "rtsp_conns_bytes_sent 0\n"+ + "\n"+ + "# RTSP sessions\n"+ + "rtsp_sessions 0\n"+ + "rtsp_sessions_inbound_bytes 0\n"+ + "rtsp_sessions_inbound_rtp_packets 0\n"+ + "rtsp_sessions_inbound_rtp_packets_lost 0\n"+ + "rtsp_sessions_inbound_rtp_packets_in_error 0\n"+ + "rtsp_sessions_inbound_rtp_packets_jitter 0\n"+ + "rtsp_sessions_inbound_rtcp_packets 0\n"+ + "rtsp_sessions_inbound_rtcp_packets_in_error 0\n"+ + "rtsp_sessions_outbound_bytes 0\n"+ + "rtsp_sessions_outbound_rtp_packets 0\n"+ + "rtsp_sessions_outbound_rtp_packets_reported_lost 0\n"+ + "rtsp_sessions_outbound_rtp_packets_discarded 0\n"+ + "rtsp_sessions_outbound_rtcp_packets 0\n"+ + "\n"+ + "# RTSP sessions (deprecated)\n"+ + "rtsp_sessions_bytes_received 0\n"+ + "rtsp_sessions_bytes_sent 0\n"+ + "rtsp_sessions_rtp_packets_received 0\n"+ + "rtsp_sessions_rtp_packets_sent 0\n"+ + "rtsp_sessions_rtp_packets_lost 0\n"+ + "rtsp_sessions_rtp_packets_in_error 0\n"+ + "rtsp_sessions_rtp_packets_jitter 0\n"+ + "rtsp_sessions_rtcp_packets_received 0\n"+ + "rtsp_sessions_rtcp_packets_sent 0\n"+ + "rtsp_sessions_rtcp_packets_in_error 0\n"+ + "\n"+ + "# SRT connections\n"+ + "srt_conns 0\n"+ + "srt_conns_packets_sent 0\n"+ + "srt_conns_packets_received 0\n"+ + "srt_conns_packets_sent_unique 0\n"+ + "srt_conns_packets_received_unique 0\n"+ + "srt_conns_packets_send_loss 0\n"+ + "srt_conns_packets_received_loss 0\n"+ + "srt_conns_packets_retrans 0\n"+ + "srt_conns_packets_received_retrans 0\n"+ + "srt_conns_packets_sent_ack 0\n"+ + "srt_conns_packets_received_ack 0\n"+ + "srt_conns_packets_sent_nak 0\n"+ + "srt_conns_packets_received_nak 0\n"+ + "srt_conns_packets_sent_km 0\n"+ + "srt_conns_packets_received_km 0\n"+ + "srt_conns_us_snd_duration 0\n"+ + "srt_conns_packets_received_belated 0\n"+ + "srt_conns_packets_send_drop 0\n"+ + "srt_conns_packets_received_drop 0\n"+ + "srt_conns_packets_received_undecrypt 0\n"+ + "srt_conns_bytes_sent 0\n"+ + "srt_conns_bytes_received 0\n"+ + "srt_conns_bytes_sent_unique 0\n"+ + "srt_conns_bytes_received_unique 0\n"+ + "srt_conns_bytes_received_loss 0\n"+ + "srt_conns_bytes_retrans 0\n"+ + "srt_conns_bytes_received_retrans 0\n"+ + "srt_conns_bytes_received_belated 0\n"+ + "srt_conns_bytes_send_drop 0\n"+ + "srt_conns_bytes_received_drop 0\n"+ + "srt_conns_bytes_received_undecrypt 0\n"+ + "srt_conns_us_packets_send_period 0\n"+ + "srt_conns_packets_flow_window 0\n"+ + "srt_conns_packets_flight_size 0\n"+ + "srt_conns_ms_rtt 0\n"+ + "srt_conns_mbps_send_rate 0\n"+ + "srt_conns_mbps_receive_rate 0\n"+ + "srt_conns_mbps_link_capacity 0\n"+ + "srt_conns_bytes_avail_send_buf 0\n"+ + "srt_conns_bytes_avail_receive_buf 0\n"+ + "srt_conns_mbps_max_bw 0\n"+ + "srt_conns_bytes_mss 0\n"+ + "srt_conns_packets_send_buf 0\n"+ + "srt_conns_bytes_send_buf 0\n"+ + "srt_conns_ms_send_buf 0\n"+ + "srt_conns_ms_send_tsb_pd_delay 0\n"+ + "srt_conns_packets_receive_buf 0\n"+ + "srt_conns_bytes_receive_buf 0\n"+ + "srt_conns_ms_receive_buf 0\n"+ + "srt_conns_ms_receive_tsb_pd_delay 0\n"+ + "srt_conns_packets_reorder_tolerance 0\n"+ + "srt_conns_packets_received_avg_belated_time 0\n"+ + "srt_conns_packets_send_loss_rate 0\n"+ + "srt_conns_packets_received_loss_rate 0\n"+ + "srt_conns_outbound_frames_discarded 0\n"+ + "\n"+ + "# WebRTC sessions\n"+ + "webrtc_sessions 0\n"+ + "webrtc_sessions_inbound_bytes 0\n"+ + "webrtc_sessions_inbound_rtp_packets 0\n"+ + "webrtc_sessions_inbound_rtp_packets_lost 0\n"+ + "webrtc_sessions_inbound_rtp_packets_jitter 0\n"+ + "webrtc_sessions_inbound_rtcp_packets 0\n"+ + "webrtc_sessions_outbound_bytes 0\n"+ + "webrtc_sessions_outbound_rtp_packets 0\n"+ + "webrtc_sessions_outbound_rtcp_packets 0\n"+ + "webrtc_sessions_outbound_frames_discarded 0\n"+ + "\n"+ + "# WebRTC sessions (deprecated)\n"+ + "webrtc_sessions_bytes_received 0\n"+ + "webrtc_sessions_bytes_sent 0\n"+ + "webrtc_sessions_rtp_packets_received 0\n"+ + "webrtc_sessions_rtp_packets_sent 0\n"+ + "webrtc_sessions_rtp_packets_lost 0\n"+ + "webrtc_sessions_rtp_packets_jitter 0\n"+ + "webrtc_sessions_rtcp_packets_received 0\n"+ + "webrtc_sessions_rtcp_packets_sent 0\n"+ + "\n"+ + "# MoQ sessions\n"+ + "moq_sessions 0\n"+ + "moq_sessions_inbound_bytes 0\n"+ + "moq_sessions_outbound_bytes 0\n"+ + "\n", + string(byts)) +} + +func TestFilter(t *testing.T) { + for _, ca := range []string{ + "path", + "hls_muxer", + "hls_session", + "rtsp_conn", + "rtsp_session", + "rtsps_conn", + "rtsps_session", + "rtmp_conn", + "rtmps_conn", + "srt_conn", + "webrtc_session", + "moq_session", + } { + t.Run(ca, func(t *testing.T) { + m := Metrics{ + Address: "localhost:9998", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + AuthManager: test.NilAuthManager, + Parent: test.NilLogger, + } + err := m.Initialize() + require.NoError(t, err) + defer m.Close() + + m.SetPathManager(&dummyPathManager{}) + m.SetHLSServer(&dummyHLSServer{}) + m.SetRTSPServer(&dummyRTSPServer{}) + m.SetRTSPSServer(&dummyRTSPServer{}) + m.SetRTMPServer(&dummyRTMPServer{}) + m.SetRTMPSServer(&dummyRTMPServer{}) + m.SetSRTServer(&dummySRTServer{}) + m.SetWebRTCServer(&dummyWebRTCServer{}) + m.SetMoQServer(&dummyMoQServer{}) + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + u := "http://localhost:9998/metrics" + + switch ca { + case "path": + u += "?path=mypath" + case "hls_muxer": + u += "?hls_muxer=mypath" + case "hls_session": + u += "?hls_session=18294761-f9d1-4ea9-9a35-fe265b62eb41" + case "rtsp_conn": + u += "?rtsp_conn=18294761-f9d1-4ea9-9a35-fe265b62eb41" + case "rtsp_session": + u += "?rtsp_session=124b22ce-9c34-4387-b045-44caf98049f7" + case "rtsps_conn": + u += "?rtsps_conn=18294761-f9d1-4ea9-9a35-fe265b62eb41" + case "rtsps_session": + u += "?rtsps_session=124b22ce-9c34-4387-b045-44caf98049f7" + case "rtmp_conn": + u += "?rtmp_conn=9a07afe4-fc07-4c9b-be6e-6255720c36d0" + case "rtmps_conn": + u += "?rtmps_conn=9a07afe4-fc07-4c9b-be6e-6255720c36d0" + case "srt_conn": + u += "?srt_conn=a0b1c2d3-e4f5-6789-abcd-ef0123456789" + case "webrtc_session": + u += "?webrtc_session=f47ac10b-58cc-4372-a567-0e02b2c3d479" + case "moq_session": + u += "?moq_session=b47ac10b-58cc-4372-a567-0e02b2c3d479" + } + + res, err := hc.Get(u) + require.NoError(t, err) + defer res.Body.Close() + + byts, err := io.ReadAll(res.Body) + require.NoError(t, err) + + switch ca { + case "path": + require.Equal(t, + "# Paths\n"+ + `paths{name="mypath",state="ready"} 1`+"\n"+ + `paths_readers{name="mypath",readerType="rtmpConn",state="ready"} 1`+"\n"+ + `paths_readers{name="mypath",readerType="rtspSession",state="ready"} 2`+"\n"+ + `paths_inbound_bytes{name="mypath",state="ready"} 123`+"\n"+ + `paths_outbound_bytes{name="mypath",state="ready"} 456`+"\n"+ + `paths_inbound_frames_in_error{name="mypath",state="ready"} 7`+"\n"+ + "\n"+ + "# Paths (deprecated)\n"+ + `paths_bytes_received{name="mypath",state="ready"} 123`+"\n"+ + `paths_bytes_sent{name="mypath",state="ready"} 456`+"\n\n", + string(byts)) + + case "hls_muxer": + require.Equal(t, + "# HLS muxers\n"+ + `hls_muxers{name="mypath"} 1`+"\n"+ + `hls_muxers_outbound_bytes{name="mypath"} 789`+"\n"+ + `hls_muxers_outbound_frames_discarded{name="mypath"} 12`+"\n"+ + "\n"+ + "# HLS muxers (deprecated)\n"+ + `hls_muxers_bytes_sent{name="mypath"} 789`+"\n\n", + string(byts)) + + case "hls_session": + require.Equal(t, + "# HLS sessions\n"+ + `hls_sessions{id="18294761-f9d1-4ea9-9a35-fe265b62eb41",path="mypath",`+ + `remoteAddr="124.5.5.5:34542"} 1`+"\n"+ + `hls_sessions_outbound_bytes{id="18294761-f9d1-4ea9-9a35-fe265b62eb41",path="mypath",`+ + `remoteAddr="124.5.5.5:34542"} 187`+"\n"+ + "\n", + string(byts)) + + case "rtsp_conn": + require.Equal(t, + "# RTSP connections\n"+ + `rtsp_conns{id="18294761-f9d1-4ea9-9a35-fe265b62eb41"} 1`+"\n"+ + `rtsp_conns_inbound_bytes{id="18294761-f9d1-4ea9-9a35-fe265b62eb41"} 123`+"\n"+ + `rtsp_conns_outbound_bytes{id="18294761-f9d1-4ea9-9a35-fe265b62eb41"} 456`+"\n"+ + "\n"+ + "# RTSP connections (deprecated)\n"+ + `rtsp_conns_bytes_received{id="18294761-f9d1-4ea9-9a35-fe265b62eb41"} 123`+"\n"+ + `rtsp_conns_bytes_sent{id="18294761-f9d1-4ea9-9a35-fe265b62eb41"} 456`+"\n\n", + string(byts)) + + case "rtsp_session": //nolint:dupl + require.Equal(t, + "# RTSP sessions\n"+ + `rtsp_sessions{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 1`+"\n"+ + `rtsp_sessions_inbound_bytes{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsp_sessions_inbound_rtp_packets{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + `rtsp_sessions_inbound_rtp_packets_lost{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsp_sessions_inbound_rtp_packets_in_error{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + `rtsp_sessions_inbound_rtp_packets_jitter{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsp_sessions_inbound_rtcp_packets{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsp_sessions_inbound_rtcp_packets_in_error{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsp_sessions_outbound_bytes{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsp_sessions_outbound_rtp_packets{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsp_sessions_outbound_rtp_packets_reported_lost{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 321`+"\n"+ + `rtsp_sessions_outbound_rtp_packets_discarded{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 111`+"\n"+ + `rtsp_sessions_outbound_rtcp_packets{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + "\n"+ + "# RTSP sessions (deprecated)\n"+ + `rtsp_sessions_bytes_received{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsp_sessions_bytes_sent{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsp_sessions_rtp_packets_received{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + `rtsp_sessions_rtp_packets_sent{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsp_sessions_rtp_packets_lost{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsp_sessions_rtp_packets_in_error{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + `rtsp_sessions_rtp_packets_jitter{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsp_sessions_rtcp_packets_received{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsp_sessions_rtcp_packets_sent{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + `rtsp_sessions_rtcp_packets_in_error{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n\n", + string(byts)) + + case "rtsps_conn": + require.Equal(t, + "# RTSPS connections\n"+ + `rtsps_conns{id="18294761-f9d1-4ea9-9a35-fe265b62eb41"} 1`+"\n"+ + `rtsps_conns_inbound_bytes{id="18294761-f9d1-4ea9-9a35-fe265b62eb41"} 123`+"\n"+ + `rtsps_conns_outbound_bytes{id="18294761-f9d1-4ea9-9a35-fe265b62eb41"} 456`+"\n"+ + "\n"+ + "# RTSPS connections (deprecated)\n"+ + `rtsps_conns_bytes_received{id="18294761-f9d1-4ea9-9a35-fe265b62eb41"} 123`+"\n"+ + `rtsps_conns_bytes_sent{id="18294761-f9d1-4ea9-9a35-fe265b62eb41"} 456`+"\n\n", + string(byts)) + + case "rtsps_session": //nolint:dupl + require.Equal(t, + "# RTSPS sessions\n"+ + `rtsps_sessions{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 1`+"\n"+ + `rtsps_sessions_inbound_bytes{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsps_sessions_inbound_rtp_packets{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + `rtsps_sessions_inbound_rtp_packets_lost{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsps_sessions_inbound_rtp_packets_in_error{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + `rtsps_sessions_inbound_rtp_packets_jitter{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsps_sessions_inbound_rtcp_packets{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsps_sessions_inbound_rtcp_packets_in_error{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsps_sessions_outbound_bytes{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsps_sessions_outbound_rtp_packets{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsps_sessions_outbound_rtp_packets_reported_lost{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 321`+"\n"+ + `rtsps_sessions_outbound_rtp_packets_discarded{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 111`+"\n"+ + `rtsps_sessions_outbound_rtcp_packets{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + "\n"+ + "# RTSPS sessions (deprecated)\n"+ + `rtsps_sessions_bytes_received{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsps_sessions_bytes_sent{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsps_sessions_rtp_packets_received{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + `rtsps_sessions_rtp_packets_sent{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsps_sessions_rtp_packets_lost{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsps_sessions_rtp_packets_in_error{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + `rtsps_sessions_rtp_packets_jitter{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 123`+"\n"+ + `rtsps_sessions_rtcp_packets_received{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n"+ + `rtsps_sessions_rtcp_packets_sent{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 789`+"\n"+ + `rtsps_sessions_rtcp_packets_in_error{id="124b22ce-9c34-4387-b045-44caf98049f7",`+ + `path="mypath",remoteAddr="124.5.5.5:34542",state="publish"} 456`+"\n\n", + string(byts)) + + case "rtmp_conn": + require.Equal(t, + "# RTMP connections\n"+ + "rtmp_conns{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 1\n"+ + "rtmp_conns_inbound_bytes{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 123\n"+ + "rtmp_conns_outbound_bytes{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 456\n"+ + "rtmp_conns_outbound_frames_discarded{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 12\n"+ + "\n"+ + "# RTMP connections (deprecated)\n"+ + "rtmp_conns_bytes_received{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 123\n"+ + "rtmp_conns_bytes_sent{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 456\n\n", + string(byts)) + + case "rtmps_conn": + require.Equal(t, + "# RTMPS connections\n"+ + `rtmps_conns{id="9a07afe4-fc07-4c9b-be6e-6255720c36d0",`+ + `path="mypath",remoteAddr="3.3.3.3:5678",state="read"} 1`+"\n"+ + `rtmps_conns_inbound_bytes{id="9a07afe4-fc07-4c9b-be6e-6255720c36d0",`+ + `path="mypath",remoteAddr="3.3.3.3:5678",state="read"} 123`+"\n"+ + `rtmps_conns_outbound_bytes{id="9a07afe4-fc07-4c9b-be6e-6255720c36d0",`+ + `path="mypath",remoteAddr="3.3.3.3:5678",state="read"} 456`+"\n"+ + `rtmps_conns_outbound_frames_discarded{id="9a07afe4-fc07-4c9b-be6e-6255720c36d0",`+ + `path="mypath",remoteAddr="3.3.3.3:5678",state="read"} 12`+"\n"+ + "\n"+ + "# RTMPS connections (deprecated)\n"+ + `rtmps_conns_bytes_received{id="9a07afe4-fc07-4c9b-be6e-6255720c36d0",`+ + `path="mypath",remoteAddr="3.3.3.3:5678",state="read"} 123`+"\n"+ + `rtmps_conns_bytes_sent{id="9a07afe4-fc07-4c9b-be6e-6255720c36d0",`+ + `path="mypath",remoteAddr="3.3.3.3:5678",state="read"} 456`+"\n\n", + string(byts)) + + case "srt_conn": + require.Equal(t, + "# SRT connections\n"+ //nolint:dupl + `srt_conns{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 1`+"\n"+ + `srt_conns_packets_sent{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 100`+"\n"+ + `srt_conns_packets_received{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 200`+"\n"+ + `srt_conns_packets_sent_unique{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 90`+"\n"+ + `srt_conns_packets_received_unique{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 180`+"\n"+ + `srt_conns_packets_send_loss{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 10`+"\n"+ + `srt_conns_packets_received_loss{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 20`+"\n"+ + `srt_conns_packets_retrans{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 5`+"\n"+ + `srt_conns_packets_received_retrans{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 3`+"\n"+ + `srt_conns_packets_sent_ack{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 50`+"\n"+ + `srt_conns_packets_received_ack{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 40`+"\n"+ + `srt_conns_packets_sent_nak{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 2`+"\n"+ + `srt_conns_packets_received_nak{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 1`+"\n"+ + `srt_conns_packets_sent_km{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 4`+"\n"+ + `srt_conns_packets_received_km{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 3`+"\n"+ + `srt_conns_us_snd_duration{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 1000000`+"\n"+ + `srt_conns_packets_received_belated{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 7`+"\n"+ + `srt_conns_packets_send_drop{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 8`+"\n"+ + `srt_conns_packets_received_drop{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 6`+"\n"+ + `srt_conns_packets_received_undecrypt{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 0`+"\n"+ + `srt_conns_bytes_sent{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 12345`+"\n"+ + `srt_conns_bytes_received{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 67890`+"\n"+ + `srt_conns_bytes_sent_unique{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 11000`+"\n"+ + `srt_conns_bytes_received_unique{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 60000`+"\n"+ + `srt_conns_bytes_received_loss{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 500`+"\n"+ + `srt_conns_bytes_retrans{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 300`+"\n"+ + `srt_conns_bytes_received_retrans{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 200`+"\n"+ + `srt_conns_bytes_received_belated{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 100`+"\n"+ + `srt_conns_bytes_send_drop{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 400`+"\n"+ + `srt_conns_bytes_received_drop{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 350`+"\n"+ + `srt_conns_bytes_received_undecrypt{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 0`+"\n"+ + `srt_conns_us_packets_send_period{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 10.5`+"\n"+ + `srt_conns_packets_flow_window{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 8192`+"\n"+ + `srt_conns_packets_flight_size{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 25`+"\n"+ + `srt_conns_ms_rtt{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 1.5`+"\n"+ + `srt_conns_mbps_send_rate{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 50`+"\n"+ + `srt_conns_mbps_receive_rate{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 48`+"\n"+ + `srt_conns_mbps_link_capacity{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 100`+"\n"+ + `srt_conns_bytes_avail_send_buf{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 65536`+"\n"+ + `srt_conns_bytes_avail_receive_buf{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 65536`+"\n"+ + `srt_conns_mbps_max_bw{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 100`+"\n"+ + `srt_conns_bytes_mss{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 1500`+"\n"+ + `srt_conns_packets_send_buf{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 10`+"\n"+ + `srt_conns_bytes_send_buf{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 15000`+"\n"+ + `srt_conns_ms_send_buf{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 120`+"\n"+ + `srt_conns_ms_send_tsb_pd_delay{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 120`+"\n"+ + `srt_conns_packets_receive_buf{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 15`+"\n"+ + `srt_conns_bytes_receive_buf{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 22500`+"\n"+ + `srt_conns_ms_receive_buf{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 120`+"\n"+ + `srt_conns_ms_receive_tsb_pd_delay{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 120`+"\n"+ + `srt_conns_packets_reorder_tolerance{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 3`+"\n"+ + `srt_conns_packets_received_avg_belated_time{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 50`+"\n"+ + `srt_conns_packets_send_loss_rate{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 0.01`+"\n"+ + `srt_conns_packets_received_loss_rate{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 0.02`+"\n"+ + `srt_conns_outbound_frames_discarded{id="a0b1c2d3-e4f5-6789-abcd-ef0123456789",`+ + `path="mypath",remoteAddr="5.5.5.5:4321",state="publish"} 5`+"\n\n", + string(byts)) + + case "webrtc_session": + require.Equal(t, + "# WebRTC sessions\n"+ + `webrtc_sessions{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 1`+"\n"+ + `webrtc_sessions_inbound_bytes{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 123`+"\n"+ + `webrtc_sessions_inbound_rtp_packets{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 789`+"\n"+ + `webrtc_sessions_inbound_rtp_packets_lost{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 456`+"\n"+ + `webrtc_sessions_inbound_rtp_packets_jitter{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 789`+"\n"+ + `webrtc_sessions_inbound_rtcp_packets{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 123`+"\n"+ + `webrtc_sessions_outbound_bytes{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 456`+"\n"+ + `webrtc_sessions_outbound_rtp_packets{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 123`+"\n"+ + `webrtc_sessions_outbound_rtcp_packets{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 456`+"\n"+ + `webrtc_sessions_outbound_frames_discarded{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 12`+"\n"+ + "\n"+ + "# WebRTC sessions (deprecated)\n"+ + `webrtc_sessions_bytes_received{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 123`+"\n"+ + `webrtc_sessions_bytes_sent{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 456`+"\n"+ + `webrtc_sessions_rtp_packets_received{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 789`+"\n"+ + `webrtc_sessions_rtp_packets_sent{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 123`+"\n"+ + `webrtc_sessions_rtp_packets_lost{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 456`+"\n"+ + `webrtc_sessions_rtp_packets_jitter{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 789`+"\n"+ + `webrtc_sessions_rtcp_packets_received{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 123`+"\n"+ + `webrtc_sessions_rtcp_packets_sent{id="f47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.1:3455",state="read"} 456`+"\n\n", + string(byts)) + + case "moq_session": + require.Equal(t, + "# MoQ sessions\n"+ + `moq_sessions{id="b47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.2:3456",state="publish"} 1`+"\n"+ + `moq_sessions_inbound_bytes{id="b47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.2:3456",state="publish"} 321`+"\n"+ + `moq_sessions_outbound_bytes{id="b47ac10b-58cc-4372-a567-0e02b2c3d479",`+ + `path="mypath",remoteAddr="127.0.0.2:3456",state="publish"} 654`+"\n\n", + string(byts)) + } + }) + } +} + +func TestFilterByType(t *testing.T) { + for _, ca := range []string{"paths", "rtmp_conns", "rtmps_conns", "webrtc_sessions"} { + t.Run(ca, func(t *testing.T) { + m := Metrics{ + Address: "localhost:9998", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + AuthManager: test.NilAuthManager, + Parent: test.NilLogger, + } + err := m.Initialize() + require.NoError(t, err) + defer m.Close() + + m.SetPathManager(&dummyPathManager{}) + m.SetHLSServer(&dummyHLSServer{}) + m.SetRTSPServer(&dummyRTSPServer{}) + m.SetRTSPSServer(&dummyRTSPServer{}) + m.SetRTMPServer(&dummyRTMPServer{}) + m.SetRTMPSServer(&dummyRTMPServer{}) + m.SetSRTServer(&dummySRTServer{}) + m.SetWebRTCServer(&dummyWebRTCServer{}) + m.SetMoQServer(&dummyMoQServer{}) + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + var query string + switch ca { + case "paths": + query = "type=paths" + + case "rtmp_conns": + query = "type=rtmp_conns" + + case "rtmps_conns": + query = "type=rtmps_conns" + + case "webrtc_sessions": + query = "type=webrtc_sessions" + } + + res, err := hc.Get("http://localhost:9998/metrics?" + query) + require.NoError(t, err) + defer res.Body.Close() + + byts, err := io.ReadAll(res.Body) + require.NoError(t, err) + + switch ca { + case "paths": + require.Equal(t, + "# Paths\n"+ + "paths{name=\"mypath\",state=\"ready\"} 1\n"+ + "paths_readers{name=\"mypath\",readerType=\"rtmpConn\",state=\"ready\"} 1\n"+ + "paths_readers{name=\"mypath\",readerType=\"rtspSession\",state=\"ready\"} 2\n"+ + "paths_inbound_bytes{name=\"mypath\",state=\"ready\"} 123\n"+ + "paths_outbound_bytes{name=\"mypath\",state=\"ready\"} 456\n"+ + "paths_inbound_frames_in_error{name=\"mypath\",state=\"ready\"} 7\n"+ + "\n"+ + "# Paths (deprecated)\n"+ + "paths_bytes_received{name=\"mypath\",state=\"ready\"} 123\n"+ + "paths_bytes_sent{name=\"mypath\",state=\"ready\"} 456\n\n", + string(byts)) + + case "rtmp_conns": + require.Equal(t, + "# RTMP connections\n"+ + "rtmp_conns{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 1\n"+ + "rtmp_conns_inbound_bytes{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 123\n"+ + "rtmp_conns_outbound_bytes{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 456\n"+ + "rtmp_conns_outbound_frames_discarded{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 12\n"+ + "\n"+ + "# RTMP connections (deprecated)\n"+ + "rtmp_conns_bytes_received{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 123\n"+ + "rtmp_conns_bytes_sent{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 456\n\n", + string(byts)) + + case "rtmps_conns": + require.Equal(t, + "# RTMPS connections\n"+ + "rtmps_conns{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 1\n"+ + "rtmps_conns_inbound_bytes{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 123\n"+ + "rtmps_conns_outbound_bytes{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 456\n"+ + "rtmps_conns_outbound_frames_discarded{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 12\n"+ + "\n"+ + "# RTMPS connections (deprecated)\n"+ + "rtmps_conns_bytes_received{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 123\n"+ + "rtmps_conns_bytes_sent{id=\"9a07afe4-fc07-4c9b-be6e-6255720c36d0\",path=\"mypath\","+ + "remoteAddr=\"3.3.3.3:5678\",state=\"read\"} 456\n\n", + string(byts)) + + case "webrtc_sessions": + require.Equal(t, + "# WebRTC sessions\n"+ + "webrtc_sessions{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 1\n"+ + "webrtc_sessions_inbound_bytes{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_inbound_rtp_packets{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 789\n"+ + "webrtc_sessions_inbound_rtp_packets_lost{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n"+ + "webrtc_sessions_inbound_rtp_packets_jitter{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 789\n"+ + "webrtc_sessions_inbound_rtcp_packets{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_outbound_bytes{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n"+ + "webrtc_sessions_outbound_rtp_packets{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_outbound_rtcp_packets{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n"+ + "webrtc_sessions_outbound_frames_discarded{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 12\n"+ + "\n"+ + "# WebRTC sessions (deprecated)\n"+ + "webrtc_sessions_bytes_received{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_bytes_sent{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n"+ + "webrtc_sessions_rtp_packets_received{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 789\n"+ + "webrtc_sessions_rtp_packets_sent{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_rtp_packets_lost{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n"+ + "webrtc_sessions_rtp_packets_jitter{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 789\n"+ + "webrtc_sessions_rtcp_packets_received{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 123\n"+ + "webrtc_sessions_rtcp_packets_sent{id=\"f47ac10b-58cc-4372-a567-0e02b2c3d479\",path=\"mypath\","+ + "remoteAddr=\"127.0.0.1:3455\",state=\"read\"} 456\n\n", + string(byts)) + } + }) + } +} + +func TestAuthError(t *testing.T) { + n := 0 + + m := Metrics{ + Address: "localhost:9998", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + AuthManager: &test.AuthManager{ + AuthenticateImpl: func(req *auth.Request) (string, *auth.Error) { + if req.Credentials.User == "" { + return "", &auth.Error{AskCredentials: true, Wrapped: fmt.Errorf("auth error")} + } + return "", &auth.Error{Wrapped: fmt.Errorf("auth error")} + }, + }, + Parent: test.Logger(func(l logger.Level, s string, i ...any) { + if l == logger.Info { + if n == 1 { + require.Regexp(t, "failed to authenticate: auth error$", fmt.Sprintf(s, i...)) + } + n++ + } + }), + } + err := m.Initialize() + require.NoError(t, err) + defer m.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + res, err := hc.Get("http://localhost:9998/metrics") + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusUnauthorized, res.StatusCode) + require.Equal(t, `Basic realm="mediamtx"`, res.Header.Get("WWW-Authenticate")) + + res, err = hc.Get("http://myuser:mypass@localhost:9998/metrics") + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusUnauthorized, res.StatusCode) + + require.Equal(t, 2, n) +} + +func TestMetricsConcurrentSettersAndReads(t *testing.T) { + m := Metrics{ + Address: "localhost:9998", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + AuthManager: test.NilAuthManager, + Parent: test.NilLogger, + } + err := m.Initialize() + require.NoError(t, err) + defer m.Close() + + m.SetPathManager(&dummyPathManager{}) + m.SetHLSServer(&dummyHLSServer{}) + m.SetRTSPServer(&dummyRTSPServer{}) + m.SetRTSPSServer(&dummyRTSPServer{}) + m.SetRTMPServer(&dummyRTMPServer{}) + m.SetRTMPSServer(&dummyRTMPServer{}) + m.SetSRTServer(&dummySRTServer{}) + m.SetWebRTCServer(&dummyWebRTCServer{}) + m.SetMoQServer(&dummyMoQServer{}) + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + var readers sync.WaitGroup + for range 8 { + readers.Go(func() { + for range 100 { + res, err2 := hc.Get("http://localhost:9998/metrics") + require.NoError(t, err2) + _, err2 = io.Copy(io.Discard, res.Body) + res.Body.Close() + require.NoError(t, err2) + } + }) + } + + for range 1000 { + m.SetPathManager(&dummyPathManager{}) + m.SetHLSServer(&dummyHLSServer{}) + m.SetRTSPServer(&dummyRTSPServer{}) + m.SetRTSPSServer(&dummyRTSPServer{}) + m.SetRTMPServer(&dummyRTMPServer{}) + m.SetRTMPSServer(&dummyRTMPServer{}) + m.SetSRTServer(&dummySRTServer{}) + m.SetWebRTCServer(&dummyWebRTCServer{}) + m.SetMoQServer(&dummyMoQServer{}) + + m.SetHLSServer(nil) + m.SetRTSPServer(nil) + m.SetRTSPSServer(nil) + m.SetRTMPServer(nil) + m.SetRTMPSServer(nil) + m.SetSRTServer(nil) + m.SetWebRTCServer(nil) + m.SetMoQServer(nil) + } + + readers.Wait() +} + +func BenchmarkTags(b *testing.B) { + m := map[string]string{ + "id": "124b22ce-9c34-4387-b045-44caf98049f7", + "state": "publish", + "path": "mypath", + "remoteAddr": "124.5.5.5:34542", + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + tags(m) + } +} + +func BenchmarkMetric(b *testing.B) { + ta := tags(map[string]string{ + "id": "124b22ce-9c34-4387-b045-44caf98049f7", + "state": "publish", + "path": "mypath", + "remoteAddr": "124.5.5.5:34542", + }) + var out strings.Builder + b.ResetTimer() + for i := 0; i < b.N; i++ { + out.Reset() + metric(&out, "rtsp_sessions_inbound_bytes", ta, 123) + } +} + +func BenchmarkFullMetricsHandler(b *testing.B) { + m := Metrics{ + Address: "localhost:9998", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + AuthManager: test.NilAuthManager, + Parent: test.NilLogger, + } + err := m.Initialize() + if err != nil { + b.Fatal(err) + } + defer m.Close() + + m.SetPathManager(&dummyPathManager{}) + m.SetHLSServer(&dummyHLSServer{}) + m.SetRTSPServer(&dummyRTSPServer{}) + m.SetRTSPSServer(&dummyRTSPServer{}) + m.SetRTMPServer(&dummyRTMPServer{}) + m.SetRTMPSServer(&dummyRTMPServer{}) + m.SetSRTServer(&dummySRTServer{}) + m.SetWebRTCServer(&dummyWebRTCServer{}) + m.SetMoQServer(&dummyMoQServer{}) + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + b.ResetTimer() + for i := 0; i < b.N; i++ { + var res *http.Response + res, err = hc.Get("http://localhost:9998/metrics") + if err != nil { + b.Fatal(err) + } + io.Copy(io.Discard, res.Body) + res.Body.Close() + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/ntpestimator/estimator.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/ntpestimator/estimator.go new file mode 100644 index 0000000000000000000000000000000000000000..ecdf8e8cf8ea95eac75e29b9f014f98c5c53f8f2 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/ntpestimator/estimator.go @@ -0,0 +1,53 @@ +// Package ntpestimator contains a NTP estimator. +package ntpestimator + +import ( + "time" +) + +const ( + maxTimeDifference = 5 * time.Second +) + +var timeNow = time.Now + +func multiplyAndDivide(v, m, d time.Duration) time.Duration { + secs := v / d + dec := v % d + return (secs*m + dec*m/d) +} + +// Estimator is a NTP estimator. +type Estimator struct { + ClockRate int + + refNTP time.Time + refPTS int64 +} + +var zero = time.Time{} + +// Estimate returns estimated NTP. +func (e *Estimator) Estimate(pts int64) time.Time { + now := timeNow() + + // do not store monotonic clock, in order to include + // system clock changes into time differences + now = now.Round(0) + + if e.refNTP.Equal(zero) { + e.refNTP = now + e.refPTS = pts + return now + } + + computed := e.refNTP.Add((multiplyAndDivide(time.Duration(pts-e.refPTS), time.Second, time.Duration(e.ClockRate)))) + + if computed.After(now) || computed.Before(now.Add(-maxTimeDifference)) { + e.refNTP = now + e.refPTS = pts + return now + } + + return computed +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/ntpestimator/estimator_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/ntpestimator/estimator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f9f5e5c75009153facc38b6ecf78e2793727b676 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/ntpestimator/estimator_test.go @@ -0,0 +1,36 @@ +package ntpestimator + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestEstimator(t *testing.T) { + e := &Estimator{ClockRate: 90000} + + timeNow = func() time.Time { return time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC) } + ntp := e.Estimate(90000) + require.Equal(t, time.Date(2003, 11, 4, 23, 15, 7, 0, time.UTC), ntp) + + timeNow = func() time.Time { return time.Date(2003, 11, 4, 23, 15, 8, 0, time.UTC) } + ntp = e.Estimate(2 * 90000) + require.Equal(t, time.Date(2003, 11, 4, 23, 15, 8, 0, time.UTC), ntp) + + timeNow = func() time.Time { return time.Date(2003, 11, 4, 23, 15, 10, 0, time.UTC) } + ntp = e.Estimate(3 * 90000) + require.Equal(t, time.Date(2003, 11, 4, 23, 15, 9, 0, time.UTC), ntp) + + timeNow = func() time.Time { return time.Date(2003, 11, 4, 23, 15, 9, 0, time.UTC) } + ntp = e.Estimate(4 * 90000) + require.Equal(t, time.Date(2003, 11, 4, 23, 15, 9, 0, time.UTC), ntp) + + timeNow = func() time.Time { return time.Date(2003, 11, 4, 23, 15, 15, 0, time.UTC) } + ntp = e.Estimate(5 * 90000) + require.Equal(t, time.Date(2003, 11, 4, 23, 15, 10, 0, time.UTC), ntp) + + timeNow = func() time.Time { return time.Date(2003, 11, 4, 23, 15, 20, 0, time.UTC) } + ntp = e.Estimate(6 * 90000) + require.Equal(t, time.Date(2003, 11, 4, 23, 15, 20, 0, time.UTC), ntp) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/conn.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/conn.go new file mode 100644 index 0000000000000000000000000000000000000000..11fbbcecbcdd96b5b158e5252655c8c15eefc426 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/conn.go @@ -0,0 +1,318 @@ +// Package packetdumper provides utilities to dump packets to disk. +package packetdumper + +import ( + "encoding/binary" + "fmt" + "io" + "net" + "os" + "sync" + "sync/atomic" + "time" + + "github.com/google/gopacket" + "github.com/google/gopacket/layers" + "github.com/google/gopacket/pcapgo" + "github.com/google/uuid" +) + +var _ net.Conn = (*conn)(nil) + +type direction int + +const ( + dirInbound direction = iota + dirOutbound + dirHandshake + dirSecret +) + +func writeDecryptionSecretsBlock(f io.Writer, data []byte) { + const ( + dsbSecretTypeTLS = 0x544c534b + blockType = 0x0000000A + fixedHeaderBytes = 4 + 4 + 4 + 4 // type + totalLen + secretsType + secretsLen + trailerBytes = 4 // repeated totalLen + overheadBytes = fixedHeaderBytes + trailerBytes + ) + + secretsLen := len(data) + paddedLen := (secretsLen + 3) &^ 3 + padBytes := paddedLen - secretsLen + + totalLen := uint32(overheadBytes + paddedLen) + + buf := make([]byte, totalLen) + pos := 0 + + binary.LittleEndian.PutUint32(buf[pos:], blockType) + pos += 4 + binary.LittleEndian.PutUint32(buf[pos:], totalLen) + pos += 4 + binary.LittleEndian.PutUint32(buf[pos:], dsbSecretTypeTLS) + pos += 4 + binary.LittleEndian.PutUint32(buf[pos:], uint32(secretsLen)) // unpadded length, per spec + pos += 4 + pos += copy(buf[pos:], data) + pos += padBytes // zero padding already present (make zeroes) + binary.LittleEndian.PutUint32(buf[pos:], totalLen) // trailing repeat + + f.Write(buf) //nolint:errcheck +} + +type dumpEntry struct { + ntp time.Time + data []byte + direction direction +} + +// conn is a wrapper around net.Conn that dumps packets to disk. +type conn struct { + Prefix string + Conn net.Conn + ServerSide bool + + expectingSecrets atomic.Int32 + f *os.File + pw *pcapgo.NgWriter + once sync.Once + local *net.TCPAddr + remote *net.TCPAddr + nextLocalSequence uint32 + nextRemoteSequence uint32 + delayed []dumpEntry + + queue chan dumpEntry + terminated chan struct{} + done chan struct{} +} + +// Initialize initializes conn. +func (c *conn) Initialize() error { + var err error + c.f, err = os.Create(fmt.Sprintf("%s_%d_%s.pcapng", c.Prefix, time.Now().UnixNano(), uuid.New().String())) + if err != nil { + return err + } + + c.pw, err = pcapgo.NewNgWriter(c.f, layers.LinkTypeEthernet) + if err != nil { + c.f.Close() + return err + } + + c.local = c.Conn.LocalAddr().(*net.TCPAddr) + c.remote = c.Conn.RemoteAddr().(*net.TCPAddr) + + if c.ServerSide { + c.nextLocalSequence = uint32(2000) + c.nextRemoteSequence = uint32(1000) + } else { + c.nextLocalSequence = uint32(1000) + c.nextRemoteSequence = uint32(2000) + } + + c.queue = make(chan dumpEntry, 64) + c.terminated = make(chan struct{}) + c.done = make(chan struct{}) + + go c.run() + + c.enqueue(dumpEntry{ntp: time.Now(), direction: dirHandshake}) + + return nil +} + +// Close implements net.Conn. +func (c *conn) Close() error { + c.once.Do(func() { + close(c.terminated) + }) + <-c.done + return c.Conn.Close() +} + +func (c *conn) run() { + defer close(c.done) + defer c.f.Close() + defer c.pw.Flush() //nolint:errcheck + + for { + select { + case e := <-c.queue: + c.processEntry(e) + + case <-c.terminated: + // Drain anything already in the queue before exiting. + for { + select { + case e := <-c.queue: + c.processEntry(e) + default: + return + } + } + } + } +} + +func (c *conn) processEntry(e dumpEntry) { + if c.expectingSecrets.Load() > 0 && e.direction != dirSecret { + c.delayed = append(c.delayed, e) + return + } + + switch e.direction { + case dirHandshake: + clientAddr, serverAddr := c.local, c.remote // client side: local initiates + clientSeq, serverSeq := &c.nextLocalSequence, &c.nextRemoteSequence + if c.ServerSide { + clientAddr, serverAddr = c.remote, c.local // server side: remote initiates + clientSeq, serverSeq = &c.nextRemoteSequence, &c.nextLocalSequence + } + + // SYN (client -> server) + c.writePacket(e.ntp, clientAddr, serverAddr, + layers.TCP{SYN: true, Window: 65535, Seq: *clientSeq, Ack: 0}, nil) + *clientSeq++ + + // SYN-ACK (server -> client) + c.writePacket(e.ntp, serverAddr, clientAddr, + layers.TCP{SYN: true, ACK: true, Window: 65535, Seq: *serverSeq, Ack: *clientSeq}, nil) + *serverSeq++ + + // ACK (client -> server) + c.writePacket(e.ntp, clientAddr, serverAddr, + layers.TCP{ACK: true, Window: 65535, Seq: *clientSeq, Ack: *serverSeq}, nil) + + case dirSecret: + c.pw.Flush() //nolint:errcheck + writeDecryptionSecretsBlock(c.f, e.data) + + if c.expectingSecrets.Add(-1) == 0 { + for _, e2 := range c.delayed { + c.processEntry(e2) + } + c.delayed = nil + } + + case dirInbound: + tcpFlags := layers.TCP{ + PSH: true, + ACK: true, + Window: 14600, + Seq: c.nextRemoteSequence, + Ack: c.nextLocalSequence, + } + c.writePacket(e.ntp, c.remote, c.local, tcpFlags, e.data) + c.nextRemoteSequence += uint32(len(e.data)) + + case dirOutbound: + tcpFlags := layers.TCP{ + PSH: true, + ACK: true, + Window: 14600, + Seq: c.nextLocalSequence, + Ack: c.nextRemoteSequence, + } + c.writePacket(e.ntp, c.local, c.remote, tcpFlags, e.data) + c.nextLocalSequence += uint32(len(e.data)) + } +} + +func (c *conn) writePacket( + ntp time.Time, + src, dst *net.TCPAddr, + tcpFlags layers.TCP, + payload []byte, +) { + eth := &layers.Ethernet{ + SrcMAC: net.HardwareAddr{0, 0, 0, 0, 0, 0}, + DstMAC: net.HardwareAddr{0, 0, 0, 0, 0, 0}, + EthernetType: layers.EthernetTypeIPv6, + } + + ipv6 := &layers.IPv6{ + Version: 6, + SrcIP: src.IP.To16(), + DstIP: dst.IP.To16(), + NextHeader: layers.IPProtocolTCP, + HopLimit: 64, + } + + tcp := &layers.TCP{ + SrcPort: layers.TCPPort(src.Port), + DstPort: layers.TCPPort(dst.Port), + Seq: tcpFlags.Seq, + Ack: tcpFlags.Ack, + Window: tcpFlags.Window, + SYN: tcpFlags.SYN, + ACK: tcpFlags.ACK, + PSH: tcpFlags.PSH, + FIN: tcpFlags.FIN, + } + tcp.SetNetworkLayerForChecksum(ipv6) //nolint:errcheck + + buf := gopacket.NewSerializeBuffer() + opts := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true} + gopacket.SerializeLayers(buf, opts, eth, ipv6, tcp, gopacket.Payload(payload)) //nolint:errcheck + + raw := buf.Bytes() + + c.pw.WritePacket(gopacket.CaptureInfo{ //nolint:errcheck + Timestamp: ntp, + CaptureLength: len(raw), + Length: len(raw), + }, raw) +} + +func (c *conn) enqueue(e dumpEntry) { + select { + case c.queue <- e: + case <-c.terminated: + } +} + +func (c *conn) Read(p []byte) (n int, err error) { + n, err = c.Conn.Read(p) + + if n != 0 { + c.enqueue(dumpEntry{ + ntp: time.Now(), + data: append([]byte(nil), p[:n]...), + direction: dirInbound, + }) + } + + return n, err +} + +func (c *conn) Write(p []byte) (n int, err error) { + n, err = c.Conn.Write(p) + + if err == nil { + c.enqueue(dumpEntry{ + ntp: time.Now(), + data: append([]byte(nil), p...), + direction: dirOutbound, + }) + } + + return n, err +} + +// LocalAddr implements net.Conn. +func (c *conn) LocalAddr() net.Addr { return c.Conn.LocalAddr() } + +// RemoteAddr implements net.Conn. +func (c *conn) RemoteAddr() net.Addr { return c.Conn.RemoteAddr() } + +// SetDeadline implements net.Conn. +func (c *conn) SetDeadline(t time.Time) error { return c.Conn.SetDeadline(t) } + +// SetReadDeadline implements net.Conn. +func (c *conn) SetReadDeadline(t time.Time) error { return c.Conn.SetReadDeadline(t) } + +// SetWriteDeadline implements net.Conn. +func (c *conn) SetWriteDeadline(t time.Time) error { return c.Conn.SetWriteDeadline(t) } diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/conn_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/conn_test.go new file mode 100644 index 0000000000000000000000000000000000000000..44c9344b4438dad6e6543492dd928da99986ee6e --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/conn_test.go @@ -0,0 +1,193 @@ +package packetdumper + +import ( + "io" + "net" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// startTCPPair dials a local TCP listener and returns both ends of the connection. +func startTCPPair(t *testing.T) (client, server net.Conn) { + t.Helper() + + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + + serverCh := make(chan net.Conn, 1) + go func() { + conn, err2 := ln.Accept() + if err2 == nil { + serverCh <- conn + } + }() + + client, err = net.Dial("tcp", ln.Addr().String()) + require.NoError(t, err) + + t.Cleanup(func() { ln.Close() }) + + select { + case server = <-serverCh: + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for server connection") + } + + return client, server +} + +func checkPcapngPresence(t *testing.T, prefix string) { + t.Helper() + matches, err := filepath.Glob(prefix + "_*.pcapng") + require.NoError(t, err) + require.NotEmpty(t, matches, "expected at least one pcapng file to have been created") +} + +func TestConnInitialize_CreatesFile(t *testing.T) { + client, server := startTCPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &conn{Prefix: prefix, Conn: client} + require.NoError(t, c.Initialize()) + + c.Close() //nolint:errcheck + server.Close() + + checkPcapngPresence(t, prefix) +} + +func TestConnWrite(t *testing.T) { + client, server := startTCPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &conn{Prefix: prefix, Conn: client} + require.NoError(t, c.Initialize()) + + n, err := c.Write([]byte("hello world")) + require.NoError(t, err) + require.Equal(t, 11, n) + + buf := make([]byte, 11) + _, err = io.ReadFull(server, buf) + require.NoError(t, err) + require.Equal(t, []byte("hello world"), buf) + + c.Close() //nolint:errcheck + server.Close() + + checkPcapngPresence(t, prefix) +} + +func TestConnRead(t *testing.T) { + client, server := startTCPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &conn{Prefix: prefix, Conn: client} + require.NoError(t, c.Initialize()) + + _, err := server.Write([]byte("incoming data")) + require.NoError(t, err) + + buf := make([]byte, 32) + n, err := c.Read(buf) + require.NoError(t, err) + require.Equal(t, []byte("incoming data"), buf[:n]) + + c.Close() //nolint:errcheck + server.Close() + + checkPcapngPresence(t, prefix) +} + +func TestConnServerSide(t *testing.T) { + client, server := startTCPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &conn{Prefix: prefix, Conn: server, ServerSide: true} + require.NoError(t, c.Initialize()) + + n, err := c.Write([]byte("server response")) + require.NoError(t, err) + require.Equal(t, 15, n) + + buf := make([]byte, 15) + _, err = io.ReadFull(client, buf) + require.NoError(t, err) + require.Equal(t, []byte("server response"), buf) + + c.Close() //nolint:errcheck + client.Close() + + checkPcapngPresence(t, prefix) +} + +func TestConnMultipleWriteRead(t *testing.T) { + client, server := startTCPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &conn{Prefix: prefix, Conn: client} + require.NoError(t, c.Initialize()) + + for _, msg := range []string{"foo", "bar", "baz"} { + n, err := c.Write([]byte(msg)) + require.NoError(t, err) + require.Equal(t, len(msg), n) + } + + buf := make([]byte, len("foobarbaz")) + _, err := io.ReadFull(server, buf) + require.NoError(t, err) + require.Equal(t, []byte("foobarbaz"), buf) + + _, err = server.Write([]byte("abcde")) + require.NoError(t, err) + _, err = server.Write([]byte("fghij")) + require.NoError(t, err) + + readBuf := make([]byte, 10) + _, err = io.ReadFull(c, readBuf) + require.NoError(t, err) + require.Equal(t, []byte("abcdefghij"), readBuf) + + c.Close() //nolint:errcheck + server.Close() + + checkPcapngPresence(t, prefix) +} + +func TestConnCloseIdempotent(t *testing.T) { + client, server := startTCPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &conn{Prefix: prefix, Conn: client} + require.NoError(t, c.Initialize()) + + c.Close() //nolint:errcheck + c.Close() //nolint:errcheck + server.Close() + + checkPcapngPresence(t, prefix) +} + +func TestConnDelegatesAddrMethods(t *testing.T) { + client, server := startTCPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &conn{Prefix: prefix, Conn: client} + require.NoError(t, c.Initialize()) + + require.Equal(t, client.LocalAddr(), c.LocalAddr()) + require.Equal(t, client.RemoteAddr(), c.RemoteAddr()) + + require.NoError(t, c.SetDeadline(time.Now().Add(time.Second))) + require.NoError(t, c.SetReadDeadline(time.Now().Add(time.Second))) + require.NoError(t, c.SetWriteDeadline(time.Now().Add(time.Second))) + + c.Close() //nolint:errcheck + server.Close() + + checkPcapngPresence(t, prefix) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/dial_context.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/dial_context.go new file mode 100644 index 0000000000000000000000000000000000000000..7664f4715e4de3881dc36477631a758e7513a6c5 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/dial_context.go @@ -0,0 +1,31 @@ +package packetdumper + +import ( + "context" + "net" +) + +// DialContext is a wrapper around net.Dialer.DialContext that dumps packets to disk. +type DialContext struct { + Prefix string +} + +// Do mimics net.Dialer.DialContext. +func (d *DialContext) Do(ctx context.Context, network, address string) (net.Conn, error) { + netConn, err := (&net.Dialer{}).DialContext(ctx, network, address) + if err != nil { + return nil, err + } + + pdConn := &conn{ + Prefix: d.Prefix, + Conn: netConn, + } + err = pdConn.Initialize() + if err != nil { + netConn.Close() + return nil, err + } + + return pdConn, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/dial_tls_context.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/dial_tls_context.go new file mode 100644 index 0000000000000000000000000000000000000000..6792db8524b49f780dc0625dbf681dd3c1269f54 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/dial_tls_context.go @@ -0,0 +1,43 @@ +package packetdumper + +import ( + "context" + "crypto/tls" + "net" +) + +// DialTLSContext provides the DialTLSContext function. +type DialTLSContext struct { + DialContext func(ctx context.Context, network, addr string) (net.Conn, error) + TLSConfig *tls.Config +} + +// Do provides DialTLSContext. +func (t *DialTLSContext) Do(ctx context.Context, network, addr string) (net.Conn, error) { + netConn, err := t.DialContext(ctx, network, addr) + if err != nil { + return nil, err + } + + // clone TLS config and fill ServerName if empty. + // this is the same behavior of http.Client. + // https://cs.opensource.google/go/go/+/master:src/net/http/transport.go;l=1754;drc=a4b534f5e42fe58d58c0ff0562d76680cedb0466 + tlsConfig := t.TLSConfig + + if tlsConfig == nil { + tlsConfig = &tls.Config{} + } else { + tlsConfig = tlsConfig.Clone() + } + + if tlsConfig.ServerName == "" { + host, _, _ := net.SplitHostPort(addr) + tlsConfig.ServerName = host + } + + pdConn := netConn.(*conn) + pdConn.expectingSecrets.Store(4) + tlsConfig.KeyLogWriter = &connKeyLogWriter{c: pdConn} + + return tls.Client(netConn, tlsConfig), nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/listener.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/listener.go new file mode 100644 index 0000000000000000000000000000000000000000..b6a4463a15a33a447128afaab2a7aa055cbdc057 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/listener.go @@ -0,0 +1,42 @@ +package packetdumper + +import "net" + +var _ net.Listener = (*Listener)(nil) + +// Listener is a wrapper around a net.Listener that dumps packets to disk. +type Listener struct { + Wrapped net.Listener + Prefix string +} + +// Accept implements net.Listener. +func (l *Listener) Accept() (net.Conn, error) { + netConn, err := l.Wrapped.Accept() + if err != nil { + return nil, err + } + + pdConn := &conn{ + Prefix: l.Prefix, + Conn: netConn, + ServerSide: true, + } + err = pdConn.Initialize() + if err != nil { + netConn.Close() //nolint:errcheck + return nil, err + } + + return pdConn, nil +} + +// Close implements net.Listener. +func (l *Listener) Close() error { + return l.Wrapped.Close() +} + +// Addr implements net.Listener. +func (l *Listener) Addr() net.Addr { + return l.Wrapped.Addr() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/listener_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/listener_test.go new file mode 100644 index 0000000000000000000000000000000000000000..fb2a2b752645beae311395620ad3e8a2ce343fee --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/listener_test.go @@ -0,0 +1,44 @@ +package packetdumper + +import ( + "net" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestListener(t *testing.T) { + innerLn, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + + prefix := filepath.Join(t.TempDir(), "capture") + ln := &Listener{ + Wrapped: innerLn, + Prefix: prefix, + } + + require.Equal(t, innerLn.Addr(), ln.Addr()) + + clientConn, err := net.Dial("tcp", ln.Addr().String()) + require.NoError(t, err) + defer clientConn.Close() + + serverConn, err := ln.Accept() + require.NoError(t, err) + defer serverConn.Close() + + _, err = clientConn.Write([]byte("ping")) + require.NoError(t, err) + + buf := make([]byte, 4) + _, err = serverConn.Read(buf) + require.NoError(t, err) + require.Equal(t, []byte("ping"), buf) + + serverConn.Close() + clientConn.Close() + ln.Close() //nolint:errcheck + + checkPcapngPresence(t, prefix) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/packet_conn.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/packet_conn.go new file mode 100644 index 0000000000000000000000000000000000000000..6b45abb1863350f5750c1a24336905c880e12f4b --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/packet_conn.go @@ -0,0 +1,198 @@ +package packetdumper + +import ( + "fmt" + "net" + "os" + "sync" + "syscall" + "time" + + "github.com/google/gopacket" + "github.com/google/gopacket/layers" + "github.com/google/gopacket/pcapgo" + "github.com/google/uuid" +) + +var _ net.PacketConn = (*PacketConn)(nil) + +type extendedPacketConn interface { + net.PacketConn + SetReadBuffer(bytes int) error + SyscallConn() (syscall.RawConn, error) +} + +type packetDumpEntry struct { + ntp time.Time + data []byte + src, dst *net.UDPAddr +} + +// PacketConn is a wrapper around net.PacketConn that dumps packets to disk. +type PacketConn struct { + Prefix string + Wrapped net.PacketConn + + f *os.File + pw *pcapgo.NgWriter + once sync.Once + + queue chan packetDumpEntry + terminated chan struct{} + done chan struct{} +} + +// Initialize initializes packetConn. +func (c *PacketConn) Initialize() error { + var err error + c.f, err = os.Create(fmt.Sprintf("%s_%d_%s.pcapng", c.Prefix, time.Now().UnixNano(), uuid.New().String())) + if err != nil { + return err + } + + c.pw, err = pcapgo.NewNgWriter(c.f, layers.LinkTypeEthernet) + if err != nil { + c.f.Close() + return err + } + + c.queue = make(chan packetDumpEntry, 64) + c.terminated = make(chan struct{}) + c.done = make(chan struct{}) + + go c.run() + + return nil +} + +// Close implements net.PacketConn. +func (c *PacketConn) Close() error { + c.once.Do(func() { + close(c.terminated) + }) + <-c.done + return c.Wrapped.Close() +} + +func (c *PacketConn) run() { + defer close(c.done) + defer c.f.Close() + + for { + select { + case e := <-c.queue: + c.writePacket(e.ntp, e.src, e.dst, e.data) + + case <-c.terminated: + for { + select { + case e := <-c.queue: + c.writePacket(e.ntp, e.src, e.dst, e.data) + default: + c.pw.Flush() //nolint:errcheck + return + } + } + } + } +} + +func (c *PacketConn) writePacket(ntp time.Time, src, dst *net.UDPAddr, payload []byte) { + eth := &layers.Ethernet{ + SrcMAC: net.HardwareAddr{0, 0, 0, 0, 0, 0}, + DstMAC: net.HardwareAddr{0, 0, 0, 0, 0, 0}, + EthernetType: layers.EthernetTypeIPv6, + } + + ipv6 := &layers.IPv6{ + Version: 6, + SrcIP: src.IP.To16(), + DstIP: dst.IP.To16(), + NextHeader: layers.IPProtocolUDP, + HopLimit: 64, + } + + udp := &layers.UDP{ + SrcPort: layers.UDPPort(src.Port), + DstPort: layers.UDPPort(dst.Port), + } + udp.SetNetworkLayerForChecksum(ipv6) //nolint:errcheck + + buf := gopacket.NewSerializeBuffer() + opts := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true} + gopacket.SerializeLayers(buf, opts, eth, ipv6, udp, gopacket.Payload(payload)) //nolint:errcheck + + raw := buf.Bytes() + c.pw.WritePacket(gopacket.CaptureInfo{ //nolint:errcheck + Timestamp: ntp, + CaptureLength: len(raw), + Length: len(raw), + }, raw) +} + +func (c *PacketConn) enqueue(e packetDumpEntry) { + select { + case c.queue <- e: + case <-c.terminated: + } +} + +// ReadFrom implements net.PacketConn. +func (c *PacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { + n, addr, err = c.Wrapped.ReadFrom(p) + + if n != 0 { + local := c.Wrapped.LocalAddr().(*net.UDPAddr) + remote := addr.(*net.UDPAddr) + + c.enqueue(packetDumpEntry{ + ntp: time.Now(), + data: append([]byte(nil), p[:n]...), + src: remote, + dst: local, + }) + } + + return n, addr, err +} + +// WriteTo implements net.PacketConn. +func (c *PacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) { + n, err = c.Wrapped.WriteTo(p, addr) + + if err == nil { + local := c.Wrapped.LocalAddr().(*net.UDPAddr) + remote := addr.(*net.UDPAddr) + + c.enqueue(packetDumpEntry{ + ntp: time.Now(), + data: append([]byte(nil), p...), + src: local, + dst: remote, + }) + } + + return n, err +} + +// LocalAddr implements net.PacketConn. +func (c *PacketConn) LocalAddr() net.Addr { return c.Wrapped.LocalAddr() } + +// SetDeadline implements net.PacketConn. +func (c *PacketConn) SetDeadline(t time.Time) error { return c.Wrapped.SetDeadline(t) } + +// SetReadDeadline implements net.PacketConn. +func (c *PacketConn) SetReadDeadline(t time.Time) error { return c.Wrapped.SetReadDeadline(t) } + +// SetWriteDeadline implements net.PacketConn. +func (c *PacketConn) SetWriteDeadline(t time.Time) error { return c.Wrapped.SetWriteDeadline(t) } + +// SetReadBuffer implements extendedPacketConn. +func (c *PacketConn) SetReadBuffer(bytes int) error { + return c.Wrapped.(extendedPacketConn).SetReadBuffer(bytes) +} + +// SyscallConn implements extendedPacketConn. +func (c *PacketConn) SyscallConn() (syscall.RawConn, error) { + return c.Wrapped.(extendedPacketConn).SyscallConn() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/packet_conn_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/packet_conn_test.go new file mode 100644 index 0000000000000000000000000000000000000000..fc1114761350ce5902def5873bb2c46a6efc2451 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/packet_conn_test.go @@ -0,0 +1,195 @@ +package packetdumper + +import ( + "net" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// startUDPPair creates a pair of UDP connections and returns both ends. +func startUDPPair(t *testing.T) (client, server *net.UDPConn) { + t.Helper() + + serverAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0") + require.NoError(t, err) + + server, err = net.ListenUDP("udp", serverAddr) + require.NoError(t, err) + + clientAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0") + require.NoError(t, err) + + client, err = net.ListenUDP("udp", clientAddr) + require.NoError(t, err) + + t.Cleanup(func() { + server.Close() //nolint:errcheck + client.Close() //nolint:errcheck + }) + + return client, server +} + +func TestPacketConnInitialize_CreatesFile(t *testing.T) { + client, server := startUDPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &PacketConn{Prefix: prefix, Wrapped: client} + require.NoError(t, c.Initialize()) + + c.Close() //nolint:errcheck + server.Close() //nolint:errcheck + + checkPcapngPresence(t, prefix) +} + +func TestPacketConnWriteTo(t *testing.T) { + client, server := startUDPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &PacketConn{Prefix: prefix, Wrapped: client} + require.NoError(t, c.Initialize()) + + n, err := c.WriteTo([]byte("hello world"), server.LocalAddr()) + require.NoError(t, err) + require.Equal(t, 11, n) + + buf := make([]byte, 32) + server.SetReadDeadline(time.Now().Add(2 * time.Second)) //nolint:errcheck + rn, _, err := server.ReadFromUDP(buf) + require.NoError(t, err) + require.Equal(t, []byte("hello world"), buf[:rn]) + + c.Close() //nolint:errcheck + server.Close() //nolint:errcheck + + checkPcapngPresence(t, prefix) +} + +func TestPacketConnReadFrom(t *testing.T) { + client, server := startUDPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &PacketConn{Prefix: prefix, Wrapped: client} + require.NoError(t, c.Initialize()) + + _, err := server.WriteTo([]byte("incoming data"), client.LocalAddr()) + require.NoError(t, err) + + buf := make([]byte, 32) + c.SetReadDeadline(time.Now().Add(2 * time.Second)) //nolint:errcheck + n, addr, err := c.ReadFrom(buf) + require.NoError(t, err) + require.Equal(t, []byte("incoming data"), buf[:n]) + require.NotNil(t, addr) + + c.Close() //nolint:errcheck + server.Close() //nolint:errcheck + + checkPcapngPresence(t, prefix) +} + +func TestPacketConnMultipleWriteRead(t *testing.T) { + client, server := startUDPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &PacketConn{Prefix: prefix, Wrapped: client} + require.NoError(t, c.Initialize()) + + serverAddr := server.LocalAddr() + for _, msg := range []string{"foo", "bar", "baz"} { + n, err := c.WriteTo([]byte(msg), serverAddr) + require.NoError(t, err) + require.Equal(t, len(msg), n) + } + + server.SetReadDeadline(time.Now().Add(2 * time.Second)) //nolint:errcheck + buf := make([]byte, 32) + received := make([]byte, 0, 9) + for range 3 { + n, _, err := server.ReadFromUDP(buf) + require.NoError(t, err) + received = append(received, buf[:n]...) + } + require.Equal(t, []byte("foobarbaz"), received) + + for _, msg := range []string{"abcde", "fghij"} { + _, err := server.WriteTo([]byte(msg), client.LocalAddr()) + require.NoError(t, err) + } + + c.SetReadDeadline(time.Now().Add(2 * time.Second)) //nolint:errcheck + readReceived := make([]byte, 0, 10) + for range 2 { + n, _, err := c.ReadFrom(buf) + require.NoError(t, err) + readReceived = append(readReceived, buf[:n]...) + } + require.Equal(t, []byte("abcdefghij"), readReceived) + + c.Close() //nolint:errcheck + server.Close() //nolint:errcheck + + checkPcapngPresence(t, prefix) +} + +func TestPacketConnCloseIdempotent(t *testing.T) { + client, server := startUDPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &PacketConn{Prefix: prefix, Wrapped: client} + require.NoError(t, c.Initialize()) + + c.Close() //nolint:errcheck + c.Close() //nolint:errcheck + server.Close() //nolint:errcheck + + checkPcapngPresence(t, prefix) +} + +func TestPacketConnDelegatesAddrMethods(t *testing.T) { + client, server := startUDPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &PacketConn{Prefix: prefix, Wrapped: client} + require.NoError(t, c.Initialize()) + + require.Equal(t, client.LocalAddr(), c.LocalAddr()) + + require.NoError(t, c.SetDeadline(time.Now().Add(time.Second))) + require.NoError(t, c.SetReadDeadline(time.Now().Add(time.Second))) + require.NoError(t, c.SetWriteDeadline(time.Now().Add(time.Second))) + + c.Close() //nolint:errcheck + server.Close() //nolint:errcheck + + checkPcapngPresence(t, prefix) +} + +func TestPacketConnReadFromRecordsSource(t *testing.T) { + client, server := startUDPPair(t) + + prefix := filepath.Join(t.TempDir(), "capture") + c := &PacketConn{Prefix: prefix, Wrapped: client} + require.NoError(t, c.Initialize()) + + _, err := server.WriteTo([]byte("ping"), client.LocalAddr()) + require.NoError(t, err) + + buf := make([]byte, 32) + c.SetReadDeadline(time.Now().Add(2 * time.Second)) //nolint:errcheck + n, addr, err := c.ReadFrom(buf) + require.NoError(t, err) + require.Equal(t, []byte("ping"), buf[:n]) + + // The reported source address should match the server's address. + require.Equal(t, server.LocalAddr().String(), addr.String()) + + c.Close() //nolint:errcheck + server.Close() //nolint:errcheck + + checkPcapngPresence(t, prefix) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/tls_listener.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/tls_listener.go new file mode 100644 index 0000000000000000000000000000000000000000..69598435f3c9b884f3530f3460e40cc9451d5fc7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/tls_listener.go @@ -0,0 +1,54 @@ +package packetdumper + +import ( + "crypto/tls" + "net" + "time" +) + +type connKeyLogWriter struct { + c *conn +} + +func (w *connKeyLogWriter) Write(p []byte) (int, error) { + w.c.enqueue(dumpEntry{ + ntp: time.Now(), + data: append([]byte(nil), p...), + direction: dirSecret, + }) + + return len(p), nil +} + +var _ net.Listener = (*TLSListener)(nil) + +// TLSListener is a wrapper around a net.Listener that dumps TLS master secrets to disk. +type TLSListener struct { + Wrapped net.Listener + TLSConfig *tls.Config +} + +// Close implements net.Listener. +func (l *TLSListener) Close() error { + return l.Wrapped.Close() +} + +// Addr implements net.Listener. +func (l *TLSListener) Addr() net.Addr { + return l.Wrapped.Addr() +} + +// Accept implements net.Listener. +func (l *TLSListener) Accept() (net.Conn, error) { + netConn, err := l.Wrapped.Accept() + if err != nil { + return nil, err + } + + tlsConfig := l.TLSConfig.Clone() + pdConn := netConn.(*conn) + pdConn.expectingSecrets.Store(4) + tlsConfig.KeyLogWriter = &connKeyLogWriter{c: pdConn} + + return tls.Server(netConn, tlsConfig), nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/tls_listener_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/tls_listener_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c5fa7e3d35a921bc7cd84a18b2f28314caaa2544 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/packetdumper/tls_listener_test.go @@ -0,0 +1,64 @@ +package packetdumper + +import ( + "crypto/tls" + "net" + "path/filepath" + "testing" + + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestTLSListener(t *testing.T) { + cert, err := tls.X509KeyPair(test.TLSCertPub, test.TLSCertKey) + require.NoError(t, err) + + serverTLSConfig := &tls.Config{Certificates: []tls.Certificate{cert}} + + innerLn, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + + prefix := filepath.Join(t.TempDir(), "capture") + + pdLn := &Listener{ + Wrapped: innerLn, + Prefix: prefix, + } + + tlsLn := &TLSListener{ + Wrapped: pdLn, + TLSConfig: serverTLSConfig, + } + + require.Equal(t, innerLn.Addr(), tlsLn.Addr()) + + clientDone := make(chan error, 1) + go func() { + clientConn, err2 := tls.Dial("tcp", tlsLn.Addr().String(), &tls.Config{InsecureSkipVerify: true}) //nolint:gosec + if err2 != nil { + clientDone <- err2 + return + } + defer clientConn.Close() //nolint:errcheck + + _, err2 = clientConn.Write([]byte("ping")) + clientDone <- err2 + }() + + serverConn, err := tlsLn.Accept() + require.NoError(t, err) + defer serverConn.Close() + + buf := make([]byte, 4) + _, err = serverConn.Read(buf) + require.NoError(t, err) + require.Equal(t, []byte("ping"), buf) + + require.NoError(t, <-clientDone) + + serverConn.Close() + tlsLn.Close() //nolint:errcheck + + checkPcapngPresence(t, prefix) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer.go new file mode 100644 index 0000000000000000000000000000000000000000..e7e4d29403e0317cfcadc5df9fe922dc8b668300 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer.go @@ -0,0 +1,17 @@ +package playback + +import "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + +type muxer interface { + writeInit(init *fmp4.Init) + setTrack(trackID int) + writeSample( + dts int64, + ptsOffset int32, + isNonSyncSample bool, + payloadSize uint32, + getPayload func() ([]byte, error), + ) error + writeFinalDTS(dts int64) + flush() error +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer_fmp4.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer_fmp4.go new file mode 100644 index 0000000000000000000000000000000000000000..a93af141ac3abe137c13fb87c8931f7f6b49bb3c --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer_fmp4.go @@ -0,0 +1,204 @@ +package playback + +import ( + "io" + "time" + + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4/seekablebuffer" + "github.com/bluenviron/mediamtx/internal/recordstore" +) + +const ( + partDuration = 1 * time.Second +) + +type muxerFMP4Track struct { + id int + timeScale uint32 + firstDTS int64 + lastDTS int64 + samples []*fmp4.Sample +} + +func findTrack(tracks []*muxerFMP4Track, id int) *muxerFMP4Track { + for _, track := range tracks { + if track.id == id { + return track + } + } + return nil +} + +type muxerFMP4 struct { + w io.Writer + + init *fmp4.Init + nextSequenceNumber uint32 + tracks []*muxerFMP4Track + curTrack *muxerFMP4Track + outBuf seekablebuffer.Buffer +} + +func (w *muxerFMP4) writeInit(init *fmp4.Init) { + w.init = init + + w.tracks = make([]*muxerFMP4Track, len(init.Tracks)) + + for i, track := range init.Tracks { + w.tracks[i] = &muxerFMP4Track{ + id: track.ID, + timeScale: track.TimeScale, + firstDTS: -1, + } + } +} + +func (w *muxerFMP4) setTrack(trackID int) { + w.curTrack = findTrack(w.tracks, trackID) +} + +func (w *muxerFMP4) writeSample( + dts int64, + ptsOffset int32, + isNonSyncSample bool, + _ uint32, + getPayload func() ([]byte, error), +) error { + pl, err := getPayload() + if err != nil { + return err + } + + if dts >= 0 { + // this is the first visible sample of this track + if w.curTrack.firstDTS < 0 { + w.curTrack.firstDTS = dts + + // if sample is a IDR, remove previous GOP + if !isNonSyncSample { + w.curTrack.samples = w.curTrack.samples[:0] + } + } else { + duration := max(dts-w.curTrack.lastDTS, 0) + w.curTrack.samples[len(w.curTrack.samples)-1].Duration = uint32(duration) + } + + w.curTrack.samples = append(w.curTrack.samples, &fmp4.Sample{ + PTSOffset: ptsOffset, + IsNonSyncSample: isNonSyncSample, + Payload: pl, + }) + w.curTrack.lastDTS = dts + + partDurationMP4 := durationGoToMp4(partDuration, w.curTrack.timeScale) + + if (w.curTrack.lastDTS - w.curTrack.firstDTS) >= partDurationMP4 { + err = w.innerFlush(false) + if err != nil { + return err + } + } + } else { + if !isNonSyncSample { // sample is IDR + // create a new GOP that starts from this sample. + // set sample duration to zero + w.curTrack.samples = w.curTrack.samples[:0] + w.curTrack.samples = append(w.curTrack.samples, &fmp4.Sample{ + IsNonSyncSample: isNonSyncSample, + Payload: pl, + PTSOffset: ptsOffset, + }) + } else { // sample is not IDR + // append sample to current GOP + // set sample duration to zero + w.curTrack.samples = append(w.curTrack.samples, &fmp4.Sample{ + IsNonSyncSample: isNonSyncSample, + Payload: pl, + PTSOffset: ptsOffset, + }) + } + } + + return nil +} + +func (w *muxerFMP4) writeFinalDTS(dts int64) { + if len(w.curTrack.samples) != 0 && w.curTrack.firstDTS >= 0 { + duration := max(dts-w.curTrack.lastDTS, 0) + w.curTrack.samples[len(w.curTrack.samples)-1].Duration = uint32(duration) + } +} + +func (w *muxerFMP4) innerFlush(final bool) error { + var part fmp4.Part + + for _, track := range w.tracks { + if track.firstDTS >= 0 && (len(track.samples) > 1 || (final && len(track.samples) != 0)) { + // do not write the final sample + // in order to allow changing its duration to compensate NTP-DTS differences + var samples []*fmp4.Sample + if !final { + samples = track.samples[:len(track.samples)-1] + } else { + samples = track.samples + } + + part.Tracks = append(part.Tracks, &fmp4.PartTrack{ + ID: track.id, + BaseTime: uint64(track.firstDTS), + Samples: samples, + }) + + if !final { + track.samples = track.samples[len(track.samples)-1:] + track.firstDTS = track.lastDTS + } + } + } + + // no samples to write + if part.Tracks == nil { + // if no samples has been written before, return an error + if w.init != nil { + return recordstore.ErrNoSegmentsFound + } + return nil + } + + part.SequenceNumber = w.nextSequenceNumber + w.nextSequenceNumber++ + + if w.init != nil { + err := w.init.Marshal(&w.outBuf) + if err != nil { + return err + } + + _, err = w.w.Write(w.outBuf.Bytes()) + if err != nil { + return err + } + + w.init = nil + w.outBuf.Reset() + } + + err := part.Marshal(&w.outBuf) + if err != nil { + return err + } + + _, err = w.w.Write(w.outBuf.Bytes()) + if err != nil { + return err + } + + w.outBuf.Reset() + + return nil +} + +func (w *muxerFMP4) flush() error { + return w.innerFlush(true) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer_mp4.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer_mp4.go new file mode 100644 index 0000000000000000000000000000000000000000..3d5779627caa0040195eba4f74c46985bd1e57ab --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer_mp4.go @@ -0,0 +1,109 @@ +package playback + +import ( + "io" + + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + "github.com/bluenviron/mediacommon/v2/pkg/formats/pmp4" + "github.com/bluenviron/mediamtx/internal/recordstore" +) + +type muxerMP4Track struct { + pmp4.Track + lastDTS int64 +} + +func findTrackMP4(tracks []*muxerMP4Track, id int) *muxerMP4Track { + for _, track := range tracks { + if track.ID == id { + return track + } + } + return nil +} + +type muxerMP4 struct { + w io.Writer + + tracks []*muxerMP4Track + curTrack *muxerMP4Track +} + +func (w *muxerMP4) writeInit(init *fmp4.Init) { + w.tracks = make([]*muxerMP4Track, len(init.Tracks)) + + for i, track := range init.Tracks { + w.tracks[i] = &muxerMP4Track{ + Track: pmp4.Track{ + ID: track.ID, + TimeScale: track.TimeScale, + Codec: track.Codec, + }, + } + } +} + +func (w *muxerMP4) setTrack(trackID int) { + w.curTrack = findTrackMP4(w.tracks, trackID) +} + +func (w *muxerMP4) writeSample( + dts int64, + ptsOffset int32, + isNonSyncSample bool, + payloadSize uint32, + getPayload func() ([]byte, error), +) error { + // remove GOPs before the GOP of the first sample + if (dts < 0 || (dts >= 0 && w.curTrack.lastDTS < 0)) && !isNonSyncSample { + w.curTrack.Samples = w.curTrack.Samples[:0] + } + + if len(w.curTrack.Samples) == 0 { + w.curTrack.TimeOffset = int32(dts) + } else { + duration := max(dts-w.curTrack.lastDTS, 0) + w.curTrack.Samples[len(w.curTrack.Samples)-1].Duration = uint32(duration) + } + + // prevent warning "edit list: 1 Missing key frame while searching for timestamp: 0" + if !isNonSyncSample { + ptsOffset = 0 + } + + w.curTrack.Samples = append(w.curTrack.Samples, &pmp4.Sample{ + PTSOffset: ptsOffset, + IsNonSyncSample: isNonSyncSample, + PayloadSize: payloadSize, + GetPayload: getPayload, + }) + w.curTrack.lastDTS = dts + + return nil +} + +func (w *muxerMP4) writeFinalDTS(dts int64) { + if len(w.curTrack.Samples) != 0 { + duration := max(dts-w.curTrack.lastDTS, 0) + w.curTrack.Samples[len(w.curTrack.Samples)-1].Duration = uint32(duration) + } +} + +func (w *muxerMP4) flush() error { + if w.curTrack == nil || len(w.curTrack.Samples) == 0 || w.curTrack.lastDTS < 0 { + return recordstore.ErrNoSegmentsFound + } + + var tracks []*pmp4.Track + for _, track := range w.tracks { + if len(track.Samples) != 0 { + tracks = append(tracks, &track.Track) + } + } + + h := pmp4.Presentation{ + Tracks: tracks, + } + + return h.Marshal(w.w) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer_mp4_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer_mp4_test.go new file mode 100644 index 0000000000000000000000000000000000000000..207eb84dd46f44d61169a5c698f7d3b0c2eaf027 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/muxer_mp4_test.go @@ -0,0 +1,87 @@ +package playback + +import ( + "bytes" + "testing" + + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + mcodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mp4/codecs" + "github.com/bluenviron/mediamtx/internal/recordstore" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +// Test that tracks with no samples are not included in the output +func TestMuxerMP4EmptyTracks(t *testing.T) { + var buf bytes.Buffer + + mux := &muxerMP4{ + w: &buf, + } + + init := &fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + { + ID: 2, + TimeScale: 48000, + Codec: &mcodecs.Opus{}, + }, + }, + } + + mux.writeInit(init) + + // Only write samples to the first track + mux.setTrack(1) + err := mux.writeSample(0, 0, false, 5, func() ([]byte, error) { + return []byte{0x01, 0x02, 0x03, 0x04, 0x05}, nil + }) + require.NoError(t, err) + + err = mux.writeSample(90000, 0, true, 5, func() ([]byte, error) { + return []byte{0x06, 0x07, 0x08, 0x09, 0x0a}, nil + }) + require.NoError(t, err) + + mux.writeFinalDTS(180000) + + err = mux.flush() + require.NoError(t, err) + + require.Greater(t, buf.Len(), 0) +} + +// Test that flushing without any written sample returns an error instead of panicking +func TestMuxerMP4NoSamples(t *testing.T) { + var buf bytes.Buffer + + mux := &muxerMP4{ + w: &buf, + } + + init := &fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + }, + } + + mux.writeInit(init) + + err := mux.flush() + require.ErrorIs(t, err, recordstore.ErrNoSegmentsFound) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_get.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_get.go new file mode 100644 index 0000000000000000000000000000000000000000..2acdeb8ac18dd7c6065c48f8cc0f5b6388cce391 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_get.go @@ -0,0 +1,202 @@ +package playback + +import ( + "errors" + "fmt" + "net" + "net/http" + "os" + "strconv" + "time" + + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/recordstore" + "github.com/gin-gonic/gin" +) + +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) +} + +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 []*recordstore.Segment, + start time.Time, + duration time.Duration, + m muxer, +) error { + if recordFormat == conf.RecordFormatFMP4 { + f, err := os.Open(segments[0].Fpath) + if err != nil { + return err + } + defer f.Close() + + firstInit, _, err := segmentFMP4ReadHeader(f) + if err != nil { + return err + } + + m.writeInit(&fmp4.Init{ + Tracks: firstInit.Tracks, + }) + + firstMtxi := findMtxi(firstInit.UserData) + startOffset := segments[0].Start.Sub(start) // this is negative + dts := startOffset + prevInit := firstInit + + segmentDuration, err := segmentFMP4MuxParts(f, dts, duration, firstInit.Tracks, m) + if err != nil { + return err + } + + segmentEnd := segments[0].Start.Add(segmentDuration) + + for _, seg := range segments[1:] { + f, err = os.Open(seg.Fpath) + if err != nil { + return err + } + defer f.Close() + + var init *fmp4.Init + init, _, err = segmentFMP4ReadHeader(f) + if err != nil { + return err + } + + if !segmentFMP4CanBeConcatenated(prevInit, segmentEnd, init, seg.Start) { + break + } + + if firstMtxi != nil { + mtxi := findMtxi(init.UserData) + dts = time.Duration(mtxi.DTS-firstMtxi.DTS) + startOffset + } else { // legacy method + dts = seg.Start.Sub(start) // this is positive + } + + segmentDuration, err = segmentFMP4MuxParts(f, dts, duration, firstInit.Tracks, m) + if err != nil { + return err + } + + segmentEnd = seg.Start.Add(segmentDuration) + prevInit = init + } + + err = m.flush() + if err != nil { + return err + } + + return nil + } + + return fmt.Errorf("MPEG-TS format is not supported yet") +} + +func (s *Server) onGet(ctx *gin.Context) { + pathName := ctx.Query("path") + + // validate path name before passing it to the authentication manager + err := conf.IsValidPathName(pathName) + if err != nil { + s.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid path name: %w (%s)", err, pathName)) + return + } + + if !s.doAuth(ctx, pathName) { + return + } + + start, err := time.Parse(time.RFC3339, ctx.Query("start")) + if err != nil { + s.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid start: %w", err)) + return + } + + duration, err := parseDuration(ctx.Query("duration")) + if err != nil { + s.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid duration: %w", err)) + return + } + + ww := &writerWrapper{ctx: ctx} + var m muxer + + format := ctx.Query("format") + switch format { + case "", "fmp4": + m = &muxerFMP4{w: ww} + + case "mp4": + m = &muxerMP4{w: ww} + + default: + s.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid format: %s", format)) + return + } + + pathConf, err := s.safeFindPathConf(pathName) + if err != nil { + s.writeError(ctx, http.StatusBadRequest, err) + return + } + + end := start.Add(duration) + segments, err := recordstore.FindSegments(pathConf, pathName, &start, &end) + if err != nil { + if errors.Is(err, recordstore.ErrNoSegmentsFound) { + s.writeError(ctx, http.StatusNotFound, err) + } else { + s.writeError(ctx, http.StatusBadRequest, err) + } + return + } + + err = seekAndMux(pathConf.RecordFormat, segments, start, duration, m) + if err != nil { + // user aborted the download + if _, ok := errors.AsType[*net.OpError](err); ok { + return + } + + // nothing has been written yet; send back JSON + if !ww.written { + if errors.Is(err, recordstore.ErrNoSegmentsFound) { + s.writeError(ctx, http.StatusNotFound, err) + } else { + s.writeError(ctx, http.StatusBadRequest, err) + } + return + } + + // something has already been written: abort and write logs only + s.Log(logger.Error, err.Error()) + return + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_get_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_get_test.go new file mode 100644 index 0000000000000000000000000000000000000000..99fefd2cd0241bebf58e6c23af422ab7061dd240 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_get_test.go @@ -0,0 +1,1081 @@ +package playback + +import ( + "bytes" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "testing" + "time" + + amp4 "github.com/abema/go-mp4" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4/seekablebuffer" + mcodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mp4/codecs" + "github.com/bluenviron/mediacommon/v2/pkg/formats/pmp4" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/recordstore" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/google/uuid" + "github.com/stretchr/testify/require" +) + +func writeSegment1(t *testing.T, fpath string) { + init := fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + { + ID: 2, + TimeScale: 48000, + Codec: &mcodecs.MPEG4Audio{ + Config: mpeg4audio.AudioSpecificConfig{ + 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{ + { + Tracks: []*fmp4.PartTrack{ + { + ID: 1, + BaseTime: 30 * 90000, + Samples: []*fmp4.Sample{ + { + Duration: 30 * 90000, + Payload: []byte{1, 2}, + }, + { + Duration: 1 * 90000, + PTSOffset: 90000, + Payload: []byte{3, 4}, + }, + { + Duration: 1 * 90000, + PTSOffset: -90000, + IsNonSyncSample: true, + Payload: []byte{5, 6}, + }, // 62 secs + }, + }, + { + ID: 2, + BaseTime: 31 * 48000, + Samples: []*fmp4.Sample{ + { + Duration: 29 * 48000, + Payload: []byte{1, 2}, + }, + { + Duration: 1 * 48000, + Payload: []byte{3, 4}, + }, // 61 secs + }, + }, + }, + }, + } + 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: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + { + ID: 2, + TimeScale: 48000, + Codec: &mcodecs.MPEG4Audio{ + Config: mpeg4audio.AudioSpecificConfig{ + 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{ //nolint:dupl + { + Tracks: []*fmp4.PartTrack{{ + ID: 1, + BaseTime: 0, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 90000, + Payload: []byte{7, 8}, + }, // 1 sec + }, + }}, + }, + { + Tracks: []*fmp4.PartTrack{{ + ID: 2, + BaseTime: 0, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 48000, + Payload: []byte{5, 6}, + }, + { + Duration: 1 * 48000, + Payload: []byte{7, 8}, + }, // 2 secs + }, + }}, + }, + { + SequenceNumber: 5, + Tracks: []*fmp4.PartTrack{{ + ID: 1, + BaseTime: 1 * 90000, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 90000, + Payload: []byte{9, 10}, + }, + { + Duration: 1 * 90000, + Payload: []byte{11, 12}, + }, + { + Duration: 1 * 90000, + Payload: []byte{13, 14}, + }, // 4 secs + }, + }}, + }, + } + 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: &mcodecs.H264{ + 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{ + { + Tracks: []*fmp4.PartTrack{{ + ID: 1, + BaseTime: 0, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 90000, + Payload: []byte{13, 14}, + }, + }, + }}, + }, + } + err = parts.Marshal(&buf2) + require.NoError(t, err) + + err = os.WriteFile(fpath, append(buf1.Bytes(), buf2.Bytes()...), 0o644) + require.NoError(t, err) +} + +func TestOnGet(t *testing.T) { + for _, format := range []string{ + "fmp4", + "mp4", + } { + for _, mode := range []string{ + "no_mtxi", + "mtxi", + } { + t.Run(format+"_"+mode, func(t *testing.T) { + dir := t.TempDir() + + err := os.Mkdir(filepath.Join(dir, "mypath"), 0o755) + require.NoError(t, err) + + init := fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + { + ID: 2, + TimeScale: 48000, + Codec: &mcodecs.MPEG4Audio{ + Config: mpeg4audio.AudioSpecificConfig{ + Type: mpeg4audio.ObjectTypeAACLC, + SampleRate: 48000, + ChannelCount: 2, + }, + }, + }, + }, + } + + // segment 1 + func() { + if mode == "mtxi" { + init.UserData = []amp4.IBox{&recordstore.Mtxi{ + StreamID: uuid.MustParse("31564107-9e7e-4923-bf2f-631371a35397"), + SegmentNumber: 4, + DTS: int64(11 * time.Second), + }} + } + + var buf1 seekablebuffer.Buffer + err = init.Marshal(&buf1) + require.NoError(t, err) + + var buf2 seekablebuffer.Buffer + parts := fmp4.Parts{ + { + Tracks: []*fmp4.PartTrack{ + { + ID: 1, + BaseTime: 30 * 90000, + Samples: []*fmp4.Sample{ + { + Duration: 30 * 90000, + Payload: []byte{1, 2}, + }, + { + Duration: 1 * 90000, + PTSOffset: 90000, + Payload: []byte{3, 4}, + }, + { + Duration: 1 * 90000, + PTSOffset: -90000, + IsNonSyncSample: true, + Payload: []byte{5, 6}, + }, // 62 secs + }, + }, + { + ID: 2, + BaseTime: 31 * 48000, + Samples: []*fmp4.Sample{ + { + Duration: 29 * 48000, + Payload: []byte{1, 2}, + }, + { + Duration: 1 * 48000, + Payload: []byte{3, 4}, + }, // 61 secs + }, + }, + }, + }, + } + err = parts.Marshal(&buf2) + require.NoError(t, err) + + err = os.WriteFile(filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4"), + append(buf1.Bytes(), buf2.Bytes()...), 0o644) + require.NoError(t, err) + }() + + // segment 2 + func() { //nolint:dupl + if mode == "mtxi" { + init.UserData = []amp4.IBox{&recordstore.Mtxi{ + StreamID: uuid.MustParse("31564107-9e7e-4923-bf2f-631371a35397"), + SegmentNumber: 5, + DTS: int64(73 * time.Second), + }} + } + + var buf1 seekablebuffer.Buffer + err = init.Marshal(&buf1) + require.NoError(t, err) + + var buf2 seekablebuffer.Buffer + parts := fmp4.Parts{ //nolint:dupl + { + Tracks: []*fmp4.PartTrack{{ + ID: 1, + BaseTime: 0, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 90000, + Payload: []byte{7, 8}, + }, // 1 sec + }, + }}, + }, + { + Tracks: []*fmp4.PartTrack{{ + ID: 2, + BaseTime: 0, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 48000, + Payload: []byte{5, 6}, + }, + { + Duration: 1 * 48000, + Payload: []byte{7, 8}, + }, // 2 secs + }, + }}, + }, + { + SequenceNumber: 5, + Tracks: []*fmp4.PartTrack{{ + ID: 1, + BaseTime: 1 * 90000, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 90000, + Payload: []byte{9, 10}, + }, + { + Duration: 1 * 90000, + Payload: []byte{11, 12}, + }, + { + Duration: 1 * 90000, + Payload: []byte{13, 14}, + }, // 4 secs + }, + }}, + }, + } + err = parts.Marshal(&buf2) + require.NoError(t, err) + + err = os.WriteFile(filepath.Join(dir, "mypath", "2008-11-07_11-23-02-500000.mp4"), + append(buf1.Bytes(), buf2.Bytes()...), 0o644) + require.NoError(t, err) + }() + + // segment 3 + func() { //nolint:dupl + if mode == "mtxi" { + init.UserData = []amp4.IBox{&recordstore.Mtxi{ + StreamID: uuid.MustParse("31564107-9e7e-4923-bf2f-631371a35397"), + SegmentNumber: 6, + DTS: int64(75 * time.Second), + }} + } + + var buf1 seekablebuffer.Buffer + err = init.Marshal(&buf1) + require.NoError(t, err) + + var buf2 seekablebuffer.Buffer + parts := fmp4.Parts{ //nolint:dupl + { + Tracks: []*fmp4.PartTrack{{ + ID: 1, + BaseTime: 0, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 90000, + Payload: []byte{7, 8}, + }, // 1 sec + }, + }}, + }, + { + Tracks: []*fmp4.PartTrack{{ + ID: 2, + BaseTime: 0, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 48000, + Payload: []byte{5, 6}, + }, + { + Duration: 1 * 48000, + Payload: []byte{7, 8}, + }, // 2 secs + }, + }}, + }, + { + SequenceNumber: 5, + Tracks: []*fmp4.PartTrack{{ + ID: 1, + BaseTime: 1 * 90000, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 90000, + Payload: []byte{9, 10}, + }, + { + Duration: 1 * 90000, + Payload: []byte{11, 12}, + }, + { + Duration: 1 * 90000, + Payload: []byte{13, 14}, + }, // 4 secs + }, + }}, + }, + } + err = parts.Marshal(&buf2) + require.NoError(t, err) + + err = os.WriteFile(filepath.Join(dir, "mypath", "2008-11-07_11-23-04-500000.mp4"), + append(buf1.Bytes(), buf2.Bytes()...), 0o644) + require.NoError(t, err) + }() + + s := &Server{ + Address: "127.0.0.1:9996", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathConfs: map[string]*conf.Path{ + "mypath": { + Name: "mypath", + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + }, + AuthManager: test.NilAuthManager, + 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, 7, 11, 23, 1, 500000000, time.Local).Format(time.RFC3339Nano)) + v.Set("duration", "3") + v.Set("format", format) + 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) + + switch format { + case "fmp4": + 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.Sample{ + { + Duration: 0, + PTSOffset: 90000, + Payload: []byte{3, 4}, + }, + { + Duration: 90000, + PTSOffset: -90000, + IsNonSyncSample: true, + Payload: []byte{5, 6}, + }, + }, + }, + }, + }, + { + SequenceNumber: 1, + Tracks: []*fmp4.PartTrack{ + { + ID: 2, + BaseTime: 48000, + Samples: []*fmp4.Sample{ + { + Duration: 48000, + Payload: []byte{5, 6}, + }, + }, + }, + }, + }, + { + SequenceNumber: 2, + Tracks: []*fmp4.PartTrack{ + { + ID: 1, + BaseTime: 90000, + Samples: []*fmp4.Sample{ + { + Duration: 90000, + Payload: []byte{7, 8}, + }, + }, + }, + }, + }, + { + SequenceNumber: 3, + Tracks: []*fmp4.PartTrack{ + { + ID: 1, + BaseTime: 2 * 90000, + Samples: []*fmp4.Sample{ + { + Duration: 90000, + Payload: []byte{9, 10}, + }, + }, + }, + { + ID: 2, + BaseTime: 2 * 48000, + Samples: []*fmp4.Sample{ + { + Duration: 48000, + Payload: []byte{7, 8}, + }, + }, + }, + }, + }, + }, parts) + + case "mp4": + var p pmp4.Presentation + err = p.Unmarshal(bytes.NewReader(buf)) + require.NoError(t, err) + + sampleData := make(map[int][][]byte) + for _, track := range p.Tracks { + samples := make([][]byte, len(track.Samples)) + for i, sample := range track.Samples { + buf, err = sample.GetPayload() + require.NoError(t, err) + samples[i] = buf + sample.GetPayload = nil + } + sampleData[track.ID] = samples + } + + require.Equal(t, pmp4.Presentation{ + Tracks: []*pmp4.Track{ + { + ID: 1, + TimeScale: 90000, + TimeOffset: -90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + Samples: []*pmp4.Sample{ + { + Duration: 90000, + PayloadSize: 2, + }, + { + Duration: 90000, + PTSOffset: -90000, + IsNonSyncSample: true, + PayloadSize: 2, + }, + { + Duration: 90000, + PayloadSize: 2, + }, + { + Duration: 90000, + PayloadSize: 2, + }, + }, + }, + { + ID: 2, + TimeScale: 48000, + TimeOffset: 48000, + Codec: &mcodecs.MPEG4Audio{ + Config: mpeg4audio.AudioSpecificConfig{ + Type: mpeg4audio.ObjectTypeAACLC, + SampleRate: 48000, + ChannelCount: 2, + ChannelConfig: 2, + }, + }, + Samples: []*pmp4.Sample{ + { + Duration: 48000, + PayloadSize: 2, + }, + { + Duration: 48000, + PayloadSize: 2, + }, + }, + }, + }, + }, p) + + require.Equal(t, map[int][][]byte{ + 1: { + {3, 4}, + {5, 6}, + {7, 8}, + {9, 10}, + }, + 2: { + {5, 6}, + {7, 8}, + }, + }, sampleData) + } + }) + } + } +} + +func TestOnGetDifferentInit(t *testing.T) { + dir := t.TempDir() + + 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.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathConfs: map[string]*conf.Path{ + "mypath": { + Name: "mypath", + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + }, + AuthManager: test.NilAuthManager, + 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, 7, 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.Sample{ + { + Duration: 0, + PTSOffset: 90000, + Payload: []byte{3, 4}, + }, + { + Duration: 90000, + PTSOffset: -90000, + IsNonSyncSample: true, + Payload: []byte{5, 6}, + }, + }, + }, + }, + }, + }, parts) +} + +func TestOnGetInMiddleOfLastSample(t *testing.T) { + for _, format := range []string{"fmp4", "mp4"} { + t.Run(format, func(t *testing.T) { + dir := t.TempDir() + + err := os.Mkdir(filepath.Join(dir, "mypath"), 0o755) + require.NoError(t, err) + + init := fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + }, + } + + func() { + fpath := filepath.Join(dir, "mypath", "2008-11-07_11-22-00-000000.mp4") + + var buf1 seekablebuffer.Buffer + err = init.Marshal(&buf1) + require.NoError(t, err) + + var buf2 seekablebuffer.Buffer + parts := fmp4.Parts{ + { + Tracks: []*fmp4.PartTrack{ + { + ID: 1, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 90000, + IsNonSyncSample: false, + Payload: []byte{1, 2}, + }, + }, + }, + }, + }, + } + err = parts.Marshal(&buf2) + require.NoError(t, err) + + err = os.WriteFile(fpath, append(buf1.Bytes(), buf2.Bytes()...), 0o644) + require.NoError(t, err) + }() + + s := &Server{ + Address: "127.0.0.1:9996", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathConfs: map[string]*conf.Path{ + "mypath": { + Name: "mypath", + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + }, + AuthManager: test.NilAuthManager, + 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, 7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano)) + v.Set("duration", "3") + v.Set("format", format) + 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.StatusNotFound, res.StatusCode) + }) + } +} + +func TestOnGetInvalidPath(t *testing.T) { + s := &Server{ + Address: "127.0.0.1:9996", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathConfs: map[string]*conf.Path{ + "all_others": { + Name: "all_others", + RecordPath: filepath.Join(t.TempDir(), "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + }, + AuthManager: test.NilAuthManager, + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + u, err := url.Parse("http://localhost:9996/get") + require.NoError(t, err) + + v := url.Values{} + v.Set("path", "group/../cam1") + v.Set("start", time.Date(2008, 11, 7, 11, 23, 1, 500000000, time.Local).Format(time.RFC3339Nano)) + v.Set("duration", "3") + u.RawQuery = v.Encode() + + res, err := http.Get(u.String()) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusBadRequest, res.StatusCode) +} + +func TestOnGetBetweenSegments(t *testing.T) { + for _, ca := range []string{ + "idr before", + "idr after", + } { + t.Run(ca, func(t *testing.T) { + dir := t.TempDir() + + err := os.Mkdir(filepath.Join(dir, "mypath"), 0o755) + require.NoError(t, err) + + init := fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + }, + } + + func() { + fpath := filepath.Join(dir, "mypath", "2008-11-07_11-22-00-000000.mp4") + + var buf1 seekablebuffer.Buffer + err = init.Marshal(&buf1) + require.NoError(t, err) + + var buf2 seekablebuffer.Buffer + parts := fmp4.Parts{ + { + Tracks: []*fmp4.PartTrack{ + { + ID: 1, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 90000, + IsNonSyncSample: false, + Payload: []byte{1, 2}, + }, + }, + }, + }, + }, + } + err = parts.Marshal(&buf2) + require.NoError(t, err) + + err = os.WriteFile(fpath, append(buf1.Bytes(), buf2.Bytes()...), 0o644) + require.NoError(t, err) + }() + + func() { + fpath := filepath.Join(dir, "mypath", "2008-11-07_11-22-01-000000.mp4") + + var buf1 seekablebuffer.Buffer + err = init.Marshal(&buf1) + require.NoError(t, err) + + var buf2 seekablebuffer.Buffer + parts := fmp4.Parts{ + { + Tracks: []*fmp4.PartTrack{ + { + ID: 1, + Samples: []*fmp4.Sample{ + { + Duration: 1 * 90000, + IsNonSyncSample: (ca == "idr before"), + Payload: []byte{3, 4}, + }, + }, + }, + }, + }, + } + err = parts.Marshal(&buf2) + require.NoError(t, err) + + err = os.WriteFile(fpath, append(buf1.Bytes(), buf2.Bytes()...), 0o644) + require.NoError(t, err) + }() + + s := &Server{ + Address: "127.0.0.1:9996", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathConfs: map[string]*conf.Path{ + "mypath": { + Name: "mypath", + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + }, + AuthManager: test.NilAuthManager, + 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, 7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano)) + v.Set("duration", "3") + 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) + + switch ca { + case "idr before": + require.Equal(t, fmp4.Parts{ + { + SequenceNumber: 0, + Tracks: []*fmp4.PartTrack{ + { + ID: 1, + BaseTime: 45000, + Samples: []*fmp4.Sample{ + { + Duration: 0, + Payload: []byte{1, 2}, + }, + { + Duration: 90000, + Payload: []byte{3, 4}, + IsNonSyncSample: true, + }, + }, + }, + }, + }, + }, parts) + + case "idr after": + require.Equal(t, fmp4.Parts{ + { + SequenceNumber: 0, + Tracks: []*fmp4.PartTrack{ + { + ID: 1, + BaseTime: 45000, + Samples: []*fmp4.Sample{ + { + Duration: 90000, + Payload: []byte{3, 4}, + }, + }, + }, + }, + }, + }, parts) + } + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_list.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_list.go new file mode 100644 index 0000000000000000000000000000000000000000..02f3ea7a41aa1b9795a3e468150ec2d75dda407c --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_list.go @@ -0,0 +1,255 @@ +package playback + +import ( + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "net/url" + "os" + "strconv" + "time" + + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/recordstore" + "github.com/gin-gonic/gin" +) + +type listEntryDuration time.Duration + +func (d listEntryDuration) MarshalJSON() ([]byte, error) { + return json.Marshal(time.Duration(d).Seconds()) +} + +type parsedSegment struct { + start time.Time + init *fmp4.Init + duration time.Duration +} + +func parseSegment(seg *recordstore.Segment) (*parsedSegment, error) { + f, err := os.Open(seg.Fpath) + if err != nil { + return nil, err + } + defer f.Close() + + init, duration, err := segmentFMP4ReadHeader(f) + if err != nil { + return nil, err + } + + // if duration is not present in the header, compute it + // by parsing each part + if duration == 0 { + duration, err = segmentFMP4ReadDurationFromParts(f, init) + if err != nil { + return nil, err + } + } + + return &parsedSegment{ + start: seg.Start, + init: init, + duration: duration, + }, nil +} + +func parseSegments(segments []*recordstore.Segment) ([]*parsedSegment, error) { + parsed := make([]*parsedSegment, len(segments)) + ch := make(chan error) + + // process segments in parallel. + // parallel random access should improve performance in most cases. + // ref: https://pkolaczk.github.io/disk-parallelism/ + for i, seg := range segments { + go func(i int, seg *recordstore.Segment) { + var err error + parsed[i], err = parseSegment(seg) + ch <- err + }(i, seg) + } + + var err error + + for range segments { + err2 := <-ch + if err2 != nil { + err = err2 + } + } + + return parsed, err +} + +func urlScheme(ctx *gin.Context, trustedProxies conf.IPNetworks, encryption bool) string { + if trustedProxies.Contains(net.ParseIP(ctx.RemoteIP())) { + xForwardedProto := ctx.Request.Header.Get("X-Forwarded-Proto") + if xForwardedProto != "" { + return xForwardedProto + } + } + + if encryption { + return "https" + } + + return "http" +} + +type listEntry struct { + Start time.Time `json:"start"` + Duration listEntryDuration `json:"duration"` + URL string `json:"url"` +} + +func concatenateSegments(parsed []*parsedSegment) []listEntry { + out := []listEntry{} + var prevInit *fmp4.Init + + for _, parsed := range parsed { + if len(out) != 0 && segmentFMP4CanBeConcatenated( + prevInit, + out[len(out)-1].Start.Add(time.Duration(out[len(out)-1].Duration)), + parsed.init, + parsed.start) { + prevStart := out[len(out)-1].Start + curEnd := parsed.start.Add(parsed.duration) + out[len(out)-1].Duration = listEntryDuration(curEnd.Sub(prevStart)) + } else { + out = append(out, listEntry{ + Start: parsed.start, + Duration: listEntryDuration(parsed.duration), + }) + } + + prevInit = parsed.init + } + + return out +} + +func parseAndConcatenate( + recordFormat conf.RecordFormat, + segments []*recordstore.Segment, +) ([]listEntry, error) { + if recordFormat == conf.RecordFormatFMP4 { + parsed, err := parseSegments(segments) + if err != nil { + return nil, err + } + + out := concatenateSegments(parsed) + return out, nil + } + + return nil, fmt.Errorf("MPEG-TS format is not supported yet") +} + +func (s *Server) onList(ctx *gin.Context) { + pathName := ctx.Query("path") + + // validate path name before passing it to the authentication manager + err := conf.IsValidPathName(pathName) + if err != nil { + s.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid path name: %w (%s)", err, pathName)) + return + } + + if !s.doAuth(ctx, pathName) { + return + } + + pathConf, err := s.safeFindPathConf(pathName) + if err != nil { + s.writeError(ctx, http.StatusBadRequest, err) + return + } + + var start *time.Time + rawStart := ctx.Query("start") + if rawStart != "" { + var tmp time.Time + tmp, err = time.Parse(time.RFC3339, rawStart) + if err != nil { + s.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid start: %w", err)) + return + } + start = &tmp + } + + var end *time.Time + rawEnd := ctx.Query("end") + if rawEnd != "" { + var tmp time.Time + tmp, err = time.Parse(time.RFC3339, rawEnd) + if err != nil { + s.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid end: %w", err)) + return + } + end = &tmp + } + + segments, err := recordstore.FindSegments(pathConf, pathName, start, end) + if err != nil { + if errors.Is(err, recordstore.ErrNoSegmentsFound) { + s.writeError(ctx, http.StatusNotFound, err) + } else { + s.writeError(ctx, http.StatusBadRequest, err) + } + return + } + + entries, err := parseAndConcatenate(pathConf.RecordFormat, segments) + if err != nil { + s.writeError(ctx, http.StatusInternalServerError, err) + return + } + + if start != nil { + firstEntry := entries[0] + + // when start is placed in a gap between the first and second segment, + // or when there's no second segment, + // the first segment is erroneously included with a negative duration. + // remove it. + if firstEntry.Start.Add(time.Duration(firstEntry.Duration)).Before(*start) { + entries = entries[1:] + + if len(entries) == 0 { + s.writeError(ctx, http.StatusNotFound, recordstore.ErrNoSegmentsFound) + return + } + } else if firstEntry.Start.Before(*start) { + entries[0].Duration -= listEntryDuration(start.Sub(firstEntry.Start)) + entries[0].Start = *start + } + } + + if end != nil { + lastEntry := entries[len(entries)-1] + if lastEntry.Start.Add(time.Duration(lastEntry.Duration)).After(*end) { + entries[len(entries)-1].Duration = listEntryDuration(end.Sub(lastEntry.Start)) + } + } + + scheme := urlScheme(ctx, s.TrustedProxies, s.Encryption) + + for i := range entries { + v := url.Values{} + v.Add("path", pathName) + v.Add("start", entries[i].Start.Format(time.RFC3339Nano)) + v.Add("duration", strconv.FormatFloat(time.Duration(entries[i].Duration).Seconds(), 'f', -1, 64)) + u := &url.URL{ + Scheme: scheme, + Host: ctx.Request.Host, + Path: "/get", + RawQuery: v.Encode(), + } + entries[i].URL = u.String() + } + + ctx.JSON(http.StatusOK, entries) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_list_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_list_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5dafa698770c07a14fe14fc5599adf38983d273e --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/on_list_test.go @@ -0,0 +1,430 @@ +package playback + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "testing" + "time" + + amp4 "github.com/abema/go-mp4" + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + mcodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mp4/codecs" + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestOnList(t *testing.T) { + for _, ca := range []string{ + "unfiltered", + "filtered", + "filtered and gap", + "different init", + "start after duration", + "start before first", + } { + t.Run(ca, func(t *testing.T) { + dir := t.TempDir() + + err := os.Mkdir(filepath.Join(dir, "mypath"), 0o755) + require.NoError(t, err) + + switch ca { + case "unfiltered", "filtered", "start before first": + 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")) + + case "filtered and gap": + writeSegment1(t, filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4")) + writeSegment2(t, filepath.Join(dir, "mypath", "2008-11-07_11-24-02-500000.mp4")) + + case "different init": + 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")) + + case "start after duration": + writeSegment1(t, filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4")) + } + + checked := false + + s := &Server{ + Address: "127.0.0.1:9996", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathConfs: map[string]*conf.Path{ + "mypath": { + Name: "mypath", + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + }, + AuthManager: &test.AuthManager{ + AuthenticateImpl: func(req *auth.Request) (string, *auth.Error) { + require.Equal(t, conf.AuthActionPlayback, req.Action) + require.Equal(t, "myuser", req.Credentials.User) + require.Equal(t, "mypass", req.Credentials.Pass) + checked = true + return req.Credentials.User, nil + }, + }, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + u, err := url.Parse("http://myuser:mypass@localhost:9996/list?start=") + require.NoError(t, err) + + v := url.Values{} + v.Set("path", "mypath") + + switch ca { + case "filtered": + v.Set("start", time.Date(2008, 11, 7, 11, 22, 1, 500000000, time.Local).Format(time.RFC3339Nano)) + v.Set("end", time.Date(2009, 11, 7, 11, 23, 4, 500000000, time.Local).Format(time.RFC3339Nano)) + + case "filtered and gap": + v.Set("start", time.Date(2008, 11, 7, 11, 23, 20, 500000000, time.Local).Format(time.RFC3339Nano)) + v.Set("end", time.Date(2009, 11, 7, 11, 23, 4, 500000000, time.Local).Format(time.RFC3339Nano)) + + case "start after duration": + v.Set("start", time.Date(2010, 11, 7, 11, 23, 20, 500000000, time.Local).Format(time.RFC3339Nano)) + + case "start before first": + v.Set("start", time.Date(2007, 11, 7, 11, 23, 20, 500000000, time.Local).Format(time.RFC3339Nano)) + } + + 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() + + if ca == "start after duration" { + require.Equal(t, http.StatusNotFound, res.StatusCode) + return + } + + require.Equal(t, http.StatusOK, res.StatusCode) + + var out any + err = json.NewDecoder(res.Body).Decode(&out) + require.NoError(t, err) + + switch ca { + case "unfiltered", "start before first": + require.Equal(t, []any{ + map[string]any{ + "duration": float64(66), + "start": time.Date(2008, 11, 7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano), + "url": "http://localhost:9996/get?duration=66&path=mypath&start=" + + url.QueryEscape(time.Date(2008, 11, 7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano)), + }, + map[string]any{ + "duration": float64(4), + "start": time.Date(2009, 11, 7, 11, 23, 2, 500000000, time.Local).Format(time.RFC3339Nano), + "url": "http://localhost:9996/get?duration=4&path=mypath&start=" + + url.QueryEscape(time.Date(2009, 11, 7, 11, 23, 2, 500000000, time.Local).Format(time.RFC3339Nano)), + }, + }, out) + + case "filtered": + require.Equal(t, []any{ + map[string]any{ + "duration": float64(65), + "start": time.Date(2008, 11, 7, 11, 22, 1, 500000000, time.Local).Format(time.RFC3339Nano), + "url": "http://localhost:9996/get?duration=65&path=mypath&start=" + + url.QueryEscape(time.Date(2008, 11, 7, 11, 22, 1, 500000000, time.Local).Format(time.RFC3339Nano)), + }, + map[string]any{ + "duration": float64(2), + "start": time.Date(2009, 11, 7, 11, 23, 2, 500000000, time.Local).Format(time.RFC3339Nano), + "url": "http://localhost:9996/get?duration=2&path=mypath&start=" + + url.QueryEscape(time.Date(2009, 11, 7, 11, 23, 2, 500000000, time.Local).Format(time.RFC3339Nano)), + }, + }, out) + + case "filtered and gap": + require.Equal(t, []any{ + map[string]any{ + "duration": float64(4), + "start": time.Date(2008, 11, 7, 11, 24, 2, 500000000, time.Local).Format(time.RFC3339Nano), + "url": "http://localhost:9996/get?duration=4&path=mypath&start=" + + url.QueryEscape(time.Date(2008, 11, 7, 11, 24, 2, 500000000, time.Local).Format(time.RFC3339Nano)), + }, + }, out) + + case "different init": + require.Equal(t, []any{ + map[string]any{ + "duration": float64(62), + "start": time.Date(2008, 11, 7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano), + "url": "http://localhost:9996/get?duration=62&path=mypath&start=" + + url.QueryEscape(time.Date(2008, 11, 7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano)), + }, + map[string]any{ + "duration": float64(1), + "start": time.Date(2008, 11, 7, 11, 23, 2, 500000000, time.Local).Format(time.RFC3339Nano), + "url": "http://localhost:9996/get?duration=1&path=mypath&start=" + + url.QueryEscape(time.Date(2008, 11, 7, 11, 23, 2, 500000000, time.Local).Format(time.RFC3339Nano)), + }, + }, out) + } + + require.True(t, checked) + }) + } +} + +func writeDuration(f io.ReadWriteSeeker, d time.Duration) error { + _, err := f.Seek(0, io.SeekStart) + if err != nil { + return err + } + + // check and skip ftyp header and content + + buf := make([]byte, 8) + _, err = io.ReadFull(f, buf) + if err != nil { + return err + } + + if !bytes.Equal(buf[4:], []byte{'f', 't', 'y', 'p'}) { + return fmt.Errorf("ftyp box not found") + } + + ftypSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) + + _, err = f.Seek(int64(ftypSize), io.SeekStart) + if err != nil { + return err + } + + // check and skip moov header + + _, err = io.ReadFull(f, buf) + if err != nil { + return err + } + + if !bytes.Equal(buf[4:], []byte{'m', 'o', 'o', 'v'}) { + return fmt.Errorf("moov box not found") + } + + moovSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) + + moovPos, err := f.Seek(8, io.SeekCurrent) + if err != nil { + return err + } + + var mvhd amp4.Mvhd + _, err = amp4.Unmarshal(f, uint64(moovSize-8), &mvhd, amp4.Context{}) + if err != nil { + return err + } + + mvhd.DurationV0 = uint32(d / time.Millisecond) + + _, err = f.Seek(moovPos, io.SeekStart) + if err != nil { + return err + } + + _, err = amp4.Marshal(f, &mvhd, amp4.Context{}) + if err != nil { + return err + } + + return nil +} + +func TestOnListInvalidPath(t *testing.T) { + s := &Server{ + Address: "127.0.0.1:9996", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathConfs: map[string]*conf.Path{ + "all_others": { + Name: "all_others", + RecordPath: filepath.Join(t.TempDir(), "mypath/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + }, + AuthManager: test.NilAuthManager, + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + u, err := url.Parse("http://localhost:9996/list") + require.NoError(t, err) + + v := url.Values{} + v.Set("path", "group/../cam1") + u.RawQuery = v.Encode() + + res, err := http.Get(u.String()) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusBadRequest, res.StatusCode) +} + +func TestOnListCachedDuration(t *testing.T) { + dir := t.TempDir() + + err := os.Mkdir(filepath.Join(dir, "mypath"), 0o755) + require.NoError(t, err) + + func() { + var f *os.File + f, err = os.Create(filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4")) + require.NoError(t, err) + defer f.Close() + + init := fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + }, + } + + err = init.Marshal(f) + require.NoError(t, err) + + err = writeDuration(f, 50*time.Second) + require.NoError(t, err) + }() + + s := &Server{ + Address: "127.0.0.1:9996", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathConfs: map[string]*conf.Path{ + "mypath": { + Name: "mypath", + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + }, + AuthManager: test.NilAuthManager, + 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 any + err = json.NewDecoder(res.Body).Decode(&out) + require.NoError(t, err) + + require.Equal(t, []any{ + map[string]any{ + "duration": float64(50), + "start": time.Date(2008, 11, 7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano), + "url": "http://localhost:9996/get?duration=50&path=mypath&start=" + + url.QueryEscape(time.Date(2008, 11, 7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano)), + }, + }, out) +} + +func TestOnListXForwardedProto(t *testing.T) { + dir := t.TempDir() + + 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")) + + var trustedProxies conf.IPNetworks + err = json.Unmarshal([]byte(`["127.0.0.0/8"]`), &trustedProxies) + require.NoError(t, err) + + s := &Server{ + Address: "127.0.0.1:9996", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + TrustedProxies: trustedProxies, + PathConfs: map[string]*conf.Path{ + "mypath": { + Name: "mypath", + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + }, + AuthManager: test.NilAuthManager, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + u, err := url.Parse("http://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) + + req.Header.Set("X-Forwarded-Proto", "https") + + res, err := http.DefaultClient.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusOK, res.StatusCode) + + var out any + err = json.NewDecoder(res.Body).Decode(&out) + require.NoError(t, err) + + require.Equal(t, []any{ + map[string]any{ + "duration": float64(62), + "start": time.Date(2008, 11, 7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano), + "url": "https://localhost:9996/get?duration=62&path=mypath&start=" + + url.QueryEscape(time.Date(2008, 11, 7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano)), + }, + }, out) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/segment_fmp4.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/segment_fmp4.go new file mode 100644 index 0000000000000000000000000000000000000000..be776391531c05428afab1685bfe89af54393a21 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/segment_fmp4.go @@ -0,0 +1,532 @@ +package playback + +import ( + "bytes" + "errors" + "fmt" + "io" + "reflect" + "time" + + amp4 "github.com/abema/go-mp4" + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + "github.com/bluenviron/mediamtx/internal/recordstore" +) + +const ( + sampleFlagIsNonSyncSample = 1 << 16 + concatenationTolerance = 1 * time.Second +) + +var errTerminated = errors.New("terminated") + +type readSeekerAt interface { + io.Reader + io.Seeker + io.ReaderAt +} + +func durationGoToMp4(v time.Duration, timeScale uint32) int64 { + timeScale64 := int64(timeScale) + secs := v / time.Second + dec := v % time.Second + return int64(secs)*timeScale64 + int64(dec)*timeScale64/int64(time.Second) +} + +func durationMp4ToGo(v int64, timeScale uint32) time.Duration { + timeScale64 := int64(timeScale) + secs := v / timeScale64 + dec := v % timeScale64 + return time.Duration(secs)*time.Second + time.Duration(dec)*time.Second/time.Duration(timeScale64) +} + +func findInitTrack(tracks []*fmp4.InitTrack, id int) *fmp4.InitTrack { + for _, track := range tracks { + if track.ID == id { + return track + } + } + return nil +} + +func findMtxi(userData []amp4.IBox) *recordstore.Mtxi { + for _, box := range userData { + if i, ok := box.(*recordstore.Mtxi); ok { + return i + } + } + return nil +} + +func segmentFMP4TracksAreEqual(tracks1 []*fmp4.InitTrack, tracks2 []*fmp4.InitTrack) bool { + if len(tracks1) != len(tracks2) { + return false + } + + for i, track1 := range tracks1 { + track2 := tracks2[i] + + if track1.ID != track2.ID || + track1.TimeScale != track2.TimeScale || + reflect.TypeOf(track1.Codec) != reflect.TypeOf(track2.Codec) { + return false + } + } + + return true +} + +func segmentFMP4CanBeConcatenated( + prevInit *fmp4.Init, + prevEnd time.Time, + curInit *fmp4.Init, + curStart time.Time, +) bool { + mtxi1 := findMtxi(prevInit.UserData) + mtxi2 := findMtxi(curInit.UserData) + + switch { + case mtxi1 == nil && mtxi2 != nil: + return false + + case mtxi1 != nil && mtxi2 == nil: + return false + + case mtxi1 == nil && mtxi2 == nil: // legacy method + return segmentFMP4TracksAreEqual(prevInit.Tracks, curInit.Tracks) && + !curStart.Before(prevEnd.Add(-concatenationTolerance)) && + !curStart.After(prevEnd.Add(concatenationTolerance)) + + default: + return bytes.Equal(mtxi1.StreamID[:], mtxi2.StreamID[:]) && + (mtxi1.SegmentNumber+1) == mtxi2.SegmentNumber + } +} + +func segmentFMP4ReadHeader(r io.ReadSeeker) (*fmp4.Init, time.Duration, error) { + // check and skip ftyp + + buf := make([]byte, 8) + _, err := io.ReadFull(r, buf) + if err != nil { + return nil, 0, err + } + + if !bytes.Equal(buf[4:], []byte{'f', 't', 'y', 'p'}) { + return nil, 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 nil, 0, err + } + + // check moov + + _, err = io.ReadFull(r, buf) + if err != nil { + return nil, 0, err + } + + if !bytes.Equal(buf[4:], []byte{'m', 'o', 'o', 'v'}) { + return nil, 0, fmt.Errorf("moov box not found") + } + + moovSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) + + // skip moov header + + _, err = r.Seek(8, io.SeekCurrent) + if err != nil { + return nil, 0, err + } + + // read mvhd + + var mvhd amp4.Mvhd + _, err = amp4.Unmarshal(r, uint64(moovSize-8), &mvhd, amp4.Context{}) + if err != nil { + return nil, 0, err + } + + d := time.Duration(mvhd.DurationV0) * time.Second / time.Duration(mvhd.Timescale) + + // read ftyp and moov + + _, err = r.Seek(0, io.SeekStart) + if err != nil { + return nil, 0, err + } + + buf = make([]byte, uint64(ftypSize+moovSize)) + + _, err = io.ReadFull(r, buf) + if err != nil { + return nil, 0, err + } + + // pass ftyp and moov to fmp4.Init + + var init fmp4.Init + err = init.Unmarshal(bytes.NewReader(buf)) + if err != nil { + return nil, 0, err + } + + return &init, d, nil +} + +func segmentFMP4ReadDurationFromParts( + r io.ReadSeeker, + init *fmp4.Init, +) (time.Duration, error) { + _, err := r.Seek(0, io.SeekStart) + if err != nil { + return 0, err + } + + // check 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 + } + + // check 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 { + var moofPos int64 + 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'}) { + break + } + + 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'}) { + break + } + + 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 + } + + var maxElapsed time.Duration + + // foreach traf + +outer: + for { + _, err = io.ReadFull(r, buf) + if err != nil { + return 0, err + } + + switch { + case bytes.Equal(buf[4:], []byte{'t', 'r', 'a', 'f'}): + case bytes.Equal(buf[4:], []byte{'m', 'd', 'a', 't'}): + break outer + default: + return 0, fmt.Errorf("unexpected box %x", buf[4:8]) + } + + // parse 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]) + + buf2 := make([]byte, tfhdSize-8) + + _, err = io.ReadFull(r, buf2) + if err != nil { + return 0, err + } + + var tfhd amp4.Tfhd + _, err = amp4.Unmarshal(bytes.NewReader(buf2), uint64(len(buf2)), &tfhd, amp4.Context{}) + if err != nil { + return 0, fmt.Errorf("invalid tfhd box: %w", err) + } + + track := findInitTrack(init.Tracks, int(tfhd.TrackID)) + if track == nil { + return 0, fmt.Errorf("invalid track ID: %v", tfhd.TrackID) + } + + // 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 amp4.Tfdt + _, err = amp4.Unmarshal(bytes.NewReader(buf2), uint64(len(buf2)), &tfdt, amp4.Context{}) + if err != nil { + return 0, fmt.Errorf("invalid tfdt box: %w", err) + } + + // 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 amp4.Trun + _, err = amp4.Unmarshal(bytes.NewReader(buf2), uint64(len(buf2)), &trun, amp4.Context{}) + if err != nil { + return 0, fmt.Errorf("invalid trun box: %w", err) + } + + elapsed := int64(tfdt.BaseMediaDecodeTimeV1) + + for _, entry := range trun.Entries { + elapsed += int64(entry.SampleDuration) + } + + elapsedGo := durationMp4ToGo(elapsed, track.TimeScale) + + if elapsedGo > maxElapsed { + maxElapsed = elapsedGo + } + } + + return maxElapsed, nil +} + +func segmentFMP4MuxParts( + r readSeekerAt, + startDTS time.Duration, + duration time.Duration, + tracks []*fmp4.InitTrack, + m muxer, +) (time.Duration, error) { + var startDTSMP4 int64 + var durationMP4 int64 + moofOffset := uint64(0) + var tfhd *amp4.Tfhd + var tfdt *amp4.Tfdt + var timeScale uint32 + var segmentDuration time.Duration + breakAtNextMdat := false + + _, err := amp4.ReadBoxStructure(r, func(h *amp4.ReadHandle) (any, error) { + switch h.BoxInfo.Type.String() { + case "moof": + moofOffset = h.BoxInfo.Offset + return h.Expand() + + case "traf": + return h.Expand() + + case "tfhd": + box, _, err := h.ReadPayload() + if err != nil { + return nil, err + } + tfhd = box.(*amp4.Tfhd) + + case "tfdt": + box, _, err := h.ReadPayload() + if err != nil { + return nil, err + } + tfdt = box.(*amp4.Tfdt) + + track := findInitTrack(tracks, int(tfhd.TrackID)) + if track == nil { + return nil, fmt.Errorf("invalid track ID: %v", tfhd.TrackID) + } + + m.setTrack(int(tfhd.TrackID)) + timeScale = track.TimeScale + startDTSMP4 = durationGoToMp4(startDTS, track.TimeScale) + durationMP4 = durationGoToMp4(duration, track.TimeScale) + + case "trun": + box, _, err := h.ReadPayload() + if err != nil { + return nil, err + } + trun := box.(*amp4.Trun) + + dataOffset := moofOffset + uint64(trun.DataOffset) + dts := int64(tfdt.BaseMediaDecodeTimeV1) + startDTSMP4 + + for _, e := range trun.Entries { + if dts >= durationMP4 { + breakAtNextMdat = true + break + } + + sampleOffset := dataOffset + sampleSize := e.SampleSize + + err = m.writeSample( + dts, + e.SampleCompositionTimeOffsetV1, + (e.SampleFlags&sampleFlagIsNonSyncSample) != 0, + e.SampleSize, + func() ([]byte, error) { + payload := make([]byte, sampleSize) + n, err2 := r.ReadAt(payload, int64(sampleOffset)) + if err2 != nil { + return nil, err2 + } + if n != int(sampleSize) { + return nil, fmt.Errorf("partial read") + } + + return payload, nil + }, + ) + if err != nil { + return nil, err + } + + dataOffset += uint64(e.SampleSize) + dts += int64(e.SampleDuration) + } + + m.writeFinalDTS(dts) + + segmentElapsed := durationMp4ToGo(dts-startDTSMP4, timeScale) + + if segmentElapsed > segmentDuration { + segmentDuration = segmentElapsed + } + + case "mdat": + if breakAtNextMdat { + return nil, errTerminated + } + } + return nil, nil + }) + if err != nil && !errors.Is(err, errTerminated) { + return 0, err + } + + return segmentDuration, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/segment_fmp4_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/segment_fmp4_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4a100e2f4c08d6df9be068a65b5ca381ffc70871 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/segment_fmp4_test.go @@ -0,0 +1,426 @@ +package playback + +import ( + "io" + "os" + "testing" + "time" + + amp4 "github.com/abema/go-mp4" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + mcodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mp4/codecs" + "github.com/bluenviron/mediamtx/internal/recordstore" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func writeBenchInit(f io.WriteSeeker) { + init := fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + { + ID: 2, + TimeScale: 90000, + Codec: &mcodecs.MPEG4Audio{ + Config: mpeg4audio.AudioSpecificConfig{ + Type: mpeg4audio.ObjectTypeAACLC, + SampleRate: 48000, + ChannelCount: 2, + }, + }, + }, + }, + } + + err := init.Marshal(f) + if err != nil { + panic(err) + } + + _, err = f.Write([]byte{ + 0x00, 0x00, 0x00, 0x10, 'm', 'o', 'o', 'f', + }) + if err != nil { + panic(err) + } +} + +func BenchmarkFMP4ReadHeader(b *testing.B) { + f, err := os.CreateTemp(b.TempDir(), "mediamtx-playback-fmp4-") + if err != nil { + panic(err) + } + + writeBenchInit(f) + f.Close() + + for b.Loop() { + func() { + f, err = os.Open(f.Name()) + if err != nil { + panic(err) + } + defer f.Close() + + _, _, err = segmentFMP4ReadHeader(f) + if err != nil { + panic(err) + } + }() + } +} + +func TestSegmentFMP4CanBeConcatenated(t *testing.T) { + baseTime := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC) + streamID1 := [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} + streamID2 := [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17} + + baseTracks := []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + { + ID: 2, + TimeScale: 48000, + Codec: &mcodecs.MPEG4Audio{ + Config: mpeg4audio.AudioSpecificConfig{ + Type: mpeg4audio.ObjectTypeAACLC, + SampleRate: 48000, + ChannelCount: 2, + }, + }, + }, + } + + differentTracks := []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + } + + for _, tt := range []struct { + name string + prevInit *fmp4.Init + prevEnd time.Time + curInit *fmp4.Init + curStart time.Time + want bool + }{ + { + name: "with mtxi - consecutive segments, same stream", + prevInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{ + &recordstore.Mtxi{ + StreamID: streamID1, + SegmentNumber: 1, + }, + }, + }, + prevEnd: baseTime, + curInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{ + &recordstore.Mtxi{ + StreamID: streamID1, + SegmentNumber: 2, + }, + }, + }, + curStart: baseTime.Add(5 * time.Second), + want: true, + }, + { + name: "with mtxi - non-consecutive segments, same stream", + prevInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{ + &recordstore.Mtxi{ + StreamID: streamID1, + SegmentNumber: 1, + }, + }, + }, + prevEnd: baseTime, + curInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{ + &recordstore.Mtxi{ + StreamID: streamID1, + SegmentNumber: 3, + }, + }, + }, + curStart: baseTime.Add(5 * time.Second), + want: false, + }, + { + name: "with mtxi - consecutive segments, different streams", + prevInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{ + &recordstore.Mtxi{ + StreamID: streamID1, + SegmentNumber: 1, + }, + }, + }, + prevEnd: baseTime, + curInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{ + &recordstore.Mtxi{ + StreamID: streamID2, + SegmentNumber: 2, + }, + }, + }, + curStart: baseTime.Add(5 * time.Second), + want: false, + }, + { + name: "prev has mtxi, current does not", + prevInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{ + &recordstore.Mtxi{ + StreamID: streamID1, + SegmentNumber: 1, + }, + }, + }, + prevEnd: baseTime, + curInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + curStart: baseTime.Add(5 * time.Second), + want: false, + }, + { + name: "prev does not have mtxi, current has mtxi", + prevInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + prevEnd: baseTime, + curInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{ + &recordstore.Mtxi{ + StreamID: streamID1, + SegmentNumber: 1, + }, + }, + }, + curStart: baseTime.Add(5 * time.Second), + want: false, + }, + { + name: "legacy mode - same tracks, within time tolerance", + prevInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + prevEnd: baseTime.Add(10 * time.Second), + curInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + curStart: baseTime.Add(10 * time.Second), + want: true, + }, + { + name: "legacy mode - same tracks, exactly at tolerance boundary (before)", + prevInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + prevEnd: baseTime.Add(10 * time.Second), + curInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + curStart: baseTime.Add(9 * time.Second), + want: true, + }, + { + name: "legacy mode - same tracks, exactly at tolerance boundary (after)", + prevInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + prevEnd: baseTime.Add(10 * time.Second), + curInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + curStart: baseTime.Add(11 * time.Second), + want: true, + }, + { + name: "legacy mode - same tracks, outside time tolerance (too early)", + prevInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + prevEnd: baseTime.Add(10 * time.Second), + curInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + curStart: baseTime.Add(8*time.Second + 999*time.Millisecond), + want: false, + }, + { + name: "legacy mode - same tracks, outside time tolerance (too late)", + prevInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + prevEnd: baseTime.Add(10 * time.Second), + curInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + curStart: baseTime.Add(11*time.Second + 1*time.Millisecond), + want: false, + }, + { + name: "legacy mode - different number of tracks", + prevInit: &fmp4.Init{ + Tracks: baseTracks, + UserData: []amp4.IBox{}, + }, + prevEnd: baseTime, + curInit: &fmp4.Init{ + Tracks: differentTracks, + UserData: []amp4.IBox{}, + }, + curStart: baseTime.Add(5 * time.Second), + want: false, + }, + { + name: "legacy mode - different track IDs", + prevInit: &fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + }, + UserData: []amp4.IBox{}, + }, + prevEnd: baseTime, + curInit: &fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 2, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + }, + UserData: []amp4.IBox{}, + }, + curStart: baseTime.Add(5 * time.Second), + want: false, + }, + { + name: "legacy mode - different time scales", + prevInit: &fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + }, + UserData: []amp4.IBox{}, + }, + prevEnd: baseTime, + curInit: &fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 48000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + }, + UserData: []amp4.IBox{}, + }, + curStart: baseTime.Add(5 * time.Second), + want: false, + }, + { + name: "legacy mode - different codec types", + prevInit: &fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + }, + UserData: []amp4.IBox{}, + }, + prevEnd: baseTime, + curInit: &fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.MPEG4Audio{ + Config: mpeg4audio.AudioSpecificConfig{ + Type: mpeg4audio.ObjectTypeAACLC, + SampleRate: 48000, + ChannelCount: 2, + }, + }, + }, + }, + UserData: []amp4.IBox{}, + }, + curStart: baseTime.Add(5 * time.Second), + want: false, + }, + } { + t.Run(tt.name, func(t *testing.T) { + got := segmentFMP4CanBeConcatenated(tt.prevInit, tt.prevEnd, tt.curInit, tt.curStart) + require.Equal(t, tt.want, got) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/server.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/server.go new file mode 100644 index 0000000000000000000000000000000000000000..1a31d1283bc74693aeb7d57fa79089be919360b4 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/server.go @@ -0,0 +1,161 @@ +// Package playback contains the playback server. +package playback + +import ( + "fmt" + "net" + "net/http" + "sync" + "time" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/httpp" + "github.com/gin-gonic/gin" +) + +type serverAuthManager interface { + Authenticate(req *auth.Request) (string, *auth.Error) +} + +// Server is the playback server. +type Server struct { + Address string + DumpPackets bool + Encryption bool + ServerKey string + ServerCert string + AllowOrigins []string + TrustedProxies conf.IPNetworks + ReadTimeout conf.Duration + WriteTimeout conf.Duration + PathConfs map[string]*conf.Path + AuthManager serverAuthManager + Parent logger.Writer + + httpServer *httpp.Server + mutex sync.RWMutex +} + +// Initialize initializes Server. +func (s *Server) Initialize() error { + router := gin.New() + router.SetTrustedProxies(s.TrustedProxies.ToTrustedProxies()) //nolint:errcheck + router.Use(s.middlewarePreflightRequests) + + router.GET("/list", s.onList) + router.GET("/get", s.onGet) + + s.httpServer = &httpp.Server{ + Address: s.Address, + AllowOrigins: s.AllowOrigins, + DumpPackets: s.DumpPackets, + DumpPacketsPrefix: "playback_server_conn", + ReadTimeout: time.Duration(s.ReadTimeout), + WriteTimeout: time.Duration(s.WriteTimeout), + Encryption: s.Encryption, + ServerCert: s.ServerCert, + ServerKey: s.ServerKey, + Handler: router, + Parent: s, + } + err := s.httpServer.Initialize() + if err != nil { + return err + } + + str := "started with listener on " + s.Address + if !s.Encryption { + str += " (TCP/HTTP)" + } else { + str += " (TCP/HTTPS)" + } + s.Log(logger.Info, str) + + return nil +} + +// Close closes Server. +func (s *Server) Close() { + s.Log(logger.Info, "closing") + s.httpServer.Close() +} + +// Log implements logger.Writer. +func (s *Server) Log(level logger.Level, format string, args ...any) { + s.Parent.Log(level, "[playback] "+format, args...) +} + +// ReloadPathConfs is called by core.Core. +func (s *Server) ReloadPathConfs(pathConfs map[string]*conf.Path) { + s.mutex.Lock() + defer s.mutex.Unlock() + s.PathConfs = pathConfs +} + +func (s *Server) writeError(ctx *gin.Context, status int, err error) { + // show error in logs + s.Log(logger.Error, err.Error()) + + // add error to response + ctx.AbortWithStatusJSON(status, &defs.APIError{ + Status: defs.APIErrorStatusError, + Error: err.Error(), + }) +} + +func (s *Server) writeErrorNoLog(ctx *gin.Context, status int, err error) { + ctx.AbortWithStatusJSON(status, &defs.APIError{ + Status: defs.APIErrorStatusError, + Error: err.Error(), + }) +} + +func (s *Server) safeFindPathConf(name string) (*conf.Path, error) { + s.mutex.RLock() + defer s.mutex.RUnlock() + + pathConf, _, err := conf.FindPathConf(s.PathConfs, name) + return pathConf, err +} + +func (s *Server) middlewarePreflightRequests(ctx *gin.Context) { + if ctx.Request.Method == http.MethodOptions && + ctx.Request.Header.Get("Access-Control-Request-Method") != "" { + ctx.Header("Access-Control-Allow-Methods", "OPTIONS, GET") + ctx.Header("Access-Control-Allow-Headers", "Authorization") + ctx.AbortWithStatus(http.StatusNoContent) + return + } +} + +func (s *Server) doAuth(ctx *gin.Context, pathName string) bool { + req := &auth.Request{ + Action: conf.AuthActionPlayback, + Path: pathName, + Query: ctx.Request.URL.RawQuery, + Credentials: httpp.Credentials(ctx.Request), + IP: net.ParseIP(ctx.ClientIP()), + } + + _, err := s.AuthManager.Authenticate(req) + if err != nil { + auth.DelayBruteForce(err) + + if err.AskCredentials { + ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`) + s.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return false + } + + s.Log(logger.Info, "connection %v failed to authenticate: %v", + httpp.RemoteAddr(ctx), err.Wrapped) + + s.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return false + } + + return true +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/server_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e059e46744896cddd4c6c0aa6c54acb6597b5f32 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/playback/server_test.go @@ -0,0 +1,117 @@ +package playback + +import ( + "fmt" + "io" + "net/http" + "net/url" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestPreflightRequest(t *testing.T) { + s := &Server{ + Address: "127.0.0.1:9996", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + req, err := http.NewRequest(http.MethodOptions, "http://localhost:9996", nil) + require.NoError(t, err) + + req.Header.Add("Access-Control-Request-Method", "GET") + + res, err := hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusNoContent, res.StatusCode) + + byts, err := io.ReadAll(res.Body) + require.NoError(t, err) + + require.Equal(t, "*", res.Header.Get("Access-Control-Allow-Origin")) + require.Equal(t, "true", res.Header.Get("Access-Control-Allow-Credentials")) + require.Equal(t, "OPTIONS, GET", res.Header.Get("Access-Control-Allow-Methods")) + require.Equal(t, "Authorization", res.Header.Get("Access-Control-Allow-Headers")) + require.Equal(t, byts, []byte{}) +} + +func TestAuthError(t *testing.T) { + n := 0 + + s := &Server{ + Address: "127.0.0.1:9996", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + AuthManager: &test.AuthManager{ + AuthenticateImpl: func(req *auth.Request) (string, *auth.Error) { + if req.Credentials.User == "" { + return "", &auth.Error{AskCredentials: true, Wrapped: fmt.Errorf("auth error")} + } + return "", &auth.Error{Wrapped: fmt.Errorf("auth error")} + }, + }, + Parent: test.Logger(func(l logger.Level, s string, i ...any) { + if l == logger.Info { + if n == 1 { + require.Regexp(t, "failed to authenticate: auth error$", fmt.Sprintf(s, i...)) + } + n++ + } + }), + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + u, err := url.Parse("http://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.StatusUnauthorized, res.StatusCode) + require.Equal(t, `Basic realm="mediamtx"`, res.Header.Get("WWW-Authenticate")) + + 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.StatusUnauthorized, res.StatusCode) + + require.Equal(t, 2, n) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/pprof/pprof.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/pprof/pprof.go new file mode 100644 index 0000000000000000000000000000000000000000..3cc31b329d4f1bfcdaf20ec0a426f8cf47bb8154 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/pprof/pprof.go @@ -0,0 +1,134 @@ +// Package pprof contains a pprof exporter. +package pprof //nolint:revive + +import ( + "fmt" + "net" + "net/http" + "time" + + "github.com/gin-contrib/pprof" + "github.com/gin-gonic/gin" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/httpp" +) + +type pprofAuthManager interface { + Authenticate(req *auth.Request) (string, *auth.Error) +} + +type pprofParent interface { + logger.Writer +} + +// PPROF is a pprof exporter. +type PPROF struct { + Address string + DumpPackets bool + Encryption bool + ServerKey string + ServerCert string + AllowOrigins []string + TrustedProxies conf.IPNetworks + ReadTimeout conf.Duration + WriteTimeout conf.Duration + AuthManager pprofAuthManager + Parent pprofParent + + httpServer *httpp.Server +} + +// Initialize initializes PPROF. +func (pp *PPROF) Initialize() error { + router := gin.New() + router.SetTrustedProxies(pp.TrustedProxies.ToTrustedProxies()) //nolint:errcheck + router.Use(pp.middlewarePreflightRequests) + router.Use(pp.middlewareAuth) + + pprof.Register(router) + + pp.httpServer = &httpp.Server{ + Address: pp.Address, + DumpPackets: pp.DumpPackets, + AllowOrigins: pp.AllowOrigins, + DumpPacketsPrefix: "pprof_server_conn", + ReadTimeout: time.Duration(pp.ReadTimeout), + WriteTimeout: time.Duration(pp.WriteTimeout), + Encryption: pp.Encryption, + ServerCert: pp.ServerCert, + ServerKey: pp.ServerKey, + Handler: router, + Parent: pp, + } + err := pp.httpServer.Initialize() + if err != nil { + return err + } + + str := "started with listener on " + pp.Address + if !pp.Encryption { + str += " (TCP/HTTP)" + } else { + str += " (TCP/HTTPS)" + } + pp.Log(logger.Info, str) + + return nil +} + +// Close closes PPROF. +func (pp *PPROF) Close() { + pp.Log(logger.Info, "closing") + pp.httpServer.Close() +} + +// Log implements logger.Writer. +func (pp *PPROF) Log(level logger.Level, format string, args ...any) { + pp.Parent.Log(level, "[pprof] "+format, args...) +} + +func (pp *PPROF) middlewarePreflightRequests(ctx *gin.Context) { + if ctx.Request.Method == http.MethodOptions && + ctx.Request.Header.Get("Access-Control-Request-Method") != "" { + ctx.Header("Access-Control-Allow-Methods", "OPTIONS, GET") + ctx.Header("Access-Control-Allow-Headers", "Authorization") + ctx.AbortWithStatus(http.StatusNoContent) + return + } +} + +func (pp *PPROF) writeErrorNoLog(ctx *gin.Context, status int, err error) { + ctx.AbortWithStatusJSON(status, &defs.APIError{ + Status: defs.APIErrorStatusError, + Error: err.Error(), + }) +} + +func (pp *PPROF) middlewareAuth(ctx *gin.Context) { + req := &auth.Request{ + Action: conf.AuthActionPprof, + Query: ctx.Request.URL.RawQuery, + Credentials: httpp.Credentials(ctx.Request), + IP: net.ParseIP(ctx.ClientIP()), + } + + _, err := pp.AuthManager.Authenticate(req) + if err != nil { + auth.DelayBruteForce(err) + + if err.AskCredentials { + ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`) + pp.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return + } + + pp.Log(logger.Info, "connection %v failed to authenticate: %v", httpp.RemoteAddr(ctx), err.Wrapped) + + pp.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/pprof/pprof_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/pprof/pprof_test.go new file mode 100644 index 0000000000000000000000000000000000000000..5e75478f3dd566b17f7e106207d0d80fe3a5215e --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/pprof/pprof_test.go @@ -0,0 +1,150 @@ +package pprof //nolint:revive + +import ( + "fmt" + "io" + "net/http" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestPreflightRequest(t *testing.T) { + s := &PPROF{ + Address: "127.0.0.1:9999", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + req, err := http.NewRequest(http.MethodOptions, "http://localhost:9999", nil) + require.NoError(t, err) + + req.Header.Add("Access-Control-Request-Method", "GET") + + res, err := hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusNoContent, res.StatusCode) + + byts, err := io.ReadAll(res.Body) + require.NoError(t, err) + + require.Equal(t, "*", res.Header.Get("Access-Control-Allow-Origin")) + require.Equal(t, "true", res.Header.Get("Access-Control-Allow-Credentials")) + require.Equal(t, "OPTIONS, GET", res.Header.Get("Access-Control-Allow-Methods")) + require.Equal(t, "Authorization", res.Header.Get("Access-Control-Allow-Headers")) + require.Equal(t, byts, []byte{}) +} + +func TestPprof(t *testing.T) { + checked := false + + s := &PPROF{ + Address: "127.0.0.1:9999", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + AuthManager: &test.AuthManager{ + AuthenticateImpl: func(req *auth.Request) (string, *auth.Error) { + require.Equal(t, conf.AuthActionPprof, req.Action) + require.Equal(t, "myuser", req.Credentials.User) + require.Equal(t, "mypass", req.Credentials.Pass) + checked = true + return req.Credentials.User, nil + }, + }, + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + req, err := http.NewRequest(http.MethodGet, "http://myuser:mypass@127.0.0.1:9999/debug/pprof/heap", 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) + + byts, err := io.ReadAll(res.Body) + require.NoError(t, err) + require.NotEmpty(t, byts) + + require.True(t, checked) +} + +func TestAuthError(t *testing.T) { + n := 0 + + s := &PPROF{ + Address: "127.0.0.1:9999", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + AuthManager: &test.AuthManager{ + AuthenticateImpl: func(req *auth.Request) (string, *auth.Error) { + if req.Credentials.User == "" { + return "", &auth.Error{AskCredentials: true, Wrapped: fmt.Errorf("auth error")} + } + return "", &auth.Error{Wrapped: fmt.Errorf("auth error")} + }, + }, + Parent: test.Logger(func(l logger.Level, s string, i ...any) { + if l == logger.Info { + if n == 1 { + require.Regexp(t, "failed to authenticate: auth error$", fmt.Sprintf(s, i...)) + } + n++ + } + }), + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:9999/debug/pprof/heap", nil) + require.NoError(t, err) + + res, err := hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusUnauthorized, res.StatusCode) + require.Equal(t, `Basic realm="mediamtx"`, res.Header.Get("WWW-Authenticate")) + + req, err = http.NewRequest(http.MethodGet, "http://myuser:mypass@127.0.0.1:9999/debug/pprof/heap", nil) + require.NoError(t, err) + + res, err = hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusUnauthorized, res.StatusCode) + + require.Equal(t, 2, n) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/from_stream.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/from_stream.go new file mode 100644 index 0000000000000000000000000000000000000000..1b17e0932c545a29902d9dce4f2caba4887bbd34 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/from_stream.go @@ -0,0 +1,460 @@ +// Package hls contains HLS utilities. +package hls + +import ( + "encoding/hex" + "errors" + "fmt" + "reflect" + "slices" + "strings" + + "github.com/bluenviron/gohlslib/v2" + "github.com/bluenviron/gohlslib/v2/pkg/codecs" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/flac" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediamtx/internal/formatlabel" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" +) + +// ErrNoSupportedCodecs is returned by FromStream when there are no supported codecs. +var ErrNoSupportedCodecs = errors.New( + "the stream doesn't contain any supported codec, which are currently AV1, VP9, H265, H264, Opus, MPEG-4 Audio, KLV") + +func findFormatAndIndexInMedia(media *description.Media, forma any) int { + for i, forma2 := range media.Formats { + if reflect.TypeOf(forma2) == reflect.TypeOf(forma).Elem() { + reflect.ValueOf(forma).Elem().Set(reflect.ValueOf(forma2)) + return i + } + } + + return -1 +} + +func findFormatAndIndexes(d *description.Session, forma any) (*description.Media, int, int) { + for i, media := range d.Medias { + j := findFormatAndIndexInMedia(media, forma) + if j >= 0 { + return media, i, j + } + } + return nil, -1, -1 +} + +func setupVideoTrack( + origDesc *description.Session, + outDesc *description.Session, + r *stream.Reader, + muxer *gohlslib.Muxer, +) { + addTrack := func( + media *description.Media, + forma format.Format, + track *gohlslib.Track, + onData stream.OnDataFunc, + ) { + muxer.Tracks = append(muxer.Tracks, track) + r.OnData(media, forma, onData) + } + + var videoFormatAV1 *format.AV1 + videoMedia, _, _ := findFormatAndIndexes(origDesc, &videoFormatAV1) + + if videoFormatAV1 != nil { + track := &gohlslib.Track{ + Codec: &codecs.AV1{}, + ClockRate: videoFormatAV1.ClockRate(), + } + + addTrack( + videoMedia, + videoFormatAV1, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + err := muxer.WriteAV1( + track, + u.NTP, + u.PTS, // no conversion is needed since we set gohlslib.Track.ClockRate = format.ClockRate + u.Payload.(unit.PayloadAV1)) + if err != nil { + return fmt.Errorf("muxer error: %w", err) + } + + return nil + }) + + return + } + + var videoFormatVP9 *format.VP9 + videoMedia, _, _ = findFormatAndIndexes(origDesc, &videoFormatVP9) + + if videoFormatVP9 != nil { + track := &gohlslib.Track{ + Codec: &codecs.VP9{}, + ClockRate: videoFormatVP9.ClockRate(), + } + + addTrack( + videoMedia, + videoFormatVP9, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + err := muxer.WriteVP9( + track, + u.NTP, + u.PTS, // no conversion is needed since we set gohlslib.Track.ClockRate = format.ClockRate + u.Payload.(unit.PayloadVP9)) + if err != nil { + return fmt.Errorf("muxer error: %w", err) + } + + return nil + }) + + return + } + + var videoFormatH265 *format.H265 + videoMedia, i, j := findFormatAndIndexes(origDesc, &videoFormatH265) + + if videoFormatH265 != nil { + outFormat := outDesc.Medias[i].Formats[j].(*format.H265) + + track := &gohlslib.Track{ + Codec: &codecs.H265{ + VPS: outFormat.VPS, + SPS: outFormat.SPS, + PPS: outFormat.PPS, + }, + ClockRate: videoFormatH265.ClockRate(), + } + + addTrack( + videoMedia, + videoFormatH265, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + err := muxer.WriteH265( + track, + u.NTP, + u.PTS, // no conversion is needed since we set gohlslib.Track.ClockRate = format.ClockRate + u.Payload.(unit.PayloadH265)) + if err != nil { + return fmt.Errorf("muxer error: %w", err) + } + + return nil + }) + + return + } + + var videoFormatH264 *format.H264 + videoMedia, i, j = findFormatAndIndexes(origDesc, &videoFormatH264) + + if videoFormatH264 != nil { + outFormat := outDesc.Medias[i].Formats[j].(*format.H264) + + track := &gohlslib.Track{ + Codec: &codecs.H264{ + SPS: outFormat.SPS, + PPS: outFormat.PPS, + }, + ClockRate: videoFormatH264.ClockRate(), + } + + addTrack( + videoMedia, + videoFormatH264, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + err := muxer.WriteH264( + track, + u.NTP, + u.PTS, // no conversion is needed since we set gohlslib.Track.ClockRate = format.ClockRate + u.Payload.(unit.PayloadH264)) + if err != nil { + return fmt.Errorf("muxer error: %w", err) + } + + return nil + }) + + return + } +} + +func setupAudioTracks( + origDesc *description.Session, + _ *description.Session, + r *stream.Reader, + muxer *gohlslib.Muxer, +) error { + addTrack := func( + medi *description.Media, + forma format.Format, + track *gohlslib.Track, + onData stream.OnDataFunc, + ) { + muxer.Tracks = append(muxer.Tracks, track) + r.OnData(medi, forma, onData) + } + + for _, media := range origDesc.Medias { + for _, forma := range media.Formats { + switch forma := forma.(type) { + case *format.Opus: + track := &gohlslib.Track{ + Codec: &codecs.Opus{ + ChannelCount: forma.ChannelCount, + }, + ClockRate: forma.ClockRate(), + } + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + err := muxer.WriteOpus( + track, + u.NTP, + u.PTS, // no conversion is needed since we set gohlslib.Track.ClockRate = format.ClockRate + u.Payload.(unit.PayloadOpus)) + if err != nil { + return fmt.Errorf("muxer error: %w", err) + } + + return nil + }) + + case *format.Generic: + if strings.HasPrefix(strings.ToLower(forma.RTPMap()), "flac/") { + enc, err := hex.DecodeString(forma.FMT["streaminfo"]) + if err != nil { + return err + } + + var streamInfo flac.StreamInfo + err = streamInfo.Unmarshal(enc) + if err != nil { + return err + } + + track := &gohlslib.Track{ + Codec: &codecs.FLAC{ + StreamInfo: &streamInfo, + }, + ClockRate: forma.ClockRate(), + } + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + err2 := muxer.WriteFLAC( + track, + u.NTP, + u.PTS, // no conversion is needed since we set gohlslib.Track.ClockRate = format.ClockRate + u.Payload.(unit.PayloadFLAC)) + if err2 != nil { + return fmt.Errorf("muxer error: %w", err2) + } + + return nil + }) + } + + case *format.MPEG4Audio: + track := &gohlslib.Track{ + Codec: &codecs.MPEG4Audio{ + Config: *forma.Config, + }, + ClockRate: forma.ClockRate(), + } + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + err := muxer.WriteMPEG4Audio( + track, + u.NTP, + u.PTS, // no conversion is needed since we set gohlslib.Track.ClockRate = format.ClockRate + u.Payload.(unit.PayloadMPEG4Audio)) + if err != nil { + return fmt.Errorf("muxer error: %w", err) + } + + return nil + }) + + case *format.MPEG4AudioLATM: + if !forma.CPresent { + track := &gohlslib.Track{ + Codec: &codecs.MPEG4Audio{ + Config: *forma.StreamMuxConfig.Programs[0].Layers[0].AudioSpecificConfig, + }, + ClockRate: forma.ClockRate(), + } + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + var ame mpeg4audio.AudioMuxElement + ame.StreamMuxConfig = forma.StreamMuxConfig + err := ame.Unmarshal(u.Payload.(unit.PayloadMPEG4AudioLATM)) + if err != nil { + return err + } + + return muxer.WriteMPEG4Audio( + track, + u.NTP, + u.PTS, // no conversion is needed since we set gohlslib.Track.ClockRate = format.ClockRate + [][]byte{ame.Payloads[0][0][0]}) + }) + } + } + } + } + + return nil +} + +func setupDataTracks( + origDesc *description.Session, + _ *description.Session, + r *stream.Reader, + muxer *gohlslib.Muxer, +) { + addTrack := func( + media *description.Media, + forma format.Format, + track *gohlslib.Track, + onData stream.OnDataFunc, + ) { + muxer.Tracks = append(muxer.Tracks, track) + r.OnData(media, forma, onData) + } + + for _, media := range origDesc.Medias { + for _, forma := range media.Formats { + if forma, ok := forma.(*format.KLV); ok && muxer.Variant == gohlslib.MuxerVariantMPEGTS { + track := &gohlslib.Track{ + Codec: &codecs.KLV{Synchronous: true}, + ClockRate: forma.ClockRate(), + } + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + err := muxer.WriteKLV( + track, + u.NTP, + u.PTS, // no conversion is needed since we set gohlslib.Track.ClockRate = format.ClockRate + u.Payload.(unit.PayloadKLV)) + if err != nil { + return fmt.Errorf("muxer error: %w", err) + } + + return nil + }) + } + } + } +} + +// FromStream maps a MediaMTX stream to a HLS muxer. +func FromStream( + origDesc *description.Session, + outDesc *description.Session, + r *stream.Reader, + muxer *gohlslib.Muxer, +) error { + setupVideoTrack( + origDesc, + outDesc, + r, + muxer, + ) + + err := setupAudioTracks( + origDesc, + outDesc, + r, + muxer, + ) + if err != nil { + return err + } + + setupDataTracks( + origDesc, + outDesc, + r, + muxer, + ) + + if len(muxer.Tracks) == 0 { + return ErrNoSupportedCodecs + } + + setuppedFormats := r.Formats() + + n := 1 + for _, media := range origDesc.Medias { + for _, forma := range media.Formats { + if !slices.Contains(setuppedFormats, forma) { + r.Parent.Log(logger.Warn, "skipping track %d (%s)", n, formatlabel.FormatToLabel(forma)) + } + n++ + } + } + + return nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/from_stream_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/from_stream_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2b3a4a8be151d3db17c9474002b9428a3152d7c0 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/from_stream_test.go @@ -0,0 +1,121 @@ +package hls + +import ( + "fmt" + "testing" + + "github.com/bluenviron/gohlslib/v2" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestFromStreamNoSupportedCodecs(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.VP8{}}, + }}} + + r := &stream.Reader{ + Parent: test.Logger(func(logger.Level, string, ...any) { + t.Error("should not happen") + }), + } + + m := &gohlslib.Muxer{} + + err := FromStream(desc, desc, r, m) + require.Equal(t, ErrNoSupportedCodecs, err) +} + +func TestFromStreamSkipUnsupportedTracks(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.VP9{}}, + }, + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.VP8{}}, + }, + { + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.MPEG1Audio{}}, + }, + }} + + m := &gohlslib.Muxer{} + + n := 0 + + r := &stream.Reader{ + Parent: test.Logger(func(l logger.Level, format string, args ...any) { + require.Equal(t, logger.Warn, l) + switch n { + case 0: + require.Equal(t, "skipping track 2 (VP8)", fmt.Sprintf(format, args...)) + case 1: + require.Equal(t, "skipping track 3 (MPEG-1/2 Audio)", fmt.Sprintf(format, args...)) + } + n++ + }), + } + + err := FromStream(desc, desc, r, m) + require.NoError(t, err) + + require.Equal(t, 2, n) +} + +func TestFromStreamKLVRequiresMPEGTSVariant(t *testing.T) { + t.Run("klv only, non-mpegts variant", func(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{{ + Type: description.MediaTypeApplication, + Formats: []format.Format{&format.KLV{PayloadTyp: 96}}, + }}} + + r := &stream.Reader{ + Parent: test.Logger(func(logger.Level, string, ...any) { + t.Error("should not happen") + }), + } + + m := &gohlslib.Muxer{Variant: gohlslib.MuxerVariantFMP4} + + err := FromStream(desc, desc, r, m) + require.Equal(t, ErrNoSupportedCodecs, err) + }) + + t.Run("klv alongside video, non-mpegts variant", func(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H264{PayloadTyp: 96, PacketizationMode: 1}}, + }, + { + Type: description.MediaTypeApplication, + Formats: []format.Format{&format.KLV{PayloadTyp: 97}}, + }, + }} + + n := 0 + + r := &stream.Reader{ + Parent: test.Logger(func(l logger.Level, f string, args ...any) { + require.Equal(t, logger.Warn, l) + require.Equal(t, "skipping track 2 (KLV)", fmt.Sprintf(f, args...)) + n++ + }), + } + + m := &gohlslib.Muxer{Variant: gohlslib.MuxerVariantFMP4} + + err := FromStream(desc, desc, r, m) + require.NoError(t, err) + require.Equal(t, 1, n) + require.Equal(t, 1, len(m.Tracks)) + }) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/to_stream.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/to_stream.go new file mode 100644 index 0000000000000000000000000000000000000000..29cc6afb33afc9ef565d5d299d0f68c8bf635d93 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/to_stream.go @@ -0,0 +1,260 @@ +package hls + +import ( + "encoding/hex" + "strconv" + "sync" + "time" + + "github.com/bluenviron/gohlslib/v2" + "github.com/bluenviron/gohlslib/v2/pkg/codecs" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/ntpestimator" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" +) + +type ntpState int + +const ( + ntpStateInitial ntpState = iota + ntpStateUnavailable + ntpStateAvailable + ntpStateReplace +) + +func multiplyAndDivide(v, m, d int64) int64 { + secs := v / d + dec := v % d + return (secs*m + dec*m/d) +} + +// ToStream maps a HLS stream to a MediaMTX stream. +func ToStream( + c *gohlslib.Client, + tracks []*gohlslib.Track, + pathConf *conf.Path, + subStream **stream.SubStream, +) ([]*description.Media, error) { + var ntpStat ntpState + var ntpStatMutex sync.Mutex + + if !pathConf.UseAbsoluteTimestamp { + ntpStat = ntpStateReplace + } + + var medias []*description.Media //nolint:prealloc + + for _, track := range tracks { + ctrack := track + ntpEstimator := &ntpestimator.Estimator{ClockRate: track.ClockRate} + + handleNTP := func(pts int64) time.Time { + ntpStatMutex.Lock() + defer ntpStatMutex.Unlock() + + switch ntpStat { + case ntpStateInitial: + ntp, avail := c.AbsoluteTime(ctrack) + if !avail { + ntpStat = ntpStateUnavailable + return ntpEstimator.Estimate(pts) + } + ntpStat = ntpStateAvailable + return ntp + + case ntpStateAvailable: + ntp, avail := c.AbsoluteTime(ctrack) + if !avail { + panic("should not happen") + } + return ntp + + case ntpStateUnavailable: + _, avail := c.AbsoluteTime(ctrack) + if avail { + // absolute timestamp appeared after stream started, we are not using it + ntpStat = ntpStateReplace + } + return ntpEstimator.Estimate(pts) + + default: // ntpStateReplace + return ntpEstimator.Estimate(pts) + } + } + + var medi *description.Media + + switch tcodec := ctrack.Codec.(type) { + case *codecs.AV1: + medi = &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.AV1{ + PayloadTyp: 96, + }}, + } + newClockRate := medi.Formats[0].ClockRate() + + c.OnDataAV1(ctrack, func(pts int64, tu [][]byte) { + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + NTP: handleNTP(pts), + PTS: multiplyAndDivide(pts, int64(newClockRate), int64(ctrack.ClockRate)), + Payload: unit.PayloadAV1(tu), + }) + }) + + case *codecs.VP9: + medi = &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.VP9{ + PayloadTyp: 96, + }}, + } + newClockRate := medi.Formats[0].ClockRate() + + c.OnDataVP9(ctrack, func(pts int64, frame []byte) { + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + NTP: handleNTP(pts), + PTS: multiplyAndDivide(pts, int64(newClockRate), int64(ctrack.ClockRate)), + Payload: unit.PayloadVP9(frame), + }) + }) + + case *codecs.H265: + medi = &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H265{ + PayloadTyp: 96, + VPS: tcodec.VPS, + SPS: tcodec.SPS, + PPS: tcodec.PPS, + }}, + } + newClockRate := medi.Formats[0].ClockRate() + + c.OnDataH26x(ctrack, func(pts int64, _ int64, au [][]byte) { + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + NTP: handleNTP(pts), + PTS: multiplyAndDivide(pts, int64(newClockRate), int64(ctrack.ClockRate)), + Payload: unit.PayloadH265(au), + }) + }) + + case *codecs.H264: + medi = &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + SPS: tcodec.SPS, + PPS: tcodec.PPS, + }}, + } + newClockRate := medi.Formats[0].ClockRate() + + c.OnDataH26x(ctrack, func(pts int64, _ int64, au [][]byte) { + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + NTP: handleNTP(pts), + PTS: multiplyAndDivide(pts, int64(newClockRate), int64(ctrack.ClockRate)), + Payload: unit.PayloadH264(au), + }) + }) + + case *codecs.Opus: + medi = &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.Opus{ + PayloadTyp: 96, + ChannelCount: tcodec.ChannelCount, + }}, + } + newClockRate := medi.Formats[0].ClockRate() + + c.OnDataOpus(ctrack, func(pts int64, packets [][]byte) { + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + NTP: handleNTP(pts), + PTS: multiplyAndDivide(pts, int64(newClockRate), int64(ctrack.ClockRate)), + Payload: unit.PayloadOpus(packets), + }) + }) + + case *codecs.FLAC: + enc, err := tcodec.StreamInfo.Marshal() + if err != nil { + return nil, err + } + + sampleRate := int(tcodec.StreamInfo.SampleRate) + medi = &description.Media{ + Type: description.MediaTypeApplication, + Formats: []format.Format{&format.Generic{ + PayloadTyp: 96, + RTPMa: "flac/" + strconv.Itoa(sampleRate), + ClockRat: sampleRate, + FMT: map[string]string{ + "streaminfo": hex.EncodeToString(enc), + }, + }}, + } + + c.OnDataFLAC(ctrack, func(pts int64, frame []byte) { + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + NTP: handleNTP(pts), + PTS: multiplyAndDivide(pts, int64(sampleRate), int64(ctrack.ClockRate)), + Payload: unit.PayloadFLAC(frame), + }) + }) + + case *codecs.MPEG4Audio: + medi = &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.MPEG4Audio{ + PayloadTyp: 96, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + Config: &tcodec.Config, + }}, + } + newClockRate := medi.Formats[0].ClockRate() + + c.OnDataMPEG4Audio(ctrack, func(pts int64, aus [][]byte) { + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + NTP: handleNTP(pts), + PTS: multiplyAndDivide(pts, int64(newClockRate), int64(ctrack.ClockRate)), + Payload: unit.PayloadMPEG4Audio(aus), + }) + }) + + case *codecs.KLV: + medi = &description.Media{ + Type: description.MediaTypeApplication, + Formats: []format.Format{&format.KLV{ + PayloadTyp: 96, + }}, + } + newClockRate := medi.Formats[0].ClockRate() + + c.OnDataKLV(ctrack, func(pts int64, uni []byte) { + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + NTP: handleNTP(pts), + PTS: multiplyAndDivide(pts, int64(newClockRate), int64(ctrack.ClockRate)), + Payload: unit.PayloadKLV(uni), + }) + }) + + default: + panic("should not happen") + } + + medias = append(medias, medi) + } + + if len(medias) == 0 { + return nil, ErrNoSupportedCodecs + } + + return medias, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/to_stream_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/to_stream_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9e34fbf45350c385e28c6628130fb2f726839c5f --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/hls/to_stream_test.go @@ -0,0 +1,222 @@ +package hls + +import ( + "context" + "net" + "net/http" + "testing" + "time" + + "github.com/bluenviron/gohlslib/v2" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts" + tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/stretchr/testify/require" +) + +func TestToStreamNoSupportedCodecs(t *testing.T) { + _, err := ToStream(nil, []*gohlslib.Track{}, &conf.Path{}, nil) + require.Equal(t, ErrNoSupportedCodecs, err) +} + +// this is impossible to test since currently we support all gohlslib.Tracks. +// func TestToStreamSkipUnsupportedTracks(t *testing.T) + +func TestToStream(t *testing.T) { + for _, ca := range []string{ + "h264", + "klv", + } { + t.Run(ca, func(t *testing.T) { + var track1 *mpegts.Track + + switch ca { + case "h264": + track1 = &mpegts.Track{ + Codec: &tscodecs.H264{}, + } + case "klv": + track1 = &mpegts.Track{ + Codec: &tscodecs.KLV{Synchronous: true}, + } + } + + s := &http.Server{ + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && r.URL.Path == "/stream.m3u8": + w.Header().Set("Content-Type", `application/vnd.apple.mpegurl`) + w.Write([]byte("#EXTM3U\n" + + "#EXT-X-VERSION:3\n" + + "#EXT-X-ALLOW-CACHE:NO\n" + + "#EXT-X-TARGETDURATION:2\n" + + "#EXT-X-MEDIA-SEQUENCE:0\n" + + "#EXT-X-PROGRAM-DATE-TIME:2018-05-20T08:17:15Z\n" + + "#EXTINF:2,\n" + + "segment1.ts\n" + + "#EXTINF:2,\n" + + "segment2.ts\n" + + "#EXTINF:2,\n" + + "segment3.ts\n" + + "#EXT-X-ENDLIST\n")) + + case r.Method == http.MethodGet && r.URL.Path == "/segment1.ts": + w.Header().Set("Content-Type", `video/MP2T`) + + mw := &mpegts.Writer{W: w, Tracks: []*mpegts.Track{track1}} + err := mw.Initialize() + require.NoError(t, err) + + switch ca { + case "h264": + err = mw.WriteH264(track1, 2*90000, 2*90000, [][]byte{ + {7, 1, 2, 3}, // SPS + {8}, // PPS + {5, 1}, + }) + case "klv": + err = mw.WriteKLV(track1, 2*90000, []byte{0x06, 0x0e, 0x2b, 0x34}) + } + require.NoError(t, err) + + case r.Method == http.MethodGet && r.URL.Path == "/segment2.ts": + w.Header().Set("Content-Type", `video/MP2T`) + + mw := &mpegts.Writer{W: w, Tracks: []*mpegts.Track{track1}} + err := mw.Initialize() + require.NoError(t, err) + + switch ca { + case "h264": + err = mw.WriteH264(track1, 2*90000, 2*90000, [][]byte{ + {5, 2}, + }) + case "klv": + err = mw.WriteKLV(track1, 2*90000, []byte{0x01, 0x02, 0x03, 0x04}) + } + require.NoError(t, err) + } + }), + } + + ln, err := net.Listen("tcp", "localhost:0") + require.NoError(t, err) + + go s.Serve(ln) + defer s.Shutdown(context.Background()) + + var strm *stream.Stream + var subStream *stream.SubStream + done := make(chan struct{}) + + r := &stream.Reader{Parent: test.NilLogger} + + var c *gohlslib.Client + c = &gohlslib.Client{ + URI: "http://" + ln.Addr().String() + "/stream.m3u8", + OnTracks: func(tracks []*gohlslib.Track) error { + medias, err2 := ToStream(c, tracks, &conf.Path{ + UseAbsoluteTimestamp: true, + }, &subStream) + require.NoError(t, err2) + + switch ca { + case "h264": + require.Equal(t, []*description.Media{{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + }}, + }}, medias) + case "klv": + require.Equal(t, []*description.Media{{ + Type: description.MediaTypeApplication, + Formats: []format.Format{&format.KLV{ + PayloadTyp: 96, + }}, + }}, medias) + } + + strm = &stream.Stream{ + OrigDesc: &description.Session{Medias: medias}, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err2 = strm.Initialize() + require.NoError(t, err2) + + subStream = &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err2 = subStream.Initialize() + require.NoError(t, err2) + + n := 0 + + r.OnData( + medias[0], + medias[0].Formats[0], + func(u *unit.Unit) error { + switch ca { + case "h264": + switch n { + case 0: + require.Equal(t, unit.PayloadH264{ + {7, 1, 2, 3}, + {8}, + {5, 1}, + }, u.Payload) + require.Equal(t, time.Date(2018, 0o5, 20, 8, 17, 15, 0, time.UTC), u.NTP) + case 1: + require.Equal(t, unit.PayloadH264{ + {7, 1, 2, 3}, + {8}, + {5, 2}, + }, u.Payload) + require.Equal(t, time.Date(2018, 0o5, 20, 8, 17, 15, 0, time.UTC), u.NTP) + close(done) + default: + t.Error("should not happen") + } + + case "klv": + switch n { + case 0: + require.Equal(t, unit.PayloadKLV{0x06, 0x0e, 0x2b, 0x34}, u.Payload) + require.Equal(t, time.Date(2018, 0o5, 20, 8, 17, 15, 0, time.UTC), u.NTP) + case 1: + require.Equal(t, unit.PayloadKLV{0x01, 0x02, 0x03, 0x04}, u.Payload) + require.Equal(t, time.Date(2018, 0o5, 20, 8, 17, 15, 0, time.UTC), u.NTP) + close(done) + default: + t.Error("should not happen") + } + } + n++ + return nil + }) + + strm.AddReader(r) + + return nil + }, + } + err = c.Start() + require.NoError(t, err) + defer c.Close() + + <-done + + strm.RemoveReader(r) + strm.Close() + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/content_type.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/content_type.go new file mode 100644 index 0000000000000000000000000000000000000000..3383240bed606cf5dd911eba7f70a9b66add8f4f --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/content_type.go @@ -0,0 +1,8 @@ +package httpp + +import "strings" + +// ParseContentType parses a Content-Type header and returns the content type. +func ParseContentType(v string) string { + return strings.TrimSpace(strings.Split(v, ";")[0]) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/credentials.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/credentials.go new file mode 100644 index 0000000000000000000000000000000000000000..65c0e273790b5b7dd6640f71fdc51be6e7143a0b --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/credentials.go @@ -0,0 +1,33 @@ +package httpp + +import ( + "net/http" + "strings" + + "github.com/bluenviron/mediamtx/internal/auth" +) + +// Credentials extracts credentials from a HTTP request. +func Credentials(h *http.Request) *auth.Credentials { + c := &auth.Credentials{} + + for _, auth := range h.Header["Authorization"] { + if strings.HasPrefix(auth, "Bearer ") { + // user:pass in Authorization Bearer + if parts := strings.Split(auth[len("Bearer "):], ":"); len(parts) == 2 { + c.User = parts[0] + c.Pass = parts[1] + return c + } + + // JWT in Authorization Bearer + c.Token = auth[len("Bearer "):] + return c + } + } + + // user:pass in Authorization Basic + c.User, c.Pass, _ = h.BasicAuth() + + return c +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/credentials_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/credentials_test.go new file mode 100644 index 0000000000000000000000000000000000000000..bce4c51064a4f553f59b2b86118848994ddca9fd --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/credentials_test.go @@ -0,0 +1,83 @@ +package httpp + +import ( + "net/http" + "net/url" + "testing" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/stretchr/testify/require" +) + +func TestCredentials(t *testing.T) { + t.Run("user and pass in basic", func(t *testing.T) { + h := &http.Request{ + URL: &url.URL{}, + Header: http.Header{ + "Authorization": []string{ + "Basic bXl1c2VyOm15cGFzcw==", + }, + }, + } + + c := Credentials(h) + + require.Equal(t, &auth.Credentials{ + User: "myuser", + Pass: "mypass", + }, c) + }) + + t.Run("user and pass in bearer", func(t *testing.T) { + h := &http.Request{ + URL: &url.URL{}, + Header: http.Header{ + "Authorization": []string{ + "Bearer myuser:mypass", + }, + }, + } + + c := Credentials(h) + + require.Equal(t, &auth.Credentials{ + User: "myuser", + Pass: "mypass", + }, c) + }) + + t.Run("token in bearer", func(t *testing.T) { + h := &http.Request{ + URL: &url.URL{}, + Header: http.Header{ + "Authorization": []string{ + "Bearer testing123", + }, + }, + } + + c := Credentials(h) + + require.Equal(t, &auth.Credentials{ + Token: "testing123", + }, c) + }) + + t.Run("user and pass and token", func(t *testing.T) { + h := &http.Request{ + URL: &url.URL{}, + Header: http.Header{ + "Authorization": []string{ + "Basic bXl1c2VyOm15cGFzcw==", + "Bearer testing123", + }, + }, + } + + c := Credentials(h) + + require.Equal(t, &auth.Credentials{ + Token: "testing123", + }, c) + }) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_exit_on_panic.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_exit_on_panic.go new file mode 100644 index 0000000000000000000000000000000000000000..d8d98c237c492f6ef6837045102cf37d96fc425b --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_exit_on_panic.go @@ -0,0 +1,27 @@ +package httpp + +import ( + "fmt" + "net/http" + "os" + "runtime" +) + +// exit when there's a panic inside the HTTP handler. +// https://github.com/golang/go/issues/16542 +type handlerExitOnPanic struct { + h http.Handler +} + +func (h *handlerExitOnPanic) ServeHTTP(w http.ResponseWriter, r *http.Request) { + defer func() { + err := recover() + if err != nil { + buf := make([]byte, 1<<20) + n := runtime.Stack(buf, true) + fmt.Fprintf(os.Stderr, "panic: %v\n\n%s", err, buf[:n]) + os.Exit(1) + } + }() + h.h.ServeHTTP(w, r) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_filter_requests.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_filter_requests.go new file mode 100644 index 0000000000000000000000000000000000000000..b038d34b61f5382c9848f7619162d120d132df71 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_filter_requests.go @@ -0,0 +1,18 @@ +package httpp + +import ( + "net/http" +) + +// reject requests with empty paths. +type handlerFilterRequests struct { + h http.Handler +} + +func (h *handlerFilterRequests) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "" || r.URL.Path[0] != '/' { + w.WriteHeader(http.StatusBadRequest) + return + } + h.h.ServeHTTP(w, r) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_filter_requests_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_filter_requests_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f85e24f71ca29bc66059552f1c4ad38f091b1b43 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_filter_requests_test.go @@ -0,0 +1,42 @@ +package httpp + +import ( + "net" + "net/http" + "strings" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestHandlerFilterRequests(t *testing.T) { + s := &Server{ + Address: "localhost:4555", + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + Parent: test.NilLogger, + Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }), + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + conn, err := net.Dial("tcp", "localhost:4555") + require.NoError(t, err) + defer conn.Close() + + _, err = conn.Write([]byte("OPTIONS / HTTP/1.1\n" + + "Host: localhost:8889\n\n")) + require.NoError(t, err) + + buf := make([]byte, 200) + n, err := conn.Read(buf) + require.NoError(t, err) + + res := strings.Split(string(buf[:n]), "\r\n") + require.Equal(t, "HTTP/1.1 200 OK", res[0]) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_logger.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_logger.go new file mode 100644 index 0000000000000000000000000000000000000000..f8477566989cee64653d9629874ea0ec0ab70262 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_logger.go @@ -0,0 +1,101 @@ +package httpp + +import ( + "bytes" + "fmt" + "io" + "net/http" + "net/http/httputil" + + "github.com/bluenviron/mediamtx/internal/logger" +) + +const ( + maxDumpedRequestBodySize = 10 * 1024 +) + +func dumpRequestLimited(r *http.Request) ([]byte, error) { + peek, err := io.ReadAll(io.LimitReader(r.Body, maxDumpedRequestBodySize+1)) + if err != nil { + return nil, err + } + + capped := peek + if int64(len(capped)) > maxDumpedRequestBodySize { + capped = append([]byte(nil), capped[:maxDumpedRequestBodySize]...) + capped = append(capped, []byte("\n\n(body truncated)\n")...) + } + + original := r.Body + r.Body = io.NopCloser(bytes.NewReader(capped)) + + dump, dumpErr := httputil.DumpRequest(r, true) + + r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(peek), original)) + + return dump, dumpErr +} + +type responseRecorder struct { + w http.ResponseWriter + status int + body []byte + size int +} + +func (w *responseRecorder) Header() http.Header { + return w.w.Header() +} + +func (w *responseRecorder) Write(b []byte) (int, error) { + if w.status == 0 { + w.status = http.StatusOK + } + + contentType := w.Header().Get("Content-Type") + if contentType == "application/sdp" || contentType == "application/trickle-ice-sdpfrag" { + w.body = append(w.body, b...) + } else { + w.size += len(b) + } + + return w.w.Write(b) +} + +func (w *responseRecorder) WriteHeader(statusCode int) { + w.status = statusCode + w.w.WriteHeader(statusCode) +} + +func (w *responseRecorder) dump() string { + var buf bytes.Buffer + fmt.Fprintf(&buf, "%s %d %s\n", "HTTP/1.1", w.status, http.StatusText(w.status)) + w.w.Header().Write(&buf) //nolint:errcheck + buf.Write([]byte("\n")) + + if w.body != nil { + buf.Write(w.body) + } else if w.size > 0 { + fmt.Fprintf(&buf, "(body of %d bytes)", w.size) + } + + return buf.String() +} + +// log requests and responses. +type handlerLogger struct { + h http.Handler + log logger.Writer +} + +func (h *handlerLogger) ServeHTTP(w http.ResponseWriter, r *http.Request) { + byts, _ := dumpRequestLimited(r) + + h.log.Log(logger.Debug, "[conn %v] [c->s] %s", r.RemoteAddr, string(byts)) + + resRecorder := &responseRecorder{w: w} + + h.h.ServeHTTP(resRecorder, r) + + h.log.Log(logger.Debug, "[conn %v] [s->c] %s", r.RemoteAddr, resRecorder.dump()) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_origin.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_origin.go new file mode 100644 index 0000000000000000000000000000000000000000..3aab9466fe106fbe1b89e6d1af8f68c3eedb0b09 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_origin.go @@ -0,0 +1,91 @@ +package httpp + +import ( + "net" + "net/http" + "net/url" + "regexp" + "strings" +) + +func isOriginAllowed(origin string, allowOrigins []string) (string, bool) { + if len(allowOrigins) == 0 { + return "", false + } + + for _, o := range allowOrigins { + if o == "*" { + if origin != "" { + return origin, true + } + return "*", true + } + } + + if origin == "" { + return "", false + } + + originURL, err := url.Parse(origin) + if err != nil || originURL.Scheme == "" { + return "", false + } + + if originURL.Port() == "" && originURL.Scheme != "" { + switch originURL.Scheme { + case "http": + originURL.Host = net.JoinHostPort(originURL.Host, "80") + case "https": + originURL.Host = net.JoinHostPort(originURL.Host, "443") + } + } + + for _, o := range allowOrigins { + allowedURL, errAllowed := url.Parse(o) + if errAllowed != nil { + continue + } + + if allowedURL.Port() == "" { + switch allowedURL.Scheme { + case "http": + allowedURL.Host = net.JoinHostPort(allowedURL.Host, "80") + case "https": + allowedURL.Host = net.JoinHostPort(allowedURL.Host, "443") + } + } + + if allowedURL.Scheme == originURL.Scheme && + allowedURL.Host == originURL.Host && + allowedURL.Port() == originURL.Port() { + return origin, true + } + + if strings.Contains(allowedURL.Host, "*") { + pattern := strings.ReplaceAll(allowedURL.Host, "*.", "(.*\\.)?") + pattern = strings.ReplaceAll(pattern, "*", ".*") + matched, errMatched := regexp.MatchString("^"+pattern+"$", originURL.Host) + if errMatched == nil && matched { + return origin, true + } + } + } + + return "", false +} + +// add Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers. +type handlerOrigin struct { + h http.Handler + allowOrigins []string +} + +func (h *handlerOrigin) ServeHTTP(w http.ResponseWriter, r *http.Request) { + origin, ok := isOriginAllowed(r.Header.Get("Origin"), h.allowOrigins) + if ok { + w.Header().Set("Access-Control-Allow-Origin", origin) + w.Header().Set("Access-Control-Allow-Credentials", "true") + } + + h.h.ServeHTTP(w, r) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_origin_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_origin_test.go new file mode 100644 index 0000000000000000000000000000000000000000..1d9ff719f4734c8133638e2f27b73e9201e6df14 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_origin_test.go @@ -0,0 +1,87 @@ +package httpp + +import ( + "net/http" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestHandlerOrigin(t *testing.T) { + for _, ca := range []struct { + name string + origin string + allowedOrigins []string + expected string + }{ + { + "empty", + "", + []string{}, + "", + }, + { + "not allowed", + "http://another.com", + []string{"http://example.com"}, + "", + }, + { + "everything allowed, no origin", + "", + []string{"*"}, + "*", + }, + { + "everything allowed, with origin", + "https://example.com", + []string{"*"}, + "https://example.com", + }, + { + "allowed", + "https://example.org", + []string{"http://example.com", "https://example.org"}, + "https://example.org", + }, + { + "wildcard", + "https://test.example.org", + []string{"https://*.example.org"}, + "https://test.example.org", + }, + } { + t.Run(ca.name, func(t *testing.T) { + s := &Server{ + Address: "localhost:4555", + AllowOrigins: ca.allowedOrigins, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + Parent: test.NilLogger, + Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }), + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + req, err := http.NewRequest(http.MethodGet, "http://localhost:4555", nil) + require.NoError(t, err) + + req.Header.Set("Origin", ca.origin) + + res, err := hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, ca.expected, res.Header.Get("Access-Control-Allow-Origin")) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_server_header.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_server_header.go new file mode 100644 index 0000000000000000000000000000000000000000..1707d7b19e04d7feece2aa291df5a8824cea9ba6 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_server_header.go @@ -0,0 +1,15 @@ +package httpp + +import ( + "net/http" +) + +// set the Server header. +type handlerServerHeader struct { + h http.Handler +} + +func (h *handlerServerHeader) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Server", "mediamtx") + h.h.ServeHTTP(w, r) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_tracker.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_tracker.go new file mode 100644 index 0000000000000000000000000000000000000000..7915c4ea3b0a9188cb2dc4da2ec5bb4db8e0b564 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_tracker.go @@ -0,0 +1,36 @@ +package httpp + +import ( + "net/http" + "sync" +) + +type handlerTracker struct { + h http.Handler + + mutex sync.Mutex + wg sync.WaitGroup + closed bool +} + +func (h *handlerTracker) close() { + h.mutex.Lock() + h.closed = true + h.mutex.Unlock() + h.wg.Wait() +} + +func (h *handlerTracker) ServeHTTP(w http.ResponseWriter, r *http.Request) { + h.mutex.Lock() + if h.closed { + h.mutex.Unlock() + return + } + + h.wg.Add(1) + h.mutex.Unlock() + + defer h.wg.Done() + + h.h.ServeHTTP(w, r) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_tracker_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_tracker_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7da9f1db8e2defe31e534d0e13cc68aedc34019d --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_tracker_test.go @@ -0,0 +1,44 @@ +package httpp + +import ( + "net/http" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestHandlerTracker(t *testing.T) { + requestReceived := make(chan struct{}) + + s := &Server{ + Address: "localhost:4667", + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + Parent: test.NilLogger, + Handler: http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { + close(requestReceived) + time.Sleep(1 * time.Second) + }), + } + err := s.Initialize() + require.NoError(t, err) + + go func() { + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + _, err2 := hc.Get("http://localhost:4667/test") //nolint:bodyclose + require.Error(t, err2) + }() + + <-requestReceived + + beforeClose := time.Now() + + s.Close() + + require.Greater(t, time.Since(beforeClose), 1*time.Second) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_write_timeout.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_write_timeout.go new file mode 100644 index 0000000000000000000000000000000000000000..aaf00dd0ce79eca3eafb81a54ee9bd8daa70c61d --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/handler_write_timeout.go @@ -0,0 +1,44 @@ +package httpp + +import ( + "net/http" + "time" +) + +type writeTimeoutWriter struct { + w http.ResponseWriter + rc *http.ResponseController + timeout time.Duration +} + +func (w *writeTimeoutWriter) Header() http.Header { + return w.w.Header() +} + +func (w *writeTimeoutWriter) Write(p []byte) (int, error) { + w.rc.SetWriteDeadline(time.Now().Add(w.timeout)) //nolint:errcheck + return w.w.Write(p) +} + +func (w *writeTimeoutWriter) WriteHeader(statusCode int) { + w.rc.SetWriteDeadline(time.Now().Add(w.timeout)) //nolint:errcheck + w.w.WriteHeader(statusCode) +} + +// apply write deadline before every Write() call. +// this allows to write long responses, splitted in chunks, +// without causing timeouts. +type handlerWriteTimeout struct { + h http.Handler + timeout time.Duration +} + +func (h *handlerWriteTimeout) ServeHTTP(w http.ResponseWriter, r *http.Request) { + ww := &writeTimeoutWriter{ + w: w, + rc: http.NewResponseController(w), + timeout: h.timeout, + } + + h.h.ServeHTTP(ww, r) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/remote_addr.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/remote_addr.go new file mode 100644 index 0000000000000000000000000000000000000000..7e86db242b6aeeb74de6267d9e66f99121dd89a7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/remote_addr.go @@ -0,0 +1,15 @@ +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) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/server.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a759662dc0b1088a76a71e4eb6eb452b2abcb643 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/server.go @@ -0,0 +1,205 @@ +// Package httpp contains HTTP utilities. +package httpp + +import ( + "crypto/tls" + "fmt" + "log" + "net" + "net/http" + "os" + "strings" + "time" + + "github.com/bluenviron/mediamtx/internal/certloader" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/packetdumper" + "github.com/bluenviron/mediamtx/internal/restrictnetwork" + "golang.org/x/net/http2" +) + +type nilWriter struct{} + +func (nilWriter) Write(p []byte) (int, error) { + return len(p), nil +} + +// Server is a wrapper around http.Server that provides: +// - net.Listener creation and destruction +// - TLS initialization and hot reload +// - exit on panic +// - logging +// - server header +// - filtering of invalid requests +type Server struct { + Address string + AllowOrigins []string + DumpPackets bool + DumpPacketsPrefix string + ReadTimeout time.Duration + WriteTimeout time.Duration + Encryption bool + ServerCert string + ServerKey string + AllowAutoCert bool + Handler http.Handler + Parent logger.Writer + + ln net.Listener + inner *http.Server + loader *certloader.CertLoader + tracker *handlerTracker +} + +// Initialize initializes a Server. +func (s *Server) Initialize() error { + if s.ReadTimeout == 0 { + return fmt.Errorf("invalid ReadTimeout") + } + if s.WriteTimeout == 0 { + return fmt.Errorf("invalid WriteTimeout") + } + + var tlsConfig *tls.Config + + if s.Encryption { + if s.ServerCert == "" { + return fmt.Errorf("server cert is missing") + } + + s.loader = &certloader.CertLoader{ + CertPath: s.ServerCert, + KeyPath: s.ServerKey, + AllowAuto: s.AllowAutoCert, + Parent: s.Parent, + } + err := s.loader.Initialize() + if err != nil { + return err + } + + tlsConfig = &tls.Config{ + GetCertificate: s.loader.GetCertificate(), + } + } + + var network string + var address string + + if strings.HasPrefix(s.Address, "unix://") { + network = "unix" + address = s.Address[len("unix://"):] + } else { + network, address = restrictnetwork.Restrict("tcp", s.Address) + } + + if network == "unix" { + os.Remove(address) + } + + h := s.Handler + h = &handlerOrigin{h, s.AllowOrigins} + h = &handlerServerHeader{h} + h = &handlerFilterRequests{h} + h = &handlerLogger{h, s.Parent} + h = &handlerExitOnPanic{h} + h = &handlerWriteTimeout{h, s.WriteTimeout} + s.tracker = &handlerTracker{h: h} + h = s.tracker + + s.inner = &http.Server{ + Handler: h, + TLSConfig: tlsConfig, + + // applied before reading any request + ReadTimeout: s.ReadTimeout, + + // applied after HTTP handler has returned + IdleTimeout: 30 * time.Second, + + ErrorLog: log.New(&nilWriter{}, "", 0), + } + + if tlsConfig != nil { + err := http2.ConfigureServer(s.inner, &http2.Server{}) + if err != nil { + if s.loader != nil { + s.loader.Close() + } + return err + } + } + + listen := func(network string, address string) (net.Listener, error) { + ln, err := net.Listen(network, address) + if err != nil { + return nil, err + } + + if s.DumpPackets { + ln = &packetdumper.Listener{ + Wrapped: ln, + Prefix: s.DumpPacketsPrefix, + } + } + + return ln, nil + } + + tlsListen := func(network string, laddr string, config *tls.Config) (net.Listener, error) { + ln, err := listen(network, laddr) + if err != nil { + return nil, err + } + + if s.DumpPackets { + ln = &packetdumper.TLSListener{ + Wrapped: ln, + TLSConfig: config, + } + } else { + ln = tls.NewListener(ln, config) + } + + return ln, nil + } + + if tlsConfig != nil { + var err error + s.ln, err = tlsListen(network, address, tlsConfig) + if err != nil { + if s.loader != nil { + s.loader.Close() + } + return err + } + } else { + var err error + s.ln, err = listen(network, address) + if err != nil { + if s.loader != nil { + s.loader.Close() + } + return err + } + } + + if network == "unix" { + os.Chmod(address, 0o755) //nolint:errcheck + } + + go s.inner.Serve(s.ln) + + return nil +} + +// Close closes all resources and waits for all routines to return. +func (s *Server) Close() { + s.ln.Close() + s.inner.Close() //nolint:errcheck + s.tracker.close() + + if s.loader != nil { + s.loader.Close() + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/server_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f83b8c56b0aea9b2acee5bcfa12011657f687319 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp/server_test.go @@ -0,0 +1,52 @@ +package httpp + +import ( + "net" + "net/http" + "os" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/bluenviron/mediamtx/internal/test" +) + +func TestUnixSocket(t *testing.T) { + s := &Server{ + Address: "unix://http.sock", + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + Parent: test.NilLogger, + Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }), + } + err := s.Initialize() + require.NoError(t, err) + + info, err := os.Stat("http.sock") + require.NoError(t, err) + require.Equal(t, os.FileMode(0o755), info.Mode().Perm()) + + conn, err := net.Dial("unix", "http.sock") + require.NoError(t, err) + + _, err = conn.Write([]byte("OPTIONS / HTTP/1.1\n" + + "Host: localhost:8889\n\n")) + require.NoError(t, err) + + buf := make([]byte, 200) + n, err := conn.Read(buf) + require.NoError(t, err) + + res := strings.Split(string(buf[:n]), "\r\n") + require.Equal(t, "HTTP/1.1 200 OK", res[0]) + + conn.Close() + s.Close() + + _, err = os.Stat("http.sock") + require.EqualError(t, err, "stat http.sock: no such file or directory") +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp3/server.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp3/server.go new file mode 100644 index 0000000000000000000000000000000000000000..ad35088c561b7d62c5275a29025c726b72ca0f11 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp3/server.go @@ -0,0 +1,197 @@ +// Package httpp3 contains HTTP/3 utilities. +package httpp3 + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "fmt" + "math/big" + "net" + "net/http" + "os" + "sync" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/readbuffer" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/quic-go/quic-go/http3" + "github.com/quic-go/webtransport-go" +) + +const ( + // WebTransport requires certificates valid for at most 14 days. + certValidity = 14 * 24 * time.Hour + certRotation = 13 * 24 * time.Hour +) + +func generateWebTransportCert() (*tls.Certificate, error) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, fmt.Errorf("generate key: %w", err) + } + + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) + if err != nil { + return nil, fmt.Errorf("generate serial: %w", err) + } + + now := time.Now() + template := x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{CommonName: "mediamtx"}, + NotBefore: now, + NotAfter: now.Add(certValidity), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + } + + certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) + if err != nil { + return nil, fmt.Errorf("create certificate: %w", err) + } + + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + return nil, fmt.Errorf("marshal key: %w", err) + } + + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}) + + cert, err := tls.X509KeyPair(certPEM, keyPEM) + if err != nil { + return nil, fmt.Errorf("parse certificate: %w", err) + } + + return &cert, nil +} + +// Server is a wrapper around http3.Server that provides: +// - net.PacketConn creation and destruction +// - JIT TLS certificate generation and rotation (WebTransport-compatible: ECDSA P-256, 14-day validity) +type Server struct { + Address string + UDPReadBufferSize uint + EnableWebTransport bool + Handler http.Handler + Parent logger.Writer + + ln net.PacketConn + inner *http3.Server + wtServer *webtransport.Server + cert *tls.Certificate + certMu sync.RWMutex + terminate chan struct{} +} + +// Initialize initializes a Server. +func (s *Server) Initialize() error { + os.Setenv("QUIC_GO_DISABLE_RECEIVE_BUFFER_WARNING", "true") //nolint:errcheck + + s.terminate = make(chan struct{}) + + var err error + s.ln, err = net.ListenPacket("udp", s.Address) + if err != nil { + return err + } + + if s.UDPReadBufferSize != 0 { + err = readbuffer.SetReadBuffer(s.ln.(*net.UDPConn), int(s.UDPReadBufferSize)) + if err != nil { + s.ln.Close() + return err + } + } + + cert, err := generateWebTransportCert() + if err != nil { + return err + } + s.cert = cert + + tlsConfig := &tls.Config{ + GetCertificate: func(_ *tls.ClientHelloInfo) (*tls.Certificate, error) { + s.certMu.RLock() + defer s.certMu.RUnlock() + return s.cert, nil + }, + } + + s.inner = &http3.Server{ + Handler: s.Handler, + TLSConfig: tlsConfig, + } + + if s.EnableWebTransport { + // webtransport.Server.Serve calls quic.ListenEarly directly with s.H3.TLSConfig, + // bypassing the http3.ConfigureTLSConfig call that http3.Server.Serve does internally. + // Pre-configure to set NextProtos = ["h3"] so QUIC ALPN negotiation succeeds. + s.inner.TLSConfig = http3.ConfigureTLSConfig(tlsConfig) + webtransport.ConfigureHTTP3Server(s.inner) + s.wtServer = &webtransport.Server{ + H3: s.inner, + CheckOrigin: func(_ *http.Request) bool { return true }, + } + go s.wtServer.Serve(s.ln) //nolint:errcheck + } else { + go s.inner.Serve(s.ln) //nolint:errcheck + } + + go s.rotateCert() + + return nil +} + +func (s *Server) rotateCert() { + t := time.NewTimer(certRotation) + defer t.Stop() + + for { + select { + case <-t.C: + cert, err := generateWebTransportCert() + if err != nil { + s.Parent.Log(logger.Error, "failed to rotate WebTransport certificate: %v", err) + } else { + s.certMu.Lock() + s.cert = cert + s.certMu.Unlock() + s.Parent.Log(logger.Info, "WebTransport certificate rotated") + } + t.Reset(certRotation) + + case <-s.terminate: + return + } + } +} + +// Close closes all resources and waits for all routines to return. +func (s *Server) Close() { + close(s.terminate) + s.ln.Close() + if s.wtServer != nil { + s.wtServer.Close() //nolint:errcheck + } else { + s.inner.Close() //nolint:errcheck + } +} + +// Certificate returns the current TLS certificate. +func (s *Server) Certificate() *tls.Certificate { + s.certMu.RLock() + defer s.certMu.RUnlock() + return s.cert +} + +// Upgrade upgrades an HTTP/3 request to a WebTransport session. +// Only valid when EnableWebTransport is true. +func (s *Server) Upgrade(w http.ResponseWriter, r *http.Request) (*webtransport.Session, error) { + return s.wtServer.Upgrade(w, r) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp3/server_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp3/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..96c6747e7f2ffe82c805a864b35fcb1e9ac69a59 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/httpp3/server_test.go @@ -0,0 +1,43 @@ +package httpp3 + +import ( + "crypto/tls" + "io" + "net/http" + "testing" + + "github.com/bluenviron/mediamtx/internal/test" + "github.com/quic-go/quic-go/http3" + "github.com/stretchr/testify/require" +) + +func TestServer(t *testing.T) { + // test that Server can be initialized and reached by a simple GET request + s := &Server{ + Address: "127.0.0.1:18443", + Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }), + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + tr := &http3.Transport{ + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: true, //nolint:gosec + }, + } + defer tr.Close() //nolint:errcheck + hc := &http.Client{Transport: tr} + + res, err := hc.Get("https://127.0.0.1:18443/") + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusOK, res.StatusCode) + + _, err = io.ReadAll(res.Body) + require.NoError(t, err) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/catalog/catalog.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/catalog/catalog.go new file mode 100644 index 0000000000000000000000000000000000000000..6749ea5e5757916e2d71054b928cc84696479c83 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/catalog/catalog.go @@ -0,0 +1,26 @@ +// Package catalog contains a media catalog. +package catalog + +// Catalog is a media catalog. +// spec: draft-ietf-moq-msf-00 +type Catalog struct { + Version int `json:"version"` + Tracks []Track `json:"tracks"` +} + +// Track is a track in a media catalog. +type Track struct { + Name string `json:"name"` + Packaging string `json:"packaging"` + IsLive bool `json:"isLive"` + Namespace string `json:"namespace,omitempty"` + Codec string `json:"codec,omitempty"` + Bitrate int `json:"bitrate,omitempty"` + Width int `json:"width,omitempty"` + Height int `json:"height,omitempty"` + Framerate float64 `json:"framerate,omitempty"` + Samplerate int `json:"samplerate,omitempty"` + Channels int `json:"channels,omitempty"` + ClockRate int `json:"clockrate,omitempty"` + InitData string `json:"initData,omitempty"` +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/message.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/message.go new file mode 100644 index 0000000000000000000000000000000000000000..5f81d3197f410113a73b3f1adcb9618e691e246c --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/message.go @@ -0,0 +1,65 @@ +// Package controlmessage contains MoQ control messages. +package controlmessage + +import ( + "fmt" + "io" + + "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" +) + +// Message is a control message. +type Message interface { + // Marshal encodes the message to bytes. + Marshal() []byte + + isMessage() + unmarshal(buf []byte) error +} + +// Read reads a Message from a Reader. +func Read(r io.Reader) (Message, error) { + var t varint.Varint + if err := t.Read(r); err != nil { + return nil, err + } + + var lenBuf [2]byte + _, err := io.ReadFull(r, lenBuf[:]) + if err != nil { + return nil, err + } + length := uint16(lenBuf[0])<<8 | uint16(lenBuf[1]) + + payload := make([]byte, length) + _, err = io.ReadFull(r, payload) + if err != nil { + return nil, err + } + + var m Message + + switch t { + case typeSetup: + m = &Setup{} + case typeSubscribe: + m = &Subscribe{} + case typeSubscribeOk: + m = &SubscribeOk{} + case typeRequestError: + m = &RequestError{} + case typePublish: + m = &Publish{} + case typeRequestOk: + m = &RequestOk{} + default: + return nil, fmt.Errorf("unknown message type: 0x%x", t) + } + + err = m.unmarshal(payload) + if err != nil { + return nil, err + } + + return m, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/message_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/message_test.go new file mode 100644 index 0000000000000000000000000000000000000000..76bdb593d9298998b58d5a6725f5b3e4febe6668 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/message_test.go @@ -0,0 +1,174 @@ +package controlmessage + +import ( + "bytes" + "testing" + + "github.com/bluenviron/mediamtx/internal/protocols/moq/parameter" + "github.com/stretchr/testify/require" +) + +var cases = []struct { + name string + enc []byte + dec Message +}{ + { + name: "setup", + enc: []byte{ + 0xAF, 0x00, // type 0x2F00 (2-byte varint) + 0x00, 0x00, // length = 0 + }, + dec: &Setup{}, + }, + { + name: "subscribe", + enc: []byte{ + 0x03, // type 0x03 + 0x00, 0x0B, // length = 11 + 0x01, // RequestID = 1 + 0x01, // namespace count = 1 + 0x03, 0x66, 0x6F, 0x6F, // namespace[0] = "foo" + 0x03, 0x62, 0x61, 0x72, // track name = "bar" + 0x00, // parameters count = 0 + }, + dec: &Subscribe{ + RequestID: 1, + Namespace: []string{"foo"}, + TrackName: "bar", + }, + }, + { + name: "subscribe with params", + enc: []byte{ + 0x03, // type 0x03 + 0x00, 0x15, // length = 21 + 0x01, // RequestID = 1 + 0x01, // namespace count = 1 + 0x03, 0x66, 0x6F, 0x6F, // namespace[0] = "foo" + 0x03, 0x62, 0x61, 0x72, // track name = "bar" + 0x01, // parameters count = 1 + 0x03, // type delta = 3 (AuthorizationToken) + 0x08, // inner length = 8 + 0x03, // alias type = UseValue + 0x01, // token type = 1 + 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, // token value = "secret" + }, + dec: &Subscribe{ + RequestID: 1, + Namespace: []string{"foo"}, + TrackName: "bar", + Parameters: []parameter.Parameter{ + ¶meter.AuthorizationToken{ + AliasType: parameter.AuthorizationTokenAliasTypeUseValue, + TokenType: 1, + TokenValue: []byte("secret"), + }, + }, + }, + }, + { + name: "subscribe_ok", + enc: []byte{ + 0x04, // type 0x04 + 0x00, 0x02, // length = 2 + 0x01, // TrackAlias = 1 + 0x00, // Number of Parameters = 0 + }, + dec: &SubscribeOk{ + TrackAlias: 1, + }, + }, + { + name: "request_error", + enc: []byte{ + 0x05, // type 0x05 + 0x00, 0x06, // length = 6 + 0x01, // Code = 1 + 0x00, // retryInterval = 0 (ignored) + 0x03, 0x66, 0x6F, 0x6F, // Reason = "foo" + }, + dec: &RequestError{ + Code: 1, + Reason: "foo", + }, + }, + { + name: "request_ok", + enc: []byte{ + 0x07, // type 0x07 + 0x00, 0x01, // length = 1 + 0x00, // Number of Parameters = 0 + }, + dec: &RequestOk{}, + }, + { + name: "publish", + enc: []byte{ + 0x1D, // type 0x1D + 0x00, 0x0C, // length = 12 + 0x01, // RequestID = 1 + 0x01, // namespace count = 1 + 0x03, 0x66, 0x6F, 0x6F, // namespace[0] = "foo" + 0x03, 0x62, 0x61, 0x72, // track name = "bar" + 0x02, // TrackAlias = 2 + 0x00, // parameters count = 0 + }, + dec: &Publish{ + RequestID: 1, + Namespace: []string{"foo"}, + TrackName: "bar", + TrackAlias: 2, + }, + }, + { + name: "publish with parameters", + enc: []byte{ + 0x1D, // type 0x1D + 0x00, 0x16, // length = 22 + 0x01, // RequestID = 1 + 0x01, // namespace count = 1 + 0x03, 0x66, 0x6F, 0x6F, // namespace[0] = "foo" + 0x03, 0x62, 0x61, 0x72, // track name = "bar" + 0x02, // TrackAlias = 2 + 0x01, // parameters count = 1 + 0x03, // type delta = 3 (AuthorizationToken) + 0x08, // inner length = 8 + 0x03, // alias type = UseValue + 0x01, // token type = 1 + 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, // token value = "secret" + }, + dec: &Publish{ + RequestID: 1, + Namespace: []string{"foo"}, + TrackName: "bar", + TrackAlias: 2, + Parameters: []parameter.Parameter{ + ¶meter.AuthorizationToken{ + AliasType: parameter.AuthorizationTokenAliasTypeUseValue, + TokenType: 1, + TokenValue: []byte("secret"), + }, + }, + }, + }, +} + +func TestUnmarshal(t *testing.T) { + for _, ca := range cases { + t.Run(ca.name, func(t *testing.T) { + m, err := Read(bytes.NewReader(ca.enc)) + require.NoError(t, err) + require.Equal(t, ca.dec, m) + }) + } +} + +func TestMarshal(t *testing.T) { + for _, ca := range cases { + t.Run(ca.name, func(t *testing.T) { + buf := ca.dec.Marshal() + require.Equal(t, ca.enc, buf) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/publish.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/publish.go new file mode 100644 index 0000000000000000000000000000000000000000..e1e754952bb39edd27e639a9242f2bc664f8acdc --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/publish.go @@ -0,0 +1,145 @@ +package controlmessage + +import ( + "fmt" + + "github.com/bluenviron/mediamtx/internal/protocols/moq/parameter" + "github.com/bluenviron/mediamtx/internal/protocols/moq/property" + "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" +) + +const typePublish varint.Varint = 0x1d + +// Publish is the PUBLISH control message. +// spec: draft-18, section 10.10 +type Publish struct { + RequestID uint64 + Namespace []string + TrackName string + TrackAlias uint64 + Parameters parameter.Parameters + TrackProperties property.Properties +} + +func (*Publish) isMessage() {} + +func (m *Publish) unmarshal(buf []byte) error { + var requestID varint.Varint + n, err := requestID.Unmarshal(buf) + if err != nil { + return err + } + m.RequestID = uint64(requestID) + buf = buf[n:] + + var nsCount varint.Varint + n, err = nsCount.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + + m.Namespace = make([]string, nsCount) + for i := range m.Namespace { + var l varint.Varint + n, err = l.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + if len(buf) < int(l) { + return fmt.Errorf("not enough bytes for namespace part") + } + m.Namespace[i] = string(buf[:l]) + buf = buf[int(l):] + } + + var tnLen varint.Varint + n, err = tnLen.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + if len(buf) < int(tnLen) { + return fmt.Errorf("not enough bytes for track name") + } + m.TrackName = string(buf[:tnLen]) + buf = buf[int(tnLen):] + + var trackAlias varint.Varint + n, err = trackAlias.Unmarshal(buf) + if err != nil { + return err + } + m.TrackAlias = uint64(trackAlias) + buf = buf[n:] + + var paramCount varint.Varint + n, err = paramCount.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + + consumed, err := m.Parameters.Unmarshal(int(paramCount), buf) + if err != nil { + return err + } + buf = buf[consumed:] + + return m.TrackProperties.Unmarshal(buf) +} + +func (m Publish) marshalSize() int { + n := varint.Varint(m.RequestID).MarshalSize() + + varint.Varint(len(m.Namespace)).MarshalSize() + for _, part := range m.Namespace { + n += varint.Varint(len(part)).MarshalSize() + len(part) + } + n += varint.Varint(len(m.TrackName)).MarshalSize() + len(m.TrackName) + n += varint.Varint(m.TrackAlias).MarshalSize() + n += varint.Varint(len(m.Parameters)).MarshalSize() + n += m.Parameters.MarshalSize() + n += m.TrackProperties.MarshalSize() + + return typePublish.MarshalSize() + 2 + n +} + +func (m Publish) marshalTo(buf []byte) int { + payloadSize := varint.Varint(m.RequestID).MarshalSize() + + varint.Varint(len(m.Namespace)).MarshalSize() + for _, part := range m.Namespace { + payloadSize += varint.Varint(len(part)).MarshalSize() + len(part) + } + payloadSize += varint.Varint(len(m.TrackName)).MarshalSize() + len(m.TrackName) + payloadSize += varint.Varint(m.TrackAlias).MarshalSize() + payloadSize += varint.Varint(len(m.Parameters)).MarshalSize() + payloadSize += m.Parameters.MarshalSize() + payloadSize += m.TrackProperties.MarshalSize() + + n := typePublish.MarshalTo(buf) + buf[n] = byte(payloadSize >> 8) + buf[n+1] = byte(payloadSize) + n += 2 + n += varint.Varint(m.RequestID).MarshalTo(buf[n:]) + n += varint.Varint(len(m.Namespace)).MarshalTo(buf[n:]) + for _, part := range m.Namespace { + n += varint.Varint(len(part)).MarshalTo(buf[n:]) + n += copy(buf[n:], part) + } + n += varint.Varint(len(m.TrackName)).MarshalTo(buf[n:]) + n += copy(buf[n:], m.TrackName) + n += varint.Varint(m.TrackAlias).MarshalTo(buf[n:]) + n += varint.Varint(len(m.Parameters)).MarshalTo(buf[n:]) + n += m.Parameters.MarshalTo(buf[n:]) + n += m.TrackProperties.MarshalTo(buf[n:]) + + return n +} + +// Marshal implements Message. +func (m Publish) Marshal() []byte { + buf := make([]byte, m.marshalSize()) + m.marshalTo(buf) + return buf +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/request_error.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/request_error.go new file mode 100644 index 0000000000000000000000000000000000000000..5b6a09ecfc9a99d66257eee025f3de0d7bd06240 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/request_error.go @@ -0,0 +1,87 @@ +package controlmessage + +import ( + "fmt" + + "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" +) + +const typeRequestError varint.Varint = 0x05 + +// RequestErrorCode is a code of REQUEST_ERROR. +type RequestErrorCode uint64 + +// spec: draft-18, section 15.10.2 +const ( + RequestErrorCodeUnauthorized RequestErrorCode = 0x01 + RequestErrorCodeNotSupported RequestErrorCode = 0x03 + RequestErrorCodeDoesNotExist RequestErrorCode = 0x10 + RequestErrorCodeUninterested RequestErrorCode = 0x20 +) + +// RequestError is the REQUEST_ERROR control message. +// spec: draft-18, section 10.6.2 +type RequestError struct { + Code RequestErrorCode + Reason string +} + +func (*RequestError) isMessage() {} + +func (m *RequestError) unmarshal(buf []byte) error { + var code varint.Varint + n, err := code.Unmarshal(buf) + if err != nil { + return err + } + m.Code = RequestErrorCode(code) + buf = buf[n:] + + var retry varint.Varint + n, err = retry.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + + var l varint.Varint + n, err = l.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + if len(buf) < int(l) { + return fmt.Errorf("not enough bytes") + } + m.Reason = string(buf[:l]) + + return nil +} + +func (m RequestError) marshalSize() int { + payloadSize := varint.Varint(m.Code).MarshalSize() + 1 + + varint.Varint(len(m.Reason)).MarshalSize() + len(m.Reason) + return typeRequestError.MarshalSize() + 2 + payloadSize +} + +func (m RequestError) marshalTo(buf []byte) int { + payloadSize := varint.Varint(m.Code).MarshalSize() + 1 + + varint.Varint(len(m.Reason)).MarshalSize() + len(m.Reason) + n := typeRequestError.MarshalTo(buf) + buf[n] = byte(payloadSize >> 8) + buf[n+1] = byte(payloadSize) + n += 2 + n += varint.Varint(m.Code).MarshalTo(buf[n:]) + buf[n] = 0x00 + n++ + n += varint.Varint(len(m.Reason)).MarshalTo(buf[n:]) + n += copy(buf[n:], m.Reason) + return n +} + +// Marshal implements Message. +func (m RequestError) Marshal() []byte { + buf := make([]byte, m.marshalSize()) + m.marshalTo(buf) + return buf +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/request_ok.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/request_ok.go new file mode 100644 index 0000000000000000000000000000000000000000..3e5375659187ff0fb8ac86f8fb45c8a64ee7db73 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/request_ok.go @@ -0,0 +1,63 @@ +package controlmessage + +import ( + "github.com/bluenviron/mediamtx/internal/protocols/moq/parameter" + "github.com/bluenviron/mediamtx/internal/protocols/moq/property" + "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" +) + +const typeRequestOk varint.Varint = 0x07 + +// RequestOk is the REQUEST_OK control message. +// spec: draft-18, section 10.5 +type RequestOk struct { + Parameters parameter.Parameters + TrackProperties property.Properties +} + +func (*RequestOk) isMessage() {} + +func (m *RequestOk) unmarshal(buf []byte) error { + var numParams varint.Varint + n, err := numParams.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + + consumed, err := m.Parameters.Unmarshal(int(numParams), buf) + if err != nil { + return err + } + buf = buf[consumed:] + + return m.TrackProperties.Unmarshal(buf) +} + +func (m RequestOk) marshalSize() int { + payloadSize := varint.Varint(len(m.Parameters)).MarshalSize() + + m.Parameters.MarshalSize() + + m.TrackProperties.MarshalSize() + return typeRequestOk.MarshalSize() + 2 + payloadSize +} + +func (m RequestOk) marshalTo(buf []byte) int { + payloadSize := varint.Varint(len(m.Parameters)).MarshalSize() + + m.Parameters.MarshalSize() + + m.TrackProperties.MarshalSize() + n := typeRequestOk.MarshalTo(buf) + buf[n] = byte(payloadSize >> 8) + buf[n+1] = byte(payloadSize) + n += 2 + n += varint.Varint(len(m.Parameters)).MarshalTo(buf[n:]) + n += m.Parameters.MarshalTo(buf[n:]) + n += m.TrackProperties.MarshalTo(buf[n:]) + return n +} + +// Marshal implements Message. +func (m RequestOk) Marshal() []byte { + buf := make([]byte, m.marshalSize()) + m.marshalTo(buf) + return buf +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/setup.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/setup.go new file mode 100644 index 0000000000000000000000000000000000000000..8f8c61cd70b175ec0690642898fa9bcf7f9a6d66 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/setup.go @@ -0,0 +1,31 @@ +package controlmessage + +import "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" + +const typeSetup varint.Varint = 0x2F00 + +// Setup is the SETUP control message. +// spec: draft-18, section 10.3 +type Setup struct{} + +func (*Setup) isMessage() {} + +func (*Setup) unmarshal(_ []byte) error { return nil } + +func (Setup) marshalSize() int { + return typeSetup.MarshalSize() + 2 +} + +func (Setup) marshalTo(buf []byte) int { + pos := typeSetup.MarshalTo(buf) + buf[pos] = 0x00 + buf[pos+1] = 0x00 + return pos + 2 +} + +// Marshal implements Message. +func (Setup) Marshal() []byte { + buf := make([]byte, Setup{}.marshalSize()) + Setup{}.marshalTo(buf) + return buf +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/subscribe.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/subscribe.go new file mode 100644 index 0000000000000000000000000000000000000000..df8b1123a844842d88a84d6c754872993d054ab7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/subscribe.go @@ -0,0 +1,128 @@ +package controlmessage + +import ( + "fmt" + + "github.com/bluenviron/mediamtx/internal/protocols/moq/parameter" + "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" +) + +const typeSubscribe varint.Varint = 0x03 + +// Subscribe is the SUBSCRIBE control message. +// spec: draft-18, section 10.7 +type Subscribe struct { + RequestID uint64 + Namespace []string + TrackName string + Parameters parameter.Parameters +} + +func (*Subscribe) isMessage() {} + +func (m *Subscribe) unmarshal(buf []byte) error { + var requestID varint.Varint + n, err := requestID.Unmarshal(buf) + if err != nil { + return err + } + m.RequestID = uint64(requestID) + buf = buf[n:] + + var nsCount varint.Varint + n, err = nsCount.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + + m.Namespace = make([]string, nsCount) + for i := range m.Namespace { + var l varint.Varint + n, err = l.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + if len(buf) < int(l) { + return fmt.Errorf("not enough bytes for namespace part") + } + m.Namespace[i] = string(buf[:l]) + buf = buf[int(l):] + } + + var tnLen varint.Varint + n, err = tnLen.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + if len(buf) < int(tnLen) { + return fmt.Errorf("not enough bytes for track name") + } + m.TrackName = string(buf[:tnLen]) + buf = buf[int(tnLen):] + + var paramCount varint.Varint + n, err = paramCount.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + + _, err = m.Parameters.Unmarshal(int(paramCount), buf) + if err != nil { + return err + } + + return nil +} + +func (m Subscribe) marshalSize() int { + n := varint.Varint(m.RequestID).MarshalSize() + + varint.Varint(len(m.Namespace)).MarshalSize() + for _, part := range m.Namespace { + n += varint.Varint(len(part)).MarshalSize() + len(part) + } + n += varint.Varint(len(m.TrackName)).MarshalSize() + len(m.TrackName) + n += varint.Varint(len(m.Parameters)).MarshalSize() + n += m.Parameters.MarshalSize() + + return typeSubscribe.MarshalSize() + 2 + n +} + +func (m Subscribe) marshalTo(buf []byte) int { + payloadSize := varint.Varint(m.RequestID).MarshalSize() + + varint.Varint(len(m.Namespace)).MarshalSize() + for _, part := range m.Namespace { + payloadSize += varint.Varint(len(part)).MarshalSize() + len(part) + } + payloadSize += varint.Varint(len(m.TrackName)).MarshalSize() + len(m.TrackName) + payloadSize += varint.Varint(len(m.Parameters)).MarshalSize() + payloadSize += m.Parameters.MarshalSize() + + n := typeSubscribe.MarshalTo(buf) + buf[n] = byte(payloadSize >> 8) + buf[n+1] = byte(payloadSize) + n += 2 + n += varint.Varint(m.RequestID).MarshalTo(buf[n:]) + n += varint.Varint(len(m.Namespace)).MarshalTo(buf[n:]) + for _, part := range m.Namespace { + n += varint.Varint(len(part)).MarshalTo(buf[n:]) + n += copy(buf[n:], part) + } + n += varint.Varint(len(m.TrackName)).MarshalTo(buf[n:]) + n += copy(buf[n:], m.TrackName) + + n += varint.Varint(len(m.Parameters)).MarshalTo(buf[n:]) + n += m.Parameters.MarshalTo(buf[n:]) + + return n +} + +// Marshal implements Message. +func (m Subscribe) Marshal() []byte { + buf := make([]byte, m.marshalSize()) + m.marshalTo(buf) + return buf +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/subscribe_ok.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/subscribe_ok.go new file mode 100644 index 0000000000000000000000000000000000000000..7a44b11287be4d7f04a5ef969f84b11dee73e0c5 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/controlmessage/subscribe_ok.go @@ -0,0 +1,75 @@ +package controlmessage + +import ( + "github.com/bluenviron/mediamtx/internal/protocols/moq/parameter" + "github.com/bluenviron/mediamtx/internal/protocols/moq/property" + "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" +) + +const typeSubscribeOk varint.Varint = 0x04 + +// SubscribeOk is the SUBSCRIBE_OK control message. +// spec: draft-18, section 10.8 +type SubscribeOk struct { + TrackAlias uint64 + Parameters parameter.Parameters + TrackProperties property.Properties +} + +func (*SubscribeOk) isMessage() {} + +func (m *SubscribeOk) unmarshal(buf []byte) error { + var v varint.Varint + n, err := v.Unmarshal(buf) + if err != nil { + return err + } + m.TrackAlias = uint64(v) + buf = buf[n:] + + var numParams varint.Varint + n, err = numParams.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n:] + + consumed, err := m.Parameters.Unmarshal(int(numParams), buf) + if err != nil { + return err + } + buf = buf[consumed:] + + return m.TrackProperties.Unmarshal(buf) +} + +func (m SubscribeOk) marshalSize() int { + payloadSize := varint.Varint(m.TrackAlias).MarshalSize() + + varint.Varint(len(m.Parameters)).MarshalSize() + + m.Parameters.MarshalSize() + + m.TrackProperties.MarshalSize() + return typeSubscribeOk.MarshalSize() + 2 + payloadSize +} + +func (m SubscribeOk) marshalTo(buf []byte) int { + payloadSize := varint.Varint(m.TrackAlias).MarshalSize() + + varint.Varint(len(m.Parameters)).MarshalSize() + + m.Parameters.MarshalSize() + + m.TrackProperties.MarshalSize() + n := typeSubscribeOk.MarshalTo(buf) + buf[n] = byte(payloadSize >> 8) + buf[n+1] = byte(payloadSize) + n += 2 + n += varint.Varint(m.TrackAlias).MarshalTo(buf[n:]) + n += varint.Varint(len(m.Parameters)).MarshalTo(buf[n:]) + n += m.Parameters.MarshalTo(buf[n:]) + n += m.TrackProperties.MarshalTo(buf[n:]) + return n +} + +// Marshal implements Message. +func (m SubscribeOk) Marshal() []byte { + buf := make([]byte, m.marshalSize()) + m.marshalTo(buf) + return buf +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/from_stream.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/from_stream.go new file mode 100644 index 0000000000000000000000000000000000000000..8cf98e371b2b0b2550cf1446246f40a82cc1f587 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/from_stream.go @@ -0,0 +1,318 @@ +// Package moq contains Media-over-QUIC utilities. +package moq + +import ( + "encoding/base64" + "encoding/hex" + "strings" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/av1" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/flac" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/g711" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/h264" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/h265" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/vp8" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/vp9" + "github.com/bluenviron/mediamtx/internal/unit" +) + +// FromStream maps a MediaMTX stream to a Media-over-QUIC stream. +func FromStream(desc *description.Session) ([]*Track, error) { + var tracks []*Track + + for _, media := range desc.Medias { + for _, forma := range media.Formats { + switch forma := forma.(type) { + case *format.AV1: + firstRandomAccess := false + + track := &Track{ + Codec: "av01.0.04M.08", + Media: media, + Format: forma, + OnData: func(u *unit.Unit, wrapped func([]byte, int64) error) error { + if u.NilPayload() { + return nil + } + + if !firstRandomAccess && !av1.IsRandomAccess2(u.Payload.(unit.PayloadAV1)) { + return nil + } + firstRandomAccess = true + + payload, err := av1.Bitstream([][]byte(u.Payload.(unit.PayloadAV1))).Marshal() + if err != nil { + return err + } + + return wrapped(payload, u.PTS) + }, + } + tracks = append(tracks, track) + + case *format.VP9: + firstRandomAccess := false + + track := &Track{ + Codec: "vp09.00.10.08", + Media: media, + Format: forma, + OnData: func(u *unit.Unit, wrapped func([]byte, int64) error) error { + if u.NilPayload() { + return nil + } + + if !firstRandomAccess && !vp9.IsRandomAccess(u.Payload.(unit.PayloadVP9)) { + return nil + } + firstRandomAccess = true + + return wrapped(u.Payload.(unit.PayloadVP9), u.PTS) + }, + } + tracks = append(tracks, track) + + case *format.VP8: + firstRandomAccess := false + + track := &Track{ + Codec: "vp8", + Media: media, + Format: forma, + OnData: func(u *unit.Unit, wrapped func([]byte, int64) error) error { + if u.NilPayload() { + return nil + } + + if !firstRandomAccess && !vp8.IsRandomAccess(u.Payload.(unit.PayloadVP8)) { + return nil + } + firstRandomAccess = true + + return wrapped(u.Payload.(unit.PayloadVP8), u.PTS) + }, + } + tracks = append(tracks, track) + + case *format.H265: + firstRandomAccess := false + + track := &Track{ + Codec: "hev1.1.6.L93.B0", + Media: media, + Format: forma, + OnData: func(u *unit.Unit, wrapped func([]byte, int64) error) error { + if u.NilPayload() { + return nil + } + + if !firstRandomAccess && !h265.IsRandomAccess(u.Payload.(unit.PayloadH265)) { + return nil + } + firstRandomAccess = true + + payload, err := h264.AVCC(u.Payload.(unit.PayloadH265)).Marshal() + if err != nil { + return err + } + + return wrapped(payload, u.PTS) + }, + } + tracks = append(tracks, track) + + case *format.H264: + firstRandomAccess := false + + track := &Track{ + Codec: "avc3.640028", + Media: media, + Format: forma, + OnData: func(u *unit.Unit, wrapped func([]byte, int64) error) error { + if u.NilPayload() { + return nil + } + + if !firstRandomAccess && !h264.IsRandomAccess(u.Payload.(unit.PayloadH264)) { + return nil + } + firstRandomAccess = true + + payload, err := h264.AVCC(u.Payload.(unit.PayloadH264)).Marshal() + if err != nil { + return err + } + + return wrapped(payload, u.PTS) + }, + } + tracks = append(tracks, track) + + case *format.Opus: + track := &Track{ + Codec: "opus", + Samplerate: 48000, + Channels: forma.ChannelCount, + Media: media, + Format: forma, + OnData: func(u *unit.Unit, wrapped func([]byte, int64) error) error { + if u.NilPayload() { + return nil + } + + for _, pkt := range u.Payload.(unit.PayloadOpus) { + err := wrapped(pkt, u.PTS) + if err != nil { + return err + } + } + return nil + }, + } + tracks = append(tracks, track) + + case *format.Generic: + if strings.HasPrefix(strings.ToLower(forma.RTPMap()), "flac/") { + enc, err := hex.DecodeString(forma.FMT["streaminfo"]) + if err != nil { + return nil, err + } + + var streamInfo flac.StreamInfo + err = streamInfo.Unmarshal(enc) + if err != nil { + return nil, err + } + + track := &Track{ + Codec: "flac", + Samplerate: int(streamInfo.SampleRate), + Channels: int(streamInfo.ChannelCount), + InitData: base64.StdEncoding.EncodeToString(enc), + Media: media, + Format: forma, + OnData: func(u *unit.Unit, wrapped func([]byte, int64) error) error { + if u.NilPayload() { + return nil + } + + return wrapped(u.Payload.(unit.PayloadFLAC), u.PTS) + }, + } + tracks = append(tracks, track) + } + + case *format.MPEG4Audio: + if forma.Config != nil { + enc, err := forma.Config.Marshal() + if err != nil { + return nil, err + } + + track := &Track{ + Codec: "mp4a.40.2", + Samplerate: forma.Config.SampleRate, + Channels: int(forma.Config.ChannelConfig), + InitData: base64.StdEncoding.EncodeToString(enc), + Media: media, + Format: forma, + OnData: func(u *unit.Unit, wrapped func([]byte, int64) error) error { + if u.NilPayload() { + return nil + } + + pts := u.PTS + + for _, au := range u.Payload.(unit.PayloadMPEG4Audio) { + err2 := wrapped(au, pts) + if err2 != nil { + return err2 + } + + pts += mpeg4audio.SamplesPerAccessUnit + } + return nil + }, + } + tracks = append(tracks, track) + } + + case *format.G711: + track := &Track{ + Codec: "pcm-s16", + Samplerate: forma.SampleRate, + Channels: forma.ChannelCount, + Media: media, + Format: forma, + OnData: func(u *unit.Unit, wrapped func([]byte, int64) error) error { + if u.NilPayload() { + return nil + } + + var bigEndian []byte + if forma.MULaw { + var mu g711.Mulaw + mu.Unmarshal(u.Payload.(unit.PayloadG711)) + bigEndian = mu + } else { + var al g711.Alaw + al.Unmarshal(u.Payload.(unit.PayloadG711)) + bigEndian = al + } + + swapped := make([]byte, len(bigEndian)) + for i := 0; i+2 <= len(bigEndian); i += 2 { + swapped[i], swapped[i+1] = bigEndian[i+1], bigEndian[i] + } + + return wrapped(swapped, u.PTS) + }, + } + tracks = append(tracks, track) + + case *format.LPCM: + var codec string + switch forma.BitDepth { + case 8: + codec = "pcm-u8" + case 16: + codec = "pcm-s16" + case 24: + codec = "pcm-s24" + default: // 32 + codec = "pcm-s32" + } + + track := &Track{ + Codec: codec, + Samplerate: forma.SampleRate, + Channels: forma.ChannelCount, + Media: media, + Format: forma, + OnData: func(u *unit.Unit, onData func([]byte, int64) error) error { + if u.NilPayload() { + return nil + } + + src := []byte(u.Payload.(unit.PayloadLPCM)) + byteDepth := forma.BitDepth / 8 + swapped := make([]byte, len(src)) + for i := 0; i+byteDepth <= len(src); i += byteDepth { + for j := range byteDepth { + swapped[i+j] = src[i+byteDepth-1-j] + } + } + + return onData(swapped, u.PTS) + }, + } + tracks = append(tracks, track) + } + } + } + + return tracks, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/from_stream_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/from_stream_test.go new file mode 100644 index 0000000000000000000000000000000000000000..522dbb272f1230f6ce61579a8c05a3257d34292e --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/from_stream_test.go @@ -0,0 +1,111 @@ +package moq + +import ( + "encoding/base64" + "encoding/hex" + "testing" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/flac" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/stretchr/testify/require" +) + +func TestFromStream(t *testing.T) { + flacEnc, err := (&flac.StreamInfo{ + SampleRate: 44100, + ChannelCount: 2, + BitDepth: 16, + }).Marshal() + require.NoError(t, err) + + mpeg4Config := &mpeg4audio.AudioSpecificConfig{ + Type: 2, + SampleRate: 44100, + ChannelConfig: 2, + } + mpeg4Enc, err := mpeg4Config.Marshal() + require.NoError(t, err) + + desc := &description.Session{ + Medias: []*description.Media{ + {Formats: []format.Format{&format.AV1{}}}, + {Formats: []format.Format{&format.VP9{}}}, + {Formats: []format.Format{&format.VP8{}}}, + {Formats: []format.Format{&format.H265{}}}, + {Formats: []format.Format{&format.H264{}}}, + {Formats: []format.Format{&format.Opus{ChannelCount: 2}}}, + {Formats: []format.Format{&format.Generic{ + RTPMa: "FLAC/44100/2", + ClockRat: 44100, + FMT: map[string]string{"streaminfo": hex.EncodeToString(flacEnc)}, + }}}, + {Formats: []format.Format{&format.MPEG4Audio{ + Config: mpeg4Config, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + }}}, + {Formats: []format.Format{&format.G711{ + SampleRate: 8000, + ChannelCount: 1, + }}}, + {Formats: []format.Format{&format.LPCM{ + BitDepth: 16, + SampleRate: 44100, + ChannelCount: 2, + }}}, + }, + } + + tracks, err := FromStream(desc) + require.NoError(t, err) + + for _, track := range tracks { + track.OnData = nil + } + + require.Equal(t, []*Track{ + { + Codec: "av01.0.04M.08", Media: desc.Medias[0], + Format: desc.Medias[0].Formats[0], + }, + { + Codec: "vp09.00.10.08", Media: desc.Medias[1], + Format: desc.Medias[1].Formats[0], + }, + { + Codec: "vp8", Media: desc.Medias[2], + Format: desc.Medias[2].Formats[0], + }, + { + Codec: "hev1.1.6.L93.B0", Media: desc.Medias[3], + Format: desc.Medias[3].Formats[0], + }, + { + Codec: "avc3.640028", Media: desc.Medias[4], + Format: desc.Medias[4].Formats[0], + }, + { + Codec: "opus", Samplerate: 48000, Channels: 2, + Media: desc.Medias[5], Format: desc.Medias[5].Formats[0], + }, + { + Codec: "flac", Samplerate: 44100, Channels: 2, + InitData: base64.StdEncoding.EncodeToString(flacEnc), Media: desc.Medias[6], Format: desc.Medias[6].Formats[0], + }, + { + Codec: "mp4a.40.2", Samplerate: 44100, Channels: 2, + InitData: base64.StdEncoding.EncodeToString(mpeg4Enc), Media: desc.Medias[7], Format: desc.Medias[7].Formats[0], + }, + { + Codec: "pcm-s16", Samplerate: 8000, Channels: 1, + Media: desc.Medias[8], Format: desc.Medias[8].Formats[0], + }, + { + Codec: "pcm-s16", Samplerate: 44100, Channels: 2, + Media: desc.Medias[9], Format: desc.Medias[9].Formats[0], + }, + }, tracks) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/parameter/authorization_token.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/parameter/authorization_token.go new file mode 100644 index 0000000000000000000000000000000000000000..423e922d56a66a6d89703601b1f0579e7a711a4e --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/parameter/authorization_token.go @@ -0,0 +1,84 @@ +package parameter + +import ( + "fmt" + + "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" +) + +const typeAuthorizationToken = 0x03 + +// AuthorizationTokenAliasType is a value of Alias Type. +// spec: draft-18, section 10.2.2 +type AuthorizationTokenAliasType uint64 + +// spec: draft-18, section 10.2.2 +const ( + AuthorizationTokenAliasTypeUseValue AuthorizationTokenAliasType = 0x03 +) + +// AuthorizationToken is the AUTHORIZATION_TOKEN parameter. +// spec: draft-18, section 10.2.2 +type AuthorizationToken struct { + AliasType AuthorizationTokenAliasType + TokenType uint64 + TokenValue []byte +} + +func (*AuthorizationToken) isParameter() {} + +func (*AuthorizationToken) paramType() uint64 { + return typeAuthorizationToken +} + +func (t *AuthorizationToken) unmarshal(buf []byte) (int, error) { + var le varint.Varint + llen, err := le.Unmarshal(buf) + if err != nil { + return 0, err + } + if len(buf)-llen < int(le) { + return 0, fmt.Errorf("not enough bytes for parameter value") + } + buf = buf[llen : llen+int(le)] + + var aliasType varint.Varint + n, err := aliasType.Unmarshal(buf) + if err != nil { + return 0, err + } + t.AliasType = AuthorizationTokenAliasType(aliasType) + + if t.AliasType != AuthorizationTokenAliasTypeUseValue { + return 0, fmt.Errorf("unsupported token alias type: %d", aliasType) + } + buf = buf[n:] + + var tokenType varint.Varint + n, err = tokenType.Unmarshal(buf) + if err != nil { + return 0, err + } + t.TokenType = uint64(tokenType) + t.TokenValue = buf[n:] + return llen + int(le), nil +} + +func (t AuthorizationToken) marshalSize() int { + n := varint.Varint(t.AliasType).MarshalSize() + + varint.Varint(t.TokenType).MarshalSize() + + len(t.TokenValue) + + return varint.Varint(n).MarshalSize() + n +} + +func (t AuthorizationToken) marshalTo(buf []byte) int { + innerSize := varint.Varint(t.AliasType).MarshalSize() + + varint.Varint(t.TokenType).MarshalSize() + + len(t.TokenValue) + n := varint.Varint(innerSize).MarshalTo(buf) + n += varint.Varint(t.AliasType).MarshalTo(buf[n:]) + n += varint.Varint(t.TokenType).MarshalTo(buf[n:]) + n += copy(buf[n:], t.TokenValue) + return n +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/parameter/parameter.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/parameter/parameter.go new file mode 100644 index 0000000000000000000000000000000000000000..d9b56587ef16fd736ac87d886902daa1e082461c --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/parameter/parameter.go @@ -0,0 +1,91 @@ +// Package parameter contains MoQ parameters. +package parameter + +import ( + "fmt" + + "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" +) + +// Parameter is a parameter of a control message. +// spec: draft-18, section 10.2 +type Parameter interface { + isParameter() + paramType() uint64 + unmarshal(data []byte) (int, error) + marshalSize() int + marshalTo(buf []byte) int +} + +// Parameters is a list of parameters. +type Parameters []Parameter + +// Unmarshal decodes parameters. Returns the number of bytes consumed. +func (p *Parameters) Unmarshal(count int, buf []byte) (int, error) { + var currentType uint64 + total := 0 + + for range uint64(count) { + var typeDelta varint.Varint + n, err := typeDelta.Unmarshal(buf) + if err != nil { + return 0, err + } + + buf = buf[n:] + total += n + currentType += uint64(typeDelta) + + var param Parameter + + switch currentType { + case typeAuthorizationToken: + param = &AuthorizationToken{} + + default: + return 0, fmt.Errorf("unsupported parameter type: %d", currentType) + } + + n, err = param.unmarshal(buf) + if err != nil { + return 0, fmt.Errorf("failed to unmarshal authorization token: %w", err) + } + + *p = append(*p, param) + buf = buf[n:] + total += n + } + + return total, nil +} + +// MarshalSize returns the size of marshaled parameters. +func (p Parameters) MarshalSize() int { + n := 0 + var prevType uint64 + + for _, param := range p { + t := param.paramType() + delta := t - prevType + n += varint.Varint(delta).MarshalSize() + param.marshalSize() + prevType = t + } + + return n +} + +// MarshalTo encodes parameters. +func (p Parameters) MarshalTo(buf []byte) int { + n := 0 + var prevType uint64 + + for _, param := range p { + t := param.paramType() + delta := t - prevType + n += varint.Varint(delta).MarshalTo(buf[n:]) + n += param.marshalTo(buf[n:]) + prevType = t + } + + return n +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/parameter/parameter_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/parameter/parameter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..4d1bfe68b2bab45f2a5a85361a5c690f50c0a8fb --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/parameter/parameter_test.go @@ -0,0 +1,60 @@ +package parameter + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +var cases = []struct { + name string + count int + enc []byte + dec Parameters +}{ + { + name: "no parameters", + count: 0, + enc: []byte{}, + dec: nil, + }, + { + name: "authorization token", + count: 1, + enc: []byte{ + 0x03, // type delta = 3 (AuthorizationToken) + 0x08, // inner length = 8 + 0x03, // alias type = UseValue + 0x01, // token type = 1 + 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, // token value = "secret" + }, + dec: Parameters{ + &AuthorizationToken{ + AliasType: AuthorizationTokenAliasTypeUseValue, + TokenType: 1, + TokenValue: []byte("secret"), + }, + }, + }, +} + +func TestUnmarshal(t *testing.T) { + for _, ca := range cases { + t.Run(ca.name, func(t *testing.T) { + var params Parameters + _, err := params.Unmarshal(ca.count, ca.enc) + require.NoError(t, err) + require.Equal(t, ca.dec, params) + }) + } +} + +func TestMarshal(t *testing.T) { + for _, ca := range cases { + t.Run(ca.name, func(t *testing.T) { + buf := make([]byte, ca.dec.MarshalSize()) + ca.dec.MarshalTo(buf) + require.Equal(t, ca.enc, buf) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/property/property.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/property/property.go new file mode 100644 index 0000000000000000000000000000000000000000..188e82920c3058b64f8ffc78993c1fdca20d1ce2 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/property/property.go @@ -0,0 +1,105 @@ +// Package property contains Media over QUIC object properties. +package property + +import ( + "fmt" + + "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" +) + +// Property is an object property. +// spec: draft-18, section 11.2.1.2 +type Property interface { + isProperty() + propType() varint.Varint + unmarshal(buf []byte) (int, error) + marshalSize() int + marshalTo(buf []byte) int +} + +// Properties are object properties. +// spec: draft-18, section 11.2.1.2 +type Properties []Property + +// Unmarshal decodes properties. +func (p *Properties) Unmarshal(buf []byte) error { + var currentType uint64 + + for len(buf) != 0 { + var delta varint.Varint + n, err := delta.Unmarshal(buf) + if err != nil { + return err + } + + buf = buf[n:] + currentType += uint64(delta) + + switch currentType { + case timestampPropertyType: + var ts Timestamp + var n2 int + n2, err = ts.unmarshal(buf) + if err != nil { + return err + } + *p = append(*p, &ts) + buf = buf[n2:] + + default: + if currentType%2 == 1 { + var length varint.Varint + var n2 int + n2, err = length.Unmarshal(buf) + if err != nil { + return err + } + if len(buf)-n2 < int(length) { + return fmt.Errorf("not enough bytes for unknown property") + } + buf = buf[n2+int(length):] + } else { + var skip varint.Varint + var n2 int + n2, err = skip.Unmarshal(buf) + if err != nil { + return err + } + buf = buf[n2:] + } + } + } + + return nil +} + +// MarshalSize returns the size of marshaled properties. +func (p Properties) MarshalSize() int { + n := 0 + var prevType varint.Varint + + for _, prop := range p { + t := prop.propType() + delta := t - prevType + n += delta.MarshalSize() + prop.marshalSize() + prevType = t + } + + return n +} + +// MarshalTo encodes properties. +func (p Properties) MarshalTo(buf []byte) int { + n := 0 + var prevType varint.Varint + + for _, prop := range p { + t := prop.propType() + delta := t - prevType + n += delta.MarshalTo(buf[n:]) + n += prop.marshalTo(buf[n:]) + prevType = t + } + + return n +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/property/property_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/property/property_test.go new file mode 100644 index 0000000000000000000000000000000000000000..f6ab2c80864a85811d4fa53a858b78871e541492 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/property/property_test.go @@ -0,0 +1,50 @@ +package property + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +var cases = []struct { + name string + enc []byte + dec Properties +}{ + { + name: "no properties", + enc: []byte{}, + dec: nil, + }, + { + name: "timestamp", + enc: []byte{ + 0x06, // type delta = 6 (Timestamp) + 0x83, 0xe8, // value = 1000 + }, + dec: Properties{ + new(Timestamp(1000)), + }, + }, +} + +func TestUnmarshal(t *testing.T) { + for _, ca := range cases { + t.Run(ca.name, func(t *testing.T) { + var props Properties + err := props.Unmarshal(ca.enc) + require.NoError(t, err) + require.Equal(t, ca.dec, props) + }) + } +} + +func TestMarshal(t *testing.T) { + for _, ca := range cases { + t.Run(ca.name, func(t *testing.T) { + buf := make([]byte, ca.dec.MarshalSize()) + ca.dec.MarshalTo(buf) + require.Equal(t, ca.enc, buf) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/property/timestamp.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/property/timestamp.go new file mode 100644 index 0000000000000000000000000000000000000000..956475b4a65f27576bd4459cb0ee6abc524f4f85 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/property/timestamp.go @@ -0,0 +1,33 @@ +package property + +import "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" + +const timestampPropertyType = 0x06 + +// Timestamp is the timestamp property. +// spec: draft-ietf-moq-loc, section 2.3.1.1 +type Timestamp int64 + +func (t *Timestamp) isProperty() {} + +func (Timestamp) propType() varint.Varint { + return timestampPropertyType +} + +func (t *Timestamp) unmarshal(buf []byte) (int, error) { + var val varint.Varint + n, err := val.Unmarshal(buf) + if err != nil { + return 0, err + } + *t = Timestamp(val) + return n, nil +} + +func (t Timestamp) marshalSize() int { + return varint.Varint(t).MarshalSize() +} + +func (t Timestamp) marshalTo(buf []byte) int { + return varint.Varint(t).MarshalTo(buf) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/reorderer/reorderer.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/reorderer/reorderer.go new file mode 100644 index 0000000000000000000000000000000000000000..d3a8ce4a79da2bd6b876d6074b3df9c0c5728629 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/reorderer/reorderer.go @@ -0,0 +1,88 @@ +// Package reorderer contains a subgroup reorderer. +package reorderer + +import ( + "sync" + + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/moq/subgroup" +) + +// Reorderer is a subgroup reorderer. +type Reorderer struct { + MaxReordered int + Parent logger.Writer + + initialized bool + mu sync.Mutex + curGroupID uint64 + pending map[uint64]*subgroup.SubGroup +} + +// Initialize initializes the reorderer. +func (r *Reorderer) Initialize() { + r.pending = make(map[uint64]*subgroup.SubGroup) +} + +// Push pushes a subgroup and returns a list of subgroups that are now in order. +func (r *Reorderer) Push(sg *subgroup.SubGroup) ([]*subgroup.SubGroup, error) { + r.mu.Lock() + defer r.mu.Unlock() + + if !r.initialized { + r.initialized = true + r.curGroupID = sg.Header.GroupID + return []*subgroup.SubGroup{sg}, nil + } + + switch { + case sg.Header.GroupID <= r.curGroupID: + r.Parent.Log(logger.Warn, "skipping out-of-order subgroup") + + case sg.Header.GroupID == r.curGroupID+1 && len(r.pending) == 0: + r.curGroupID = sg.Header.GroupID + return []*subgroup.SubGroup{sg}, nil + + default: + r.pending[sg.Header.GroupID] = sg + + diff := sg.Header.GroupID - r.curGroupID + + var countInRange uint64 + for id := range r.pending { + if id <= sg.Header.GroupID { + countInRange++ + } + } + + if countInRange == diff { + return r.flushUpTo(sg.Header.GroupID), nil + } else if len(r.pending) > r.MaxReordered { + r.Parent.Log(logger.Warn, "too many reordered subgroups, flushing") + return r.flushUpTo(sg.Header.GroupID), nil + } + } + + return nil, nil +} + +func (r *Reorderer) flushUpTo(maxGroupID uint64) []*subgroup.SubGroup { + out := make([]*subgroup.SubGroup, 0, len(r.pending)) + for i := r.curGroupID + 1; i <= maxGroupID; i++ { + if e, ok := r.pending[i]; ok { + out = append(out, e) + delete(r.pending, i) + } + } + r.curGroupID = maxGroupID + for { + next, ok := r.pending[r.curGroupID+1] + if !ok { + break + } + out = append(out, next) + delete(r.pending, r.curGroupID+1) + r.curGroupID++ + } + return out +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/reorderer/reorderer_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/reorderer/reorderer_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9fdfc090850aeca2e59cf78d22ce44a7c45ad553 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/reorderer/reorderer_test.go @@ -0,0 +1,163 @@ +package reorderer + +import ( + "testing" + + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/moq/subgroup" + "github.com/stretchr/testify/require" +) + +type nopLogger struct{} + +func (nopLogger) Log(logger.Level, string, ...any) {} + +func makeSG(groupID uint64) *subgroup.SubGroup { + return &subgroup.SubGroup{ + Header: subgroup.Header{GroupID: groupID}, + } +} + +func TestReordererFirstPush(t *testing.T) { + r := &Reorderer{MaxReordered: 5, Parent: nopLogger{}} + r.Initialize() + + sg0 := makeSG(0) + out, err := r.Push(sg0) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg0}, out) +} + +func TestReordererInOrder(t *testing.T) { + r := &Reorderer{MaxReordered: 5, Parent: nopLogger{}} + r.Initialize() + + sg0 := makeSG(0) + out, err := r.Push(sg0) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg0}, out) + + sg1 := makeSG(1) + out, err = r.Push(sg1) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg1}, out) + + sg2 := makeSG(2) + out, err = r.Push(sg2) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg2}, out) +} + +func TestReordererStale(t *testing.T) { + r := &Reorderer{MaxReordered: 5, Parent: nopLogger{}} + r.Initialize() + + sg5 := makeSG(5) + out, err := r.Push(sg5) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg5}, out) + + // same GroupID again + out, err = r.Push(makeSG(5)) + require.NoError(t, err) + require.Nil(t, out) + + // older GroupID + out, err = r.Push(makeSG(3)) + require.NoError(t, err) + require.Nil(t, out) +} + +func TestReordererOutOfOrderPending(t *testing.T) { + r := &Reorderer{MaxReordered: 5, Parent: nopLogger{}} + r.Initialize() + + sg0 := makeSG(0) + out, err := r.Push(sg0) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg0}, out) + + // sg2 arrives before sg1; held in pending + out, err = r.Push(makeSG(2)) + require.NoError(t, err) + require.Nil(t, out) +} + +func TestReordererOutOfOrderFilled(t *testing.T) { + r := &Reorderer{MaxReordered: 5, Parent: nopLogger{}} + r.Initialize() + + sg0 := makeSG(0) + out, err := r.Push(sg0) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg0}, out) + + // sg2 arrives out of order, held in pending + sg2 := makeSG(2) + out, err = r.Push(sg2) + require.NoError(t, err) + require.Nil(t, out) + + // sg1 (the missing piece) arrives; gap is now filled; sg1 and the + // already-pending sg2 are both returned together + sg1 := makeSG(1) + out, err = r.Push(sg1) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg1, sg2}, out) +} + +func TestReordererDrainAfterFill(t *testing.T) { //nolint:dupl + r := &Reorderer{MaxReordered: 5, Parent: nopLogger{}} + r.Initialize() + + sg0 := makeSG(0) + out, err := r.Push(sg0) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg0}, out) + + // sg2 and sg3 arrive before sg1 + sg2 := makeSG(2) + out, err = r.Push(sg2) + require.NoError(t, err) + require.Nil(t, out) + + sg3 := makeSG(3) + out, err = r.Push(sg3) + require.NoError(t, err) + require.Nil(t, out) + + // sg1 arrives; fills the gap; sg1, sg2, and sg3 are all returned together + sg1 := makeSG(1) + out, err = r.Push(sg1) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg1, sg2, sg3}, out) +} + +func TestReordererMaxReordered(t *testing.T) { //nolint:dupl + r := &Reorderer{MaxReordered: 2, Parent: nopLogger{}} + r.Initialize() + + sg0 := makeSG(0) + out, err := r.Push(sg0) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg0}, out) + + // first out-of-order item (pending=1, not over limit) + sg2 := makeSG(2) + out, err = r.Push(sg2) + require.NoError(t, err) + require.Nil(t, out) + + // second out-of-order item (pending=2, not over limit) + sg4 := makeSG(4) + out, err = r.Push(sg4) + require.NoError(t, err) + require.Nil(t, out) + + // third out-of-order item pushes pending to 3, which exceeds MaxReordered=2; + // all available items are flushed in order, skipping the missing ones (1, 3) + sg5 := makeSG(5) + out, err = r.Push(sg5) + require.NoError(t, err) + require.Equal(t, []*subgroup.SubGroup{sg2, sg4, sg5}, out) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/header.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/header.go new file mode 100644 index 0000000000000000000000000000000000000000..0fae64db3c8ae4c4569c3f27607dd5dbdae38f3f --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/header.go @@ -0,0 +1,70 @@ +// Package subgroup implements the subgroup stream. +package subgroup + +import ( + "io" + + "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" +) + +// Header is the SUBGROUP_HEADER structure. +// spec: draft-18, section 11.4.2 +type Header struct { + Properties bool + FirstObject bool + TrackAlias uint64 + GroupID uint64 +} + +func (h *Header) read(r io.Reader) error { + var b [1]byte + _, err := r.Read(b[:]) + if err != nil { + return err + } + h.Properties = (b[0] & 0x01) != 0 + h.FirstObject = (b[0] & 0x40) != 0 + + var trackAlias varint.Varint + err = trackAlias.Read(r) + if err != nil { + return err + } + h.TrackAlias = uint64(trackAlias) + + var groupID varint.Varint + err = groupID.Read(r) + if err != nil { + return err + } + h.GroupID = uint64(groupID) + + return nil +} + +func (h Header) marshalSize() int { + st := varint.Varint(0x30) + if h.Properties { + st |= 0x01 + } + if h.FirstObject { + st |= 0x40 + } + return st.MarshalSize() + + varint.Varint(h.TrackAlias).MarshalSize() + + varint.Varint(h.GroupID).MarshalSize() +} + +func (h Header) marshalTo(buf []byte) int { + st := varint.Varint(0x30) + if h.Properties { + st |= 0x01 + } + if h.FirstObject { + st |= 0x40 + } + pos := st.MarshalTo(buf) + pos += varint.Varint(h.TrackAlias).MarshalTo(buf[pos:]) + pos += varint.Varint(h.GroupID).MarshalTo(buf[pos:]) + return pos +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/object.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/object.go new file mode 100644 index 0000000000000000000000000000000000000000..16d632a6272421e4643be5150a546d314d95c0bd --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/object.go @@ -0,0 +1,120 @@ +package subgroup + +import ( + "fmt" + "io" + + "github.com/bluenviron/mediamtx/internal/protocols/moq/property" + "github.com/bluenviron/mediamtx/internal/protocols/moq/varint" +) + +const maxPayloadSize = 10 * 1024 * 1024 + +// Object is an object of a subgroup stream. +// spec: draft-18, section 11.4.2 +type Object struct { + IDDelta uint64 + Properties property.Properties + Payload []byte +} + +func (o *Object) read(r io.Reader, header *Header) error { + var idDelta varint.Varint + if err := idDelta.Read(r); err != nil { + return err + } + + o.IDDelta = uint64(idDelta) + + if header.Properties { + var propsLen varint.Varint + err := propsLen.Read(r) + if err != nil { + return err + } + + if propsLen > 0 { + props := make([]byte, propsLen) + _, err = io.ReadFull(r, props) + if err != nil { + return err + } + + err = o.Properties.Unmarshal(props) + if err != nil { + return err + } + } + } + + var payloadLen varint.Varint + err := payloadLen.Read(r) + if err != nil { + return err + } + + if payloadLen == 0 { + var status varint.Varint + if err = status.Read(r); err != nil { + return err + } + + if status != 0x03 && status != 0x04 { + return fmt.Errorf("unexpected status: 0x%x", status) + } + + return nil + } + + if payloadLen > maxPayloadSize { + return fmt.Errorf("payload too large: %d", payloadLen) + } + + o.Payload = make([]byte, payloadLen) + _, err = io.ReadFull(r, o.Payload) + if err != nil { + return err + } + + return nil +} + +func (o Object) marshalSize(header *Header) int { + propsFieldSize := 0 + if header.Properties { + propsLen := o.Properties.MarshalSize() + propsFieldSize = varint.Varint(propsLen).MarshalSize() + propsLen + } + + if len(o.Payload) == 0 { + return varint.Varint(o.IDDelta).MarshalSize() + propsFieldSize + 2 + } + + return varint.Varint(o.IDDelta).MarshalSize() + + propsFieldSize + + varint.Varint(len(o.Payload)).MarshalSize() + + len(o.Payload) +} + +func (o Object) marshalTo(buf []byte, header *Header) int { + n := varint.Varint(o.IDDelta).MarshalTo(buf) + + if header.Properties { + propsLen := o.Properties.MarshalSize() + n += varint.Varint(propsLen).MarshalTo(buf[n:]) + n += o.Properties.MarshalTo(buf[n:]) + } + + if len(o.Payload) == 0 { + buf[n] = 0x00 + n++ + buf[n] = 0x03 + n++ + return n + } + + n += varint.Varint(len(o.Payload)).MarshalTo(buf[n:]) + n += copy(buf[n:], o.Payload) + + return n +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/subgroup.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/subgroup.go new file mode 100644 index 0000000000000000000000000000000000000000..66edc94f89c1745fa48749fe9fde5a980552d95d --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/subgroup.go @@ -0,0 +1,70 @@ +package subgroup + +import ( + "fmt" + "io" +) + +// SubGroup is a subgroup stream. +type SubGroup struct { + Header Header + Objects []Object +} + +// Read reads a SubGroup. +func (s *SubGroup) Read(r io.Reader) error { + if err := s.Header.read(r); err != nil { + return err + } + + // for the moment, support reading a single object only. + + var o1 Object + err := o1.read(r, &s.Header) + if err != nil { + return err + } + s.Objects = []Object{o1} + + var o2 Object + err = o2.read(r, &s.Header) + if err != nil { + return err + } + if len(o2.Payload) != 0 { + return fmt.Errorf("unexpected second object") + } + + return nil +} + +func (s SubGroup) marshalSize() int { + n := s.Header.marshalSize() + + for _, o := range s.Objects { + n += o.marshalSize(&s.Header) + } + + n += Object{Payload: nil}.marshalSize(&s.Header) + + return n +} + +func (s SubGroup) marshalTo(buf []byte) int { + n := s.Header.marshalTo(buf) + + for _, o := range s.Objects { + n += o.marshalTo(buf[n:], &s.Header) + } + + n += Object{Payload: nil}.marshalTo(buf[n:], &s.Header) + + return n +} + +// Marshal encodes a SubGroup. +func (s *SubGroup) Marshal() []byte { + buf := make([]byte, s.marshalSize()) + s.marshalTo(buf) + return buf +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/subgroup_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/subgroup_test.go new file mode 100644 index 0000000000000000000000000000000000000000..049d53f7a3139cde7f3c9d35b6c923fd7db0f696 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/subgroup/subgroup_test.go @@ -0,0 +1,92 @@ +package subgroup + +import ( + "bytes" + "testing" + + "github.com/bluenviron/mediamtx/internal/protocols/moq/property" + "github.com/stretchr/testify/require" +) + +var cases = []struct { + name string + enc []byte + dec SubGroup +}{ + { + name: "stream without properties", + enc: []byte{ + 0x30, // type (Properties=false, FirstObject=false) + 0x01, // TrackAlias = 1 + 0x00, // GroupID = 0 + 0x00, // object IDDelta = 0 + 0x05, // payload length = 5 + 0x68, 0x65, 0x6c, 0x6c, 0x6f, // payload = "hello" + 0x00, // end-of-stream IDDelta = 0 + 0x00, // payload length = 0 (end-of-stream) + 0x03, // status = EndOfGroup + }, + dec: SubGroup{ + Header: Header{ + Properties: false, + FirstObject: false, + TrackAlias: 1, + GroupID: 0, + }, + Objects: []Object{{ + Payload: []byte("hello"), + }}, + }, + }, + { + name: "stream with properties", + enc: []byte{ + 0x31, // type (Properties=true) + 0x01, // TrackAlias = 1 + 0x00, // GroupID = 0 + 0x00, // object IDDelta = 0 + 0x03, // properties length = 3 + 0x06, // property type delta = 6 (Timestamp) + 0x83, 0xe8, // Timestamp value = 1000 + 0x05, // payload length = 5 + 0x68, 0x65, 0x6c, 0x6c, 0x6f, // payload = "hello" + 0x00, // end-of-stream IDDelta = 0 + 0x00, // properties length = 0 + 0x00, // payload length = 0 (end-of-stream) + 0x03, // status = EndOfGroup + }, + dec: SubGroup{ + Header: Header{ + Properties: true, + FirstObject: false, + TrackAlias: 1, + GroupID: 0, + }, + Objects: []Object{{ + Properties: property.Properties{ + new(property.Timestamp(1000)), + }, + Payload: []byte("hello"), + }}, + }, + }, +} + +func TestUnmarshal(t *testing.T) { + for _, ca := range cases { + t.Run(ca.name, func(t *testing.T) { + var s SubGroup + err := s.Read(bytes.NewReader(ca.enc)) + require.NoError(t, err) + require.Equal(t, ca.dec, s) + }) + } +} + +func TestMarshal(t *testing.T) { + for _, ca := range cases { + t.Run(ca.name, func(t *testing.T) { + require.Equal(t, ca.enc, ca.dec.Marshal()) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/to_stream.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/to_stream.go new file mode 100644 index 0000000000000000000000000000000000000000..1565caeedd56967721e04cd5ee4794ff90fd9d08 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/to_stream.go @@ -0,0 +1,199 @@ +package moq + +import ( + "fmt" + "strings" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/av1" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/h264" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediamtx/internal/protocols/moq/catalog" + "github.com/bluenviron/mediamtx/internal/protocols/moq/property" + "github.com/bluenviron/mediamtx/internal/protocols/moq/subgroup" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" +) + +func findTimestamp(props []property.Property) (int64, bool) { + for _, pr := range props { + if ts, ok := pr.(*property.Timestamp); ok { + return int64(*ts), true + } + } + return 0, false +} + +// ToStream maps a Media-over-QUIC stream to a MediaMTX stream. +func ToStream( + cat *catalog.Catalog, + subStream **stream.SubStream, +) ( + []*description.Media, + map[uint64]func(sg *subgroup.SubGroup) error, + error, +) { + var medias []*description.Media + writeFuncs := make(map[uint64]func(sg *subgroup.SubGroup) error) + + wrap := func(wrapped func(payload []byte, pts int64) error) func(sg *subgroup.SubGroup) error { + return func(sg *subgroup.SubGroup) error { + ts, ok := findTimestamp(sg.Objects[0].Properties) + if !ok { + return fmt.Errorf("timestamp property is required") + } + + return wrapped(sg.Objects[0].Payload, ts) + } + } + + for i, track := range cat.Tracks { + trackAlias := uint64(i + 1) + + switch { + case strings.HasPrefix(track.Codec, "av01"): + forma := &format.AV1{ + PayloadTyp: 96, + } + media := &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{forma}, + } + medias = append(medias, media) + + writeFuncs[trackAlias] = wrap(func(payload []byte, pts int64) error { + var bs av1.Bitstream + err := bs.Unmarshal(payload) + if err != nil { + return err + } + + (*subStream).WriteUnit(media, forma, &unit.Unit{PTS: pts, Payload: unit.PayloadAV1(bs)}) + return nil + }) + + case strings.HasPrefix(track.Codec, "vp09"): + forma := &format.VP9{ + PayloadTyp: 96, + } + media := &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{forma}, + } + medias = append(medias, media) + + writeFuncs[trackAlias] = wrap(func(payload []byte, pts int64) error { + (*subStream).WriteUnit(media, forma, &unit.Unit{PTS: pts, Payload: unit.PayloadVP9(payload)}) + return nil + }) + + case track.Codec == "vp8": + forma := &format.VP8{ + PayloadTyp: 96, + } + media := &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{forma}, + } + medias = append(medias, media) + + writeFuncs[trackAlias] = wrap(func(payload []byte, pts int64) error { + (*subStream).WriteUnit(media, forma, &unit.Unit{PTS: pts, Payload: unit.PayloadVP8(payload)}) + return nil + }) + case strings.HasPrefix(track.Codec, "avc3"): + forma := &format.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + } + media := &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{forma}, + } + medias = append(medias, media) + + writeFuncs[trackAlias] = wrap(func(payload []byte, pts int64) error { + var nalus h264.AVCC + err := nalus.Unmarshal(payload) + if err != nil { + return err + } + + (*subStream).WriteUnit(media, forma, &unit.Unit{PTS: pts, Payload: unit.PayloadH264(nalus)}) + return nil + }) + + case strings.HasPrefix(track.Codec, "hev1"): + forma := &format.H265{ + PayloadTyp: 96, + } + media := &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{forma}, + } + medias = append(medias, media) + + writeFuncs[trackAlias] = wrap(func(payload []byte, pts int64) error { + var nalus h264.AVCC + err := nalus.Unmarshal(payload) + if err != nil { + return err + } + + (*subStream).WriteUnit(media, forma, &unit.Unit{PTS: pts, Payload: unit.PayloadH265(nalus)}) + return nil + }) + + case track.Codec == "opus": + channels := track.Channels + if channels == 0 { + channels = 2 + } + forma := &format.Opus{ + PayloadTyp: 96, + ChannelCount: channels, + } + media := &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{forma}, + } + medias = append(medias, media) + + writeFuncs[trackAlias] = wrap(func(payload []byte, pts int64) error { + (*subStream).WriteUnit(media, forma, &unit.Unit{PTS: pts, Payload: unit.PayloadOpus{payload}}) + return nil + }) + + case strings.HasPrefix(track.Codec, "mp4a"): + config := &mpeg4audio.AudioSpecificConfig{ + Type: mpeg4audio.ObjectTypeAACLC, + SampleRate: track.Samplerate, + ChannelConfig: uint8(track.Channels), + } + + forma := &format.MPEG4Audio{ + PayloadTyp: 96, + Config: config, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + } + media := &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{forma}, + } + medias = append(medias, media) + + writeFuncs[trackAlias] = wrap(func(payload []byte, pts int64) error { + (*subStream).WriteUnit(media, forma, &unit.Unit{PTS: pts, Payload: unit.PayloadMPEG4Audio{payload}}) + return nil + }) + + default: + return nil, nil, fmt.Errorf("unsupported codec: %s", track.Codec) + } + } + + return medias, writeFuncs, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/to_stream_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/to_stream_test.go new file mode 100644 index 0000000000000000000000000000000000000000..954c49d288414c2a72e57012a58b2ffd8bb2c371 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/to_stream_test.go @@ -0,0 +1,69 @@ +package moq + +import ( + "testing" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediamtx/internal/protocols/moq/catalog" + "github.com/stretchr/testify/require" +) + +func TestToStream(t *testing.T) { + cat := &catalog.Catalog{ + Tracks: []catalog.Track{ + {Codec: "av01.0.04M.08"}, + {Codec: "vp09.00.10.08"}, + {Codec: "vp8"}, + {Codec: "hev1.1.6.L93.B0"}, + {Codec: "avc3.640028"}, + {Codec: "opus"}, + {Codec: "mp4a.40.2", Samplerate: 44100, Channels: 2}, + }, + } + + medias, _, err := ToStream(cat, nil) + require.NoError(t, err) + + require.Equal(t, []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.AV1{PayloadTyp: 96}}, + }, + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.VP9{PayloadTyp: 96}}, + }, + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.VP8{PayloadTyp: 96}}, + }, + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H265{PayloadTyp: 96}}, + }, + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H264{PayloadTyp: 96, PacketizationMode: 1}}, + }, + { + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.Opus{PayloadTyp: 96, ChannelCount: 2}}, + }, + { + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.MPEG4Audio{ + PayloadTyp: 96, + Config: &mpeg4audio.AudioSpecificConfig{ + Type: mpeg4audio.ObjectTypeAACLC, + SampleRate: 44100, + ChannelConfig: 2, + }, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + }}, + }, + }, medias) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/track.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/track.go new file mode 100644 index 0000000000000000000000000000000000000000..13962500cafb669bc75935c6b79548bfa35e40d3 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/track.go @@ -0,0 +1,18 @@ +package moq + +import ( + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediamtx/internal/unit" +) + +// Track is a Media-over-QUIC track. +type Track struct { + Codec string + Samplerate int + Channels int + InitData string + Media *description.Media + Format format.Format + OnData func(u *unit.Unit, wrapped func([]byte, int64) error) error +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/varint/varint.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/varint/varint.go new file mode 100644 index 0000000000000000000000000000000000000000..a60dfddd3566e84afdde439f84bc1cdbd82d9546 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/varint/varint.go @@ -0,0 +1,245 @@ +// Package varint implements variable-length integers. +package varint + +import ( + "fmt" + "io" +) + +// Varint is a variable-length integer. +// spec: draft-18, section 1.4.1 +type Varint uint64 + +// Read reads a Varint from a Reader. +func (v *Varint) Read(r io.Reader) error { + var first [1]byte + _, err := io.ReadFull(r, first[:]) + if err != nil { + return err + } + b := first[0] + + var size int + switch { + case b&0x80 == 0: + *v = Varint(b) + return nil + case b&0xC0 == 0x80: + size = 2 + case b&0xE0 == 0xC0: + size = 3 + case b&0xF0 == 0xE0: + size = 4 + case b&0xF8 == 0xF0: + size = 5 + case b&0xFC == 0xF8: + size = 6 + case b&0xFE == 0xFC: + size = 7 + case b == 0xFE: + size = 8 + case b == 0xFF: + size = 9 + default: + return fmt.Errorf("unsupported varint prefix: 0x%02X", b) + } + + rest := make([]byte, size-1) + _, err = io.ReadFull(r, rest) + if err != nil { + return err + } + + switch size { //nolint:dupl + case 2: + *v = Varint(b&0x3F)<<8 | Varint(rest[0]) + case 3: + *v = Varint(b&0x1F)<<16 | Varint(rest[0])<<8 | Varint(rest[1]) + case 4: + *v = Varint(b&0x0F)<<24 | Varint(rest[0])<<16 | Varint(rest[1])<<8 | + Varint(rest[2]) + case 5: + *v = Varint(b&0x07)<<32 | Varint(rest[0])<<24 | Varint(rest[1])<<16 | + Varint(rest[2])<<8 | Varint(rest[3]) + case 6: + *v = Varint(b&0x03)<<40 | Varint(rest[0])<<32 | Varint(rest[1])<<24 | + Varint(rest[2])<<16 | Varint(rest[3])<<8 | Varint(rest[4]) + case 7: + *v = Varint(b&0x01)<<48 | Varint(rest[0])<<40 | Varint(rest[1])<<32 | + Varint(rest[2])<<24 | Varint(rest[3])<<16 | Varint(rest[4])<<8 | Varint(rest[5]) + case 8: + *v = Varint(rest[0])<<48 | Varint(rest[1])<<40 | Varint(rest[2])<<32 | + Varint(rest[3])<<24 | Varint(rest[4])<<16 | Varint(rest[5])<<8 | Varint(rest[6]) + default: // 9 + *v = Varint(rest[0])<<56 | Varint(rest[1])<<48 | Varint(rest[2])<<40 | + Varint(rest[3])<<32 | Varint(rest[4])<<24 | Varint(rest[5])<<16 | + Varint(rest[6])<<8 | Varint(rest[7]) + } + + return nil +} + +// Unmarshal decodes a Varinat from a buffer. +func (v *Varint) Unmarshal(buf []byte) (int, error) { + if len(buf) == 0 { + return 0, fmt.Errorf("not enough bytes") + } + b := buf[0] + + var size int + switch { + case b&0x80 == 0: + *v = Varint(b) + return 1, nil + case b&0xC0 == 0x80: + size = 2 + case b&0xE0 == 0xC0: + size = 3 + case b&0xF0 == 0xE0: + size = 4 + case b&0xF8 == 0xF0: + size = 5 + case b&0xFC == 0xF8: + size = 6 + case b&0xFE == 0xFC: + size = 7 + case b == 0xFE: + size = 8 + case b == 0xFF: + size = 9 + default: + return 0, fmt.Errorf("unsupported varint prefix: 0x%02X", b) + } + + if len(buf) < size { + return 0, fmt.Errorf("not enough bytes") + } + + switch size { //nolint:dupl + case 2: + *v = Varint(b&0x3F)<<8 | Varint(buf[1]) + case 3: + *v = Varint(b&0x1F)<<16 | Varint(buf[1])<<8 | Varint(buf[2]) + case 4: + *v = Varint(b&0x0F)<<24 | Varint(buf[1])<<16 | Varint(buf[2])<<8 | + Varint(buf[3]) + case 5: + *v = Varint(b&0x07)<<32 | Varint(buf[1])<<24 | Varint(buf[2])<<16 | + Varint(buf[3])<<8 | Varint(buf[4]) + case 6: + *v = Varint(b&0x03)<<40 | Varint(buf[1])<<32 | Varint(buf[2])<<24 | + Varint(buf[3])<<16 | Varint(buf[4])<<8 | Varint(buf[5]) + case 7: + *v = Varint(b&0x01)<<48 | Varint(buf[1])<<40 | Varint(buf[2])<<32 | + Varint(buf[3])<<24 | Varint(buf[4])<<16 | Varint(buf[5])<<8 | Varint(buf[6]) + case 8: + *v = Varint(buf[1])<<48 | Varint(buf[2])<<40 | Varint(buf[3])<<32 | + Varint(buf[4])<<24 | Varint(buf[5])<<16 | Varint(buf[6])<<8 | Varint(buf[7]) + default: // 9 + *v = Varint(buf[1])<<56 | Varint(buf[2])<<48 | Varint(buf[3])<<40 | + Varint(buf[4])<<32 | Varint(buf[5])<<24 | Varint(buf[6])<<16 | + Varint(buf[7])<<8 | Varint(buf[8]) + } + + return size, nil +} + +// MarshalSize returns the number of bytes required to marshal the Varint. +func (v Varint) MarshalSize() int { + switch { + case v < 1<<7: + return 1 + case v < 1<<14: + return 2 + case v < 1<<21: + return 3 + case v < 1<<28: + return 4 + case v < 1<<35: + return 5 + case v < 1<<42: + return 6 + case v < 1<<49: + return 7 + case v < 1<<56: + return 8 + default: + return 9 + } +} + +// MarshalTo encodes the Varint to a buffer. +func (v Varint) MarshalTo(buf []byte) int { + switch { + case v < 1<<7: + buf[0] = byte(v) + return 1 + case v < 1<<14: + buf[0] = 0x80 | byte(v>>8) + buf[1] = byte(v) + return 2 + case v < 1<<21: + buf[0] = 0xC0 | byte(v>>16) + buf[1] = byte(v >> 8) + buf[2] = byte(v) + return 3 + case v < 1<<28: + buf[0] = 0xE0 | byte(v>>24) + buf[1] = byte(v >> 16) + buf[2] = byte(v >> 8) + buf[3] = byte(v) + return 4 + case v < 1<<35: + buf[0] = 0xF0 | byte(v>>32) + buf[1] = byte(v >> 24) + buf[2] = byte(v >> 16) + buf[3] = byte(v >> 8) + buf[4] = byte(v) + return 5 + case v < 1<<42: + buf[0] = 0xF8 | byte(v>>40) + buf[1] = byte(v >> 32) + buf[2] = byte(v >> 24) + buf[3] = byte(v >> 16) + buf[4] = byte(v >> 8) + buf[5] = byte(v) + return 6 + case v < 1<<49: + buf[0] = 0xFC | byte(v>>48) + buf[1] = byte(v >> 40) + buf[2] = byte(v >> 32) + buf[3] = byte(v >> 24) + buf[4] = byte(v >> 16) + buf[5] = byte(v >> 8) + buf[6] = byte(v) + return 7 + case v < 1<<56: + buf[0] = 0xFE + buf[1] = byte(v >> 48) + buf[2] = byte(v >> 40) + buf[3] = byte(v >> 32) + buf[4] = byte(v >> 24) + buf[5] = byte(v >> 16) + buf[6] = byte(v >> 8) + buf[7] = byte(v) + return 8 + default: + buf[0] = 0xFF + buf[1] = byte(v >> 56) + buf[2] = byte(v >> 48) + buf[3] = byte(v >> 40) + buf[4] = byte(v >> 32) + buf[5] = byte(v >> 24) + buf[6] = byte(v >> 16) + buf[7] = byte(v >> 8) + buf[8] = byte(v) + return 9 + } +} + +// Marshal encodes the Varint to bytes. +func (v Varint) Marshal() []byte { + buf := make([]byte, v.MarshalSize()) + v.MarshalTo(buf) + return buf +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/varint/varint_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/varint/varint_test.go new file mode 100644 index 0000000000000000000000000000000000000000..20a7183ca816b706c35908da39c1c665ae86bcee --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/moq/varint/varint_test.go @@ -0,0 +1,91 @@ +package varint + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/require" +) + +var cases = []struct { + name string + enc []byte + dec Varint +}{ + { + name: "1 byte", + enc: []byte{0x00}, + dec: 0, + }, + { + name: "2 bytes", + enc: []byte{0x83, 0xe8}, + dec: 1000, + }, + { + name: "3 bytes", + enc: []byte{0xc0, 0x40, 0x00}, + dec: 16384, + }, + { + name: "4 bytes", + enc: []byte{0xe0, 0x20, 0x00, 0x00}, + dec: 2097152, + }, + { + name: "5 bytes", + enc: []byte{0xf0, 0x10, 0x00, 0x00, 0x00}, + dec: 268435456, + }, + { + name: "6 bytes", + enc: []byte{0xf8, 0x08, 0x00, 0x00, 0x00, 0x00}, + dec: 34359738368, + }, + { + name: "7 bytes", + enc: []byte{0xfc, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00}, + dec: 4398046511104, + }, + { + name: "8 bytes", + enc: []byte{0xfe, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + dec: 562949953421312, + }, + { + name: "9 bytes", + enc: []byte{0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + dec: 72057594037927936, + }, +} + +func TestRead(t *testing.T) { + for _, ca := range cases { + t.Run(ca.name, func(t *testing.T) { + var v Varint + err := v.Read(bytes.NewReader(ca.enc)) + require.NoError(t, err) + require.Equal(t, ca.dec, v) + }) + } +} + +func TestUnmarshal(t *testing.T) { + for _, ca := range cases { + t.Run(ca.name, func(t *testing.T) { + var v Varint + n, err := v.Unmarshal(ca.enc) + require.NoError(t, err) + require.Equal(t, len(ca.enc), n) + require.Equal(t, ca.dec, v) + }) + } +} + +func TestMarshal(t *testing.T) { + for _, ca := range cases { + t.Run(ca.name, func(t *testing.T) { + require.Equal(t, ca.enc, ca.dec.Marshal()) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/enhanced_reader.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/enhanced_reader.go new file mode 100644 index 0000000000000000000000000000000000000000..d099c07ea0e43e5b477c58eb8c5fd19f5866135f --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/enhanced_reader.go @@ -0,0 +1,79 @@ +package mpegts + +import ( + "io" + + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + mcmpegts "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts" + tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs" + "github.com/bluenviron/mediacommon/v2/pkg/rewindablereader" +) + +// EnhancedReader is a mpegts.Reader wrapper +// That provides additional informations that are needed in order +// to perform conversion to RTSP. +type EnhancedReader struct { + R io.Reader + + *mcmpegts.Reader + + latmConfigs map[uint16]*mpeg4audio.StreamMuxConfig +} + +// Initialize initializes EnhancedReader. +func (r *EnhancedReader) Initialize() error { + rr := &rewindablereader.Reader{R: r.R} + mr := &mcmpegts.Reader{R: rr} + err := mr.Initialize() + if err != nil { + return err + } + + r.latmConfigs = make(map[uint16]*mpeg4audio.StreamMuxConfig) + tracksToParse := 0 + + for _, track := range mr.Tracks() { + if _, ok := track.Codec.(*tscodecs.MPEG4AudioLATM); ok { + cpid := track.PID + done := false + tracksToParse++ + + mr.OnDataMPEG4AudioLATM(track, func(_ int64, els [][]byte) error { + if done { + return nil + } + + var ame mpeg4audio.AudioMuxElement + ame.MuxConfigPresent = true + err2 := ame.Unmarshal(els[0]) + if err2 != nil { + return nil //nolint:nilerr + } + + if ame.MuxConfigPresent { + r.latmConfigs[cpid] = ame.StreamMuxConfig + tracksToParse-- + done = true + } + + return nil + }) + } + } + + for tracksToParse > 0 { + err = mr.Read() + if err != nil { + return err + } + } + + rr.Rewind() + r.Reader = &mcmpegts.Reader{R: rr} + err = r.Reader.Initialize() + if err != nil { + return err + } + + return err +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/from_stream.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/from_stream.go new file mode 100644 index 0000000000000000000000000000000000000000..175dd7060ac915a9854d65f4b5af3b93ec82f372 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/from_stream.go @@ -0,0 +1,414 @@ +package mpegts + +import ( + "bufio" + "fmt" + "slices" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/ac3" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/h264" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/h265" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + mcmpegts "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts" + tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs" + "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/substructs" + srt "github.com/datarhei/gosrt" + + "github.com/bluenviron/mediamtx/internal/formatlabel" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" +) + +func multiplyAndDivide(v, m, d int64) int64 { + secs := v / d + dec := v % d + return (secs*m + dec*m/d) +} + +// FromStream maps a MediaMTX stream to a MPEG-TS writer. +func FromStream( + desc *description.Session, + r *stream.Reader, + bw *bufio.Writer, + sconn srt.Conn, + writeTimeout time.Duration, +) error { + var w *mcmpegts.Writer + var tracks []*mcmpegts.Track + + addTrack := func( + media *description.Media, + forma format.Format, + track *mcmpegts.Track, + onData stream.OnDataFunc, + ) { + tracks = append(tracks, track) + r.OnData(media, forma, onData) + } + + for _, media := range desc.Medias { + for _, forma := range media.Formats { + clockRate := forma.ClockRate() + + switch forma := forma.(type) { + case *format.H265: //nolint:dupl + track := &mcmpegts.Track{Codec: &tscodecs.H265{}} + + var dtsExtractor *h265.DTSExtractor + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + if dtsExtractor == nil { + if !h265.IsRandomAccess(u.Payload.(unit.PayloadH265)) { + return nil + } + dtsExtractor = &h265.DTSExtractor{} + dtsExtractor.Initialize() + } + + dts, err := dtsExtractor.Extract(u.Payload.(unit.PayloadH265), u.PTS) + if err != nil { + return err + } + + sconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err = (*w).WriteH265( + track, + u.PTS, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + dts, + u.Payload.(unit.PayloadH265)) + if err != nil { + return err + } + return bw.Flush() + }) + + case *format.H264: //nolint:dupl + track := &mcmpegts.Track{Codec: &tscodecs.H264{}} + + var dtsExtractor *h264.DTSExtractor + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + idrPresent := h264.IsRandomAccess(u.Payload.(unit.PayloadH264)) + + if dtsExtractor == nil { + if !idrPresent { + return nil + } + dtsExtractor = &h264.DTSExtractor{} + dtsExtractor.Initialize() + } + + dts, err := dtsExtractor.Extract(u.Payload.(unit.PayloadH264), u.PTS) + if err != nil { + return err + } + + sconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err = (*w).WriteH264( + track, + u.PTS, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + dts, + u.Payload.(unit.PayloadH264)) + if err != nil { + return err + } + return bw.Flush() + }) + + case *format.MPEG4Video: + track := &mcmpegts.Track{Codec: &tscodecs.MPEG4Video{}} + + firstReceived := false + var lastPTS int64 + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + if !firstReceived { + firstReceived = true + } else if u.PTS < lastPTS { + return fmt.Errorf("MPEG-4 Video streams with B-frames are not supported (yet)") + } + lastPTS = u.PTS + + sconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err := (*w).WriteMPEG4Video( + track, + u.PTS, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + u.Payload.(unit.PayloadMPEG4Video)) + if err != nil { + return err + } + return bw.Flush() + }) + + case *format.MPEG1Video: + track := &mcmpegts.Track{Codec: &tscodecs.MPEG1Video{}} + + firstReceived := false + var lastPTS int64 + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + if !firstReceived { + firstReceived = true + } else if u.PTS < lastPTS { + return fmt.Errorf("MPEG-1/2 Video streams with B-frames are not supported (yet)") + } + lastPTS = u.PTS + + sconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err := (*w).WriteMPEG1Video( + track, + u.PTS, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + u.Payload.(unit.PayloadMPEG1Video)) + if err != nil { + return err + } + return bw.Flush() + }) + + case *format.Opus: + track := &mcmpegts.Track{Codec: &tscodecs.Opus{ + Desc: &substructs.OpusAudioDescriptor{ + ChannelConfigCode: uint8(forma.ChannelCount), + }, + }} + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + sconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err := (*w).WriteOpus( + track, + multiplyAndDivide(u.PTS, 90000, int64(clockRate)), + u.Payload.(unit.PayloadOpus)) + if err != nil { + return err + } + return bw.Flush() + }) + + case *format.KLV: + track := &mcmpegts.Track{ + Codec: &tscodecs.KLV{ + Synchronous: true, + }, + } + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + sconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err := (*w).WriteKLV(track, multiplyAndDivide(u.PTS, 90000, 90000), u.Payload.(unit.PayloadKLV)) + if err != nil { + return err + } + return bw.Flush() + }) + + case *format.MPEG4Audio: + track := &mcmpegts.Track{Codec: &tscodecs.MPEG4Audio{ + Config: *forma.Config, + }} + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + sconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err := (*w).WriteMPEG4Audio( + track, + multiplyAndDivide(u.PTS, 90000, int64(clockRate)), + u.Payload.(unit.PayloadMPEG4Audio)) + if err != nil { + return err + } + return bw.Flush() + }) + + case *format.MPEG4AudioLATM: + track := &mcmpegts.Track{Codec: &tscodecs.MPEG4AudioLATM{}} + + if !forma.CPresent { + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + var elIn mpeg4audio.AudioMuxElement + elIn.MuxConfigPresent = false + elIn.StreamMuxConfig = forma.StreamMuxConfig + err := elIn.Unmarshal(u.Payload.(unit.PayloadMPEG4AudioLATM)) + if err != nil { + return err + } + + var elOut mpeg4audio.AudioMuxElement + elOut.MuxConfigPresent = true + elOut.StreamMuxConfig = forma.StreamMuxConfig + elOut.UseSameStreamMux = false + elOut.Payloads = elIn.Payloads + buf, err := elOut.Marshal() + if err != nil { + return err + } + + sconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err = (*w).WriteMPEG4AudioLATM( + track, + multiplyAndDivide(u.PTS, 90000, int64(clockRate)), + [][]byte{buf}) + if err != nil { + return err + } + return bw.Flush() + }) + } else { + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + sconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err := (*w).WriteMPEG4AudioLATM( + track, + multiplyAndDivide(u.PTS, 90000, int64(clockRate)), + [][]byte{u.Payload.(unit.PayloadMPEG4AudioLATM)}) + if err != nil { + return err + } + return bw.Flush() + }) + } + + case *format.MPEG1Audio: + track := &mcmpegts.Track{Codec: &tscodecs.MPEG1Audio{}} + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + sconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err := (*w).WriteMPEG1Audio( + track, + u.PTS, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + u.Payload.(unit.PayloadMPEG1Audio)) + if err != nil { + return err + } + return bw.Flush() + }) + + case *format.AC3: + track := &mcmpegts.Track{Codec: &tscodecs.AC3{}} + + addTrack( + media, + forma, + track, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + for i, frame := range u.Payload.(unit.PayloadAC3) { + framePTS := u.PTS + int64(i)*ac3.SamplesPerFrame + + sconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err := (*w).WriteAC3( + track, + multiplyAndDivide(framePTS, 90000, int64(clockRate)), + frame) + if err != nil { + return err + } + } + return bw.Flush() + }) + } + } + } + + if len(tracks) == 0 { + return errNoSupportedCodecs + } + + setuppedFormats := r.Formats() + + n := 1 + for _, medi := range desc.Medias { + for _, forma := range medi.Formats { + if !slices.Contains(setuppedFormats, forma) { + r.Parent.Log(logger.Warn, "skipping track %d (%s)", n, formatlabel.FormatToLabel(forma)) + } + n++ + } + } + + w = &mcmpegts.Writer{W: bw, Tracks: tracks} + return w.Initialize() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/from_stream_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/from_stream_test.go new file mode 100644 index 0000000000000000000000000000000000000000..883b2ab24c434a71f0a8308425374e8dc4dac2b7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/from_stream_test.go @@ -0,0 +1,59 @@ +package mpegts + +import ( + "fmt" + "testing" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestFromStreamNoSupportedCodecs(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.VP8{}}, + }}} + + r := &stream.Reader{ + Parent: test.Logger(func(logger.Level, string, ...any) { + t.Error("should not happen") + }), + } + + err := FromStream(desc, r, nil, nil, 0) + require.Equal(t, errNoSupportedCodecs, err) +} + +func TestFromStreamSkipUnsupportedTracks(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H265{}}, + }, + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.VP8{}}, + }, + }} + + n := 0 + + r := &stream.Reader{ + Parent: test.Logger(func(l logger.Level, format string, args ...any) { + require.Equal(t, logger.Warn, l) + if n == 0 { + require.Equal(t, "skipping track 2 (VP8)", fmt.Sprintf(format, args...)) + } + n++ + }), + } + + err := FromStream(desc, r, nil, nil, 0) + require.NoError(t, err) + + require.Equal(t, 1, n) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/to_stream.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/to_stream.go new file mode 100644 index 0000000000000000000000000000000000000000..fdb319918837da9aed69cb5e4d0131ee238469b0 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/to_stream.go @@ -0,0 +1,277 @@ +// Package mpegts contains MPEG-ts utilities. +package mpegts + +import ( + "errors" + "fmt" + "reflect" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts" + tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs" + + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" +) + +var errNoSupportedCodecs = errors.New( + "the stream doesn't contain any supported codec, which are currently " + + "H265, H264, MPEG-4 Video, MPEG-1/2 Video, Opus, MPEG-4 Audio, MPEG-1/2 Audio, AC-3") + +// ToStream maps a MPEG-TS stream to a MediaMTX stream. +func ToStream( + r *EnhancedReader, + subStream **stream.SubStream, + l logger.Writer, +) ([]*description.Media, error) { + var medias []*description.Media //nolint:prealloc + var unsupportedTracks []int + + td := &mpegts.TimeDecoder{} + td.Initialize() + + for i, track := range r.Tracks() { //nolint:dupl + var medi *description.Media + + switch codec := track.Codec.(type) { + case *tscodecs.H265: + medi = &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H265{ + PayloadTyp: 96, + }}, + } + + r.OnDataH265(track, func(pts int64, _ int64, au [][]byte) error { + pts = td.Decode(pts) + + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + PTS: pts, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + Payload: unit.PayloadH265(au), + }) + return nil + }) + + case *tscodecs.H264: + medi = &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + }}, + } + + r.OnDataH264(track, func(pts int64, _ int64, au [][]byte) error { + pts = td.Decode(pts) + + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + PTS: pts, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + Payload: unit.PayloadH264(au), + }) + return nil + }) + + case *tscodecs.MPEG4Video: + medi = &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.MPEG4Video{ + PayloadTyp: 96, + }}, + } + + r.OnDataMPEGxVideo(track, func(pts int64, frame []byte) error { + pts = td.Decode(pts) + + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + PTS: pts, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + Payload: unit.PayloadMPEG4Video(frame), + }) + return nil + }) + + case *tscodecs.MPEG1Video: + medi = &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.MPEG1Video{}}, + } + + r.OnDataMPEGxVideo(track, func(pts int64, frame []byte) error { + pts = td.Decode(pts) + + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + PTS: pts, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + Payload: unit.PayloadMPEG1Video(frame), + }) + return nil + }) + + case *tscodecs.Opus: + medi = &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.Opus{ + PayloadTyp: 96, + ChannelCount: codec.Desc.ChannelCount(), + }}, + } + + r.OnDataOpus(track, func(pts int64, packets [][]byte) error { + pts = td.Decode(pts) + + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + PTS: multiplyAndDivide(pts, int64(medi.Formats[0].ClockRate()), 90000), + Payload: unit.PayloadOpus(packets), + }) + return nil + }) + + case *tscodecs.KLV: + medi = &description.Media{ + Type: description.MediaTypeApplication, + Formats: []format.Format{&format.KLV{ + PayloadTyp: 96, + }}, + } + r.OnDataKLV(track, func(pts int64, uni []byte) error { + pts = td.Decode(pts) + + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + PTS: pts, + Payload: unit.PayloadKLV(uni), + }) + return nil + }) + + case *tscodecs.MPEG4Audio: + medi = &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.MPEG4Audio{ + PayloadTyp: 96, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + Config: &codec.Config, + }}, + } + + r.OnDataMPEG4Audio(track, func(pts int64, aus [][]byte) error { + pts = td.Decode(pts) + + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + PTS: multiplyAndDivide(pts, int64(medi.Formats[0].ClockRate()), 90000), + Payload: unit.PayloadMPEG4Audio(aus), + }) + return nil + }) + + case *tscodecs.MPEG4AudioLATM: + // We are dealing with a LATM stream with in-band configuration. + // Although in theory this can be streamed with RTSP (RFC6416 with cpresent=1), + // in practice there is no player that supports it. + // Therefore, convert the stream to a LATM stream with out-of-band configuration. + streamMuxConfig := r.latmConfigs[track.PID] + medi = &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.MPEG4AudioLATM{ + PayloadTyp: 96, + CPresent: false, + ProfileLevelID: 30, + StreamMuxConfig: streamMuxConfig, + }}, + } + clockRate := medi.Formats[0].ClockRate() + + r.OnDataMPEG4AudioLATM(track, func(pts int64, els [][]byte) error { + pts = td.Decode(pts) + + pts = multiplyAndDivide(pts, int64(clockRate), 90000) + + for _, el := range els { + var elIn mpeg4audio.AudioMuxElement + elIn.MuxConfigPresent = true + elIn.StreamMuxConfig = streamMuxConfig + err := elIn.Unmarshal(el) + if err != nil { + return err + } + + if !reflect.DeepEqual(elIn.StreamMuxConfig, streamMuxConfig) { + return fmt.Errorf("dynamic stream mux config is not supported") + } + + var elOut mpeg4audio.AudioMuxElement + elOut.MuxConfigPresent = false + elOut.StreamMuxConfig = streamMuxConfig + elOut.Payloads = elIn.Payloads + buf, err := elOut.Marshal() + if err != nil { + return err + } + + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + PTS: pts, + Payload: unit.PayloadMPEG4AudioLATM(buf), + }) + + pts += mpeg4audio.SamplesPerAccessUnit + } + + return nil + }) + + case *tscodecs.MPEG1Audio: + medi = &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.MPEG1Audio{}}, + } + + r.OnDataMPEG1Audio(track, func(pts int64, frames [][]byte) error { + pts = td.Decode(pts) + + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + PTS: pts, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + Payload: unit.PayloadMPEG1Audio(frames), + }) + return nil + }) + + case *tscodecs.AC3: + medi = &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.AC3{ + PayloadTyp: 96, + SampleRate: codec.SampleRate, + ChannelCount: codec.ChannelCount, + }}, + } + + r.OnDataAC3(track, func(pts int64, frame []byte) error { + pts = td.Decode(pts) + + (*subStream).WriteUnit(medi, medi.Formats[0], &unit.Unit{ + PTS: multiplyAndDivide(pts, int64(medi.Formats[0].ClockRate()), 90000), + Payload: unit.PayloadAC3{frame}, + }) + return nil + }) + + default: + unsupportedTracks = append(unsupportedTracks, i+1) + continue + } + + medias = append(medias, medi) + } + + if len(medias) == 0 { + return nil, errNoSupportedCodecs + } + + for _, id := range unsupportedTracks { + l.Log(logger.Warn, "skipping track %d (unsupported codec)", id) + } + + return medias, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/to_stream_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/to_stream_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e13107cac22025a9c8db8d9b835f6c9eb91dbe03 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/mpegts/to_stream_test.go @@ -0,0 +1,216 @@ +package mpegts + +import ( + "bytes" + "context" + "fmt" + "testing" + + "github.com/asticode/go-astits" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestToStream(t *testing.T) { + for _, ca := range []string{ + "h265", + "h264", + "mpeg-4 audio latm", + } { + t.Run(ca, func(t *testing.T) { + var buf bytes.Buffer + mux := astits.NewMuxer(context.Background(), &buf) + + switch ca { + case "h265": + err := mux.AddElementaryStream(astits.PMTElementaryStream{ + ElementaryPID: 122, + StreamType: astits.StreamTypeH265Video, + }) + require.NoError(t, err) + + mux.SetPCRPID(122) + + _, err = mux.WriteTables() + require.NoError(t, err) + + case "h264": + err := mux.AddElementaryStream(astits.PMTElementaryStream{ + ElementaryPID: 122, + StreamType: astits.StreamTypeH264Video, + }) + require.NoError(t, err) + + mux.SetPCRPID(122) + + _, err = mux.WriteTables() + require.NoError(t, err) + + case "mpeg-4 audio latm": + err := mux.AddElementaryStream(astits.PMTElementaryStream{ + ElementaryPID: 122, + StreamType: astits.StreamTypeAACLATMAudio, + }) + require.NoError(t, err) + + mux.SetPCRPID(122) + + enc1, err := mpeg4audio.AudioMuxElement{ + MuxConfigPresent: true, + StreamMuxConfig: &mpeg4audio.StreamMuxConfig{ + Programs: []*mpeg4audio.StreamMuxConfigProgram{{ + Layers: []*mpeg4audio.StreamMuxConfigLayer{{ + AudioSpecificConfig: &mpeg4audio.AudioSpecificConfig{ + Type: 2, + SampleRate: 48000, + ChannelCount: 2, + }, + LatmBufferFullness: 255, + }}, + }}, + }, + Payloads: [][][][]byte{{{{1, 2, 3, 4}}}}, + }.Marshal() + require.NoError(t, err) + + enc2, err := mpeg4audio.AudioSyncStream{ + AudioMuxElements: [][]byte{enc1}, + }.Marshal() + require.NoError(t, err) + + _, err = mux.WriteData(&astits.MuxerData{ + PID: 122, + PES: &astits.PESData{ + Header: &astits.PESHeader{ + OptionalHeader: &astits.PESOptionalHeader{ + MarkerBits: 2, + PTSDTSIndicator: astits.PTSDTSIndicatorOnlyPTS, + PTS: &astits.ClockReference{Base: 90000}, + }, + StreamID: 192, + }, + Data: enc2, + }, + }) + require.NoError(t, err) + } + + r := &EnhancedReader{R: &buf} + err := r.Initialize() + require.NoError(t, err) + + desc, err := ToStream(r, nil, nil) + require.NoError(t, err) + + switch ca { + case "h265": + require.Equal(t, []*description.Media{{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H265{ + PayloadTyp: 96, + }}, + }}, desc) + + case "h264": + require.Equal(t, []*description.Media{{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + }}, + }}, desc) + + case "mpeg-4 audio latm": + require.Equal(t, []*description.Media{{ + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.MPEG4AudioLATM{ + PayloadTyp: 96, + ProfileLevelID: 30, + StreamMuxConfig: &mpeg4audio.StreamMuxConfig{ + Programs: []*mpeg4audio.StreamMuxConfigProgram{{ + Layers: []*mpeg4audio.StreamMuxConfigLayer{{ + AudioSpecificConfig: &mpeg4audio.AudioSpecificConfig{ + Type: 2, + SampleRate: 48000, + ChannelCount: 2, + ChannelConfig: 2, + }, + LatmBufferFullness: 255, + }}, + }}, + }, + }}, + }}, desc) + } + }) + } +} + +func TestToStreamNoSupportedCodecs(t *testing.T) { + var buf bytes.Buffer + mux := astits.NewMuxer(context.Background(), &buf) + + err := mux.AddElementaryStream(astits.PMTElementaryStream{ + ElementaryPID: 122, + StreamType: astits.StreamTypeDTSAudio, + }) + require.NoError(t, err) + + mux.SetPCRPID(122) + + _, err = mux.WriteTables() + require.NoError(t, err) + + r := &EnhancedReader{R: &buf} + err = r.Initialize() + require.NoError(t, err) + + l := test.Logger(func(logger.Level, string, ...any) { + t.Error("should not happen") + }) + _, err = ToStream(r, nil, l) + require.Equal(t, errNoSupportedCodecs, err) +} + +func TestToStreamSkipUnsupportedTracks(t *testing.T) { + var buf bytes.Buffer + mux := astits.NewMuxer(context.Background(), &buf) + + err := mux.AddElementaryStream(astits.PMTElementaryStream{ + ElementaryPID: 122, + StreamType: astits.StreamTypeDTSAudio, + }) + require.NoError(t, err) + + err = mux.AddElementaryStream(astits.PMTElementaryStream{ + ElementaryPID: 123, + StreamType: astits.StreamTypeH264Video, + }) + require.NoError(t, err) + + mux.SetPCRPID(122) + + _, err = mux.WriteTables() + require.NoError(t, err) + + r := &EnhancedReader{R: &buf} + err = r.Initialize() + require.NoError(t, err) + + n := 0 + + l := test.Logger(func(l logger.Level, format string, args ...any) { + require.Equal(t, logger.Warn, l) + if n == 0 { + require.Equal(t, "skipping track 1 (unsupported codec)", fmt.Sprintf(format, args...)) + } + n++ + }) + + _, err = ToStream(r, nil, l) + require.NoError(t, err) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/proxy/listener.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/proxy/listener.go new file mode 100644 index 0000000000000000000000000000000000000000..bb70a80c733baf324d5ab1d5130471cf53dc86a1 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/proxy/listener.go @@ -0,0 +1,49 @@ +// Package proxy provides PROXY protocol support for net.Listener. +package proxy + +import ( + "net" + + "github.com/pires/go-proxyproto" + + "github.com/bluenviron/mediamtx/internal/conf" +) + +var _ net.Listener = (*Listener)(nil) + +// Listener is a net.Listener that supports PROXY protocol. +type Listener struct { + Wrapped net.Listener + TrustedProxies conf.IPNetworks + + inner *proxyproto.Listener +} + +// Initialize initializes the listener. +func (l *Listener) Initialize() { + l.inner = &proxyproto.Listener{ + Listener: l.Wrapped, + Policy: func(upstream net.Addr) (proxyproto.Policy, error) { + tcpAddr, ok := upstream.(*net.TCPAddr) + if ok && l.TrustedProxies.Contains(tcpAddr.IP) { + return proxyproto.USE, nil + } + return proxyproto.IGNORE, nil + }, + } +} + +// Close implements net.Listener. +func (l *Listener) Close() error { + return l.Wrapped.Close() +} + +// Accept implements net.Listener. +func (l *Listener) Accept() (net.Conn, error) { + return l.inner.Accept() +} + +// Addr implements net.Listener. +func (l *Listener) Addr() net.Addr { + return l.Wrapped.Addr() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/proxy/listener_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/proxy/listener_test.go new file mode 100644 index 0000000000000000000000000000000000000000..313ebe1304e66ea61cc4dbee796b6e3a5341dfc4 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/proxy/listener_test.go @@ -0,0 +1,135 @@ +package proxy + +import ( + "fmt" + "net" + "testing" + + "github.com/pires/go-proxyproto" + "github.com/stretchr/testify/require" + + "github.com/bluenviron/mediamtx/internal/conf" +) + +func trustedProxies(cidrs ...string) conf.IPNetworks { + networks := make(conf.IPNetworks, 0, len(cidrs)) + for _, cidr := range cidrs { + _, ipnet, err := net.ParseCIDR(cidr) + if err != nil { + panic(err) + } + networks = append(networks, conf.IPNetwork(*ipnet)) + } + return networks +} + +func TestListenerTrustedWithHeader(t *testing.T) { + for _, version := range []byte{1, 2} { + t.Run(fmt.Sprintf("v%d", version), func(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + defer ln.Close() + + wrapped := &Listener{Wrapped: ln, TrustedProxies: trustedProxies("127.0.0.1/32")} + wrapped.Initialize() + + done := make(chan struct{}) + + go func() { + defer close(done) + + conn, err2 := wrapped.Accept() + require.NoError(t, err2) + defer conn.Close() + + require.Equal(t, "192.168.1.100:1234", conn.RemoteAddr().String()) + }() + + clientConn, err := net.Dial("tcp", ln.Addr().String()) + require.NoError(t, err) + defer clientConn.Close() + + header := &proxyproto.Header{ + Version: version, + Command: proxyproto.PROXY, + TransportProtocol: proxyproto.TCPv4, + SourceAddr: &net.TCPAddr{IP: net.ParseIP("192.168.1.100"), Port: 1234}, + DestinationAddr: &net.TCPAddr{IP: net.ParseIP("10.0.0.1"), Port: 1935}, + } + _, err = header.WriteTo(clientConn) + require.NoError(t, err) + + <-done + }) + } +} + +func TestListenerTrustedWithoutHeader(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + defer ln.Close() + + wrapped := &Listener{Wrapped: ln, TrustedProxies: trustedProxies("127.0.0.1/32")} + wrapped.Initialize() + + done := make(chan struct{}) + + go func() { + defer close(done) + + conn, err2 := wrapped.Accept() + require.NoError(t, err2) + defer conn.Close() + + buf := make([]byte, 7) + _, err2 = conn.Read(buf) + require.NoError(t, err2) + require.Equal(t, []byte("testing"), buf) + }() + + clientConn, err := net.Dial("tcp", ln.Addr().String()) + require.NoError(t, err) + defer clientConn.Close() + + _, err = clientConn.Write([]byte("testing")) + require.NoError(t, err) + + <-done +} + +func TestListenerUntrustedIgnoresHeader(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + defer ln.Close() + + wrapped := &Listener{Wrapped: ln, TrustedProxies: trustedProxies("10.0.0.0/8")} + wrapped.Initialize() + + done := make(chan struct{}) + + go func() { + defer close(done) + + conn, err2 := wrapped.Accept() + require.NoError(t, err2) + defer conn.Close() + + require.Equal(t, "127.0.0.1", conn.RemoteAddr().(*net.TCPAddr).IP.String()) + }() + + clientConn, err := net.Dial("tcp", ln.Addr().String()) + require.NoError(t, err) + defer clientConn.Close() + + header := &proxyproto.Header{ + Version: 1, + Command: proxyproto.PROXY, + TransportProtocol: proxyproto.TCPv4, + SourceAddr: &net.TCPAddr{IP: net.ParseIP("192.168.1.100"), Port: 1234}, + DestinationAddr: &net.TCPAddr{IP: net.ParseIP("10.0.0.1"), Port: 1935}, + } + _, err = header.WriteTo(clientConn) + require.NoError(t, err) + + <-done +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/from_stream.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/from_stream.go new file mode 100644 index 0000000000000000000000000000000000000000..667ed9d0326c5896a8273dee43a2d36c867e5e53 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/from_stream.go @@ -0,0 +1,535 @@ +// Package rtmp provides RTMP utilities. +package rtmp + +import ( + "encoding/hex" + "errors" + "net" + "slices" + "strings" + "time" + + "github.com/bluenviron/gortmplib" + "github.com/bluenviron/gortmplib/pkg/codecs" + "github.com/bluenviron/gortmplib/pkg/message" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/ac3" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/flac" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/h264" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/h265" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg1audio" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/opus" + "github.com/bluenviron/mediamtx/internal/formatlabel" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" +) + +var errNoSupportedCodecsFrom = errors.New( + "the stream doesn't contain any supported codec, which are currently " + + "AV1, VP9, H265, H264, Opus, FLAC, MPEG-4 Audio (AAC), MPEG-1/2 Audio (MP3), AC-3, G711, LPCM") + +func multiplyAndDivide2(v, m, d time.Duration) time.Duration { + secs := v / d + dec := v % d + return (secs*m + dec*m/d) +} + +func timestampToDuration(t int64, clockRate int) time.Duration { + return multiplyAndDivide2(time.Duration(t), time.Second, time.Duration(clockRate)) +} + +// FromStream maps a MediaMTX stream to a RTMP stream. +func FromStream( + origDesc *description.Session, + outDesc *description.Session, + r *stream.Reader, + conn *gortmplib.ServerConn, + nconn net.Conn, + writeTimeout time.Duration, +) error { + var tracks []*gortmplib.Track + var w *gortmplib.Writer + + isEnhanced := len(conn.FourCcList) != 0 + legacyVideoTrackCount := 0 + legacyAudioTrackCount := 0 + + for i, origMedia := range origDesc.Medias { + for j, origFormat := range origMedia.Formats { + switch origFormat := origFormat.(type) { + case *format.AV1: + if slices.Contains(conn.FourCcList, any(fourCCToString(message.FourCCAV1))) { + track := &gortmplib.Track{ + Codec: &codecs.AV1{}, + } + tracks = append(tracks, track) + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + return (*w).WriteAV1( + track, + timestampToDuration(u.PTS, origFormat.ClockRate()), + u.Payload.(unit.PayloadAV1)) + }) + } + + case *format.VP9: + if slices.Contains(conn.FourCcList, any(fourCCToString(message.FourCCVP9))) { + track := &gortmplib.Track{ + Codec: &codecs.VP9{}, + } + tracks = append(tracks, track) + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + return (*w).WriteVP9( + track, + timestampToDuration(u.PTS, origFormat.ClockRate()), + u.Payload.(unit.PayloadVP9)) + }) + } + + case *format.H265: + if slices.Contains(conn.FourCcList, any(fourCCToString(message.FourCCHEVC))) { + outFormat := outDesc.Medias[i].Formats[j].(*format.H265) + + track := &gortmplib.Track{ + Codec: &codecs.H265{ + VPS: outFormat.VPS, + SPS: outFormat.SPS, + PPS: outFormat.PPS, + }, + } + tracks = append(tracks, track) + + var videoDTSExtractor *h265.DTSExtractor + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + if videoDTSExtractor == nil { + if !h265.IsRandomAccess(u.Payload.(unit.PayloadH265)) { + return nil + } + videoDTSExtractor = &h265.DTSExtractor{} + videoDTSExtractor.Initialize() + } + + dts, err := videoDTSExtractor.Extract(u.Payload.(unit.PayloadH265), u.PTS) + if err != nil { + return err + } + + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + return (*w).WriteH265( + track, + timestampToDuration(u.PTS, origFormat.ClockRate()), + timestampToDuration(dts, origFormat.ClockRate()), + u.Payload.(unit.PayloadH265)) + }) + } + + case *format.H264: + if isEnhanced || legacyVideoTrackCount == 0 { + legacyVideoTrackCount++ + + outFormat := outDesc.Medias[i].Formats[j].(*format.H264) + + track := &gortmplib.Track{ + Codec: &codecs.H264{ + SPS: outFormat.SPS, + PPS: outFormat.PPS, + }, + } + tracks = append(tracks, track) + + var videoDTSExtractor *h264.DTSExtractor + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + idrPresent := false + nonIDRPresent := false + + for _, nalu := range u.Payload.(unit.PayloadH264) { + typ := h264.NALUType(nalu[0] & 0x1F) + switch typ { + case h264.NALUTypeIDR: + idrPresent = true + + case h264.NALUTypeNonIDR: + nonIDRPresent = true + } + } + + // wait until we receive an IDR + if videoDTSExtractor == nil { + if !idrPresent { + return nil + } + + videoDTSExtractor = &h264.DTSExtractor{} + videoDTSExtractor.Initialize() + } else if !idrPresent && !nonIDRPresent { + return nil + } + + dts, err := videoDTSExtractor.Extract(u.Payload.(unit.PayloadH264), u.PTS) + if err != nil { + return err + } + + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + return (*w).WriteH264( + track, + timestampToDuration(u.PTS, origFormat.ClockRate()), + timestampToDuration(dts, origFormat.ClockRate()), + u.Payload.(unit.PayloadH264)) + }) + } + + case *format.Opus: + if slices.Contains(conn.FourCcList, any(fourCCToString(message.FourCCOpus))) { + track := &gortmplib.Track{ + Codec: &codecs.Opus{ + IDHeader: &opus.IDHeader{ + Version: 0x1, + ChannelCount: uint8(origFormat.ChannelCount), + PreSkip: 3840, + }, + }, + } + tracks = append(tracks, track) + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + pts := u.PTS + + for _, pkt := range u.Payload.(unit.PayloadOpus) { + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err := (*w).WriteOpus( + track, + timestampToDuration(pts, origFormat.ClockRate()), + pkt, + ) + if err != nil { + return err + } + + pts += opus.PacketDuration2(pkt) + } + + return nil + }) + } + + case *format.MPEG4Audio: + if isEnhanced || legacyAudioTrackCount == 0 { + legacyAudioTrackCount++ + track := &gortmplib.Track{ + Codec: &codecs.MPEG4Audio{ + Config: origFormat.Config, + }, + } + tracks = append(tracks, track) + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + for i, au := range u.Payload.(unit.PayloadMPEG4Audio) { + pts := u.PTS + int64(i)*mpeg4audio.SamplesPerAccessUnit + + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err := (*w).WriteMPEG4Audio( + track, + timestampToDuration(pts, origFormat.ClockRate()), + au, + ) + if err != nil { + return err + } + } + + return nil + }) + } + + case *format.MPEG4AudioLATM: + if !origFormat.CPresent && (isEnhanced || legacyAudioTrackCount == 0) { + legacyAudioTrackCount++ + track := &gortmplib.Track{ + Codec: &codecs.MPEG4Audio{ + Config: origFormat.StreamMuxConfig.Programs[0].Layers[0].AudioSpecificConfig, + }, + } + tracks = append(tracks, track) + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + var ame mpeg4audio.AudioMuxElement + ame.StreamMuxConfig = origFormat.StreamMuxConfig + err := ame.Unmarshal(u.Payload.(unit.PayloadMPEG4AudioLATM)) + if err != nil { + return err + } + + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + return (*w).WriteMPEG4Audio( + track, + timestampToDuration(u.PTS, origFormat.ClockRate()), + ame.Payloads[0][0][0], + ) + }) + } + + case *format.MPEG1Audio: + if isEnhanced || legacyAudioTrackCount == 0 { + legacyAudioTrackCount++ + track := &gortmplib.Track{ + Codec: &codecs.MPEG1Audio{}, + } + tracks = append(tracks, track) + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + pts := u.PTS + + for _, frame := range u.Payload.(unit.PayloadMPEG1Audio) { + var h mpeg1audio.FrameHeader + err := h.Unmarshal(frame) + if err != nil { + return err + } + + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err = (*w).WriteMPEG1Audio( + track, + timestampToDuration(pts, origFormat.ClockRate()), + frame) + if err != nil { + return err + } + + pts += int64(h.SampleCount()) * + int64(origFormat.ClockRate()) / int64(h.SampleRate) + } + + return nil + }) + } + + case *format.AC3: + if slices.Contains(conn.FourCcList, any(fourCCToString(message.FourCCAC3))) { + track := &gortmplib.Track{ + Codec: &codecs.AC3{ + SampleRate: origFormat.SampleRate, + ChannelCount: origFormat.ChannelCount, + }, + } + tracks = append(tracks, track) + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + for i, frame := range u.Payload.(unit.PayloadAC3) { + pts := u.PTS + int64(i)*ac3.SamplesPerFrame + + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + err := (*w).WriteAC3( + track, + timestampToDuration(pts, origFormat.ClockRate()), + frame) + if err != nil { + return err + } + } + + return nil + }) + } + + case *format.G711: + if origFormat.SampleRate == 8000 && (isEnhanced || legacyAudioTrackCount == 0) { + legacyAudioTrackCount++ + track := &gortmplib.Track{ + Codec: &codecs.G711{ + MULaw: origFormat.MULaw, + ChannelCount: origFormat.ChannelCount, + }, + } + tracks = append(tracks, track) + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + return (*w).WriteG711( + track, + timestampToDuration(u.PTS, origFormat.ClockRate()), + u.Payload.(unit.PayloadG711), + ) + }) + } + + case *format.LPCM: + if (origFormat.ChannelCount == 1 || origFormat.ChannelCount == 2) && + (origFormat.SampleRate == 5512 || + origFormat.SampleRate == 11025 || + origFormat.SampleRate == 22050 || + origFormat.SampleRate == 44100) && + (isEnhanced || legacyAudioTrackCount == 0) { + legacyAudioTrackCount++ + track := &gortmplib.Track{ + Codec: &codecs.LPCM{ + BitDepth: origFormat.BitDepth, + SampleRate: origFormat.SampleRate, + ChannelCount: origFormat.ChannelCount, + }, + } + tracks = append(tracks, track) + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + return (*w).WriteLPCM( + track, + timestampToDuration(u.PTS, origFormat.ClockRate()), + u.Payload.(unit.PayloadLPCM), + ) + }) + } + + case *format.Generic: + if strings.HasPrefix(strings.ToLower(origFormat.RTPMap()), "flac/") && + slices.Contains(conn.FourCcList, any(fourCCToString(message.FourCCFLAC))) { + enc, err := hex.DecodeString(origFormat.FMT["streaminfo"]) + if err != nil { + return err + } + + var streamInfo flac.StreamInfo + err = streamInfo.Unmarshal(enc) + if err != nil { + return err + } + + track := &gortmplib.Track{ + Codec: &codecs.FLAC{ + StreamInfo: &streamInfo, + }, + } + tracks = append(tracks, track) + + r.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + nconn.SetWriteDeadline(time.Now().Add(writeTimeout)) + return (*w).WriteFLAC( + track, + timestampToDuration(u.PTS, origFormat.ClockRate()), + u.Payload.(unit.PayloadFLAC), + ) + }) + } + } + } + } + + if len(tracks) == 0 { + return errNoSupportedCodecsFrom + } + + w = &gortmplib.Writer{ + Conn: conn, + Tracks: tracks, + } + err := w.Initialize() + if err != nil { + return err + } + + setuppedFormats := r.Formats() + + n := 1 + for _, origMedia := range origDesc.Medias { + for _, origFormat := range origMedia.Formats { + if !slices.Contains(setuppedFormats, origFormat) { + r.Parent.Log(logger.Warn, "skipping track %d (%s)", n, formatlabel.FormatToLabel(origFormat)) + } + n++ + } + } + + return nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/from_stream_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/from_stream_test.go new file mode 100644 index 0000000000000000000000000000000000000000..405b0ba0eec0bc5abaaccbf3f1bc8db04da417bb --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/from_stream_test.go @@ -0,0 +1,920 @@ +package rtmp + +import ( + "context" + "encoding/hex" + "fmt" + "net" + "net/url" + "testing" + "time" + + "github.com/bluenviron/gortmplib" + "github.com/bluenviron/gortmplib/pkg/codecs" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/flac" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/opus" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/stretchr/testify/require" +) + +var ( + h265DefaultVPS = []byte{ + 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x02, 0x20, + 0x00, 0x00, 0x03, 0x00, 0xb0, 0x00, 0x00, 0x03, + 0x00, 0x00, 0x03, 0x00, 0x7b, 0x18, 0xb0, 0x24, + } + + h265DefaultSPS = []byte{ + 0x42, 0x01, 0x01, 0x02, 0x20, 0x00, 0x00, 0x03, + 0x00, 0xb0, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, + 0x00, 0x7b, 0xa0, 0x07, 0x82, 0x00, 0x88, 0x7d, + 0xb6, 0x71, 0x8b, 0x92, 0x44, 0x80, 0x53, 0x88, + 0x88, 0x92, 0xcf, 0x24, 0xa6, 0x92, 0x72, 0xc9, + 0x12, 0x49, 0x22, 0xdc, 0x91, 0xaa, 0x48, 0xfc, + 0xa2, 0x23, 0xff, 0x00, 0x01, 0x00, 0x01, 0x6a, + 0x02, 0x02, 0x02, 0x01, + } + + h265DefaultPPS = []byte{ + 0x44, 0x01, 0xc0, 0x25, 0x2f, 0x05, 0x32, 0x40, + } + + h264DefaultSPS = []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, + } + + h264DefaultPPS = []byte{0x08, 0x06, 0x07, 0x08} +) + +func TestFromStream(t *testing.T) { + h265VPS := []byte{ + 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x01, 0x60, + 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, + 0x00, 0x00, 0x03, 0x00, 0x78, 0xba, 0x02, 0x40, + } + h265SPS := []byte{ + 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, + 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, + 0x00, 0x78, 0xa0, 0x03, 0xc0, 0x80, 0x11, 0x07, + 0xcb, 0x96, 0xe9, 0x29, 0x30, 0xbc, 0x05, 0xa0, + 0x20, 0x00, 0x00, 0x03, 0x00, 0x20, 0x00, 0x00, + 0x03, 0x03, 0xc1, + } + h265PPS := []byte{ + 0x44, 0x01, 0xc0, 0x73, 0xc1, 0x89, + } + + cases := []struct { + name string + medias []*description.Media + expectedTracks []*gortmplib.Track + writeUnits func([]*description.Media, *stream.SubStream) + }{ + { + name: "h264 + aac", + medias: []*description.Media{ + { + Formats: []format.Format{test.FormatH264}, + }, + { + Formats: []format.Format{test.FormatMPEG4Audio}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }}, + {Codec: &codecs.MPEG4Audio{ + Config: test.FormatMPEG4Audio.Config, + }}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 0, + Payload: unit.PayloadH264{ + {5, 2}, // IDR + }, + }) + + subStream.WriteUnit(medias[1], medias[1].Formats[0], &unit.Unit{ + PTS: 90000 * 5, + Payload: unit.PayloadMPEG4Audio{ + {3, 4}, + }, + }) + }, + }, + { + name: "av1", + medias: []*description.Media{ + { + Formats: []format.Format{&format.AV1{ + PayloadTyp: 96, + }}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.AV1{}}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 2 * int64(i), + Payload: unit.PayloadAV1{{ + 0x0a, 0x0e, 0x00, 0x00, 0x00, 0x4a, 0xab, 0xbf, + 0xc3, 0x77, 0x6b, 0xe4, 0x40, 0x40, 0x40, 0x41, + }}, + }) + } + }, + }, + { + name: "vp9", + medias: []*description.Media{ + { + Formats: []format.Format{&format.VP9{ + PayloadTyp: 96, + }}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.VP9{}}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 2 * int64(i), + Payload: unit.PayloadVP9{1, 2}, + }) + } + }, + }, + { + name: "h265", + medias: []*description.Media{ + { + Formats: []format.Format{ + &format.H265{ + PayloadTyp: 96, + VPS: h265VPS, + SPS: h265SPS, + PPS: h265PPS, + }, + }, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.H265{ + VPS: h265VPS, + SPS: h265SPS, + PPS: h265PPS, + }}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 2 * int64(i), + Payload: unit.PayloadH265{{ + 0x2a, 0x01, 0xad, 0xe0, 0xf5, 0x34, 0x11, 0x0b, + 0x41, 0xe8, + }}, + }) + } + }, + }, + { + name: "h264", + medias: []*description.Media{ + { + Formats: []format.Format{test.FormatH264}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 2 * int64(i), + Payload: unit.PayloadH264{ + {5, 2}, // IDR + }, + }) + } + }, + }, + { + name: "opus", + medias: []*description.Media{ + { + Formats: []format.Format{&format.Opus{ + PayloadTyp: 96, + ChannelCount: 2, + }}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.Opus{ + IDHeader: &opus.IDHeader{ + Version: 0x1, + ChannelCount: 2, + PreSkip: 3840, + ChannelMappingTable: []uint8{}, + }, + }}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 5 * int64(i), + Payload: unit.PayloadOpus{ + {3, 4}, + }, + }) + } + }, + }, + { + name: "aac", + medias: []*description.Media{ + { + Formats: []format.Format{test.FormatMPEG4Audio}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.MPEG4Audio{ + Config: test.FormatMPEG4Audio.Config, + }}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 5 * int64(i), + Payload: unit.PayloadMPEG4Audio{ + {3, 4}, + }, + }) + } + }, + }, + { + name: "mp3", + medias: []*description.Media{ + { + Formats: []format.Format{&format.MPEG1Audio{}}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.MPEG1Audio{}}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 5 * int64(i), + Payload: unit.PayloadMPEG1Audio{ + { + 0xff, 0xfa, 0x52, 0x04, 0x00, + }, + }, + }) + } + }, + }, + { + name: "ac-3", + medias: []*description.Media{ + { + Formats: []format.Format{&format.AC3{ + SampleRate: 44100, + ChannelCount: 2, + }}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.AC3{ + SampleRate: 48000, + ChannelCount: 1, + }}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 5 * int64(i), + Payload: unit.PayloadAC3{ + { + 0x0b, 0x77, 0x47, 0x11, 0x0c, 0x40, 0x2f, 0x84, + 0x2b, 0xc1, 0x07, 0x7a, 0xb0, 0xfa, 0xbb, 0xea, + 0xef, 0x9f, 0x57, 0x7c, 0xf9, 0xf3, 0xf7, 0xcf, + 0x9f, 0x3e, 0x32, 0xfe, 0xd5, 0xc1, 0x50, 0xde, + 0xc5, 0x1e, 0x73, 0xd2, 0x6c, 0xa6, 0x94, 0x46, + 0x4e, 0x92, 0x8c, 0x0f, 0xb9, 0xcf, 0xad, 0x07, + 0x54, 0x4a, 0x2e, 0xf3, 0x7d, 0x07, 0x2e, 0xa4, + 0x2f, 0xba, 0xbf, 0x39, 0xb5, 0xc9, 0x92, 0xa6, + 0xe1, 0xb4, 0x70, 0xc5, 0xc4, 0xb5, 0xe6, 0x5d, + 0x0f, 0xa8, 0x71, 0xa4, 0xcc, 0xc5, 0xbc, 0x75, + 0x67, 0x92, 0x52, 0x4f, 0x7e, 0x62, 0x1c, 0xa9, + 0xd9, 0xb5, 0x19, 0x6a, 0xd7, 0xb0, 0x44, 0x92, + 0x30, 0x3b, 0xf7, 0x61, 0xd6, 0x49, 0x96, 0x66, + 0x98, 0x28, 0x1a, 0x95, 0xa9, 0x42, 0xad, 0xb7, + 0x50, 0x90, 0xad, 0x1c, 0x34, 0x80, 0xe2, 0xef, + 0xcd, 0x41, 0x0b, 0xf0, 0x9d, 0x57, 0x62, 0x78, + 0xfd, 0xc6, 0xc2, 0x19, 0x9e, 0x26, 0x31, 0xca, + 0x1e, 0x75, 0xb1, 0x7a, 0x8e, 0xb5, 0x51, 0x3a, + 0xfe, 0xe4, 0xf1, 0x0b, 0x4f, 0x14, 0x90, 0xdb, + 0x9f, 0x44, 0x50, 0xbb, 0xef, 0x74, 0x00, 0x8c, + 0x1f, 0x97, 0xa1, 0xa2, 0xfa, 0x72, 0x16, 0x47, + 0xc6, 0xc0, 0xe5, 0xfe, 0x67, 0x03, 0x9c, 0xfe, + 0x62, 0x01, 0xa1, 0x00, 0x5d, 0xff, 0xa5, 0x03, + 0x59, 0xfa, 0xa8, 0x25, 0x5f, 0x6b, 0x83, 0x51, + 0xf2, 0xc0, 0x44, 0xff, 0x2d, 0x05, 0x4b, 0xee, + 0xe0, 0x54, 0x9e, 0xae, 0x86, 0x45, 0xf3, 0xbd, + 0x0e, 0x42, 0xf2, 0xbf, 0x0f, 0x7f, 0xc6, 0x09, + 0x07, 0xdc, 0x22, 0x11, 0x77, 0xbe, 0x31, 0x27, + 0x5b, 0xa4, 0x13, 0x47, 0x07, 0x32, 0x9f, 0x1f, + 0xcb, 0xb0, 0xdf, 0x3e, 0x7d, 0x0d, 0xf3, 0xe7, + 0xcf, 0x9f, 0x3e, 0xae, 0xf9, 0xf3, 0xe7, 0xcf, + 0x9f, 0x3e, 0x85, 0x5d, 0xf3, 0xe7, 0xcf, 0x9f, + 0x3e, 0x7c, 0xf9, 0xf3, 0xe7, 0xcf, 0x9f, 0x3f, + 0x53, 0x5d, 0xf3, 0xe7, 0xcf, 0x9f, 0x3e, 0x7c, + 0xf9, 0xf3, 0xe7, 0xcf, 0x9f, 0x3e, 0x7c, 0xf9, + 0xf3, 0xe7, 0xcf, 0x9f, 0x3e, 0x7c, 0xf9, 0xf3, + 0xe7, 0xcf, 0x9f, 0x3e, 0x00, 0x46, 0x28, 0x26, + 0x20, 0x4a, 0x5a, 0xc0, 0x8a, 0xc5, 0xae, 0xa0, + 0x55, 0x78, 0x82, 0x7a, 0x38, 0x10, 0x09, 0xc9, + 0xb8, 0x0c, 0xfa, 0x5b, 0xc9, 0xd2, 0xec, 0x44, + 0x25, 0xf8, 0x20, 0xf2, 0xc8, 0x8a, 0xe9, 0x40, + 0x18, 0x06, 0xc6, 0x2b, 0xc8, 0xed, 0x8f, 0x33, + 0x09, 0x92, 0x28, 0x1e, 0xc4, 0x24, 0xd8, 0x33, + 0xa5, 0x00, 0xf5, 0xea, 0x18, 0xfa, 0x90, 0x97, + 0x97, 0xe8, 0x39, 0x6a, 0xcf, 0xf1, 0xdd, 0xff, + 0x9e, 0x8e, 0x04, 0x02, 0xae, 0x65, 0x87, 0x5c, + 0x4e, 0x72, 0xfd, 0x3c, 0x01, 0x86, 0xfe, 0x56, + 0x59, 0x74, 0x44, 0x3a, 0x40, 0x00, 0xec, 0xfc, + }, + }, + }) + } + }, + }, + { + name: "pcma", + medias: []*description.Media{ + { + Formats: []format.Format{&format.G711{ + MULaw: false, + SampleRate: 8000, + ChannelCount: 1, + }}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.G711{ + MULaw: false, + ChannelCount: 1, + }}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 5 * int64(i), + Payload: unit.PayloadG711{ + 3, 4, + }, + }) + } + }, + }, + { + name: "pcmu", + medias: []*description.Media{ + { + Formats: []format.Format{&format.G711{ + MULaw: true, + SampleRate: 8000, + ChannelCount: 1, + }}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.G711{ + MULaw: true, + ChannelCount: 1, + }}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 5 * int64(i), + Payload: unit.PayloadG711{ + 3, 4, + }, + }) + } + }, + }, + { + name: "lpcm", + medias: []*description.Media{ + { + Formats: []format.Format{&format.LPCM{ + BitDepth: 16, + SampleRate: 44100, + ChannelCount: 2, + }}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.LPCM{ + BitDepth: 16, + SampleRate: 44100, + ChannelCount: 2, + }}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 5 * int64(i), + Payload: unit.PayloadLPCM{ + 3, 4, 5, 6, + }, + }) + } + }, + }, + { + name: "flac", + medias: []*description.Media{ + { + Formats: []format.Format{&format.Generic{ + PayloadTyp: 96, + RTPMa: "FLAC/90000", + ClockRat: 90000, + FMT: map[string]string{ + "streaminfo": func() string { + si := &flac.StreamInfo{ + SampleRate: 44100, + ChannelCount: 2, + BitDepth: 16, + } + enc, err := si.Marshal() + require.NoError(t, err) + + return hex.EncodeToString(enc) + }(), + }, + }}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.FLAC{ + StreamInfo: &flac.StreamInfo{ + SampleRate: 44100, + ChannelCount: 2, + BitDepth: 16, + }, + }}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + for i := range 2 { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 90000 * 5 * int64(i), + Payload: unit.PayloadFLAC{3, 4}, + }) + } + }, + }, + { + name: "h265 + h264 + vp9 + av1 + opus + aac", + medias: []*description.Media{ + { + Formats: []format.Format{&format.H265{}}, + }, + { + Formats: []format.Format{&format.H264{PacketizationMode: 1}}, + }, + { + Formats: []format.Format{&format.VP9{}}, + }, + { + Formats: []format.Format{&format.AV1{}}, + }, + { + Formats: []format.Format{&format.Opus{ + PayloadTyp: 96, + ChannelCount: 2, + }}, + }, + { + Formats: []format.Format{&format.MPEG4Audio{ + PayloadTyp: 96, + Config: test.FormatMPEG4Audio.Config, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + }}, + }, + }, + expectedTracks: []*gortmplib.Track{ + {Codec: &codecs.H265{ + VPS: h265DefaultVPS, + SPS: h265DefaultSPS, + PPS: h265DefaultPPS, + }}, + {Codec: &codecs.H264{ + SPS: h264DefaultSPS, + PPS: h264DefaultPPS, + }}, + {Codec: &codecs.VP9{}}, + {Codec: &codecs.AV1{}}, + {Codec: &codecs.Opus{ + IDHeader: &opus.IDHeader{ + Version: 0x1, + ChannelCount: 2, + PreSkip: 3840, + ChannelMappingTable: []uint8{}, + }, + }}, + {Codec: &codecs.MPEG4Audio{ + Config: test.FormatMPEG4Audio.Config, + }}, + }, + writeUnits: func(medias []*description.Media, subStream *stream.SubStream) { + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + Payload: unit.PayloadH265{ + { + 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x01, 0x60, + 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, + 0x00, 0x00, 0x03, 0x00, 0x78, 0xba, 0x02, 0x40, + }, + { + 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, + 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, + 0x00, 0x78, 0xa0, 0x03, 0xc0, 0x80, 0x11, 0x07, + 0xcb, 0x96, 0xe9, 0x29, 0x30, 0xbc, 0x05, 0xa0, + 0x20, 0x00, 0x00, 0x03, 0x00, 0x20, 0x00, 0x00, + 0x03, 0x03, 0xc1, + }, + { + 0x44, 0x01, 0xc0, 0x73, 0xc1, 0x89, + }, + { + 0x2a, 0x01, 0xad, 0xe0, 0xf5, 0x34, 0x11, 0x0b, + 0x41, 0xe8, + }, + }, + }) + + subStream.WriteUnit(medias[1], medias[1].Formats[0], &unit.Unit{ + Payload: unit.PayloadH264{ + h264DefaultSPS, + h264DefaultPPS, + {5, 2}, // IDR + }, + }) + + subStream.WriteUnit(medias[2], medias[2].Formats[0], &unit.Unit{ + Payload: unit.PayloadVP9{1, 2}, + }) + + subStream.WriteUnit(medias[3], medias[3].Formats[0], &unit.Unit{ + Payload: unit.PayloadAV1{{ + 0x0a, 0x0e, 0x00, 0x00, 0x00, 0x4a, 0xab, 0xbf, + 0xc3, 0x77, 0x6b, 0xe4, 0x40, 0x40, 0x40, 0x41, + }}, + }) + + subStream.WriteUnit(medias[4], medias[4].Formats[0], &unit.Unit{ + Payload: unit.PayloadOpus{ + {3, 4}, + }, + }) + + subStream.WriteUnit(medias[5], medias[5].Formats[0], &unit.Unit{ + PTS: 90000 * 5, + Payload: unit.PayloadMPEG4Audio{ + {3, 4}, + }, + }) + }, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + medias := tc.medias + + strm := &stream.Stream{ + OrigDesc: &description.Session{Medias: medias}, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + ln, err := net.Listen("tcp", "127.0.0.1:9121") + require.NoError(t, err) + defer ln.Close() + + done := make(chan struct{}) + + go func() { + u, err2 := url.Parse("rtmp://127.0.0.1:9121/stream") + require.NoError(t, err2) + + c := &gortmplib.Client{ + URL: u, + } + err2 = c.Initialize(context.Background()) + require.NoError(t, err2) + + r := &gortmplib.Reader{ + Conn: c, + } + err2 = r.Initialize() + require.NoError(t, err2) + + require.Equal(t, tc.expectedTracks, r.Tracks()) + + close(done) + }() + + nconn, err := ln.Accept() + require.NoError(t, err) + defer nconn.Close() + + conn := &gortmplib.ServerConn{ + RW: nconn, + } + err = conn.Initialize() + require.NoError(t, err) + + err = conn.Accept() + require.NoError(t, err) + + r := &stream.Reader{Parent: test.NilLogger} + + err = FromStream(strm.OrigDesc, strm.OutDescCopy(), r, conn, nconn, 10*time.Second) + require.NoError(t, err) + + strm.AddReader(r) + defer strm.RemoveReader(r) + + tc.writeUnits(medias, subStream) + + <-done + }) + } +} + +func TestFromStreamLegacyClientMultipleTracks(t *testing.T) { + // Test that legacy RTMP clients (without enhanced RTMP) + // only receive one H264 track and one MPEG4-audio track + // when multiple tracks of each type are available + + h264SPS1 := []byte{ + 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, + } + h264PPS1 := []byte{0x08, 0x06, 0x07, 0x08} + + h264SPS2 := []byte{ + 0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02, + 0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04, + 0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, 0x21, + } + h264PPS2 := []byte{0x08, 0x06, 0x07, 0x09} + + aacConfig1 := test.FormatMPEG4Audio.Config + aacConfig2 := &mpeg4audio.AudioSpecificConfig{ + Type: 2, // MPEG4-AAC LC + SampleRate: 48000, + ChannelCount: 2, + ChannelConfig: 2, + } + + medias := []*description.Media{ + { + Formats: []format.Format{&format.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + SPS: h264SPS1, + PPS: h264PPS1, + }}, + }, + { + Formats: []format.Format{&format.H264{ + PayloadTyp: 97, + PacketizationMode: 1, + SPS: h264SPS2, + PPS: h264PPS2, + }}, + }, + { + Formats: []format.Format{&format.MPEG4Audio{ + PayloadTyp: 98, + Config: aacConfig1, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + }}, + }, + { + Formats: []format.Format{&format.MPEG4Audio{ + PayloadTyp: 99, + Config: aacConfig2, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + }}, + }, + } + + strm := &stream.Stream{ + OrigDesc: &description.Session{Medias: medias}, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + ln, err := net.Listen("tcp", "127.0.0.1:9121") + require.NoError(t, err) + defer ln.Close() + + done := make(chan struct{}) + + go func() { + u, err2 := url.Parse("rtmp://127.0.0.1:9121/stream") + require.NoError(t, err2) + + c := &gortmplib.Client{ + URL: u, + } + err2 = c.Initialize(context.Background()) + require.NoError(t, err2) + + r := &gortmplib.Reader{ + Conn: c, + } + err2 = r.Initialize() + require.NoError(t, err2) + + require.Equal(t, []*gortmplib.Track{ + {Codec: &codecs.H264{ + SPS: h264SPS1, + PPS: h264PPS1, + }}, + {Codec: &codecs.MPEG4Audio{ + Config: aacConfig1, + }}, + }, r.Tracks()) + + close(done) + }() + + nconn, err := ln.Accept() + require.NoError(t, err) + defer nconn.Close() + + conn := &gortmplib.ServerConn{ + RW: nconn, + } + err = conn.Initialize() + require.NoError(t, err) + + err = conn.Accept() + require.NoError(t, err) + + // Simulate a legacy client by clearing the FourCcList + conn.FourCcList = []any{} + + r := &stream.Reader{Parent: test.NilLogger} + + err = FromStream(strm.OrigDesc, strm.OutDescCopy(), r, conn, nconn, 10*time.Second) + require.NoError(t, err) + + strm.AddReader(r) + defer strm.RemoveReader(r) + + // Write units to trigger track setup + subStream.WriteUnit(medias[0], medias[0].Formats[0], &unit.Unit{ + PTS: 0, + Payload: unit.PayloadH264{ + {5, 1}, // IDR + }, + }) + + subStream.WriteUnit(medias[2], medias[2].Formats[0], &unit.Unit{ + PTS: 90000, + Payload: unit.PayloadMPEG4Audio{ + {3, 4}, + }, + }) + + <-done +} + +func TestFromStreamNoSupportedCodecs(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.VP8{}}, + }}} + + r := &stream.Reader{ + Parent: test.Logger(func(logger.Level, string, ...any) { + t.Error("should not happen") + }), + } + + conn := &gortmplib.ServerConn{} + + err := FromStream(desc, desc, r, conn, nil, 0) + require.Equal(t, errNoSupportedCodecsFrom, err) +} + +func TestFromStreamSkipUnsupportedTracks(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.VP8{}}, + }, + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H264{PacketizationMode: 1}}, + }, + }} + + n := 0 + + r := &stream.Reader{ + Parent: test.Logger(func(l logger.Level, format string, args ...any) { + require.Equal(t, logger.Warn, l) + if n == 0 { + require.Equal(t, "skipping track 1 (VP8)", fmt.Sprintf(format, args...)) + } + n++ + }), + } + + ln, err := net.Listen("tcp", "127.0.0.1:9121") + require.NoError(t, err) + defer ln.Close() + + go func() { + u, err2 := url.Parse("rtmp://127.0.0.1:9121/stream") + require.NoError(t, err2) + + c := &gortmplib.Client{ + URL: u, + } + err2 = c.Initialize(context.Background()) + require.NoError(t, err2) + }() + + nconn, err := ln.Accept() + require.NoError(t, err) + defer nconn.Close() + + conn := &gortmplib.ServerConn{ + RW: nconn, + } + err = conn.Initialize() + require.NoError(t, err) + + err = conn.Accept() + require.NoError(t, err) + + err = FromStream(desc, desc, r, conn, nil, 0) + require.NoError(t, err) + + require.Equal(t, 1, n) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/to_stream.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/to_stream.go new file mode 100644 index 0000000000000000000000000000000000000000..3e91adeb0fea48b3426be607859cd67a25baec8b --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/to_stream.go @@ -0,0 +1,280 @@ +package rtmp + +import ( + "encoding/hex" + "errors" + "strconv" + "time" + + "github.com/bluenviron/gortmplib" + "github.com/bluenviron/gortmplib/pkg/codecs" + "github.com/bluenviron/gortmplib/pkg/message" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" +) + +var errNoSupportedCodecsTo = errors.New( + "the stream doesn't contain any supported codec, which are currently " + + "AV1, VP9, H265, H264, Opus, FLAC, MPEG-4 Audio (AAC), MPEG-1/2 Audio (MP3), AC-3, G711, LPCM") + +func multiplyAndDivide(v, m, d int64) int64 { + secs := v / d + dec := v % d + return (secs*m + dec*m/d) +} + +func durationToTimestamp(d time.Duration, clockRate int) int64 { + return multiplyAndDivide(int64(d), int64(clockRate), int64(time.Second)) +} + +func fourCCToString(c message.FourCC) string { + return string([]byte{byte(c >> 24), byte(c >> 16), byte(c >> 8), byte(c)}) +} + +// ToStream maps a RTMP stream to a MediaMTX stream. +func ToStream( + r *gortmplib.Reader, + subStream **stream.SubStream, +) ([]*description.Media, error) { + var medias []*description.Media + + for _, track := range r.Tracks() { + switch codec := track.Codec.(type) { + case *codecs.AV1: + forma := &format.AV1{ + PayloadTyp: 96, + } + medi := &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{forma}, + } + medias = append(medias, medi) + + r.OnDataAV1(track, func(pts time.Duration, tu [][]byte) { + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: durationToTimestamp(pts, forma.ClockRate()), + Payload: unit.PayloadAV1(tu), + }) + }) + + case *codecs.VP9: + forma := &format.VP9{ + PayloadTyp: 96, + } + medi := &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{forma}, + } + medias = append(medias, medi) + + r.OnDataVP9(track, func(pts time.Duration, frame []byte) { + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: durationToTimestamp(pts, forma.ClockRate()), + Payload: unit.PayloadVP9(frame), + }) + }) + + case *codecs.H265: + forma := &format.H265{ + PayloadTyp: 96, + VPS: codec.VPS, + SPS: codec.SPS, + PPS: codec.PPS, + } + medi := &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{forma}, + } + medias = append(medias, medi) + + r.OnDataH265(track, func(pts time.Duration, _ time.Duration, au [][]byte) { + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: durationToTimestamp(pts, forma.ClockRate()), + Payload: unit.PayloadH265(au), + }) + }) + + case *codecs.H264: + forma := &format.H264{ + PayloadTyp: 96, + SPS: codec.SPS, + PPS: codec.PPS, + PacketizationMode: 1, + } + medi := &description.Media{ + Type: description.MediaTypeVideo, + Formats: []format.Format{forma}, + } + medias = append(medias, medi) + + r.OnDataH264(track, func(pts time.Duration, _ time.Duration, au [][]byte) { + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: durationToTimestamp(pts, forma.ClockRate()), + Payload: unit.PayloadH264(au), + }) + }) + + case *codecs.Opus: + channelCount := 2 + if codec.IDHeader != nil { + channelCount = int(codec.IDHeader.ChannelCount) + } + forma := &format.Opus{ + PayloadTyp: 96, + ChannelCount: channelCount, + } + medi := &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{forma}, + } + medias = append(medias, medi) + + r.OnDataOpus(track, func(pts time.Duration, packet []byte) { + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: durationToTimestamp(pts, forma.ClockRate()), + Payload: unit.PayloadOpus{packet}, + }) + }) + + case *codecs.FLAC: + enc, err := codec.StreamInfo.Marshal() + if err != nil { + return nil, err + } + + sampleRate := int(codec.StreamInfo.SampleRate) + forma := &format.Generic{ + PayloadTyp: 96, + RTPMa: "flac/" + strconv.Itoa(sampleRate), + ClockRat: sampleRate, + FMT: map[string]string{ + "streaminfo": hex.EncodeToString(enc), + }, + } + medi := &description.Media{ + Type: description.MediaTypeApplication, + Formats: []format.Format{forma}, + } + medias = append(medias, medi) + + r.OnDataFLAC(track, func(pts time.Duration, frame []byte) { + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: durationToTimestamp(pts, sampleRate), + Payload: unit.PayloadFLAC(frame), + }) + }) + + case *codecs.MPEG4Audio: + forma := &format.MPEG4Audio{ + PayloadTyp: 96, + Config: codec.Config, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + } + medi := &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{forma}, + } + medias = append(medias, medi) + + r.OnDataMPEG4Audio(track, func(pts time.Duration, au []byte) { + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: durationToTimestamp(pts, forma.ClockRate()), + Payload: unit.PayloadMPEG4Audio{au}, + }) + }) + + case *codecs.MPEG1Audio: + forma := &format.MPEG1Audio{} + medi := &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{forma}, + } + medias = append(medias, medi) + + r.OnDataMPEG1Audio(track, func(pts time.Duration, frame []byte) { + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: durationToTimestamp(pts, forma.ClockRate()), + Payload: unit.PayloadMPEG1Audio{frame}, + }) + }) + + case *codecs.AC3: + forma := &format.AC3{ + PayloadTyp: 96, + SampleRate: codec.SampleRate, + ChannelCount: codec.ChannelCount, + } + medi := &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{forma}, + } + medias = append(medias, medi) + + r.OnDataAC3(track, func(pts time.Duration, frame []byte) { + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: durationToTimestamp(pts, forma.ClockRate()), + Payload: unit.PayloadAC3{frame}, + }) + }) + + case *codecs.G711: + forma := &format.G711{ + PayloadTyp: func() uint8 { + switch { + case codec.ChannelCount == 1 && codec.MULaw: + return 0 + case codec.ChannelCount == 1 && !codec.MULaw: + return 8 + default: + return 96 + } + }(), + MULaw: codec.MULaw, + SampleRate: 8000, + ChannelCount: codec.ChannelCount, + } + medi := &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{forma}, + } + medias = append(medias, medi) + + r.OnDataG711(track, func(pts time.Duration, samples []byte) { + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: durationToTimestamp(pts, forma.ClockRate()), + Payload: unit.PayloadG711(samples), + }) + }) + + case *codecs.LPCM: + forma := &format.LPCM{ + PayloadTyp: 96, + BitDepth: codec.BitDepth, + SampleRate: codec.SampleRate, + ChannelCount: codec.ChannelCount, + } + medi := &description.Media{ + Type: description.MediaTypeAudio, + Formats: []format.Format{forma}, + } + medias = append(medias, medi) + + r.OnDataLPCM(track, func(pts time.Duration, samples []byte) { + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: durationToTimestamp(pts, forma.ClockRate()), + Payload: unit.PayloadLPCM(samples), + }) + }) + } + } + + if len(medias) == 0 { + return nil, errNoSupportedCodecsTo + } + + return medias, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/to_stream_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/to_stream_test.go new file mode 100644 index 0000000000000000000000000000000000000000..16c660cd731ad88675f4a8c191f0c61ff963ba5a --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtmp/to_stream_test.go @@ -0,0 +1,18 @@ +package rtmp + +import ( + "testing" + + "github.com/bluenviron/gortmplib" + "github.com/stretchr/testify/require" +) + +func TestToStreamNoSupportedCodecs(t *testing.T) { + r := &gortmplib.Reader{} + + _, err := ToStream(r, nil) + require.Equal(t, errNoSupportedCodecsTo, err) +} + +// this is impossible to test since currently we support all RTMP tracks. +// func TestToStreamSkipUnsupportedTracks(t *testing.T) diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtsp/credentials.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtsp/credentials.go new file mode 100644 index 0000000000000000000000000000000000000000..ae0b28c04c63837b74d57974404f5bbc6eb38d89 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtsp/credentials.go @@ -0,0 +1,23 @@ +package rtsp + +import ( + "github.com/bluenviron/gortsplib/v5/pkg/base" + "github.com/bluenviron/gortsplib/v5/pkg/headers" + "github.com/bluenviron/mediamtx/internal/auth" +) + +// Credentials extracts credentials from a RTSP request. +func Credentials(rt *base.Request) *auth.Credentials { + c := &auth.Credentials{} + + var rtspAuthHeader headers.Authorization + err := rtspAuthHeader.Unmarshal(rt.Header["Authorization"]) + if err == nil { + c.User = rtspAuthHeader.Username + if rtspAuthHeader.Method == headers.AuthMethodBasic { + c.Pass = rtspAuthHeader.BasicPass + } + } + + return c +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtsp/credentials_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtsp/credentials_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ff73fdefff1cc3b11ef29db3cc51ac499a1ddbe4 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtsp/credentials_test.go @@ -0,0 +1,26 @@ +package rtsp + +import ( + "testing" + + "github.com/bluenviron/gortsplib/v5/pkg/base" + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/stretchr/testify/require" +) + +func TestCredentials(t *testing.T) { + rr := &base.Request{ + Header: base.Header{ + "Authorization": []string{ + "Basic bXl1c2VyOm15cGFzcw==", + }, + }, + } + + c := Credentials(rr) + + require.Equal(t, &auth.Credentials{ + User: "myuser", + Pass: "mypass", + }, c) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtsp/to_stream.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtsp/to_stream.go new file mode 100644 index 0000000000000000000000000000000000000000..cc330ff325254d23188dfea36dade8f90a71c939 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/rtsp/to_stream.go @@ -0,0 +1,94 @@ +// Package rtsp provides RTSP utilities. +package rtsp + +import ( + "time" + + "github.com/bluenviron/gortsplib/v5" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/pion/rtp" +) + +type ntpState int + +const ( + ntpStateInitial ntpState = iota + ntpStateReplace + ntpStateAvailable +) + +type rtspSource interface { + PacketPTS(*description.Media, *rtp.Packet) (int64, bool) + PacketNTP(*description.Media, *rtp.Packet) (time.Time, bool) + OnPacketRTP(*description.Media, format.Format, gortsplib.OnPacketRTPFunc) +} + +// ToStream maps a RTSP stream to a MediaMTX stream. +func ToStream( + source rtspSource, + medias []*description.Media, + pathConf *conf.Path, + subStream **stream.SubStream, + log logger.Writer, +) { + for _, medi := range medias { + for _, forma := range medi.Formats { + cmedi := medi + cforma := forma + + var ntpStat ntpState + + if !pathConf.UseAbsoluteTimestamp { + ntpStat = ntpStateReplace + } + + handleNTP := func(pkt *rtp.Packet) (time.Time, bool) { + switch ntpStat { + case ntpStateReplace: + return time.Time{}, true + + case ntpStateInitial: + ntp, avail := source.PacketNTP(cmedi, pkt) + if !avail { + log.Log(logger.Warn, "received RTP packet without absolute time, skipping it") + return time.Time{}, false + } + + ntpStat = ntpStateAvailable + return ntp, true + + default: // ntpStateAvailable + ntp, avail := source.PacketNTP(cmedi, pkt) + if !avail { + panic("should not happen") + } + + return ntp, true + } + } + + source.OnPacketRTP(cmedi, cforma, func(pkt *rtp.Packet) { + pts, ok := source.PacketPTS(cmedi, pkt) + if !ok { + return + } + + ntp, ok := handleNTP(pkt) + if !ok { + return + } + + (*subStream).WriteUnit(cmedi, cforma, &unit.Unit{ + PTS: pts, + NTP: ntp, + RTPPackets: []*rtp.Packet{pkt}, + }) + }) + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/tls/make_config.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/tls/make_config.go new file mode 100644 index 0000000000000000000000000000000000000000..79aa8cfb7c269e55cd1a9f8c9382bf3816f69937 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/tls/make_config.go @@ -0,0 +1,36 @@ +// Package tls contains TLS utilities. +package tls //nolint:revive + +import ( + "crypto/sha256" + "crypto/tls" + "encoding/hex" + "fmt" + "strings" +) + +// MakeConfig returns a tls.Config with fingerprint support. +func MakeConfig(fingerprint string) *tls.Config { + if fingerprint != "" { + conf := &tls.Config{} + + fingerprintLower := strings.ToLower(fingerprint) + conf.InsecureSkipVerify = true + conf.VerifyConnection = func(cs tls.ConnectionState) error { + h := sha256.New() + h.Write(cs.PeerCertificates[0].Raw) + hstr := hex.EncodeToString(h.Sum(nil)) + + if hstr != fingerprintLower { + return fmt.Errorf("source fingerprint does not match: expected %s, got %s", + fingerprintLower, hstr) + } + + return nil + } + + return conf + } + + return nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/tls/make_config_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/tls/make_config_test.go new file mode 100644 index 0000000000000000000000000000000000000000..6d9b0b1506ee1231da617e97df5c480c49eb0cdf --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/tls/make_config_test.go @@ -0,0 +1,95 @@ +package tls //nolint:revive + +import ( + "crypto/tls" + "net" + "testing" + + "github.com/stretchr/testify/require" +) + +var testTLSCertPub = []byte(`-----BEGIN CERTIFICATE----- +MIIDazCCAlOgAwIBAgIUXw1hEC3LFpTsllv7D3ARJyEq7sIwDQYJKoZIhvcNAQEL +BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM +GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yMDEyMTMxNzQ0NThaFw0zMDEy +MTExNzQ0NThaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw +HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDG8DyyS51810GsGwgWr5rjJK7OE1kTTLSNEEKax8Bj +zOyiaz8rA2JGl2VUEpi2UjDr9Cm7nd+YIEVs91IIBOb7LGqObBh1kGF3u5aZxLkv +NJE+HrLVvUhaDobK2NU+Wibqc/EI3DfUkt1rSINvv9flwTFu1qHeuLWhoySzDKEp +OzYxpFhwjVSokZIjT4Red3OtFz7gl2E6OAWe2qoh5CwLYVdMWtKR0Xuw3BkDPk9I +qkQKx3fqv97LPEzhyZYjDT5WvGrgZ1WDAN3booxXF3oA1H3GHQc4m/vcLatOtb8e +nI59gMQLEbnp08cl873bAuNuM95EZieXTHNbwUnq5iybAgMBAAGjUzBRMB0GA1Ud +DgQWBBQBKhJh8eWu0a4au9X/2fKhkFX2vjAfBgNVHSMEGDAWgBQBKhJh8eWu0a4a +u9X/2fKhkFX2vjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBj +3aCW0YPKukYgVK9cwN0IbVy/D0C1UPT4nupJcy/E0iC7MXPZ9D/SZxYQoAkdptdO +xfI+RXkpQZLdODNx9uvV+cHyZHZyjtE5ENu/i5Rer2cWI/mSLZm5lUQyx+0KZ2Yu +tEI1bsebDK30msa8QSTn0WidW9XhFnl3gRi4wRdimcQapOWYVs7ih+nAlSvng7NI +XpAyRs8PIEbpDDBMWnldrX4TP6EWYUi49gCp8OUDRREKX3l6Ls1vZ02F34yHIt/7 +7IV/XSKG096bhW+icKBWV0IpcEsgTzPK1J1hMxgjhzIMxGboAeUU+kidthOob6Sd +XQxaORfgM//NzX9LhUPk +-----END CERTIFICATE----- +`) + +var testTLSCertKey = []byte(`-----BEGIN RSA PRIVATE KEY----- +MIIEogIBAAKCAQEAxvA8skudfNdBrBsIFq+a4ySuzhNZE0y0jRBCmsfAY8zsoms/ +KwNiRpdlVBKYtlIw6/Qpu53fmCBFbPdSCATm+yxqjmwYdZBhd7uWmcS5LzSRPh6y +1b1IWg6GytjVPlom6nPxCNw31JLda0iDb7/X5cExbtah3ri1oaMkswyhKTs2MaRY +cI1UqJGSI0+EXndzrRc+4JdhOjgFntqqIeQsC2FXTFrSkdF7sNwZAz5PSKpECsd3 +6r/eyzxM4cmWIw0+Vrxq4GdVgwDd26KMVxd6ANR9xh0HOJv73C2rTrW/HpyOfYDE +CxG56dPHJfO92wLjbjPeRGYnl0xzW8FJ6uYsmwIDAQABAoIBACi0BKcyQ3HElSJC +kaAao+Uvnzh4yvPg8Nwf5JDIp/uDdTMyIEWLtrLczRWrjGVZYbsVROinP5VfnPTT +kYwkfKINj2u+gC6lsNuPnRuvHXikF8eO/mYvCTur1zZvsQnF5kp4GGwIqr+qoPUP +bB0UMndG1PdpoMryHe+JcrvTrLHDmCeH10TqOwMsQMLHYLkowvxwJWsmTY7/Qr5S +Wm3PPpOcW2i0uyPVuyuv4yD1368fqnqJ8QFsQp1K6QtYsNnJ71Hut1/IoxK/e6hj +5Z+byKtHVtmcLnABuoOT7BhleJNFBksX9sh83jid4tMBgci+zXNeGmgqo2EmaWAb +agQslkECgYEA8B1rzjOHVQx/vwSzDa4XOrpoHQRfyElrGNz9JVBvnoC7AorezBXQ +M9WTHQIFTGMjzD8pb+YJGi3gj93VN51r0SmJRxBaBRh1ZZI9kFiFzngYev8POgD3 +ygmlS3kTHCNxCK/CJkB+/jMBgtPj5ygDpCWVcTSuWlQFphePkW7jaaECgYEA1Blz +ulqgAyJHZaqgcbcCsI2q6m527hVr9pjzNjIVmkwu38yS9RTCgdlbEVVDnS0hoifl ++jVMEGXjF3xjyMvL50BKbQUH+KAa+V4n1WGlnZOxX9TMny8MBjEuSX2+362vQ3BX +4vOlX00gvoc+sY+lrzvfx/OdPCHQGVYzoKCxhLsCgYA07HcviuIAV/HsO2/vyvhp +xF5gTu+BqNUHNOZDDDid+ge+Jre2yfQLCL8VPLXIQW3Jff53IH/PGl+NtjphuLvj +7UDJvgvpZZuymIojP6+2c3gJ3CASC9aR3JBnUzdoE1O9s2eaoMqc4scpe+SWtZYf +3vzSZ+cqF6zrD/Rf/M35IQKBgHTU4E6ShPm09CcoaeC5sp2WK8OevZw/6IyZi78a +r5Oiy18zzO97U/k6xVMy6F+38ILl/2Rn31JZDVJujniY6eSkIVsUHmPxrWoXV1HO +y++U32uuSFiXDcSLarfIsE992MEJLSAynbF1Rsgsr3gXbGiuToJRyxbIeVy7gwzD +94TpAoGAY4/PejWQj9psZfAhyk5dRGra++gYRQ/gK1IIc1g+Dd2/BxbT/RHr05GK +6vwrfjsoRyMWteC1SsNs/CurjfQ/jqCfHNP5XPvxgd5Ec8sRJIiV7V5RTuWJsPu1 ++3K6cnKEyg+0ekYmLertRFIY6SwWmY1fyKgTvxudMcsBY7dC4xs= +-----END RSA PRIVATE KEY----- +`) + +func TestMakeConfigFingerprint(t *testing.T) { + l, err := net.Listen("tcp", "localhost:8556") + require.NoError(t, err) + defer l.Close() + + serverDone := make(chan struct{}) + defer func() { <-serverDone }() + + go func() { + defer close(serverDone) + + nconn, err2 := l.Accept() + require.NoError(t, err2) + defer nconn.Close() + + cert, err2 := tls.X509KeyPair(testTLSCertPub, testTLSCertKey) + require.NoError(t, err2) + + tnconn := tls.Server(nconn, &tls.Config{ + Certificates: []tls.Certificate{cert}, + InsecureSkipVerify: true, + }) + + err2 = tnconn.Handshake() + require.NoError(t, err2) + }() + + conf := MakeConfig("33949e05fffb5ff3e8aa16f8213a6251b4d9363804ba53233c4da9a46d6f2739") + + conn, err := tls.Dial("tcp", "localhost:8556", conf) + require.NoError(t, err) + defer conn.Close() //nolint:errcheck +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/udp/listener.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/udp/listener.go new file mode 100644 index 0000000000000000000000000000000000000000..003a62ed2ca9f0b0a5c619dc84ab3e573bb88e68 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/udp/listener.go @@ -0,0 +1,174 @@ +// Package udp contains utilities to work with the UDP protocol. +package udp + +import ( + "fmt" + "net" + "syscall" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/multicast" + "github.com/bluenviron/gortsplib/v5/pkg/readbuffer" + "github.com/bluenviron/mediamtx/internal/restrictnetwork" +) + +type packetConn interface { + net.PacketConn + SetReadBuffer(bytes int) error + SyscallConn() (syscall.RawConn, error) +} + +func defaultInterfaceForMulticast(multicastAddr *net.UDPAddr) (*net.Interface, error) { + conn, err := net.Dial("udp4", multicastAddr.String()) + if err != nil { + return nil, err + } + localAddr := conn.LocalAddr().(*net.UDPAddr) + conn.Close() + + interfaces, err := net.Interfaces() + if err != nil { + return nil, err + } + + for _, iface := range interfaces { + var addrs []net.Addr + addrs, err = iface.Addrs() + if err != nil { + continue + } + + for _, addr := range addrs { + var ip net.IP + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + case *net.IPAddr: + ip = v.IP + } + + if ip != nil && ip.Equal(localAddr.IP) { + return &iface, nil + } + } + } + + return nil, fmt.Errorf("could not find any interface for using multicast address %s", multicastAddr) +} + +// Listener is a listener on a UDP socket. +type Listener struct { + Address string + Source string + IntfName string + UDPReadBufferSize int + ListenPacket func(network, address string) (net.PacketConn, error) + + pc packetConn + sourceIP net.IP +} + +// Initialize initializes the listener. +func (l *Listener) Initialize() error { + if l.ListenPacket == nil { + l.ListenPacket = net.ListenPacket + } + + if l.Source != "" { + l.sourceIP = net.ParseIP(l.Source) + if l.sourceIP == nil { + return fmt.Errorf("invalid source IP") + } + } + + addr, err := net.ResolveUDPAddr("udp", l.Address) + if err != nil { + return err + } + + if ip4 := addr.IP.To4(); ip4 != nil && addr.IP.IsMulticast() { + var intf *net.Interface + + if l.IntfName != "" { + intf, err = net.InterfaceByName(l.IntfName) + if err != nil { + return err + } + } else { + intf, err = defaultInterfaceForMulticast(addr) + if err != nil { + return err + } + } + + l.pc, err = multicast.NewSingleConn(intf, addr.String(), l.ListenPacket) + if err != nil { + return err + } + } else { + var tmp net.PacketConn + tmp, err = l.ListenPacket(restrictnetwork.Restrict("udp", addr.String())) + if err != nil { + return err + } + l.pc = tmp.(packetConn) + } + + if l.UDPReadBufferSize != 0 { + err = readbuffer.SetReadBuffer(l.pc, l.UDPReadBufferSize) + if err != nil { + l.pc.Close() + return err + } + } + + return nil +} + +// Close closes the listener. +func (l *Listener) Close() error { + return l.pc.Close() +} + +// Read implements net.Conn. +func (l *Listener) Read(p []byte) (int, error) { + for { + n, addr, err := l.pc.ReadFrom(p) + + if l.sourceIP != nil && addr != nil && !addr.(*net.UDPAddr).IP.Equal(l.sourceIP) { + continue + } + + return n, err + } +} + +// Write implements net.Conn. +func (l *Listener) Write(_ []byte) (int, error) { + panic("unimplemented") +} + +// LocalAddr implements net.Conn. +func (l *Listener) LocalAddr() net.Addr { + panic("unimplemented") +} + +// RemoteAddr implements net.Conn. +func (l *Listener) RemoteAddr() net.Addr { + panic("unimplemented") +} + +// SetDeadline implements net.Conn. +func (l *Listener) SetDeadline(_ time.Time) error { + panic("unimplemented") +} + +// SetReadDeadline implements net.Conn. +func (l *Listener) SetReadDeadline(t time.Time) error { + return l.pc.SetReadDeadline(t) +} + +// SetWriteDeadline implements net.Conn. +func (l *Listener) SetWriteDeadline(_ time.Time) error { + panic("unimplemented") +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/udp/listener_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/udp/listener_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7562c7e08775acb4b730441fac9c17a0b1b66b80 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/udp/listener_test.go @@ -0,0 +1,45 @@ +package udp + +import ( + "net" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestListen(t *testing.T) { + l := &Listener{ + Address: "127.0.0.1:0", + UDPReadBufferSize: 4096, + } + err := l.Initialize() + require.NoError(t, err) + defer l.Close() //nolint:errcheck + + done := make(chan struct{}) + + go func() { + defer close(done) + + err2 := l.SetReadDeadline(time.Now().Add(2 * time.Second)) + require.NoError(t, err2) + + buf := make([]byte, 1024) + n, err2 := l.Read(buf) + require.NoError(t, err2) + + require.Equal(t, []byte("testing"), buf[:n]) + }() + + localAddr := l.pc.LocalAddr().(*net.UDPAddr) + + clientConn, err := net.DialUDP("udp", nil, localAddr) + require.NoError(t, err) + defer clientConn.Close() //nolint:errcheck + + _, err = clientConn.Write([]byte("testing")) + require.NoError(t, err) + + <-done +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/udp/params.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/udp/params.go new file mode 100644 index 0000000000000000000000000000000000000000..2d79ba02c8a639324aa872f319bf6acf4fff2c74 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/udp/params.go @@ -0,0 +1,19 @@ +package udp + +import "net/url" + +// Params are the parameters of a UDP listener. +type Params struct { + Address string + Source string + IntfName string +} + +// URLToParams converts a URL to Params. +func URLToParams(u *url.URL) *Params { + return &Params{ + Address: u.Host, + Source: u.Query().Get("source"), + IntfName: u.Query().Get("interface"), + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/unix/listener.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/unix/listener.go new file mode 100644 index 0000000000000000000000000000000000000000..d6e8154cd5e819f9a2b37fc66256594289b56290 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/unix/listener.go @@ -0,0 +1,145 @@ +// Package unix contains utilities to work with Unix sockets. +package unix + +import ( + "fmt" + "net" + "os" + "sync" + "time" +) + +// Listener is a listener on a Unix socket. +type Listener struct { + Path string + Listen func(network string, address string) (net.Listener, error) + + l net.Listener + c net.Conn + mutex sync.Mutex + closed bool + deadline time.Time +} + +// Initialize initializes the listener. +func (l *Listener) Initialize() error { + if l.Path == "" { + return fmt.Errorf("invalid unix path") + } + if l.Listen == nil { + l.Listen = net.Listen + } + + os.Remove(l.Path) + + var err error + l.l, err = l.Listen("unix", l.Path) + if err != nil { + return err + } + + return nil +} + +// Close closes the listener. +func (l *Listener) Close() error { + l.mutex.Lock() + defer l.mutex.Unlock() + + l.closed = true + + l.l.Close() + + if l.c != nil { + l.c.Close() + } + + return nil +} + +func (l *Listener) acceptWithDeadline() (net.Conn, error) { + done := make(chan struct{}) + defer func() { <-done }() + + terminate := make(chan struct{}) + defer close(terminate) + + go func() { + defer close(done) + select { + case <-time.After(time.Until(l.deadline)): + l.l.Close() + case <-terminate: + return + } + }() + + c, err := l.l.Accept() + if err != nil { + if time.Now().After(l.deadline) { + return nil, fmt.Errorf("deadline exceeded") + } + return nil, err + } + return c, nil +} + +func (l *Listener) setConn(c net.Conn) error { + l.mutex.Lock() + defer l.mutex.Unlock() + + if l.closed { + return fmt.Errorf("closed") + } + + l.c = c + return nil +} + +func (l *Listener) Read(p []byte) (int, error) { + if l.c == nil { + c, err := l.acceptWithDeadline() + if err != nil { + return 0, err + } + + err = l.setConn(c) + if err != nil { + return 0, err + } + } + + l.c.SetReadDeadline(l.deadline) + return l.c.Read(p) +} + +// Write implements net.Conn. +func (l *Listener) Write(_ []byte) (int, error) { + panic("unimplemented") +} + +// LocalAddr implements net.Conn. +func (l *Listener) LocalAddr() net.Addr { + panic("unimplemented") +} + +// RemoteAddr implements net.Conn. +func (l *Listener) RemoteAddr() net.Addr { + panic("unimplemented") +} + +// SetDeadline implements net.Conn. +func (l *Listener) SetDeadline(_ time.Time) error { + panic("unimplemented") +} + +// SetReadDeadline implements net.Conn. +func (l *Listener) SetReadDeadline(t time.Time) error { + l.deadline = t + return nil +} + +// SetWriteDeadline implements net.Conn. +func (l *Listener) SetWriteDeadline(_ time.Time) error { + panic("unimplemented") +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/unix/listener_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/unix/listener_test.go new file mode 100644 index 0000000000000000000000000000000000000000..392f522f68262612e54f0ce938f879f6e9896ef7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/unix/listener_test.go @@ -0,0 +1,47 @@ +package unix + +import ( + "net" + "os" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestListen(t *testing.T) { + socket, err := os.CreateTemp(t.TempDir(), "mtx-unix-") + require.NoError(t, err) + socket.Close() + + l := &Listener{ + Path: socket.Name(), + } + err = l.Initialize() + require.NoError(t, err) + defer l.Close() //nolint:errcheck + + done := make(chan struct{}) + + go func() { + defer close(done) + + buf := make([]byte, 1024) + l.SetReadDeadline(time.Now().Add(2 * time.Second)) //nolint:errcheck + n, err2 := l.Read(buf) + require.NoError(t, err2) + require.Equal(t, []byte("testing"), buf[:n]) + }() + + clientAddr, err := net.ResolveUnixAddr("unix", socket.Name()) + require.NoError(t, err) + + clientConn, err := net.DialUnix("unix", nil, clientAddr) + require.NoError(t, err) + defer clientConn.Close() //nolint:errcheck + + _, err = clientConn.Write([]byte("testing")) + require.NoError(t, err) + + <-done +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/unix/params.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/unix/params.go new file mode 100644 index 0000000000000000000000000000000000000000..095ed07825484208a5d340273bd8096fa57ec075 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/unix/params.go @@ -0,0 +1,22 @@ +package unix + +import "net/url" + +// Params are the parameters of a unix listener. +type Params struct { + Path string +} + +// URLToParams converts a URL to Params. +func URLToParams(u *url.URL) *Params { + var pa string + if u.Path != "" { + pa = u.Path + } else { + pa = u.Host + } + + return &Params{ + Path: pa, + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/from_stream.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/from_stream.go new file mode 100644 index 0000000000000000000000000000000000000000..3d0d0372bb2e2e699fde84c05707bec500a2ed1a --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/from_stream.go @@ -0,0 +1,725 @@ +package webrtc + +import ( + "crypto/rand" + "errors" + "fmt" + "slices" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/gortsplib/v5/pkg/format/rtpav1" + "github.com/bluenviron/gortsplib/v5/pkg/format/rtph264" + "github.com/bluenviron/gortsplib/v5/pkg/format/rtph265" + "github.com/bluenviron/gortsplib/v5/pkg/format/rtplpcm" + "github.com/bluenviron/gortsplib/v5/pkg/format/rtpvp8" + "github.com/bluenviron/gortsplib/v5/pkg/format/rtpvp9" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/g711" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/opus" + "github.com/bluenviron/mediamtx/internal/formatlabel" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/pion/rtp" + "github.com/pion/webrtc/v4" +) + +const ( + webrtcPayloadMaxSize = 1188 // 1200 - 12 (RTP header) +) + +var multichannelOpusSDP = map[int]string{ + 3: "channel_mapping=0,2,1;num_streams=2;coupled_streams=1", + 4: "channel_mapping=0,1,2,3;num_streams=2;coupled_streams=2", + 5: "channel_mapping=0,4,1,2,3;num_streams=3;coupled_streams=2", + 6: "channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2", + 7: "channel_mapping=0,4,1,2,3,5,6;num_streams=4;coupled_streams=4", + 8: "channel_mapping=0,6,1,4,5,2,3,7;num_streams=5;coupled_streams=4", +} + +var errNoSupportedCodecsFrom = errors.New( + "the stream doesn't contain any supported codec, which are currently " + + "AV1, VP9, VP8, H265, H264, Opus, G722, G711, LPCM") + +func randUint32() (uint32, error) { + var b [4]byte + _, err := rand.Read(b[:]) + if err != nil { + return 0, err + } + return uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3]), nil +} + +func multiplyAndDivide2(v, m, d time.Duration) time.Duration { + secs := v / d + dec := v % d + return (secs*m + dec*m/d) +} + +func timestampToDuration(t int64, clockRate int) time.Duration { + return multiplyAndDivide2(time.Duration(t), time.Second, time.Duration(clockRate)) +} + +func setupVideoTrack( + desc *description.Session, + r *stream.Reader, +) (*OutboundTrack, error) { + var av1Format *format.AV1 + media := desc.FindFormat(&av1Format) + + if av1Format != nil { //nolint:dupl + track := &OutboundTrack{ + Caps: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeAV1, + ClockRate: 90000, + }, + } + + encoder := &rtpav1.Encoder{ + PayloadType: 105, + PayloadMaxSize: webrtcPayloadMaxSize, + } + err := encoder.Init() + if err != nil { + return nil, err + } + + r.OnData( + media, + av1Format, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + packets, err2 := encoder.Encode(u.Payload.(unit.PayloadAV1)) + if err2 != nil { + return nil //nolint:nilerr + } + + for _, pkt := range packets { + ntp := u.NTP.Add(timestampToDuration(int64(pkt.Timestamp), 90000)) + pkt.Timestamp += u.RTPPackets[0].Timestamp + track.WriteRTPWithNTP(pkt, ntp) //nolint:errcheck + } + + return nil + }) + + return track, nil + } + + var vp9Format *format.VP9 + media = desc.FindFormat(&vp9Format) + + if vp9Format != nil { + track := &OutboundTrack{ + Caps: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP9, + ClockRate: 90000, + SDPFmtpLine: "profile-id=0", + }, + } + + encoder := &rtpvp9.Encoder{ + PayloadType: 96, + PayloadMaxSize: webrtcPayloadMaxSize, + InitialPictureID: new(uint16(8445)), + } + err := encoder.Init() + if err != nil { + return nil, err + } + + r.OnData( + media, + vp9Format, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + packets, err2 := encoder.Encode(u.Payload.(unit.PayloadVP9)) + if err2 != nil { + return nil //nolint:nilerr + } + + for _, pkt := range packets { + ntp := u.NTP.Add(timestampToDuration(int64(pkt.Timestamp), 90000)) + pkt.Timestamp += u.RTPPackets[0].Timestamp + track.WriteRTPWithNTP(pkt, ntp) //nolint:errcheck + } + + return nil + }) + + return track, nil + } + + var vp8Format *format.VP8 + media = desc.FindFormat(&vp8Format) + + if vp8Format != nil { //nolint:dupl + track := &OutboundTrack{ + Caps: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP8, + ClockRate: 90000, + }, + } + + encoder := &rtpvp8.Encoder{ + PayloadType: 96, + PayloadMaxSize: webrtcPayloadMaxSize, + } + err := encoder.Init() + if err != nil { + return nil, err + } + + r.OnData( + media, + vp8Format, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + packets, err2 := encoder.Encode(u.Payload.(unit.PayloadVP8)) + if err2 != nil { + return nil //nolint:nilerr + } + + for _, pkt := range packets { + ntp := u.NTP.Add(timestampToDuration(int64(pkt.Timestamp), 90000)) + pkt.Timestamp += u.RTPPackets[0].Timestamp + track.WriteRTPWithNTP(pkt, ntp) //nolint:errcheck + } + + return nil + }) + + return track, nil + } + + var h265Format *format.H265 + media = desc.FindFormat(&h265Format) + + if h265Format != nil { //nolint:dupl + track := &OutboundTrack{ + Caps: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeH265, + ClockRate: 90000, + SDPFmtpLine: "level-id=93;profile-id=1;tier-flag=0;tx-mode=SRST", + }, + } + + encoder := &rtph265.Encoder{ + PayloadType: 96, + PayloadMaxSize: webrtcPayloadMaxSize, + } + err := encoder.Init() + if err != nil { + return nil, err + } + + firstReceived := false + var lastPTS int64 + + r.OnData( + media, + h265Format, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + if !firstReceived { + firstReceived = true + } else if u.PTS < lastPTS { + return fmt.Errorf("WebRTC doesn't support H265 streams with B-frames") + } + lastPTS = u.PTS + + packets, err2 := encoder.Encode(u.Payload.(unit.PayloadH265)) + if err2 != nil { + return nil //nolint:nilerr + } + + for _, pkt := range packets { + ntp := u.NTP.Add(timestampToDuration(int64(pkt.Timestamp), 90000)) + pkt.Timestamp += u.RTPPackets[0].Timestamp + track.WriteRTPWithNTP(pkt, ntp) //nolint:errcheck + } + + return nil + }) + + return track, nil + } + + var h264Format *format.H264 + media = desc.FindFormat(&h264Format) + + if h264Format != nil { //nolint:dupl + track := &OutboundTrack{ + Caps: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeH264, + ClockRate: 90000, + SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f", + }, + } + + encoder := &rtph264.Encoder{ + PayloadType: 96, + PayloadMaxSize: webrtcPayloadMaxSize, + PacketizationMode: 1, + } + err := encoder.Init() + if err != nil { + return nil, err + } + + firstReceived := false + var lastPTS int64 + + r.OnData( + media, + h264Format, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + if !firstReceived { + firstReceived = true + } else if u.PTS < lastPTS { + return fmt.Errorf("WebRTC doesn't support H264 streams with B-frames") + } + lastPTS = u.PTS + + packets, err2 := encoder.Encode(u.Payload.(unit.PayloadH264)) + if err2 != nil { + return nil //nolint:nilerr + } + + for _, pkt := range packets { + ntp := u.NTP.Add(timestampToDuration(int64(pkt.Timestamp), 90000)) + pkt.Timestamp += u.RTPPackets[0].Timestamp + track.WriteRTPWithNTP(pkt, ntp) //nolint:errcheck + } + + return nil + }) + + return track, nil + } + + return nil, nil +} + +func setupAudioTrack( + desc *description.Session, + r *stream.Reader, +) (*OutboundTrack, error) { + var opusFormat *format.Opus + media := desc.FindFormat(&opusFormat) + + if opusFormat != nil { + var caps webrtc.RTPCodecCapability + + switch opusFormat.ChannelCount { + case 1, 2: + caps = webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeOpus, + ClockRate: 48000, + Channels: 2, + SDPFmtpLine: func() string { + s := "minptime=10;useinbandfec=1" + if opusFormat.ChannelCount == 2 { + s += ";stereo=1;sprop-stereo=1" + } + return s + }(), + } + + case 3, 4, 5, 6, 7, 8: + caps = webrtc.RTPCodecCapability{ + MimeType: mimeTypeMultiopus, + ClockRate: 48000, + Channels: uint16(opusFormat.ChannelCount), + SDPFmtpLine: multichannelOpusSDP[opusFormat.ChannelCount], + } + + default: + return nil, fmt.Errorf("unsupported channel count: %d", opusFormat.ChannelCount) + } + + track := &OutboundTrack{ + Caps: caps, + } + + curTimestamp, err := randUint32() + if err != nil { + return nil, err + } + + r.OnData( + media, + opusFormat, + func(u *unit.Unit) error { + baseTimestamp := curTimestamp + + for _, orig := range u.RTPPackets { + // create a copy of the packet that we can edit freely + pkt := &rtp.Packet{ + Header: orig.Header, + Payload: orig.Payload, + } + + // recompute timestamp from scratch. + // Chrome requires a precise timestamp that FFmpeg doesn't provide. + pkt.Timestamp = curTimestamp + curTimestamp += uint32(opus.PacketDuration2(pkt.Payload)) + + ntp := u.NTP.Add(timestampToDuration(int64(pkt.Timestamp-baseTimestamp), 48000)) + track.WriteRTPWithNTP(pkt, ntp) //nolint:errcheck + } + + return nil + }) + + return track, nil + } + + var g722Format *format.G722 + media = desc.FindFormat(&g722Format) + + if g722Format != nil { + track := &OutboundTrack{ + Caps: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeG722, + ClockRate: 8000, + }, + } + + r.OnData( + media, + g722Format, + func(u *unit.Unit) error { + for _, pkt := range u.RTPPackets { + ntp := u.NTP.Add(timestampToDuration(int64(pkt.Timestamp-u.RTPPackets[0].Timestamp), 8000)) + track.WriteRTPWithNTP(pkt, ntp) //nolint:errcheck + } + + return nil + }) + + return track, nil + } + + var g711Format *format.G711 + media = desc.FindFormat(&g711Format) + + if g711Format != nil { + // These are the sample rates and channels supported by Chrome. + // Different sample rates and channels can be streamed too but we don't want compatibility issues. + // https://webrtc.googlesource.com/src/+/refs/heads/main/modules/audio_coding/codecs/pcm16b/audio_decoder_pcm16b.cc#23 + if g711Format.ClockRate() != 8000 && g711Format.ClockRate() != 16000 && + g711Format.ClockRate() != 32000 && g711Format.ClockRate() != 48000 { + return nil, fmt.Errorf("unsupported clock rate: %d", g711Format.ClockRate()) + } + if g711Format.ChannelCount != 1 && g711Format.ChannelCount != 2 { + return nil, fmt.Errorf("unsupported channel count: %d", g711Format.ChannelCount) + } + + var caps webrtc.RTPCodecCapability + + if g711Format.ClockRate() == 8000 { + if g711Format.MULaw { + if g711Format.ChannelCount != 1 { + caps = webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypePCMU, + ClockRate: uint32(g711Format.ClockRate()), + Channels: uint16(g711Format.ChannelCount), + } + } else { + caps = webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypePCMU, + ClockRate: 8000, + } + } + } else { + if g711Format.ChannelCount != 1 { + caps = webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypePCMA, + ClockRate: uint32(g711Format.ClockRate()), + Channels: uint16(g711Format.ChannelCount), + } + } else { + caps = webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypePCMA, + ClockRate: 8000, + } + } + } + } else { + caps = webrtc.RTPCodecCapability{ + MimeType: mimeTypeL16, + ClockRate: uint32(g711Format.ClockRate()), + Channels: uint16(g711Format.ChannelCount), + } + } + + track := &OutboundTrack{ + Caps: caps, + } + + if g711Format.ClockRate() == 8000 { + curTimestamp, err := randUint32() + if err != nil { + return nil, err + } + + r.OnData( + media, + g711Format, + func(u *unit.Unit) error { + baseTimestamp := curTimestamp + + for _, orig := range u.RTPPackets { + // create a copy of the packet that we can edit freely + pkt := &rtp.Packet{ + Header: orig.Header, + Payload: orig.Payload, + } + + // recompute timestamp from scratch. + // Chrome requires a precise timestamp that FFmpeg doesn't provide. + pkt.Timestamp = curTimestamp + curTimestamp += uint32(len(pkt.Payload)) / uint32(g711Format.ChannelCount) + + ntp := u.NTP.Add(timestampToDuration(int64(pkt.Timestamp-baseTimestamp), 8000)) + track.WriteRTPWithNTP(pkt, ntp) //nolint:errcheck + } + + return nil + }) + } else { + encoder := &rtplpcm.Encoder{ + PayloadType: 96, + PayloadMaxSize: webrtcPayloadMaxSize, + BitDepth: 16, + ChannelCount: g711Format.ChannelCount, + } + err := encoder.Init() + if err != nil { + return nil, err + } + + curTimestamp, err := randUint32() + if err != nil { + return nil, err + } + + r.OnData( + media, + g711Format, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + var lpcm []byte + if g711Format.MULaw { + var mu g711.Mulaw + mu.Unmarshal(u.Payload.(unit.PayloadG711)) + lpcm = mu + } else { + var al g711.Alaw + al.Unmarshal(u.Payload.(unit.PayloadG711)) + lpcm = al + } + + packets, err2 := encoder.Encode(lpcm) + if err2 != nil { + return nil //nolint:nilerr + } + + baseTimestamp := curTimestamp + + for _, pkt := range packets { + // recompute timestamp from scratch. + // Chrome requires a precise timestamp that FFmpeg doesn't provide. + pkt.Timestamp = curTimestamp + curTimestamp += uint32(len(pkt.Payload)) / 2 / uint32(g711Format.ChannelCount) + + ntp := u.NTP.Add(timestampToDuration(int64(pkt.Timestamp-baseTimestamp), g711Format.ClockRate())) + track.WriteRTPWithNTP(pkt, ntp) //nolint:errcheck + } + + return nil + }) + } + + return track, nil + } + + var lpcmFormat *format.LPCM + media = desc.FindFormat(&lpcmFormat) + + if lpcmFormat != nil { + if lpcmFormat.BitDepth != 16 { + return nil, fmt.Errorf("unsupported LPCM bit depth: %d", lpcmFormat.BitDepth) + } + + // These are the sample rates and channels supported by Chrome. + // Different sample rates and channels can be streamed too but we don't want compatibility issues. + // https://webrtc.googlesource.com/src/+/refs/heads/main/modules/audio_coding/codecs/pcm16b/audio_decoder_pcm16b.cc#23 + if lpcmFormat.ClockRate() != 8000 && lpcmFormat.ClockRate() != 16000 && + lpcmFormat.ClockRate() != 32000 && lpcmFormat.ClockRate() != 48000 { + return nil, fmt.Errorf("unsupported clock rate: %d", lpcmFormat.ClockRate()) + } + if lpcmFormat.ChannelCount != 1 && lpcmFormat.ChannelCount != 2 { + return nil, fmt.Errorf("unsupported channel count: %d", lpcmFormat.ChannelCount) + } + + track := &OutboundTrack{ + Caps: webrtc.RTPCodecCapability{ + MimeType: mimeTypeL16, + ClockRate: uint32(lpcmFormat.ClockRate()), + Channels: uint16(lpcmFormat.ChannelCount), + }, + } + + encoder := &rtplpcm.Encoder{ + PayloadType: 96, + BitDepth: 16, + ChannelCount: lpcmFormat.ChannelCount, + PayloadMaxSize: webrtcPayloadMaxSize, + } + err := encoder.Init() + if err != nil { + return nil, err + } + + curTimestamp, err := randUint32() + if err != nil { + return nil, err + } + + r.OnData( + media, + lpcmFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + packets, err2 := encoder.Encode(u.Payload.(unit.PayloadLPCM)) + if err2 != nil { + return nil //nolint:nilerr + } + + baseTimestamp := curTimestamp + + for _, pkt := range packets { + // recompute timestamp from scratch. + // Chrome requires a precise timestamp that FFmpeg doesn't provide. + pkt.Timestamp = curTimestamp + curTimestamp += uint32(len(pkt.Payload)) / 2 / uint32(lpcmFormat.ChannelCount) + + ntp := u.NTP.Add(timestampToDuration(int64(pkt.Timestamp-baseTimestamp), lpcmFormat.ClockRate())) + track.WriteRTPWithNTP(pkt, ntp) //nolint:errcheck + } + + return nil + }) + + return track, nil + } + + return nil, nil +} + +func setupKLVDataChannel( + desc *description.Session, + r *stream.Reader, +) (*OutboundDataChannel, error) { + var klvFormat *format.KLV + media := desc.FindFormat(&klvFormat) + + if klvFormat != nil { + dataChan := &OutboundDataChannel{ + Label: "KLV", + } + + r.OnData( + media, + klvFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + dataChan.Write(u.Payload.(unit.PayloadKLV)) + return nil + }) + + return dataChan, nil + } + + return nil, nil +} + +// FromStream maps a MediaMTX stream to a WebRTC connection +func FromStream( + desc *description.Session, + r *stream.Reader, + pc *PeerConnection, +) error { + videoTrack, err := setupVideoTrack(desc, r) + if err != nil { + return err + } + + if videoTrack != nil { + pc.OutboundTracks = append(pc.OutboundTracks, videoTrack) + } + + audioTrack, err := setupAudioTrack(desc, r) + if err != nil { + return err + } + + if audioTrack != nil { + pc.OutboundTracks = append(pc.OutboundTracks, audioTrack) + } + + klvDataChan, err := setupKLVDataChannel(desc, r) + if err != nil { + return err + } + + if klvDataChan != nil { + pc.OutboundDataChannels = append(pc.OutboundDataChannels, klvDataChan) + } + + if len(pc.OutboundTracks) == 0 && len(pc.OutboundDataChannels) == 0 { + return errNoSupportedCodecsFrom + } + + setuppedFormats := r.Formats() + + n := 1 + for _, media := range desc.Medias { + for _, forma := range media.Formats { + if !slices.Contains(setuppedFormats, forma) { + r.Parent.Log(logger.Warn, "skipping track %d (%s)", n, formatlabel.FormatToLabel(forma)) + } + n++ + } + } + + return nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/from_stream_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/from_stream_test.go new file mode 100644 index 0000000000000000000000000000000000000000..53991b5a22d7ddb6697b6835955e12d13de8eec1 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/from_stream_test.go @@ -0,0 +1,385 @@ +package webrtc + +import ( + "fmt" + "testing" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/pion/rtp" + "github.com/stretchr/testify/require" +) + +func TestFromStreamNoSupportedCodecs(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.MJPEG{}}, + }}} + + r := &stream.Reader{ + Parent: test.Logger(func(logger.Level, string, ...any) { + t.Error("should not happen") + }), + } + + pc := &PeerConnection{} + + err := FromStream(desc, r, pc) + require.Equal(t, errNoSupportedCodecsFrom, err) +} + +func TestFromStreamSkipUnsupportedTracks(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H264{PacketizationMode: 1}}, + }, + { + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.MJPEG{}}, + }, + }} + + n := 0 + + r := &stream.Reader{ + Parent: test.Logger(func(l logger.Level, format string, args ...any) { + require.Equal(t, logger.Warn, l) + if n == 0 { + require.Equal(t, "skipping track 2 (M-JPEG)", fmt.Sprintf(format, args...)) + } + n++ + }), + } + + pc := &PeerConnection{} + + err := FromStream(desc, r, pc) + require.NoError(t, err) + + require.Equal(t, 1, n) +} + +func TestFromStream(t *testing.T) { + for _, ca := range toFromStreamCases { + t.Run(ca.name, func(t *testing.T) { + desc := &description.Session{ + Medias: []*description.Media{{ + Formats: []format.Format{ca.in}, + }}, + } + + pc := &PeerConnection{} + r := &stream.Reader{Parent: test.NilLogger} + + err := FromStream(desc, r, pc) + require.NoError(t, err) + + require.Equal(t, ca.webrtcCaps, pc.OutboundTracks[0].Caps) + }) + } +} + +func TestFromStreamResampleOpus(t *testing.T) { + strm := &stream.Stream{ + OrigDesc: &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.Opus{ + ChannelCount: 2, + }}, + }, + }}, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + ReplaceNTP: false, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: true, + } + err = subStream.Initialize() + require.NoError(t, err) + + pc1 := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: false, + Log: test.NilLogger, + } + err = pc1.Start() + require.NoError(t, err) + defer pc1.Close() + + pc2 := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: true, + Log: test.NilLogger, + } + + r := &stream.Reader{Parent: nil} + + err = FromStream(strm.OrigDesc, r, pc2) + require.NoError(t, err) + + err = pc2.Start() + require.NoError(t, err) + defer pc2.Close() + + offer, err := pc1.CreatePartialOffer(false) + require.NoError(t, err) + + answer, err := pc2.CreateFullAnswer(offer, false) + require.NoError(t, err) + + err = pc1.SetAnswer(answer) + require.NoError(t, err) + + err = pc1.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + err = pc2.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + strm.AddReader(r) + defer strm.RemoveReader(r) + + subStream.WriteUnit(strm.OrigDesc.Medias[0], strm.OrigDesc.Medias[0].Formats[0], &unit.Unit{ + PTS: 0, + NTP: time.Now(), + RTPPackets: []*rtp.Packet{{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 111, + SequenceNumber: 1123, + Timestamp: 45343, + SSRC: 563424, + }, + Payload: []byte{1}, + }}, + }) + + subStream.WriteUnit(strm.OrigDesc.Medias[0], strm.OrigDesc.Medias[0].Formats[0], &unit.Unit{ + PTS: 0, + NTP: time.Now(), + RTPPackets: []*rtp.Packet{{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 111, + SequenceNumber: 1124, + Timestamp: 45343, + SSRC: 563424, + }, + Payload: []byte{1}, + }}, + }) + + err = pc1.GatherInboundTracks(2 * time.Second) + require.NoError(t, err) + + tracks := pc1.InboundTracks() + + done := make(chan struct{}) + n := 0 + var ts uint32 + + tracks[0].OnPacketRTP = func(pkt *rtp.Packet) { + n++ + + switch n { + case 1: + ts = pkt.Timestamp + + case 2: + require.Equal(t, uint32(960), pkt.Timestamp-ts) + close(done) + } + } + + pc1.StartReading() + + <-done +} + +func TestFromStreamResampleOpusAbsoluteTimestamp(t *testing.T) { + strm := &stream.Stream{ + OrigDesc: &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeAudio, + Formats: []format.Format{&format.Opus{ + ChannelCount: 2, + }}, + }, + }}, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + ReplaceNTP: false, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: true, + } + err = subStream.Initialize() + require.NoError(t, err) + + pcReader := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: false, + Log: test.NilLogger, + } + err = pcReader.Start() + require.NoError(t, err) + t.Cleanup(pcReader.Close) + + pcPublisher := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: true, + Log: test.NilLogger, + } + + r := &stream.Reader{Parent: nil} + + err = FromStream(strm.OrigDesc, r, pcPublisher) + require.NoError(t, err) + + err = pcPublisher.Start() + require.NoError(t, err) + t.Cleanup(pcPublisher.Close) + + offer, err := pcReader.CreatePartialOffer(false) + require.NoError(t, err) + + answer, err := pcPublisher.CreateFullAnswer(offer, false) + require.NoError(t, err) + + err = pcReader.SetAnswer(answer) + require.NoError(t, err) + + err = pcReader.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + err = pcPublisher.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + strm.AddReader(r) + t.Cleanup(func() { strm.RemoveReader(r) }) + + baseNTP := time.Unix(1710000000, 0) + step := 20 * time.Millisecond + + // prime the pipeline to allow track gathering + subStream.WriteUnit(strm.OrigDesc.Medias[0], strm.OrigDesc.Medias[0].Formats[0], &unit.Unit{ + PTS: 0, + NTP: baseNTP, + RTPPackets: []*rtp.Packet{{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 111, + SequenceNumber: 1123, + Timestamp: 45343, + SSRC: 563424, + }, + Payload: []byte{1}, + }}, + }) + + err = pcReader.GatherInboundTracks(2 * time.Second) + require.NoError(t, err) + + tracks := pcReader.InboundTracks() + require.Len(t, tracks, 1) + + done := make(chan struct{}) + errCh := make(chan string, 1) + const startSeq = uint16(2000) + + expectedNTP := func(seq uint16) (time.Time, bool) { + if seq < startSeq { + return time.Time{}, false + } + return baseNTP.Add(time.Duration(seq-startSeq) * step), true + } + + tracks[0].OnPacketRTP = func(pkt *rtp.Packet) { + expected, ok := expectedNTP(pkt.SequenceNumber) + if !ok { + return + } + + ntp, avail := tracks[0].PacketNTP(pkt) + if !avail { + return + } + + if ntp.Sub(expected).Abs() > 50*time.Millisecond { + select { + case errCh <- fmt.Sprintf("absolute NTP mismatch for seq=%d: got=%v expected=%v", + pkt.SequenceNumber, ntp, expected): + default: + } + return + } + + select { + case done <- struct{}{}: + default: + } + } + + pcReader.StartReading() + + go func() { + ticker := time.NewTicker(step) + defer ticker.Stop() + + for i := range uint16(150) { + seq := startSeq + i + expected, _ := expectedNTP(seq) + + subStream.WriteUnit(strm.OrigDesc.Medias[0], strm.OrigDesc.Medias[0].Formats[0], &unit.Unit{ + PTS: 0, + NTP: expected, + RTPPackets: []*rtp.Packet{{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 111, + SequenceNumber: seq, + Timestamp: 45343, + SSRC: 563424, + }, + Payload: []byte{1}, + }}, + }) + + <-ticker.C + } + }() + + select { + case <-done: + case err := <-errCh: + t.Fatal(err) + case <-time.After(8 * time.Second): + t.Fatal("absolute timestamp mapping did not become available") + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/inbound_track.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/inbound_track.go new file mode 100644 index 0000000000000000000000000000000000000000..3c2a18538c38ddd19e81aca516b5fe406f148a95 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/inbound_track.go @@ -0,0 +1,407 @@ +package webrtc + +import ( + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/rtpreceiver" + "github.com/pion/rtcp" + "github.com/pion/rtp" + "github.com/pion/webrtc/v4" + + "github.com/bluenviron/mediamtx/internal/counterdumper" + "github.com/bluenviron/mediamtx/internal/logger" +) + +const ( + keyFrameInterval = 2 * time.Second + mimeTypeMultiopus = "audio/multiopus" + mimeTypeL16 = "audio/L16" +) + +func inboundTrackTWCCExtensionID(params webrtc.RTPParameters) uint8 { + for _, ext := range params.HeaderExtensions { + if ext.URI == twccExtensionURI { + return uint8(ext.ID) + } + } + return 0 +} + +var incomingVideoCodecs = []webrtc.RTPCodecParameters{ + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeAV1, + ClockRate: 90000, + SDPFmtpLine: "profile=1", + }, + PayloadType: 96, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeAV1, + ClockRate: 90000, + }, + PayloadType: 97, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP9, + ClockRate: 90000, + SDPFmtpLine: "profile-id=3", + }, + PayloadType: 98, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP9, + ClockRate: 90000, + SDPFmtpLine: "profile-id=2", + }, + PayloadType: 99, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP9, + ClockRate: 90000, + SDPFmtpLine: "profile-id=1", + }, + PayloadType: 100, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP9, + ClockRate: 90000, + SDPFmtpLine: "profile-id=0", + }, + PayloadType: 101, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP8, + ClockRate: 90000, + }, + PayloadType: 102, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeH265, + ClockRate: 90000, + SDPFmtpLine: "level-id=93;profile-id=2;tier-flag=0;tx-mode=SRST", + }, + PayloadType: 103, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeH265, + ClockRate: 90000, + SDPFmtpLine: "level-id=93;profile-id=1;tier-flag=0;tx-mode=SRST", + }, + PayloadType: 104, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeH264, + ClockRate: 90000, + SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f", + }, + PayloadType: 105, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeH264, + ClockRate: 90000, + SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f", + }, + PayloadType: 106, + }, +} + +var incomingAudioCodecs = []webrtc.RTPCodecParameters{ + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: mimeTypeMultiopus, + ClockRate: 48000, + Channels: 3, + SDPFmtpLine: "channel_mapping=0,2,1;num_streams=2;coupled_streams=1", + }, + PayloadType: 112, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: mimeTypeMultiopus, + ClockRate: 48000, + Channels: 4, + SDPFmtpLine: "channel_mapping=0,1,2,3;num_streams=2;coupled_streams=2", + }, + PayloadType: 113, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: mimeTypeMultiopus, + ClockRate: 48000, + Channels: 5, + SDPFmtpLine: "channel_mapping=0,4,1,2,3;num_streams=3;coupled_streams=2", + }, + PayloadType: 114, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: mimeTypeMultiopus, + ClockRate: 48000, + Channels: 6, + SDPFmtpLine: "channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2", + }, + PayloadType: 115, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: mimeTypeMultiopus, + ClockRate: 48000, + Channels: 7, + SDPFmtpLine: "channel_mapping=0,4,1,2,3,5,6;num_streams=4;coupled_streams=4", + }, + PayloadType: 116, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: mimeTypeMultiopus, + ClockRate: 48000, + Channels: 8, + SDPFmtpLine: "channel_mapping=0,6,1,4,5,2,3,7;num_streams=5;coupled_streams=4", + }, + PayloadType: 117, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeOpus, + ClockRate: 48000, + Channels: 2, + SDPFmtpLine: "minptime=10;useinbandfec=1;stereo=1;sprop-stereo=1", + }, + PayloadType: 111, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeG722, + ClockRate: 8000, + }, + PayloadType: 9, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypePCMU, + ClockRate: 8000, + Channels: 2, + }, + PayloadType: 118, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypePCMA, + ClockRate: 8000, + Channels: 2, + }, + PayloadType: 119, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypePCMU, + ClockRate: 8000, + }, + PayloadType: 0, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypePCMA, + ClockRate: 8000, + }, + PayloadType: 8, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: mimeTypeL16, + ClockRate: 8000, + Channels: 2, + }, + PayloadType: 120, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: mimeTypeL16, + ClockRate: 16000, + Channels: 2, + }, + PayloadType: 121, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: mimeTypeL16, + ClockRate: 48000, + Channels: 2, + }, + PayloadType: 122, + }, +} + +// InboundTrack is an incoming track. +type InboundTrack struct { + OnPacketRTP func(*rtp.Packet) + + track *webrtc.TrackRemote + receiver *webrtc.RTPReceiver + rid string + writeRTCP func([]rtcp.Packet) error + log logger.Writer + + twccExtID uint8 + inboundRTPPacketsLost *counterdumper.Dumper + rtpReceiver *rtpreceiver.Receiver +} + +func (t *InboundTrack) initialize() { + t.OnPacketRTP = func(*rtp.Packet) {} + t.twccExtID = inboundTrackTWCCExtensionID(t.receiver.GetParameters()) +} + +func (t *InboundTrack) stripTWCCExtension(pkt *rtp.Packet) { + if t.twccExtID == 0 || pkt.GetExtension(t.twccExtID) == nil { + return + } + + err := pkt.DelExtension(t.twccExtID) + if err != nil { + panic(err) + } + + if len(pkt.GetExtensionIDs()) == 0 { + pkt.Extension = false + pkt.ExtensionProfile = 0 + } +} + +// Codec returns the track codec. +func (t *InboundTrack) Codec() webrtc.RTPCodecParameters { + return t.track.Codec() +} + +// ClockRate returns the clock rate. Needed by rtptime.GlobalDecoder +func (t *InboundTrack) ClockRate() int { + return int(t.track.Codec().ClockRate) +} + +// PTSEqualsDTS returns whether PTS equals DTS. Needed by rtptime.GlobalDecoder +func (*InboundTrack) PTSEqualsDTS(*rtp.Packet) bool { + return true +} + +func (t *InboundTrack) start() { + t.inboundRTPPacketsLost = &counterdumper.Dumper{ + OnReport: func(val uint64) { + t.log.Log(logger.Warn, "%d RTP %s lost", + val, + func() string { + if val == 1 { + return "packet" + } + return "packets" + }()) + }, + } + t.inboundRTPPacketsLost.Start() + + t.rtpReceiver = &rtpreceiver.Receiver{ + ClockRate: int(t.track.Codec().ClockRate), + UnrealiableTransport: true, + Period: 1 * time.Second, + WritePacketRTCP: func(p rtcp.Packet) { + t.writeRTCP([]rtcp.Packet{p}) //nolint:errcheck + }, + } + err := t.rtpReceiver.Initialize() + if err != nil { + panic(err) + } + + // read incoming RTCP packets. + // incoming RTCP packets must always be read to make interceptors work. + go func() { + buf := make([]byte, 1500) + for { + n, _, err2 := t.receiver.ReadSimulcast(buf, t.rid) + if err2 != nil { + return + } + + pkts, err2 := rtcp.Unmarshal(buf[:n]) + if err2 != nil { + panic(err2) + } + + for _, pkt := range pkts { + if sr, ok := pkt.(*rtcp.SenderReport); ok { + t.rtpReceiver.ProcessSenderReport(sr, time.Now()) + } + } + } + }() + + // send period key frame requests + if t.track.Kind() == webrtc.RTPCodecTypeVideo { + go func() { + keyframeTicker := time.NewTicker(keyFrameInterval) + defer keyframeTicker.Stop() + + for range keyframeTicker.C { + err2 := t.writeRTCP([]rtcp.Packet{ + &rtcp.PictureLossIndication{ + MediaSSRC: uint32(t.track.SSRC()), + }, + }) + if err2 != nil { + return + } + } + }() + } + + // read incoming RTP packets. + go func() { + for { + pkt, _, err2 := t.track.ReadRTP() + if err2 != nil { + return + } + + packets, lost := t.rtpReceiver.ProcessPacket2(pkt, time.Now(), true) + + if lost != 0 { + t.inboundRTPPacketsLost.Add(lost) + // do not return + } + + for _, pkt := range packets { + // sometimes Chrome sends empty RTP packets. ignore them. + if len(pkt.Payload) == 0 { + continue + } + + t.stripTWCCExtension(pkt) + t.OnPacketRTP(pkt) + } + } + }() +} + +// PacketNTP returns the packet NTP. +func (t *InboundTrack) PacketNTP(pkt *rtp.Packet) (time.Time, bool) { + return t.rtpReceiver.PacketNTP(pkt.Timestamp) +} + +func (t *InboundTrack) close() { + if t.inboundRTPPacketsLost != nil { + t.inboundRTPPacketsLost.Stop() + } + if t.rtpReceiver != nil { + t.rtpReceiver.Close() + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/net.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/net.go new file mode 100644 index 0000000000000000000000000000000000000000..eb10d2a19c1912cc0b38692b0d0ff658921f64a6 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/net.go @@ -0,0 +1,97 @@ +package webrtc + +import ( + "fmt" + "net" + + "github.com/bluenviron/gortsplib/v5/pkg/readbuffer" + "github.com/pion/transport/v4" + "github.com/pion/transport/v4/stdnet" + "github.com/wlynxg/anet" +) + +// Net is stdnet.Net with the following changes: +// - Interfaces() is overridden to query the OS directly on every call without caching. +// - ListenUDP() is overridden to apply the configured read buffer size to the returned UDPConn. +type Net struct { + UDPReadBufferSize int + + stdnet.Net +} + +// Interfaces returns the current list of network interfaces by querying the OS +// on every call, with no caching. +func (n *Net) Interfaces() ([]*transport.Interface, error) { + oifs, err := anet.Interfaces() + if err != nil { + return nil, err + } + + ifs := make([]*transport.Interface, 0, len(oifs)) + for i := range oifs { + ifc := transport.NewInterface(oifs[i]) + + var addrs []net.Addr + addrs, err = anet.InterfaceAddrsByInterface(&oifs[i]) + if err != nil { + return nil, err + } + + for _, addr := range addrs { + ifc.AddAddress(addr) + } + + ifs = append(ifs, ifc) + } + + return ifs, nil +} + +// InterfaceByIndex returns the interface specified by index. +func (n *Net) InterfaceByIndex(index int) (*transport.Interface, error) { + ifaces, err := n.Interfaces() + if err != nil { + return nil, err + } + + for _, ifc := range ifaces { + if ifc.Index == index { + return ifc, nil + } + } + + return nil, fmt.Errorf("%w: index=%d", transport.ErrInterfaceNotFound, index) +} + +// InterfaceByName returns the interface specified by name. +func (n *Net) InterfaceByName(name string) (*transport.Interface, error) { + ifaces, err := n.Interfaces() + if err != nil { + return nil, err + } + + for _, ifc := range ifaces { + if ifc.Name == name { + return ifc, nil + } + } + + return nil, fmt.Errorf("%w: %s", transport.ErrInterfaceNotFound, name) +} + +// ListenUDP acts like ListenPacket for UDP networks and applies the configured +// read buffer size. +func (n *Net) ListenUDP(network string, laddr *net.UDPAddr) (transport.UDPConn, error) { + conn, err := net.ListenUDP(network, laddr) + if err != nil { + return nil, err + } + + if n.UDPReadBufferSize != 0 { + if err = readbuffer.SetReadBuffer(conn, n.UDPReadBufferSize); err != nil { + return nil, err + } + } + + return conn, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/outbound_data_channel.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/outbound_data_channel.go new file mode 100644 index 0000000000000000000000000000000000000000..57ba099fad53ee95ccb4ea57e645328683c2891b --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/outbound_data_channel.go @@ -0,0 +1,29 @@ +package webrtc + +import ( + "github.com/pion/webrtc/v4" +) + +// OutboundDataChannel is an outgoing data channel. +type OutboundDataChannel struct { + Label string + + dataChan *webrtc.DataChannel +} + +func (c *OutboundDataChannel) setup(p *PeerConnection) error { + var err error + c.dataChan, err = p.wr.CreateDataChannel(c.Label, &webrtc.DataChannelInit{ + Ordered: new(false), + }) + if err != nil { + return err + } + + return nil +} + +// Write writes data to the channel. +func (c *OutboundDataChannel) Write(data []byte) { + c.dataChan.Send(data) //nolint:errcheck +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/outbound_track.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/outbound_track.go new file mode 100644 index 0000000000000000000000000000000000000000..0823bf14515103712870f8f916d55babe4547648 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/outbound_track.go @@ -0,0 +1,99 @@ +package webrtc + +import ( + "strings" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/rtpsender" + "github.com/pion/rtcp" + "github.com/pion/rtp" + "github.com/pion/webrtc/v4" +) + +// OutboundTrack is an outgoing track. +type OutboundTrack struct { + Caps webrtc.RTPCodecCapability + + track *webrtc.TrackLocalStaticRTP + ssrc uint32 + rtcpSender *rtpsender.Sender +} + +func (t *OutboundTrack) isVideo() bool { + return strings.Split(t.Caps.MimeType, "/")[0] == "video" +} + +func (t *OutboundTrack) setup(p *PeerConnection) error { + var trackID string + if t.isVideo() { + trackID = "video" + } else { + trackID = "audio" + } + + var err error + t.track, err = webrtc.NewTrackLocalStaticRTP( + t.Caps, + trackID, + webrtcStreamID, + ) + if err != nil { + return err + } + + sender, err := p.wr.AddTrack(t.track) + if err != nil { + return err + } + + t.ssrc = uint32(sender.GetParameters().Encodings[0].SSRC) + + t.rtcpSender = &rtpsender.Sender{ + ClockRate: int(t.track.Codec().ClockRate), + Period: 1 * time.Second, + TimeNow: time.Now, + WritePacketRTCP: func(pkt rtcp.Packet) { + p.wr.WriteRTCP([]rtcp.Packet{pkt}) //nolint:errcheck + }, + } + t.rtcpSender.Initialize() + + // incoming RTCP packets must always be read to make interceptors work + go func() { + buf := make([]byte, 1500) + for { + n, _, err2 := sender.Read(buf) + if err2 != nil { + return + } + + _, err2 = rtcp.Unmarshal(buf[:n]) + if err2 != nil { + panic(err2) + } + } + }() + + return nil +} + +func (t *OutboundTrack) close() { + if t.rtcpSender != nil { + t.rtcpSender.Close() + } +} + +// WriteRTP writes a RTP packet. +func (t *OutboundTrack) WriteRTP(pkt *rtp.Packet) error { + return t.WriteRTPWithNTP(pkt, time.Now()) +} + +// WriteRTPWithNTP writes a RTP packet. +func (t *OutboundTrack) WriteRTPWithNTP(pkt *rtp.Packet, ntp time.Time) error { + // use right SSRC in packet to make rtcpSender work + pkt.SSRC = t.ssrc + + t.rtcpSender.ProcessPacket(pkt, ntp, true) + + return t.track.WriteRTP(pkt) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/peer_connection.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/peer_connection.go new file mode 100644 index 0000000000000000000000000000000000000000..84e6da5120190b6a8faafcadc62a72c513d73cde --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/peer_connection.go @@ -0,0 +1,990 @@ +// Package webrtc contains WebRTC utilities. +package webrtc + +import ( + "context" + "errors" + "fmt" + "net" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/pion/ice/v4" + "github.com/pion/interceptor" + "github.com/pion/sdp/v3" + "github.com/pion/transport/v4" + "github.com/pion/webrtc/v4" + + "github.com/bluenviron/mediamtx/internal/logger" +) + +const ( + webrtcStreamID = "mediamtx" + twccExtensionURI = "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01" +) + +func interfaceIPs(interfaceList []string) ([]string, error) { + intfs, err := net.Interfaces() + if err != nil { + return nil, err + } + + var ips []string + + for _, intf := range intfs { + if len(interfaceList) == 0 || slices.Contains(interfaceList, intf.Name) { + var addrs []net.Addr + addrs, err = intf.Addrs() + if err == nil { + for _, addr := range addrs { + var ip net.IP + + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + case *net.IPAddr: + ip = v.IP + } + + if ip != nil { + ips = append(ips, ip.String()) + } + } + } + } + } + + return ips, nil +} + +func maxTrackCount(medias []*sdp.MediaDescription) int { + total := 0 + for _, media := range medias { + ridCount := 0 + + for _, attr := range media.Attributes { + if attr.Key == "rid" { + ridCount++ + } + } + + if ridCount == 0 { + ridCount = 1 + } + total += ridCount + } + return total +} + +// * skip ConfigureRTCPReports +// * add statsInterceptor +func registerInterceptors( + mediaEngine *webrtc.MediaEngine, + interceptorRegistry *interceptor.Registry, + onStatsInterceptor func(s *statsInterceptor), +) error { + err := webrtc.ConfigureNack(mediaEngine, interceptorRegistry) + if err != nil { + return err + } + + err = webrtc.ConfigureSimulcastExtensionHeaders(mediaEngine) + if err != nil { + return err + } + + err = webrtc.ConfigureTWCCSender(mediaEngine, interceptorRegistry) + if err != nil { + return err + } + + interceptorRegistry.Add(&statsInterceptorFactory{ + onCreate: onStatsInterceptor, + }) + + return nil +} + +func candidateLabel(c *webrtc.ICECandidate) string { + return c.Typ.String() + "/" + c.Protocol.String() + "/" + + c.Address + "/" + strconv.FormatInt(int64(c.Port), 10) +} + +// TracksAreValid checks whether tracks in the SDP are valid +func TracksAreValid(medias []*sdp.MediaDescription) error { + videoTrack := false + audioTrack := false + + for _, media := range medias { + switch media.MediaName.Media { + case "video": + if videoTrack { + return fmt.Errorf("only a single video and a single audio track are supported") + } + videoTrack = true + + case "audio": + if audioTrack { + return fmt.Errorf("only a single video and a single audio track are supported") + } + audioTrack = true + + default: + return fmt.Errorf("unsupported media '%s'", media.MediaName.Media) + } + } + + if !videoTrack && !audioTrack { + return fmt.Errorf("no valid tracks found") + } + + return nil +} + +type trackRecvPair struct { + track *webrtc.TrackRemote + receiver *webrtc.RTPReceiver +} + +// PeerConnection is a wrapper around webrtc.PeerConnection. +type PeerConnection struct { + Net transport.Net + LocalRandomUDP bool + ICEUDPMux ice.UDPMux + ICETCPMux *TCPMuxWrapper + ICEServers []webrtc.ICEServer + IPsFromInterfaces bool + IPsFromInterfacesList []string + AdditionalHosts []string + STUNGatherTimeout time.Duration + Publish bool + OutboundTracks []*OutboundTrack + OutboundDataChannels []*OutboundDataChannel + Log logger.Writer + + wr *webrtc.PeerConnection + ctx context.Context + ctxCancel context.CancelFunc + readingStarted atomic.Int64 + inboundTracks []*InboundTrack + statsInterceptor *statsInterceptor + + newLocalCandidate chan *webrtc.ICECandidateInit + inboundTrack chan trackRecvPair + + stateMutex sync.Mutex + state webrtc.PeerConnectionState + stateChanged chan struct{} + + gatheringMutex sync.Mutex + gatheringDone chan struct{} + + done chan struct{} + chStartReading chan struct{} +} + +// Start starts the peer connection. +func (co *PeerConnection) Start() error { + if co.STUNGatherTimeout == 0 { + co.STUNGatherTimeout = 5 * time.Second + } + + settingsEngine := webrtc.SettingEngine{} + + settingsEngine.SetIncludeLoopbackCandidate(true) + + // always enable TCP since we might be the client of a remote TCP listener + networkTypes := []webrtc.NetworkType{ + webrtc.NetworkTypeTCP4, + webrtc.NetworkTypeTCP6, + } + + if co.LocalRandomUDP || co.ICEUDPMux != nil || len(co.ICEServers) != 0 { + networkTypes = append(networkTypes, webrtc.NetworkTypeUDP4, webrtc.NetworkTypeUDP6) + } + + settingsEngine.SetNetworkTypes(networkTypes) + + if co.ICEUDPMux != nil { + settingsEngine.SetICEUDPMux(co.ICEUDPMux) + } + + if co.ICETCPMux != nil { + settingsEngine.SetICETCPMux(co.ICETCPMux.Mux) + } + + settingsEngine.SetSTUNGatherTimeout(co.STUNGatherTimeout) + + settingsEngine.SetNet(co.Net) + + mediaEngine := &webrtc.MediaEngine{} + + if co.Publish { + videoSetupped := false + audioSetupped := false + for _, tr := range co.OutboundTracks { + if tr.isVideo() { + videoSetupped = true + } else { + audioSetupped = true + } + } + + // When audio is not used, a track has to be present anyway, + // otherwise video is not displayed on Firefox and Chrome. + if !audioSetupped { + co.OutboundTracks = append(co.OutboundTracks, &OutboundTrack{ + Caps: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypePCMU, + ClockRate: 8000, + }, + }) + } + + for i, tr := range co.OutboundTracks { + var codecType webrtc.RTPCodecType + if tr.isVideo() { + codecType = webrtc.RTPCodecTypeVideo + } else { + codecType = webrtc.RTPCodecTypeAudio + } + + err := mediaEngine.RegisterCodec(webrtc.RTPCodecParameters{ + RTPCodecCapability: tr.Caps, + PayloadType: webrtc.PayloadType(96 + i), + }, codecType) + if err != nil { + return err + } + } + + // When video is not used, a track must not be added but a codec has to present. + // Otherwise audio is muted on Firefox and Chrome. + if !videoSetupped { + err := mediaEngine.RegisterCodec(webrtc.RTPCodecParameters{ + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP8, + ClockRate: 90000, + }, + PayloadType: 96, + }, webrtc.RTPCodecTypeVideo) + if err != nil { + return err + } + } + } else { + for _, codec := range incomingVideoCodecs { + err := mediaEngine.RegisterCodec(codec, webrtc.RTPCodecTypeVideo) + if err != nil { + return err + } + } + + for _, codec := range incomingAudioCodecs { + err := mediaEngine.RegisterCodec(codec, webrtc.RTPCodecTypeAudio) + if err != nil { + return err + } + } + } + + interceptorRegistry := &interceptor.Registry{} + + err := registerInterceptors( + mediaEngine, + interceptorRegistry, + func(s *statsInterceptor) { + co.statsInterceptor = s + }, + ) + if err != nil { + return err + } + + api := webrtc.NewAPI( + webrtc.WithSettingEngine(settingsEngine), + webrtc.WithMediaEngine(mediaEngine), + webrtc.WithInterceptorRegistry(interceptorRegistry)) + + co.wr, err = api.NewPeerConnection(webrtc.Configuration{ + ICEServers: co.ICEServers, + }) + if err != nil { + return err + } + + co.ctx, co.ctxCancel = context.WithCancel(context.Background()) + + co.newLocalCandidate = make(chan *webrtc.ICECandidateInit) + co.stateChanged = make(chan struct{}) + co.gatheringDone = make(chan struct{}) + co.inboundTrack = make(chan trackRecvPair) + co.done = make(chan struct{}) + co.chStartReading = make(chan struct{}) + + if co.Publish { + for _, tr := range co.OutboundTracks { + err = tr.setup(co) + if err != nil { + co.wr.GracefulClose() //nolint:errcheck + return err + } + } + + for _, dc := range co.OutboundDataChannels { + err = dc.setup(co) + if err != nil { + co.wr.GracefulClose() //nolint:errcheck + return err + } + } + } else { + _, err = co.wr.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo, webrtc.RTPTransceiverInit{ + Direction: webrtc.RTPTransceiverDirectionRecvonly, + }) + if err != nil { + co.wr.GracefulClose() //nolint:errcheck + return err + } + + _, err = co.wr.AddTransceiverFromKind(webrtc.RTPCodecTypeAudio, webrtc.RTPTransceiverInit{ + Direction: webrtc.RTPTransceiverDirectionRecvonly, + }) + if err != nil { + co.wr.GracefulClose() //nolint:errcheck + return err + } + + co.wr.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) { + select { + case co.inboundTrack <- trackRecvPair{track, receiver}: + case <-co.ctx.Done(): + } + }) + } + + co.wr.OnConnectionStateChange(func(state webrtc.PeerConnectionState) { + co.stateMutex.Lock() + defer co.stateMutex.Unlock() + + if co.state == webrtc.PeerConnectionStateFailed || co.state == webrtc.PeerConnectionStateClosed { + return + } + + co.state = state + close(co.stateChanged) + co.stateChanged = make(chan struct{}) + + co.Log.Log(logger.Debug, "peer connection state: "+state.String()) + + if state == webrtc.PeerConnectionStateConnected { + co.Log.Log(logger.Info, "peer connection established, local candidate: %v, remote candidate: %v", + co.LocalCandidate(), co.RemoteCandidate()) + } + }) + + co.wr.OnICECandidate(func(i *webrtc.ICECandidate) { + co.gatheringMutex.Lock() + defer co.gatheringMutex.Unlock() + + if i != nil { + v := i.ToJSON() + + select { + case co.newLocalCandidate <- &v: + case <-co.Connected(): + case <-co.ctx.Done(): + } + } else { + select { + case <-co.gatheringDone: + default: + close(co.gatheringDone) + } + } + }) + + go co.run() + + return nil +} + +// Close closes the connection. +func (co *PeerConnection) Close() { + co.ctxCancel() + <-co.done +} + +func (co *PeerConnection) run() { + defer close(co.done) + + defer func() { + for _, track := range co.inboundTracks { + track.close() + } + for _, track := range co.OutboundTracks { + track.close() + } + + co.wr.GracefulClose() //nolint:errcheck + + // even if GracefulClose() should wait for any goroutine to return, + // we have to wait for OnConnectionStateChange to return anyway, + // since it is executed in an uncontrolled goroutine. + // https://github.com/pion/webrtc/blob/v4.2.8/peerconnection.go#L529 + <-co.failedNoContext() + }() + + for { + select { + case <-co.chStartReading: + for _, track := range co.inboundTracks { + track.start() + } + co.readingStarted.Store(1) + + case <-co.ctx.Done(): + return + } + } +} + +func (co *PeerConnection) removeUnwantedCandidates(firstMedia *sdp.MediaDescription) error { + var allowedIPs []string + if co.IPsFromInterfaces { + var err error + allowedIPs, err = interfaceIPs(co.IPsFromInterfacesList) + if err != nil { + return err + } + } + + var newAttributes []sdp.Attribute //nolint:prealloc + + for _, attr := range firstMedia.Attributes { + if attr.Key == "candidate" { + parts := strings.Split(attr.Value, " ") + + // hide random UDP candidates + if !co.LocalRandomUDP && co.ICEUDPMux == nil && parts[2] == "udp" && parts[7] == "host" { + continue + } + + // hide disallowed IPs + if parts[7] == "host" && !slices.Contains(allowedIPs, parts[4]) { + continue + } + } + + newAttributes = append(newAttributes, attr) + } + + firstMedia.Attributes = newAttributes + + return nil +} + +func (co *PeerConnection) addAdditionalCandidates(firstMedia *sdp.MediaDescription) error { + i := 0 + for _, attr := range firstMedia.Attributes { + if attr.Key == "end-of-candidates" { + break + } + i++ + } + + for _, host := range co.AdditionalHosts { + var ips []string + if net.ParseIP(host) != nil { + ips = []string{host} + } else { + tmp, err := net.LookupIP(host) + if err != nil { + return err + } + + ips = make([]string, len(tmp)) + for i, e := range tmp { + ips[i] = e.String() + } + } + + for _, ip := range ips { + newAttrs := append([]sdp.Attribute(nil), firstMedia.Attributes[:i]...) + + if co.ICEUDPMux != nil { + port := strconv.FormatInt(int64(co.ICEUDPMux.GetListenAddresses()[0].(*net.UDPAddr).Port), 10) + + tmp, err := randUint32() + if err != nil { + return err + } + id := strconv.FormatInt(int64(tmp), 10) + + newAttrs = append(newAttrs, sdp.Attribute{ + Key: "candidate", + Value: id + " 1 udp 2130706431 " + ip + " " + port + " typ host", + }) + newAttrs = append(newAttrs, sdp.Attribute{ + Key: "candidate", + Value: id + " 2 udp 2130706431 " + ip + " " + port + " typ host", + }) + } + + if co.ICETCPMux != nil { + port := strconv.FormatInt(int64(co.ICETCPMux.Ln.Addr().(*net.TCPAddr).Port), 10) + + tmp, err := randUint32() + if err != nil { + return err + } + id := strconv.FormatInt(int64(tmp), 10) + + newAttrs = append(newAttrs, sdp.Attribute{ + Key: "candidate", + Value: id + " 1 tcp 1671430143 " + ip + " " + port + " typ host tcptype passive", + }) + newAttrs = append(newAttrs, sdp.Attribute{ + Key: "candidate", + Value: id + " 2 tcp 1671430143 " + ip + " " + port + " typ host tcptype passive", + }) + } + + newAttrs = append(newAttrs, firstMedia.Attributes[i:]...) + firstMedia.Attributes = newAttrs + } + } + + return nil +} + +func (co *PeerConnection) filterLocalDescription(desc *webrtc.SessionDescription) (*webrtc.SessionDescription, error) { + var psdp sdp.SessionDescription + psdp.Unmarshal([]byte(desc.SDP)) //nolint:errcheck + + firstMedia := psdp.MediaDescriptions[0] + + err := co.removeUnwantedCandidates(firstMedia) + if err != nil { + return nil, err + } + + err = co.addAdditionalCandidates(firstMedia) + if err != nil { + return nil, err + } + + out, _ := psdp.Marshal() + desc.SDP = string(out) + + return desc, nil +} + +// CreatePartialOffer creates a partial offer. +func (co *PeerConnection) CreatePartialOffer(restart bool) (*webrtc.SessionDescription, error) { + var options *webrtc.OfferOptions + if restart { + co.gatheringMutex.Lock() + + select { + case <-co.gatheringDone: + default: + co.gatheringMutex.Unlock() + return nil, fmt.Errorf("tried an ICE restart before candidate gathering is complete") + } + + co.gatheringDone = make(chan struct{}) + + co.gatheringMutex.Unlock() + + options = &webrtc.OfferOptions{ + ICERestart: true, + } + } + + tmp, err := co.wr.CreateOffer(options) + if err != nil { + return nil, err + } + offer := &tmp + + err = co.wr.SetLocalDescription(*offer) + if err != nil { + return nil, err + } + + offer, err = co.filterLocalDescription(offer) + if err != nil { + return nil, err + } + + return offer, nil +} + +// CreateFullOffer creates a full offer. +func (co *PeerConnection) CreateFullOffer() (*webrtc.SessionDescription, error) { + tmp, err := co.wr.CreateOffer(nil) + if err != nil { + return nil, err + } + offer := &tmp + + err = co.wr.SetLocalDescription(*offer) + if err != nil { + return nil, err + } + + err = co.waitGatheringDone() + if err != nil { + return nil, err + } + + offer = co.wr.LocalDescription() + + offer, err = co.filterLocalDescription(offer) + if err != nil { + return nil, err + } + + return offer, nil +} + +// SetAnswer sets the answer. +func (co *PeerConnection) SetAnswer(answer *webrtc.SessionDescription) error { + return co.wr.SetRemoteDescription(*answer) +} + +// RemoteDescription returns the current remote description. +func (co *PeerConnection) RemoteDescription() *webrtc.SessionDescription { + return co.wr.RemoteDescription() +} + +// AddRemoteCandidate adds a remote candidate. +func (co *PeerConnection) AddRemoteCandidate(candidate *webrtc.ICECandidateInit) error { + return co.wr.AddICECandidate(*candidate) +} + +// CreateFullAnswer accepts an offer and creates a full answer. +func (co *PeerConnection) CreateFullAnswer( + offer *webrtc.SessionDescription, + restarted bool, +) (*webrtc.SessionDescription, error) { + if restarted { + co.gatheringMutex.Lock() + + select { + case <-co.gatheringDone: + default: + co.gatheringMutex.Unlock() + return nil, fmt.Errorf("tried an ICE restart before candidate gathering is complete") + } + + co.gatheringDone = make(chan struct{}) + + co.gatheringMutex.Unlock() + } + + err := co.wr.SetRemoteDescription(*offer) + if err != nil { + return nil, err + } + + tmp, err := co.wr.CreateAnswer(nil) + if err != nil { + if errors.Is(err, webrtc.ErrSenderWithNoCodecs) { + return nil, fmt.Errorf("codecs not supported by client") + } + return nil, err + } + answer := &tmp + + err = co.wr.SetLocalDescription(*answer) + if err != nil { + return nil, err + } + + err = co.waitGatheringDone() + if err != nil { + return nil, err + } + + answer = co.wr.LocalDescription() + + answer, err = co.filterLocalDescription(answer) + if err != nil { + return nil, err + } + + return answer, nil +} + +func (co *PeerConnection) waitGatheringDone() error { + for { + select { + case <-co.NewLocalCandidate(): + case <-co.GatheringDone(): + return nil + case <-co.ctx.Done(): + return fmt.Errorf("terminated") + } + } +} + +// WaitUntilConnected waits until connection is established. +func (co *PeerConnection) WaitUntilConnected(timeout time.Duration) error { + t := time.NewTimer(timeout) + defer t.Stop() + +outer: + for { + select { + case <-t.C: + return fmt.Errorf("deadline exceeded while waiting connection") + + case <-co.Connected(): + break outer + + case <-co.ctx.Done(): + return fmt.Errorf("terminated") + } + } + + return nil +} + +// GatherInboundTracks gathers incoming tracks. +func (co *PeerConnection) GatherInboundTracks(timeout time.Duration) error { + var sdp sdp.SessionDescription + sdp.Unmarshal([]byte(co.wr.RemoteDescription().SDP)) //nolint:errcheck + + maxTrackCount := maxTrackCount(sdp.MediaDescriptions) + + t := time.NewTimer(timeout) + defer t.Stop() + + for { + select { + case <-t.C: + if len(co.inboundTracks) != 0 { + return nil + } + return fmt.Errorf("deadline exceeded while waiting tracks") + + case pair := <-co.inboundTrack: + t := &InboundTrack{ + track: pair.track, + receiver: pair.receiver, + rid: pair.track.RID(), + writeRTCP: co.wr.WriteRTCP, + log: co.Log, + } + t.initialize() + co.inboundTracks = append(co.inboundTracks, t) + + if len(co.inboundTracks) >= maxTrackCount { + return nil + } + + case <-co.Failed(): + return fmt.Errorf("peer connection closed") + + case <-co.ctx.Done(): + return fmt.Errorf("terminated") + } + } +} + +// Connected returns when connected. +func (co *PeerConnection) Connected() <-chan struct{} { + ch := make(chan struct{}) + + go func() { + for { + co.stateMutex.Lock() + state := co.state + stateChanged := co.stateChanged + co.stateMutex.Unlock() + + if state == webrtc.PeerConnectionStateConnected { + close(ch) + return + } + + select { + case <-stateChanged: + case <-co.ctx.Done(): + // exit without closing ch + return + } + } + }() + + return ch +} + +// Failed returns when failed or closed. +func (co *PeerConnection) Failed() <-chan struct{} { + ch := make(chan struct{}) + + go func() { + defer close(ch) + for { + co.stateMutex.Lock() + state := co.state + stateChanged := co.stateChanged + co.stateMutex.Unlock() + + // "closed" can arrive before "failed" and without + // the Close() method being called at all. + // It happens when the other peer sends a termination + // message like a DTLS CloseNotify. + if state == webrtc.PeerConnectionStateFailed || state == webrtc.PeerConnectionStateClosed { + return + } + + select { + case <-stateChanged: + case <-co.ctx.Done(): + return + } + } + }() + + return ch +} + +func (co *PeerConnection) failedNoContext() <-chan struct{} { + ch := make(chan struct{}) + + go func() { + for { + co.stateMutex.Lock() + state := co.state + stateChanged := co.stateChanged + co.stateMutex.Unlock() + + if state == webrtc.PeerConnectionStateFailed || state == webrtc.PeerConnectionStateClosed { + close(ch) + return + } + + <-stateChanged + } + }() + + return ch +} + +// NewLocalCandidate returns when there's a new local candidate. +func (co *PeerConnection) NewLocalCandidate() <-chan *webrtc.ICECandidateInit { + return co.newLocalCandidate +} + +// GatheringDone returns when candidate gathering is complete. +func (co *PeerConnection) GatheringDone() <-chan struct{} { + return co.gatheringDone +} + +// InboundTracks returns incoming tracks. +func (co *PeerConnection) InboundTracks() []*InboundTrack { + return co.inboundTracks +} + +// StartReading starts reading incoming tracks. +func (co *PeerConnection) StartReading() { + select { + case co.chStartReading <- struct{}{}: + case <-co.ctx.Done(): + } +} + +// LocalCandidate returns the local candidate. +func (co *PeerConnection) LocalCandidate() string { + receivers := co.wr.GetReceivers() + if len(receivers) < 1 { + return "" + } + + cp, err := receivers[0].Transport().ICETransport().GetSelectedCandidatePair() + if err != nil || cp == nil { + return "" + } + + return candidateLabel(cp.Local) +} + +// RemoteCandidate returns the remote candidate. +func (co *PeerConnection) RemoteCandidate() string { + receivers := co.wr.GetReceivers() + if len(receivers) < 1 { + return "" + } + + cp, err := receivers[0].Transport().ICETransport().GetSelectedCandidatePair() + if err != nil || cp == nil { + return "" + } + + return candidateLabel(cp.Remote) +} + +func bytesStats(wr *webrtc.PeerConnection) (uint64, uint64) { + for _, stats := range wr.GetStats() { + if tstats, ok := stats.(webrtc.TransportStats); ok { + if tstats.ID == "iceTransport" { + return tstats.BytesReceived, tstats.BytesSent + } + } + } + return 0, 0 +} + +// Stats returns statistics. +func (co *PeerConnection) Stats() *Stats { + bytesReceived, bytesSent := bytesStats(co.wr) + + v := float64(0) + n := float64(0) + packetsReceived := uint64(0) + packetsSent := uint64(0) + packetsLost := uint64(0) + + if co.readingStarted.Load() == 1 { + for _, tr := range co.inboundTracks { + if recvStats := tr.rtpReceiver.Stats(); recvStats != nil { + v += recvStats.Jitter + n++ + packetsReceived += recvStats.Received + packetsLost += recvStats.Lost + } + } + } + + for _, tr := range co.OutboundTracks { + if sentStats := tr.rtcpSender.Stats(); sentStats != nil { + packetsSent += sentStats.Sent + } + } + + var rtpPacketsJitter float64 + if n != 0 { + rtpPacketsJitter = v / n + } else { + rtpPacketsJitter = 0 + } + + return &Stats{ + BytesReceived: bytesReceived, + BytesSent: bytesSent, + RTPPacketsReceived: packetsReceived, + RTPPacketsSent: packetsSent, + RTPPacketsLost: packetsLost, + RTPPacketsJitter: rtpPacketsJitter, + RTCPPacketsReceived: co.statsInterceptor.rtcpPacketsReceived.Load(), + RTCPPacketsSent: co.statsInterceptor.rtcpPacketsSent.Load(), + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/peer_connection_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/peer_connection_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c198ae5ea822ce08ce65574e494a688854425c20 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/peer_connection_test.go @@ -0,0 +1,888 @@ +package webrtc + +import ( + "net" + "regexp" + "sort" + "strings" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/test" + "github.com/pion/ice/v4" + "github.com/pion/logging" + "github.com/pion/rtcp" + "github.com/pion/rtp" + "github.com/pion/sdp/v3" + "github.com/pion/webrtc/v4" + "github.com/stretchr/testify/require" +) + +type nilWriter struct{} + +func (nilWriter) Write(p []byte) (int, error) { + return len(p), nil +} + +var webrtcNilLogger = logging.NewDefaultLeveledLoggerForScope("", 0, &nilWriter{}) + +func gatherCodecs(tracks []*InboundTrack) []webrtc.RTPCodecParameters { + codecs := make([]webrtc.RTPCodecParameters, len(tracks)) + for i, track := range tracks { + codecs[i] = track.Codec() + } + return codecs +} + +func senderHeaderExtensionID(params webrtc.RTPSendParameters, uri string) uint8 { + for _, ext := range params.HeaderExtensions { + if ext.URI == uri { + return uint8(ext.ID) + } + } + return 0 +} + +func TestPeerConnectionCloseImmediately(t *testing.T) { + pc := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: false, + Log: test.NilLogger, + } + err := pc.Start() + require.NoError(t, err) + defer pc.Close() +} + +func TestPeerConnectionCloseImmediately2(t *testing.T) { + pc := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: false, + Log: test.NilLogger, + } + err := pc.Start() + require.NoError(t, err) + defer pc.Close() + + _, err = pc.CreatePartialOffer(false) + require.NoError(t, err) + + // wait for ICE candidates to be generated + time.Sleep(500 * time.Millisecond) +} + +func TestPeerConnectionCandidates(t *testing.T) { + for _, ca := range []string{ + "udp random", + "udp", + "tcp", + "stun", + "udp+stun", + "udp random+stun", + } { + t.Run(ca, func(t *testing.T) { + pc2, err := webrtc.NewPeerConnection(webrtc.Configuration{}) + require.NoError(t, err) + defer pc2.Close() //nolint:errcheck + + track, err := webrtc.NewTrackLocalStaticRTP( + webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP8, + ClockRate: 90000, + }, + "video", + "publisher", + ) + require.NoError(t, err) + + _, err = pc2.AddTrack(track) + require.NoError(t, err) + + offer, err := pc2.CreateOffer(nil) + require.NoError(t, err) + + var udpMux ice.UDPMux + if ca == "udp" || ca == "udp+stun" { + var ln net.PacketConn + ln, err = net.ListenPacket("udp", ":3454") + require.NoError(t, err) + defer ln.Close() + udpMux = webrtc.NewICEUDPMux(webrtcNilLogger, ln) + } + + var tcpMux *TCPMuxWrapper + if ca == "tcp" { + var ln net.Listener + ln, err = net.Listen("tcp", ":3454") + require.NoError(t, err) + defer ln.Close() + tcpMux = &TCPMuxWrapper{ + Mux: webrtc.NewICETCPMux(webrtcNilLogger, ln, 8), + Ln: ln, + } + } + + pc := &PeerConnection{ + LocalRandomUDP: (ca == "udp random" || ca == "udp random+stun"), + ICEUDPMux: udpMux, + ICETCPMux: tcpMux, + IPsFromInterfaces: true, + IPsFromInterfacesList: []string{"lo"}, + Log: test.NilLogger, + } + + if ca == "stun" || ca == "udp+stun" || ca == "udp random+stun" { + pc.ICEServers = []webrtc.ICEServer{{ + URLs: []string{"stun:stun.l.google.com:19302"}, + }} + } + + err = pc.Start() + require.NoError(t, err) + defer pc.Close() + + answer, err := pc.CreateFullAnswer(&offer, false) + require.NoError(t, err) + + n := len(regexp.MustCompile("(?m)^a=candidate:.+? udp .+? typ host").FindAllString(answer.SDP, -1)) + if ca == "udp" || ca == "udp random" || ca == "udp+stun" || ca == "udp random+stun" { + require.Equal(t, 2, n) + } else { + require.Equal(t, 0, n) + } + + n = len(regexp.MustCompile("(?m)^a=candidate:.+? tcp .+? typ host tcptype passive").FindAllString(answer.SDP, -1)) + if ca == "tcp" { + require.Equal(t, 2, n) + } else { + require.Equal(t, 0, n) + } + + n = len(regexp.MustCompile("(?m)^a=candidate:.+? udp .+? typ srflx").FindAllString(answer.SDP, -1)) + if ca == "stun" || ca == "udp+stun" || ca == "udp random+stun" { + require.Equal(t, 2, n) + } else { + require.Equal(t, 0, n) + } + }) + } +} + +func TestPeerConnectionConnectivity(t *testing.T) { + for _, mode := range []string{ + "passive udp", + "passive tcp", + "active udp", + "active udp + stun", + } { + for _, ip := range []string{ + "from interfaces", + "additional hosts", + } { + // LocalRandomUDP doesn't work with AdditionalHosts + // we don't care since we are not currently using them together + if mode == "active udp" && ip == "additional hosts" { + continue + } + + t.Run(mode+"_"+ip, func(t *testing.T) { + var iceServers []webrtc.ICEServer + + if mode == "active udp + stun" { + iceServers = []webrtc.ICEServer{{ + URLs: []string{"stun:stun.l.google.com:19302"}, + }} + } + + clientPC := &PeerConnection{ + LocalRandomUDP: (mode == "passive udp" || mode == "active udp"), + IPsFromInterfaces: true, + IPsFromInterfacesList: []string{"lo"}, + ICEServers: iceServers, + Log: test.NilLogger, + } + err := clientPC.Start() + require.NoError(t, err) + defer clientPC.Close() + + var udpMux ice.UDPMux + var tcpMux *TCPMuxWrapper + + switch mode { + case "passive udp": + var ln net.PacketConn + ln, err = net.ListenPacket("udp4", ":4458") + require.NoError(t, err) + defer ln.Close() + udpMux = webrtc.NewICEUDPMux(webrtcNilLogger, ln) + + case "passive tcp": + var ln net.Listener + ln, err = net.Listen("tcp4", ":4458") + require.NoError(t, err) + defer ln.Close() + tcpMux = &TCPMuxWrapper{ + Mux: webrtc.NewICETCPMux(webrtcNilLogger, ln, 8), + Ln: ln, + } + } + + serverPC := &PeerConnection{ + LocalRandomUDP: (mode == "active udp"), + ICEUDPMux: udpMux, + ICETCPMux: tcpMux, + ICEServers: iceServers, + Publish: true, + OutboundTracks: []*OutboundTrack{{ + Caps: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeAV1, + ClockRate: 90000, + }, + }}, + Log: test.NilLogger, + } + + if ip == "from interfaces" { + serverPC.IPsFromInterfaces = true + serverPC.IPsFromInterfacesList = []string{"lo"} + } else { + serverPC.AdditionalHosts = []string{"127.0.0.1"} + } + + err = serverPC.Start() + require.NoError(t, err) + defer serverPC.Close() + + offer, err := clientPC.CreatePartialOffer(false) + require.NoError(t, err) + + answer, err := serverPC.CreateFullAnswer(offer, false) + require.NoError(t, err) + + require.Equal(t, 2, strings.Count(answer.SDP, "a=candidate:")) + + err = clientPC.SetAnswer(answer) + require.NoError(t, err) + + go func() { + for { + select { + case cd := <-clientPC.NewLocalCandidate(): + err2 := serverPC.AddRemoteCandidate(cd) + require.NoError(t, err2) + + case <-clientPC.Failed(): + return + } + } + }() + + err = serverPC.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + }) + } + } +} + +func TestPeerConnectionRead(t *testing.T) { + pub, err := webrtc.NewPeerConnection(webrtc.Configuration{}) + require.NoError(t, err) + defer pub.Close() //nolint:errcheck + + videoTrack, err := webrtc.NewTrackLocalStaticRTP( + webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP8, + ClockRate: 90000, + }, + "video", + "publisher") + require.NoError(t, err) + + videoSender, err := pub.AddTrack(videoTrack) + require.NoError(t, err) + + audioTrack, err := webrtc.NewTrackLocalStaticRTP( + webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeOpus, + ClockRate: 48000, + }, + "audio", + "publisher") + require.NoError(t, err) + + audioSender, err := pub.AddTrack(audioTrack) + require.NoError(t, err) + + reader := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: false, + Log: test.NilLogger, + } + err = reader.Start() + require.NoError(t, err) + defer reader.Close() + + offer, err := pub.CreateOffer(nil) + require.NoError(t, err) + + err = pub.SetLocalDescription(offer) + require.NoError(t, err) + + answer, err := reader.CreateFullAnswer(&offer, false) + require.NoError(t, err) + + err = pub.SetRemoteDescription(*answer) + require.NoError(t, err) + + err = reader.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + go func() { + time.Sleep(100 * time.Millisecond) + + err2 := videoTrack.WriteRTP(&rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 111, + SequenceNumber: 1123, + Timestamp: 45343, + SSRC: 563424, + }, + Payload: []byte{5, 2}, + }) + require.NoError(t, err2) + + err2 = audioTrack.WriteRTP(&rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 111, + SequenceNumber: 1123, + Timestamp: 45343, + SSRC: 563424, + }, + Payload: []byte{5, 2}, + }) + require.NoError(t, err2) + }() + + err = reader.GatherInboundTracks(2 * time.Second) + require.NoError(t, err) + + codecs := gatherCodecs(reader.InboundTracks()) + + sort.Slice(codecs, func(i, j int) bool { + return codecs[i].PayloadType < codecs[j].PayloadType + }) + + require.Equal(t, []webrtc.RTPCodecParameters{ + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP8, + ClockRate: 90000, + RTCPFeedback: codecs[0].RTCPFeedback, + }, + PayloadType: 96, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeOpus, + ClockRate: 48000, + Channels: 2, + SDPFmtpLine: "minptime=10;useinbandfec=1", + RTCPFeedback: codecs[1].RTCPFeedback, + }, + PayloadType: 111, + }, + }, codecs) + + reader.StartReading() + + pkts, _, err := videoSender.ReadRTCP() + require.NoError(t, err) + require.Equal(t, []rtcp.Packet{ + &rtcp.ReceiverReport{ + SSRC: pkts[0].(*rtcp.ReceiverReport).SSRC, + Reports: []rtcp.ReceptionReport{{ + SSRC: uint32(videoSender.GetParameters().Encodings[0].SSRC), + LastSequenceNumber: pkts[0].(*rtcp.ReceiverReport).Reports[0].LastSequenceNumber, + LastSenderReport: pkts[0].(*rtcp.ReceiverReport).Reports[0].LastSenderReport, + Delay: pkts[0].(*rtcp.ReceiverReport).Reports[0].Delay, + }}, + ProfileExtensions: []byte{}, + }, + }, pkts) + + pkts, _, err = audioSender.ReadRTCP() + require.NoError(t, err) + require.Equal(t, []rtcp.Packet{ + &rtcp.ReceiverReport{ + SSRC: pkts[0].(*rtcp.ReceiverReport).SSRC, + Reports: []rtcp.ReceptionReport{{ + SSRC: uint32(audioSender.GetParameters().Encodings[0].SSRC), + LastSequenceNumber: pkts[0].(*rtcp.ReceiverReport).Reports[0].LastSequenceNumber, + LastSenderReport: pkts[0].(*rtcp.ReceiverReport).Reports[0].LastSenderReport, + Delay: pkts[0].(*rtcp.ReceiverReport).Reports[0].Delay, + }}, + ProfileExtensions: []byte{}, + }, + }, pkts) +} + +func TestPeerConnectionReadSimulcast(t *testing.T) { + pub, err := webrtc.NewPeerConnection(webrtc.Configuration{}) + require.NoError(t, err) + defer pub.Close() //nolint:errcheck + + videoTrackL, err := webrtc.NewTrackLocalStaticRTP( + webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP8, + ClockRate: 90000, + }, + "video", "publisher", + webrtc.WithRTPStreamID("l"), + ) + require.NoError(t, err) + + videoTrackM, err := webrtc.NewTrackLocalStaticRTP( + webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP8, + ClockRate: 90000, + }, + "video", "publisher", + webrtc.WithRTPStreamID("m"), + ) + require.NoError(t, err) + + videoTrackH, err := webrtc.NewTrackLocalStaticRTP( + webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP8, + ClockRate: 90000, + }, + "video", "publisher", + webrtc.WithRTPStreamID("h"), + ) + require.NoError(t, err) + + transceiver, err := pub.AddTransceiverFromTrack(videoTrackL, webrtc.RTPTransceiverInit{ + Direction: webrtc.RTPTransceiverDirectionSendonly, + SendEncodings: []webrtc.RTPEncodingParameters{ + {RTPCodingParameters: webrtc.RTPCodingParameters{RID: "l"}}, + {RTPCodingParameters: webrtc.RTPCodingParameters{RID: "m"}}, + {RTPCodingParameters: webrtc.RTPCodingParameters{RID: "h"}}, + }, + }) + require.NoError(t, err) + + err = transceiver.Sender().AddEncoding(videoTrackM) + require.NoError(t, err) + + err = transceiver.Sender().AddEncoding(videoTrackH) + require.NoError(t, err) + + reader := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: false, + Log: test.NilLogger, + } + err = reader.Start() + require.NoError(t, err) + defer reader.Close() + + offer, err := pub.CreateOffer(nil) + require.NoError(t, err) + + err = pub.SetLocalDescription(offer) + require.NoError(t, err) + + answer, err := reader.CreateFullAnswer(&offer, false) + require.NoError(t, err) + + err = pub.SetRemoteDescription(*answer) + require.NoError(t, err) + + err = reader.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + params := transceiver.Sender().GetParameters() + midExtID := senderHeaderExtensionID(params, sdp.SDESMidURI) + ridExtID := senderHeaderExtensionID(params, sdp.SDESRTPStreamIDURI) + require.NotZero(t, midExtID) + require.NotZero(t, ridExtID) + + mid := transceiver.Mid() + + go func() { + time.Sleep(200 * time.Millisecond) + + layers := []struct { + track *webrtc.TrackLocalStaticRTP + rid string + ssrc uint32 + seqNum uint16 + }{ + {videoTrackL, "l", 100001, 1000}, + {videoTrackM, "m", 100002, 2000}, + {videoTrackH, "h", 100003, 3000}, + } + + for i, layer := range layers { + pkt := &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 96, + SequenceNumber: layer.seqNum, + Timestamp: 45343, + SSRC: layer.ssrc, + }, + Payload: []byte{5, 2}, + } + + pkt.ExtensionProfile = 0xBEDE + require.NoError(t, pkt.SetExtension(midExtID, []byte(mid))) + require.NoError(t, pkt.SetExtension(ridExtID, []byte(layer.rid))) + + err2 := layer.track.WriteRTP(pkt) + if err2 != nil { + return + } + layers[i].seqNum++ + } + }() + + err = reader.GatherInboundTracks(5 * time.Second) + require.NoError(t, err) + + tracks := reader.InboundTracks() + codecs := gatherCodecs(tracks) + + require.Equal(t, 3, len(codecs)) + + for _, codec := range codecs { + require.Equal(t, webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP8, + ClockRate: 90000, + RTCPFeedback: codec.RTCPFeedback, + }, codec.RTPCodecCapability) + } + + rids := make([]string, len(tracks)) + for i, track := range tracks { + rids[i] = track.track.RID() + } + sort.Strings(rids) + require.Equal(t, []string{"h", "l", "m"}, rids) +} + +func TestPeerConnectionStripIncomingTWCC(t *testing.T) { + pub, err := webrtc.NewPeerConnection(webrtc.Configuration{}) + require.NoError(t, err) + defer pub.Close() //nolint:errcheck + + videoTrack, err := webrtc.NewTrackLocalStaticRTP( + webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeVP8, + ClockRate: 90000, + }, + "video", "publisher", + webrtc.WithRTPStreamID("l"), + ) + require.NoError(t, err) + + videoSender, err := pub.AddTrack(videoTrack) + require.NoError(t, err) + + reader := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: false, + Log: test.NilLogger, + } + err = reader.Start() + require.NoError(t, err) + defer reader.Close() + + offer, err := pub.CreateOffer(nil) + require.NoError(t, err) + + err = pub.SetLocalDescription(offer) + require.NoError(t, err) + + answer, err := reader.CreateFullAnswer(&offer, false) + require.NoError(t, err) + + err = pub.SetRemoteDescription(*answer) + require.NoError(t, err) + + err = reader.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + params := videoSender.GetParameters() + twccExtID := senderHeaderExtensionID(params, twccExtensionURI) + require.NotZero(t, twccExtID) + + go func() { + time.Sleep(200 * time.Millisecond) + + pkt := &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 96, + SequenceNumber: 55421, + Timestamp: 45343, + SSRC: 124123, + }, + Payload: []byte{5, 2}, + } + + pkt.ExtensionProfile = 0xBEDE + require.NoError(t, pkt.SetExtension(twccExtID, []byte{0x12, 0x34})) + + err2 := videoTrack.WriteRTP(pkt) + if err2 != nil { + return + } + }() + + err = reader.GatherInboundTracks(5 * time.Second) + require.NoError(t, err) + + tracks := reader.InboundTracks() + require.Len(t, tracks, 1) + + done := make(chan struct{}) + + tracks[0].OnPacketRTP = func(p *rtp.Packet) { + require.False(t, p.Extension) + require.Empty(t, p.Extensions) + close(done) + } + + reader.StartReading() + + <-done +} + +func TestPeerConnectionPublishRead(t *testing.T) { + pc1 := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: false, + Log: test.NilLogger, + } + err := pc1.Start() + require.NoError(t, err) + defer pc1.Close() + + pc2 := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: true, + OutboundTracks: []*OutboundTrack{ + { + Caps: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeH264, + ClockRate: 90000, + }, + }, + { + Caps: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeOpus, + ClockRate: 48000, + Channels: 2, + }, + }, + }, + Log: test.NilLogger, + } + err = pc2.Start() + require.NoError(t, err) + defer pc2.Close() + + offer, err := pc1.CreatePartialOffer(false) + require.NoError(t, err) + + answer, err := pc2.CreateFullAnswer(offer, false) + require.NoError(t, err) + + err = pc1.SetAnswer(answer) + require.NoError(t, err) + + err = pc1.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + err = pc2.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + for _, track := range pc2.OutboundTracks { + err = track.WriteRTP(&rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 111, + SequenceNumber: 1123, + Timestamp: 45343, + SSRC: 563424, + }, + Payload: []byte{5, 2}, + }) + require.NoError(t, err) + } + + err = pc1.GatherInboundTracks(2 * time.Second) + require.NoError(t, err) + + codecs := gatherCodecs(pc1.InboundTracks()) + + sort.Slice(codecs, func(i, j int) bool { + return codecs[i].PayloadType < codecs[j].PayloadType + }) + + require.Equal(t, []webrtc.RTPCodecParameters{ + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeH264, + ClockRate: 90000, + SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f", + RTCPFeedback: codecs[0].RTCPFeedback, + }, + PayloadType: 105, + }, + { + RTPCodecCapability: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeOpus, + ClockRate: 48000, + Channels: 2, + SDPFmtpLine: "minptime=10;useinbandfec=1;stereo=1;sprop-stereo=1", + RTCPFeedback: codecs[1].RTCPFeedback, + }, + PayloadType: 111, + }, + }, codecs) +} + +// test that an audio codec is present regardless of the fact that an audio track is. +func TestPeerConnectionFallbackCodecs(t *testing.T) { + pc1 := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: false, + Log: test.NilLogger, + } + err := pc1.Start() + require.NoError(t, err) + defer pc1.Close() + + pc2 := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: true, + OutboundTracks: []*OutboundTrack{{ + Caps: webrtc.RTPCodecCapability{ + MimeType: webrtc.MimeTypeAV1, + ClockRate: 90000, + }, + }}, + Log: test.NilLogger, + } + err = pc2.Start() + require.NoError(t, err) + defer pc2.Close() + + offer, err := pc1.CreatePartialOffer(false) + require.NoError(t, err) + + answer, err := pc2.CreateFullAnswer(offer, false) + require.NoError(t, err) + + var s sdp.SessionDescription + err = s.Unmarshal([]byte(answer.SDP)) + require.NoError(t, err) + + require.Equal(t, []*sdp.MediaDescription{ + { + MediaName: sdp.MediaName{ + Media: "video", + Port: sdp.RangedPort{Value: 9}, + Protos: []string{"UDP", "TLS", "RTP", "SAVPF"}, + Formats: []string{"97"}, + }, + ConnectionInformation: s.MediaDescriptions[0].ConnectionInformation, + Attributes: s.MediaDescriptions[0].Attributes, + }, + { + MediaName: sdp.MediaName{ + Media: "audio", + Port: sdp.RangedPort{Value: 9}, + Protos: []string{"UDP", "TLS", "RTP", "SAVPF"}, + Formats: []string{"0"}, + }, + ConnectionInformation: s.MediaDescriptions[1].ConnectionInformation, + Attributes: s.MediaDescriptions[1].Attributes, + }, + }, s.MediaDescriptions) +} + +func TestPeerConnectionPublishDataChannel(t *testing.T) { + pc1, err := webrtc.NewPeerConnection(webrtc.Configuration{}) + require.NoError(t, err) + defer pc1.Close() //nolint:errcheck + + _, err = pc1.CreateDataChannel("", nil) + require.NoError(t, err) + + dataChanCreated := make(chan struct{}) + dataReceived := make(chan struct{}) + + pc1.OnDataChannel(func(dc *webrtc.DataChannel) { + close(dataChanCreated) + + dc.OnMessage(func(msg webrtc.DataChannelMessage) { + require.Equal(t, []byte("test data"), msg.Data) + close(dataReceived) + }) + }) + + offer, err := pc1.CreateOffer(nil) + require.NoError(t, err) + + err = pc1.SetLocalDescription(offer) + require.NoError(t, err) + + pc2 := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: true, + OutboundDataChannels: []*OutboundDataChannel{ + { + Label: "test-channel", + }, + }, + Log: test.NilLogger, + } + err = pc2.Start() + require.NoError(t, err) + defer pc2.Close() + + answer, err := pc2.CreateFullAnswer(&offer, false) + require.NoError(t, err) + + err = pc1.SetRemoteDescription(*answer) + require.NoError(t, err) + + err = pc2.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + <-dataChanCreated + + pc2.OutboundDataChannels[0].Write([]byte("test data")) + + <-dataReceived +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/stats.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..283734010a3f72feadffc5801578c34a77ee3811 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/stats.go @@ -0,0 +1,13 @@ +package webrtc + +// Stats are WebRTC statistics. +type Stats struct { + BytesReceived uint64 + BytesSent uint64 + RTPPacketsReceived uint64 + RTPPacketsSent uint64 + RTPPacketsLost uint64 + RTPPacketsJitter float64 + RTCPPacketsReceived uint64 + RTCPPacketsSent uint64 +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/stats_interceptor.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/stats_interceptor.go new file mode 100644 index 0000000000000000000000000000000000000000..16bf216955b7f149e19fbaa62096b8109b8de032 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/stats_interceptor.go @@ -0,0 +1,67 @@ +package webrtc + +import ( + "sync/atomic" + + "github.com/pion/interceptor" + "github.com/pion/rtcp" +) + +type statsInterceptor struct { + rtcpPacketsSent atomic.Uint64 + rtcpPacketsReceived atomic.Uint64 +} + +func (*statsInterceptor) Close() error { + return nil +} + +func (s *statsInterceptor) BindRTCPReader(reader interceptor.RTCPReader) interceptor.RTCPReader { + return interceptor.RTCPReaderFunc(func(bytes []byte, + attributes interceptor.Attributes, + ) (int, interceptor.Attributes, error) { + n, attrs, err := reader.Read(bytes, attributes) + + pkts, err2 := attrs.GetRTCPPackets(bytes) + if err2 == nil { + s.rtcpPacketsReceived.Add(uint64(len(pkts))) + } + + return n, attrs, err + }) +} + +func (s *statsInterceptor) BindRTCPWriter(writer interceptor.RTCPWriter) interceptor.RTCPWriter { + return interceptor.RTCPWriterFunc(func(pkts []rtcp.Packet, attributes interceptor.Attributes) (int, error) { + s.rtcpPacketsSent.Add(uint64(len(pkts))) + return writer.Write(pkts, attributes) + }) +} + +func (s *statsInterceptor) BindLocalStream(_ *interceptor.StreamInfo, + writer interceptor.RTPWriter, +) interceptor.RTPWriter { + return writer +} + +func (*statsInterceptor) UnbindLocalStream(_ *interceptor.StreamInfo) {} + +func (s *statsInterceptor) BindRemoteStream(_ *interceptor.StreamInfo, + reader interceptor.RTPReader, +) interceptor.RTPReader { + return reader +} + +func (*statsInterceptor) UnbindRemoteStream(_ *interceptor.StreamInfo) {} + +type statsInterceptorFactory struct { + onCreate func(s *statsInterceptor) +} + +func (f *statsInterceptorFactory) NewInterceptor(_ string) (interceptor.Interceptor, error) { + s := &statsInterceptor{} + + f.onCreate(s) + + return s, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/tcp_mux_wrapper.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/tcp_mux_wrapper.go new file mode 100644 index 0000000000000000000000000000000000000000..0ee5c4d2693a34997864feaac85994f75d9ae482 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/tcp_mux_wrapper.go @@ -0,0 +1,13 @@ +package webrtc + +import ( + "net" + + "github.com/pion/ice/v4" +) + +// TCPMuxWrapper is a wrapper around ice.TCPMux. +type TCPMuxWrapper struct { + Mux ice.TCPMux + Ln net.Listener +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/to_stream.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/to_stream.go new file mode 100644 index 0000000000000000000000000000000000000000..9d31e88b623be2cafc687bc2ab3f91d1097a0e1f --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/to_stream.go @@ -0,0 +1,217 @@ +package webrtc + +import ( + "errors" + "fmt" + "strings" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/gortsplib/v5/pkg/rtptime" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/pion/rtp" + "github.com/pion/webrtc/v4" +) + +type ntpState int + +const ( + ntpStateInitial ntpState = iota + ntpStateReplace + ntpStateAvailable +) + +var errNoSupportedCodecsTo = errors.New( + "the stream doesn't contain any supported codec, which are currently " + + "AV1, VP9, VP8, H265, H264, Opus, G722, G711, LPCM") + +// ToStream maps a WebRTC connection to a MediaMTX stream. +func ToStream( + pc *PeerConnection, + pathConf *conf.Path, + subStream **stream.SubStream, + log logger.Writer, +) ([]*description.Media, error) { + var medias []*description.Media //nolint:prealloc + timeDecoder := &rtptime.GlobalDecoder{} + timeDecoder.Initialize() + + for _, track := range pc.inboundTracks { + var typ description.MediaType + var forma format.Format + + switch strings.ToLower(track.track.Codec().MimeType) { + case strings.ToLower(webrtc.MimeTypeAV1): + typ = description.MediaTypeVideo + forma = &format.AV1{ + PayloadTyp: 96, + } + + case strings.ToLower(webrtc.MimeTypeVP9): + typ = description.MediaTypeVideo + forma = &format.VP9{ + PayloadTyp: 96, + } + + case strings.ToLower(webrtc.MimeTypeVP8): + typ = description.MediaTypeVideo + forma = &format.VP8{ + PayloadTyp: 96, + } + + case strings.ToLower(webrtc.MimeTypeH265): + typ = description.MediaTypeVideo + forma = &format.H265{ + PayloadTyp: 96, + } + + case strings.ToLower(webrtc.MimeTypeH264): + typ = description.MediaTypeVideo + forma = &format.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + } + + case strings.ToLower(mimeTypeMultiopus): + typ = description.MediaTypeAudio + forma = &format.Opus{ + PayloadTyp: 96, + ChannelCount: int(track.track.Codec().Channels), + } + + case strings.ToLower(webrtc.MimeTypeOpus): + typ = description.MediaTypeAudio + forma = &format.Opus{ + PayloadTyp: 96, + ChannelCount: func() int { + if strings.Contains(track.track.Codec().SDPFmtpLine, "stereo=1") { + return 2 + } + return 1 + }(), + } + + case strings.ToLower(webrtc.MimeTypeG722): + typ = description.MediaTypeAudio + forma = &format.G722{} + + case strings.ToLower(webrtc.MimeTypePCMU): + channels := int(track.track.Codec().Channels) + if channels == 0 { + channels = 1 + } + + typ = description.MediaTypeAudio + forma = &format.G711{ + PayloadTyp: func() uint8 { + if channels > 1 { + return 96 + } + return 0 + }(), + MULaw: true, + SampleRate: 8000, + ChannelCount: channels, + } + + case strings.ToLower(webrtc.MimeTypePCMA): + channels := int(track.track.Codec().Channels) + if channels == 0 { + channels = 1 + } + + typ = description.MediaTypeAudio + forma = &format.G711{ + PayloadTyp: func() uint8 { + if channels > 1 { + return 96 + } + return 8 + }(), + MULaw: false, + SampleRate: 8000, + ChannelCount: channels, + } + + case strings.ToLower(mimeTypeL16): + typ = description.MediaTypeAudio + forma = &format.LPCM{ + PayloadTyp: 96, + BitDepth: 16, + SampleRate: int(track.track.Codec().ClockRate), + ChannelCount: int(track.track.Codec().Channels), + } + + default: + return nil, fmt.Errorf("unsupported codec: %+v", track.track.Codec().RTPCodecCapability) + } + + medi := &description.Media{ + Type: typ, + Formats: []format.Format{forma}, + } + + var ntpStat ntpState + + if !pathConf.UseAbsoluteTimestamp { + ntpStat = ntpStateReplace + } + + handleNTP := func(pkt *rtp.Packet) (time.Time, bool) { + switch ntpStat { + case ntpStateReplace: + return time.Time{}, true + + case ntpStateInitial: + ntp, avail := track.PacketNTP(pkt) + if !avail { + log.Log(logger.Warn, "received RTP packet without absolute time, skipping it") + return time.Time{}, false + } + + ntpStat = ntpStateAvailable + return ntp, true + + default: // ntpStateAvailable + ntp, avail := track.PacketNTP(pkt) + if !avail { + panic("should not happen") + } + + return ntp, true + } + } + + track.OnPacketRTP = func(pkt *rtp.Packet) { + pkt.PayloadType = forma.PayloadType() + + pts, ok := timeDecoder.Decode(track, pkt) + if !ok { + return + } + + ntp, ok := handleNTP(pkt) + if !ok { + return + } + + (*subStream).WriteUnit(medi, forma, &unit.Unit{ + PTS: pts, + NTP: ntp, + RTPPackets: []*rtp.Packet{pkt}, + }) + } + + medias = append(medias, medi) + } + + if len(medias) == 0 { + return nil, errNoSupportedCodecsTo + } + + return medias, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/to_stream_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/to_stream_test.go new file mode 100644 index 0000000000000000000000000000000000000000..894f3631d76abb85a2f99d657a9a8931dfeb9d63 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/webrtc/to_stream_test.go @@ -0,0 +1,410 @@ +package webrtc + +import ( + "testing" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/pion/rtp" + "github.com/pion/webrtc/v4" + "github.com/stretchr/testify/require" +) + +func TestToStreamNoSupportedCodecs(t *testing.T) { + pc := &PeerConnection{} + _, err := ToStream(pc, &conf.Path{}, nil, nil) + require.Equal(t, errNoSupportedCodecsTo, err) +} + +// this is impossible to test since unsupported tracks cause an error +// as they are not included inside incomingVideoCodecs or incomingAudioCodecs +// func TestToStreamSkipUnsupportedTracks(t *testing.T) + +var toFromStreamCases = []struct { + name string + in format.Format + webrtcCaps webrtc.RTPCodecCapability + out format.Format +}{ + { + "av1", + &format.AV1{ + PayloadTyp: 96, + }, + webrtc.RTPCodecCapability{ + MimeType: "video/AV1", + ClockRate: 90000, + }, + &format.AV1{ + PayloadTyp: 96, + }, + }, + { + "vp9", + &format.VP9{ + PayloadTyp: 96, + }, + webrtc.RTPCodecCapability{ + MimeType: "video/VP9", + ClockRate: 90000, + SDPFmtpLine: "profile-id=0", + }, + &format.VP9{ + PayloadTyp: 96, + }, + }, + { + "vp8", + &format.VP8{ + PayloadTyp: 96, + }, + webrtc.RTPCodecCapability{ + MimeType: "video/VP8", + ClockRate: 90000, + }, + &format.VP8{ + PayloadTyp: 96, + }, + }, + { + "h265", + &format.H265{ + PayloadTyp: 96, + }, + webrtc.RTPCodecCapability{ + MimeType: "video/H265", + ClockRate: 90000, + SDPFmtpLine: "level-id=93;profile-id=1;tier-flag=0;tx-mode=SRST", + }, + &format.H265{ + PayloadTyp: 96, + }, + }, + { + "h264", + test.FormatH264, + webrtc.RTPCodecCapability{ + MimeType: "video/H264", + ClockRate: 90000, + SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f", + }, + &format.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + }, + }, + { + "opus multichannel", + &format.Opus{ + PayloadTyp: 96, + ChannelCount: 6, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/multiopus", + ClockRate: 48000, + Channels: 6, + SDPFmtpLine: "channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2", + }, + &format.Opus{ + PayloadTyp: 96, + ChannelCount: 6, + }, + }, + { + "opus stereo", + &format.Opus{ + PayloadTyp: 96, + ChannelCount: 2, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/opus", + ClockRate: 48000, + Channels: 2, + SDPFmtpLine: "minptime=10;useinbandfec=1;stereo=1;sprop-stereo=1", + }, + &format.Opus{ + PayloadTyp: 96, + ChannelCount: 2, + }, + }, + { + "opus mono", + &format.Opus{ + PayloadTyp: 96, + ChannelCount: 1, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/opus", + ClockRate: 48000, + Channels: 2, + SDPFmtpLine: "minptime=10;useinbandfec=1", + }, + &format.Opus{ + PayloadTyp: 96, + ChannelCount: 1, + }, + }, + { + "g722", + &format.G722{}, + webrtc.RTPCodecCapability{ + MimeType: "audio/G722", + ClockRate: 8000, + }, + &format.G722{}, + }, + { + "g711 pcma 8khz mono", + &format.G711{ + PayloadTyp: 8, + SampleRate: 8000, + ChannelCount: 1, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/PCMA", + ClockRate: 8000, + }, + &format.G711{ + PayloadTyp: 8, + SampleRate: 8000, + ChannelCount: 1, + }, + }, + { + "g711 pcmu 8khz mono", + &format.G711{ + MULaw: true, + PayloadTyp: 0, + SampleRate: 8000, + ChannelCount: 1, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/PCMU", + ClockRate: 8000, + }, + &format.G711{ + MULaw: true, + PayloadTyp: 0, + SampleRate: 8000, + ChannelCount: 1, + }, + }, + { + "g711 pcma 8khz stereo", + &format.G711{ + PayloadTyp: 96, + SampleRate: 8000, + ChannelCount: 2, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/PCMA", + ClockRate: 8000, + Channels: 2, + }, + &format.G711{ + PayloadTyp: 96, + SampleRate: 8000, + ChannelCount: 2, + }, + }, + { + "g711 pcmu 8khz stereo", + &format.G711{ + MULaw: true, + PayloadTyp: 96, + SampleRate: 8000, + ChannelCount: 2, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/PCMU", + ClockRate: 8000, + Channels: 2, + }, + &format.G711{ + MULaw: true, + PayloadTyp: 96, + SampleRate: 8000, + ChannelCount: 2, + }, + }, + { + "g711 pcma 16khz stereo", + &format.G711{ + PayloadTyp: 96, + SampleRate: 16000, + ChannelCount: 2, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/L16", + ClockRate: 16000, + Channels: 2, + }, + &format.LPCM{ + PayloadTyp: 96, + BitDepth: 16, + SampleRate: 16000, + ChannelCount: 2, + }, + }, + { + "g711 pcmu 16khz stereo", + &format.G711{ + MULaw: true, + PayloadTyp: 96, + SampleRate: 16000, + ChannelCount: 2, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/L16", + ClockRate: 16000, + Channels: 2, + }, + &format.LPCM{ + PayloadTyp: 96, + BitDepth: 16, + SampleRate: 16000, + ChannelCount: 2, + }, + }, + { + "l16 8khz stereo", + &format.LPCM{ + PayloadTyp: 96, + BitDepth: 16, + SampleRate: 8000, + ChannelCount: 2, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/L16", + ClockRate: 8000, + Channels: 2, + }, + &format.LPCM{ + PayloadTyp: 96, + BitDepth: 16, + SampleRate: 8000, + ChannelCount: 2, + }, + }, + { + "l16 16khz stereo", + &format.LPCM{ + PayloadTyp: 96, + BitDepth: 16, + SampleRate: 16000, + ChannelCount: 2, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/L16", + ClockRate: 16000, + Channels: 2, + }, + &format.LPCM{ + PayloadTyp: 96, + BitDepth: 16, + SampleRate: 16000, + ChannelCount: 2, + }, + }, + { + "l16 48khz stereo", + &format.LPCM{ + PayloadTyp: 96, + BitDepth: 16, + SampleRate: 48000, + ChannelCount: 2, + }, + webrtc.RTPCodecCapability{ + MimeType: "audio/L16", + ClockRate: 48000, + Channels: 2, + }, + &format.LPCM{ + PayloadTyp: 96, + BitDepth: 16, + SampleRate: 48000, + ChannelCount: 2, + }, + }, +} + +func TestToStream(t *testing.T) { + for _, ca := range toFromStreamCases { + t.Run(ca.name, func(t *testing.T) { + pc1 := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: true, + OutboundTracks: []*OutboundTrack{{ + Caps: ca.webrtcCaps, + }}, + Log: test.NilLogger, + } + err := pc1.Start() + require.NoError(t, err) + defer pc1.Close() + + pc2 := &PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: false, + Log: test.NilLogger, + } + err = pc2.Start() + require.NoError(t, err) + defer pc2.Close() + + offer, err := pc1.CreatePartialOffer(false) + require.NoError(t, err) + + answer, err := pc2.CreateFullAnswer(offer, false) + require.NoError(t, err) + + err = pc1.SetAnswer(answer) + require.NoError(t, err) + + go func() { + for { + select { + case cnd := <-pc1.NewLocalCandidate(): + err2 := pc2.AddRemoteCandidate(cnd) + require.NoError(t, err2) + + case <-pc1.Connected(): + return + } + } + }() + + err = pc1.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + err = pc2.WaitUntilConnected(10 * time.Second) + require.NoError(t, err) + + err = pc1.OutboundTracks[0].WriteRTP(&rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 111, + SequenceNumber: 1123, + Timestamp: 45343, + SSRC: 563424, + }, + Payload: []byte{5, 2}, + }) + require.NoError(t, err) + + err = pc2.GatherInboundTracks(2 * time.Second) + require.NoError(t, err) + + var subStream *stream.SubStream + medias, err := ToStream(pc2, &conf.Path{}, &subStream, nil) + require.NoError(t, err) + require.Equal(t, ca.out, medias[0].Formats[0]) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/websocket/serverconn.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/websocket/serverconn.go new file mode 100644 index 0000000000000000000000000000000000000000..8d3abc37d48f256c18815890202d4ed02e27ee38 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/websocket/serverconn.go @@ -0,0 +1,115 @@ +// Package websocket provides WebSocket connectivity. +package websocket + +import ( + "encoding/json" + "fmt" + "net" + "net/http" + "time" + + "github.com/gorilla/websocket" +) + +var ( + pingInterval = 30 * time.Second + pingTimeout = 5 * time.Second + writeTimeout = 2 * time.Second +) + +var upgrader = websocket.Upgrader{ + CheckOrigin: func(_ *http.Request) bool { + return true + }, +} + +// ServerConn is a server-side WebSocket connection with +// automatic, periodic ping-pong +type ServerConn struct { + wc *websocket.Conn + + // in + terminate chan struct{} + write chan []byte + + // out + writeErr chan error +} + +// NewServerConn allocates a ServerConn. +func NewServerConn(w http.ResponseWriter, req *http.Request) (*ServerConn, error) { + wc, err := upgrader.Upgrade(w, req, nil) + if err != nil { + return nil, err + } + + c := &ServerConn{ + wc: wc, + terminate: make(chan struct{}), + write: make(chan []byte), + writeErr: make(chan error), + } + + go c.run() + + return c, nil +} + +// Close closes a ServerConn. +func (c *ServerConn) Close() { + c.wc.Close() //nolint:errcheck + close(c.terminate) +} + +// RemoteAddr returns the remote address. +func (c *ServerConn) RemoteAddr() net.Addr { + return c.wc.RemoteAddr() +} + +func (c *ServerConn) run() { + c.wc.SetReadDeadline(time.Now().Add(pingInterval + pingTimeout)) //nolint:errcheck + + c.wc.SetPongHandler(func(string) error { + c.wc.SetReadDeadline(time.Now().Add(pingInterval + pingTimeout)) //nolint:errcheck + return nil + }) + + pingTicker := time.NewTicker(pingInterval) + defer pingTicker.Stop() + + for { + select { + case byts := <-c.write: + c.wc.SetWriteDeadline(time.Now().Add(writeTimeout)) //nolint:errcheck + err := c.wc.WriteMessage(websocket.TextMessage, byts) + c.writeErr <- err + + case <-pingTicker.C: + c.wc.SetWriteDeadline(time.Now().Add(writeTimeout)) //nolint:errcheck + c.wc.WriteMessage(websocket.PingMessage, nil) //nolint:errcheck + + case <-c.terminate: + return + } + } +} + +// ReadJSON reads a JSON object. +func (c *ServerConn) ReadJSON(in any) error { + return c.wc.ReadJSON(in) +} + +// WriteJSON writes a JSON object. +func (c *ServerConn) WriteJSON(in any) error { + byts, err := json.Marshal(in) + if err != nil { + return err + } + + select { + case c.write <- byts: + return <-c.writeErr + case <-c.terminate: + return fmt.Errorf("terminated") + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/websocket/serverconn_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/websocket/serverconn_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3aa808c4093643444ccd137efc247a46ce5ec158 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/websocket/serverconn_test.go @@ -0,0 +1,56 @@ +package websocket + +import ( + "context" + "net" + "net/http" + "testing" + "time" + + "github.com/gorilla/websocket" + "github.com/stretchr/testify/require" +) + +func TestServerConn(t *testing.T) { + pingReceived := make(chan struct{}) + pingInterval = 100 * time.Millisecond + + s := &http.Server{ + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c, err := NewServerConn(w, r) + require.NoError(t, err) + defer c.Close() + + err = c.WriteJSON("testing") + require.NoError(t, err) + + <-pingReceived + }), + } + + ln, err := net.Listen("tcp", "localhost:6344") + require.NoError(t, err) + + go s.Serve(ln) + defer s.Shutdown(context.Background()) + + c, res, err := websocket.DefaultDialer.Dial("ws://localhost:6344/", nil) + require.NoError(t, err) + defer res.Body.Close() + defer c.Close() //nolint:errcheck + + c.SetPingHandler(func(_ string) error { + close(pingReceived) + return nil + }) + + var msg string + err = c.ReadJSON(&msg) + require.NoError(t, err) + require.Equal(t, "testing", msg) + + _, _, err = c.ReadMessage() + require.Error(t, err) + + <-pingReceived +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/client.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/client.go new file mode 100644 index 0000000000000000000000000000000000000000..603a01870f0dd1b0ac059781669c407d7e0007a6 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/client.go @@ -0,0 +1,427 @@ +// Package whip contains a WHIP/WHEP client. +package whip + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/pion/sdp/v3" + pwebrtc "github.com/pion/webrtc/v4" + + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/httpp" + "github.com/bluenviron/mediamtx/internal/protocols/webrtc" +) + +const ( + maxInboundSDPSize = 128 * 1024 +) + +func whipAnswer(body []byte) *pwebrtc.SessionDescription { + return &pwebrtc.SessionDescription{ + Type: pwebrtc.SDPTypeAnswer, + SDP: string(body), + } +} + +func offerAndCandidateToSDPFragment( + offer *pwebrtc.SessionDescription, + candidate *pwebrtc.ICECandidateInit, +) (*SDPFragment, error) { + f := &SDPFragment{} + + var desc sdp.SessionDescription + err := desc.Unmarshal([]byte(offer.SDP)) + if err != nil { + return nil, err + } + + if candidate.SDPMLineIndex == nil { + return nil, fmt.Errorf("sdpMLineIndex is null") + } + + if len(desc.MediaDescriptions) < int(*candidate.SDPMLineIndex)+1 { + return nil, fmt.Errorf("sdpMLineIndex is out of range") + } + + media := desc.MediaDescriptions[*candidate.SDPMLineIndex] + + iceUFrag, _ := media.Attribute("ice-ufrag") + icePwd, _ := media.Attribute("ice-pwd") + + if iceUFrag == "" || icePwd == "" { + return nil, fmt.Errorf("ice-ufrag or ice-pwd are missing in the media of the candidate") + } + + f.Medias = append(f.Medias, &sdp.MediaDescription{ + MediaName: media.MediaName, + Attributes: []sdp.Attribute{ + {Key: "mid", Value: strconv.FormatUint(uint64(*candidate.SDPMLineIndex), 10)}, + {Key: "ice-ufrag", Value: iceUFrag}, + {Key: "ice-pwd", Value: icePwd}, + {Key: "candidate", Value: candidate.Candidate}, + }, + }) + + return f, nil +} + +// Client is a WHIP client. +type Client struct { + URL *url.URL + Publish bool + OutboundTracks []*webrtc.OutboundTrack + HTTPClient *http.Client + BearerToken string + UDPReadBufferSize uint + STUNGatherTimeout time.Duration + HandshakeTimeout time.Duration + TrackGatherTimeout time.Duration + Log logger.Writer + + pc *webrtc.PeerConnection + useTrickleICE bool +} + +// Initialize initializes the Client. +func (c *Client) Initialize(ctx context.Context) error { + if c.STUNGatherTimeout == 0 { + c.STUNGatherTimeout = 5 * time.Second + } + if c.HandshakeTimeout == 0 { + c.HandshakeTimeout = 10 * time.Second + } + if c.TrackGatherTimeout == 0 { + c.TrackGatherTimeout = 2 * time.Second + } + + iceServers, err := c.optionsICEServers(ctx) + if err != nil { + return err + } + + c.pc = &webrtc.PeerConnection{ + Net: &webrtc.Net{UDPReadBufferSize: int(c.UDPReadBufferSize)}, + LocalRandomUDP: true, + ICEServers: iceServers, + IPsFromInterfaces: true, + Publish: c.Publish, + STUNGatherTimeout: c.STUNGatherTimeout, + OutboundTracks: c.OutboundTracks, + Log: c.Log, + } + err = c.pc.Start() + if err != nil { + return err + } + + initializeRes := make(chan error) + + go func() { + initializeRes <- c.initializeInner(ctx) + }() + + select { + case <-ctx.Done(): + c.pc.Close() + <-initializeRes + return fmt.Errorf("terminated") + + case err = <-initializeRes: + } + + if err != nil { + c.pc.Close() + return err + } + + return nil +} + +func (c *Client) initializeInner(ctx context.Context) error { + var offer *pwebrtc.SessionDescription + if c.useTrickleICE { + var err error + offer, err = c.pc.CreatePartialOffer(false) + if err != nil { + return err + } + } else { + var err error + offer, err = c.pc.CreateFullOffer() + if err != nil { + return err + } + } + + res, err := c.postOffer(ctx, offer) + if err != nil { + return err + } + + c.URL, err = c.URL.Parse(res.Location) + if err != nil { + return err + } + + if !c.Publish { + var sdp sdp.SessionDescription + err = sdp.Unmarshal([]byte(res.Answer.SDP)) + if err != nil { + c.deleteSession(context.Background()) //nolint:errcheck + return err + } + + err = webrtc.TracksAreValid(sdp.MediaDescriptions) + if err != nil { + c.deleteSession(context.Background()) //nolint:errcheck + return err + } + } + + err = c.pc.SetAnswer(res.Answer) + if err != nil { + c.deleteSession(context.Background()) //nolint:errcheck + return err + } + + err = c.waitConnected(ctx, offer, res.ETag) + if err != nil { + c.deleteSession(context.Background()) //nolint:errcheck + return err + } + + if !c.Publish { + err = c.pc.GatherInboundTracks(c.TrackGatherTimeout) + if err != nil { + c.deleteSession(context.Background()) //nolint:errcheck + return err + } + } + + return nil +} + +func (c *Client) waitConnected(ctx context.Context, offer *pwebrtc.SessionDescription, eTag string) error { + t := time.NewTimer(c.HandshakeTimeout) + defer t.Stop() + + if c.useTrickleICE { + for { + select { + case ca := <-c.pc.NewLocalCandidate(): + err := c.patchCandidate(ctx, offer, eTag, ca) + if err != nil { + return err + } + + case <-c.pc.Connected(): + return nil + + case <-t.C: + return fmt.Errorf("deadline exceeded while waiting connection") + } + } + } + + for { + select { + case <-c.pc.Connected(): + return nil + + case <-t.C: + return fmt.Errorf("deadline exceeded while waiting connection") + } + } +} + +// PeerConnection returns the underlying peer connection. +func (c *Client) PeerConnection() *webrtc.PeerConnection { + return c.pc +} + +// InboundTracks returns incoming tracks. +func (c *Client) InboundTracks() []*webrtc.InboundTrack { + return c.pc.InboundTracks() +} + +// StartReading starts reading all incoming tracks. +func (c *Client) StartReading() { + c.pc.StartReading() +} + +// Close closes the client. +func (c *Client) Close() error { + err := c.deleteSession(context.Background()) + c.pc.Close() + return err +} + +// Wait waits until a fatal error. +func (c *Client) Wait() error { + <-c.pc.Failed() + return fmt.Errorf("peer connection closed") +} + +func (c *Client) optionsICEServers( + ctx context.Context, +) ([]pwebrtc.ICEServer, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodOptions, c.URL.String(), nil) + if err != nil { + return nil, err + } + + if c.BearerToken != "" { + req.Header.Set("Authorization", "Bearer "+c.BearerToken) + } + + res, err := c.HTTPClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusNoContent { + return nil, fmt.Errorf("bad status code: %v", res.StatusCode) + } + + for m := range strings.SplitSeq(res.Header.Get("Access-Control-Allow-Methods"), ",") { + if strings.TrimSpace(m) == "PATCH" { + c.useTrickleICE = true + break + } + } + + return LinkHeaderUnmarshal(res.Header["Link"]) +} + +type whipPostOfferResponse struct { + Answer *pwebrtc.SessionDescription + Location string + ETag string +} + +func (c *Client) postOffer( + ctx context.Context, + offer *pwebrtc.SessionDescription, +) (*whipPostOfferResponse, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.URL.String(), bytes.NewReader([]byte(offer.SDP))) + if err != nil { + return nil, err + } + + if c.BearerToken != "" { + req.Header.Set("Authorization", "Bearer "+c.BearerToken) + } + + req.Header.Set("Content-Type", "application/sdp") + + res, err := c.HTTPClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + + if res.StatusCode != http.StatusCreated { + return nil, fmt.Errorf("bad status code: %v", res.StatusCode) + } + + contentType := httpp.ParseContentType(res.Header.Get("Content-Type")) + if contentType != "application/sdp" { + return nil, fmt.Errorf("bad Content-Type: expected 'application/sdp', got '%s'", contentType) + } + + Location := res.Header.Get("Location") + + var etag string + if c.useTrickleICE { + etag = res.Header.Get("ETag") + if etag == "" { + return nil, fmt.Errorf("ETag is missing") + } + } + + sdp, err := io.ReadAll(&customLimitReader{res.Body, maxInboundSDPSize}) + if err != nil { + return nil, err + } + + return &whipPostOfferResponse{ + Answer: whipAnswer(sdp), + Location: Location, + ETag: etag, + }, nil +} + +func (c *Client) patchCandidate( + ctx context.Context, + offer *pwebrtc.SessionDescription, + etag string, + candidate *pwebrtc.ICECandidateInit, +) error { + frag, err := offerAndCandidateToSDPFragment(offer, candidate) + if err != nil { + return err + } + + enc, err := frag.Marshal() + if err != nil { + return err + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPatch, c.URL.String(), bytes.NewReader(enc)) + if err != nil { + return err + } + + if c.BearerToken != "" { + req.Header.Set("Authorization", "Bearer "+c.BearerToken) + } + + req.Header.Set("Content-Type", "application/trickle-ice-sdpfrag") + req.Header.Set("If-Match", etag) + + res, err := c.HTTPClient.Do(req) + if err != nil { + return err + } + defer res.Body.Close() + + if res.StatusCode != http.StatusNoContent { + return fmt.Errorf("bad status code: %v", res.StatusCode) + } + + return nil +} + +func (c *Client) deleteSession( + ctx context.Context, +) error { + req, err := http.NewRequestWithContext(ctx, http.MethodDelete, c.URL.String(), nil) + if err != nil { + return err + } + + if c.BearerToken != "" { + req.Header.Set("Authorization", "Bearer "+c.BearerToken) + } + + res, err := c.HTTPClient.Do(req) + if err != nil { + return err + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + return fmt.Errorf("bad status code: %v", res.StatusCode) + } + + return nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/client_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/client_test.go new file mode 100644 index 0000000000000000000000000000000000000000..efc9a600ca98f8f4d9f1e9e4b9750c8e44cd5bb7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/client_test.go @@ -0,0 +1,619 @@ +package whip + +import ( + "context" + "io" + "net" + "net/http" + "net/url" + "sort" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/protocols/webrtc" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/pion/rtp" + pwebrtc "github.com/pion/webrtc/v4" + "github.com/stretchr/testify/require" +) + +func whipOffer(body []byte) *pwebrtc.SessionDescription { + return &pwebrtc.SessionDescription{ + Type: pwebrtc.SDPTypeOffer, + SDP: string(body), + } +} + +func gatherCodecs(tracks []*webrtc.InboundTrack) []pwebrtc.RTPCodecParameters { + codecs := make([]pwebrtc.RTPCodecParameters, len(tracks)) + for i, track := range tracks { + codecs[i] = track.Codec() + } + return codecs +} + +func TestClientRead(t *testing.T) { + for _, ca := range []string{ + "audio", + "video+audio", + } { + t.Run(ca, func(t *testing.T) { + var outboundTracks []*webrtc.OutboundTrack + + switch ca { + case "audio": + outboundTracks = []*webrtc.OutboundTrack{{ + Caps: pwebrtc.RTPCodecCapability{ + MimeType: "audio/opus", + ClockRate: 48000, + Channels: 2, + }, + }} + + case "video+audio": + outboundTracks = []*webrtc.OutboundTrack{ + { + Caps: pwebrtc.RTPCodecCapability{ + MimeType: "video/H264", + ClockRate: 90000, + }, + }, + { + Caps: pwebrtc.RTPCodecCapability{ + MimeType: "audio/opus", + ClockRate: 48000, + Channels: 2, + }, + }, + } + } + + pc := &webrtc.PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Publish: true, + OutboundTracks: outboundTracks, + Log: test.NilLogger, + } + err := pc.Start() + require.NoError(t, err) + defer pc.Close() + + state := 0 + + httpServ := &http.Server{ + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch state { + case 0: + require.Equal(t, http.MethodOptions, r.Method) + require.Equal(t, "/my/resource", r.URL.Path) + + w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PATCH") + w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, If-Match") + w.WriteHeader(http.StatusNoContent) + + case 1: + require.Equal(t, http.MethodPost, r.Method) + require.Equal(t, "/my/resource", r.URL.Path) + require.Equal(t, "application/sdp", r.Header.Get("Content-Type")) + + body, err2 := io.ReadAll(r.Body) + require.NoError(t, err2) + offer := whipOffer(body) + + require.NotContains(t, offer.SDP, "a=candidate:") + + answer, err2 := pc.CreateFullAnswer(offer, false) + require.NoError(t, err2) + + w.Header().Set("Content-Type", "application/sdp") + w.Header().Set("ETag", "test_etag") + w.Header().Set("Location", "/my/resource/sessionid") + w.WriteHeader(http.StatusCreated) + w.Write([]byte(answer.SDP)) + + go func() { + err3 := pc.WaitUntilConnected(10 * time.Second) + require.NoError(t, err3) + + for _, track := range outboundTracks { + err3 = track.WriteRTP(&rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 111, + SequenceNumber: 1123, + Timestamp: 45343, + SSRC: 563424, + }, + Payload: []byte{5, 2}, + }) + require.NoError(t, err3) + } + }() + + default: + require.Equal(t, "/my/resource/sessionid", r.URL.Path) + + switch r.Method { + case http.MethodPatch: + w.WriteHeader(http.StatusNoContent) + + case http.MethodDelete: + w.WriteHeader(http.StatusOK) + + default: + t.Errorf("should not happen") + } + } + state++ + }), + } + + ln, err := net.Listen("tcp", "localhost:9005") + require.NoError(t, err) + + go httpServ.Serve(ln) + defer httpServ.Shutdown(context.Background()) + + u, err := url.Parse("http://localhost:9005/my/resource") + require.NoError(t, err) + + cl := &Client{ + URL: u, + HTTPClient: &http.Client{}, + Log: test.NilLogger, + } + err = cl.Initialize(context.Background()) + require.NoError(t, err) + defer cl.Close() //nolint:errcheck + + codecs := gatherCodecs(cl.InboundTracks()) + + switch ca { + case "audio": + require.Equal(t, []pwebrtc.RTPCodecParameters{ + { + RTPCodecCapability: pwebrtc.RTPCodecCapability{ + MimeType: pwebrtc.MimeTypeOpus, + ClockRate: 48000, + Channels: 2, + SDPFmtpLine: "minptime=10;useinbandfec=1;stereo=1;sprop-stereo=1", + RTCPFeedback: []pwebrtc.RTCPFeedback{{ + Type: "transport-cc", + }}, + }, + PayloadType: 111, + }, + }, codecs) + + case "video+audio": + sort.Slice(codecs, func(i, j int) bool { + return codecs[i].PayloadType < codecs[j].PayloadType + }) + + require.Equal(t, []pwebrtc.RTPCodecParameters{ + { + RTPCodecCapability: pwebrtc.RTPCodecCapability{ + MimeType: pwebrtc.MimeTypeH264, + ClockRate: 90000, + SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f", + RTCPFeedback: codecs[0].RTCPFeedback, + }, + PayloadType: 105, + }, + { + RTPCodecCapability: pwebrtc.RTPCodecCapability{ + MimeType: pwebrtc.MimeTypeOpus, + ClockRate: 48000, + Channels: 2, + SDPFmtpLine: "minptime=10;useinbandfec=1;stereo=1;sprop-stereo=1", + RTCPFeedback: codecs[1].RTCPFeedback, + }, + PayloadType: 111, + }, + }, codecs) + } + + recv := make([]chan struct{}, len(outboundTracks)) + for i := range outboundTracks { + recv[i] = make(chan struct{}) + } + + for i, track := range cl.InboundTracks() { + ci := i + track.OnPacketRTP = func(_ *rtp.Packet) { + close(recv[ci]) + } + } + + cl.StartReading() + + for _, rv := range recv { + <-rv + } + }) + } +} + +func TestClientPublish(t *testing.T) { + for _, ca := range []string{"audio", "video+audio"} { + t.Run(ca, func(t *testing.T) { + pc := &webrtc.PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Log: test.NilLogger, + } + err := pc.Start() + require.NoError(t, err) + defer pc.Close() + + state := 0 + var recv []chan struct{} + + httpServ := &http.Server{ + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch state { + case 0: + require.Equal(t, http.MethodOptions, r.Method) + require.Equal(t, "/my/resource", r.URL.Path) + + w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PATCH") + w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, If-Match") + w.WriteHeader(http.StatusNoContent) + + case 1: + require.Equal(t, http.MethodPost, r.Method) + require.Equal(t, "/my/resource", r.URL.Path) + require.Equal(t, "application/sdp", r.Header.Get("Content-Type")) + + body, err2 := io.ReadAll(r.Body) + require.NoError(t, err2) + offer := whipOffer(body) + + require.NotContains(t, offer.SDP, "a=candidate:") + + answer, err2 := pc.CreateFullAnswer(offer, false) + require.NoError(t, err2) + + w.Header().Set("Content-Type", "application/sdp") + w.Header().Set("ETag", "test_etag") + w.Header().Set("Location", "/my/resource/sessionid") + w.WriteHeader(http.StatusCreated) + w.Write([]byte(answer.SDP)) + + go func() { + err3 := pc.WaitUntilConnected(10 * time.Second) + require.NoError(t, err3) + + err3 = pc.GatherInboundTracks(2 * time.Second) + require.NoError(t, err3) + + codecs := gatherCodecs(pc.InboundTracks()) + + switch ca { + case "audio": + require.Equal(t, []pwebrtc.RTPCodecParameters{ + { + RTPCodecCapability: pwebrtc.RTPCodecCapability{ + MimeType: pwebrtc.MimeTypeOpus, + ClockRate: 48000, + Channels: 2, + SDPFmtpLine: "", + RTCPFeedback: codecs[0].RTCPFeedback, + }, + PayloadType: 96, + }, + }, codecs) + + case "video+audio": + sort.Slice(codecs, func(i, j int) bool { + return codecs[i].PayloadType < codecs[j].PayloadType + }) + + require.Equal(t, []pwebrtc.RTPCodecParameters{ + { + RTPCodecCapability: pwebrtc.RTPCodecCapability{ + MimeType: pwebrtc.MimeTypeH264, + ClockRate: 90000, + RTCPFeedback: codecs[0].RTCPFeedback, + }, + PayloadType: 96, + }, + { + RTPCodecCapability: pwebrtc.RTPCodecCapability{ + MimeType: pwebrtc.MimeTypeOpus, + ClockRate: 48000, + Channels: 2, + SDPFmtpLine: "", + RTCPFeedback: codecs[1].RTCPFeedback, + }, + PayloadType: 97, + }, + }, codecs) + } + + for i, track := range pc.InboundTracks() { + ci := i + track.OnPacketRTP = func(_ *rtp.Packet) { + close(recv[ci]) + } + } + + pc.StartReading() + }() + + default: + require.Equal(t, "/my/resource/sessionid", r.URL.Path) + + switch r.Method { + case http.MethodPatch: + w.WriteHeader(http.StatusNoContent) + + case http.MethodDelete: + w.WriteHeader(http.StatusOK) + + default: + t.Errorf("should not happen") + } + } + state++ + }), + } + + ln, err := net.Listen("tcp", "localhost:9005") + require.NoError(t, err) + + go httpServ.Serve(ln) + defer httpServ.Shutdown(context.Background()) + + u, err := url.Parse("http://localhost:9005/my/resource") + require.NoError(t, err) + + var outboundTracks []*webrtc.OutboundTrack + + switch ca { + case "audio": + outboundTracks = []*webrtc.OutboundTrack{{ + Caps: pwebrtc.RTPCodecCapability{ + MimeType: "audio/opus", + ClockRate: 48000, + Channels: 2, + }, + }} + + case "video+audio": + outboundTracks = []*webrtc.OutboundTrack{ + { + Caps: pwebrtc.RTPCodecCapability{ + MimeType: "video/H264", + ClockRate: 90000, + }, + }, + { + Caps: pwebrtc.RTPCodecCapability{ + MimeType: "audio/opus", + ClockRate: 48000, + Channels: 2, + }, + }, + } + } + + recv = make([]chan struct{}, len(outboundTracks)) + for i := range outboundTracks { + recv[i] = make(chan struct{}) + } + + cl := &Client{ + URL: u, + Publish: true, + OutboundTracks: outboundTracks, + HTTPClient: &http.Client{}, + Log: test.NilLogger, + } + err = cl.Initialize(context.Background()) + require.NoError(t, err) + defer cl.Close() //nolint:errcheck + + for _, track := range cl.OutboundTracks { + err = track.WriteRTP(&rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 111, + SequenceNumber: 1123, + Timestamp: 45343, + SSRC: 563424, + }, + Payload: []byte{5, 2}, + }) + require.NoError(t, err) + } + + for _, rv := range recv { + <-rv + } + }) + } +} + +func TestClientBearerToken(t *testing.T) { + pc := &webrtc.PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Log: test.NilLogger, + } + err := pc.Start() + require.NoError(t, err) + defer pc.Close() + + httpServ := &http.Server{ + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.Equal(t, "Bearer my_secret_token", r.Header.Get("Authorization")) + + switch r.Method { + case http.MethodOptions: + w.WriteHeader(http.StatusNoContent) + + case http.MethodPost: + body, err2 := io.ReadAll(r.Body) + require.NoError(t, err2) + offer := whipOffer(body) + + answer, err2 := pc.CreateFullAnswer(offer, false) + require.NoError(t, err2) + + w.Header().Set("Content-Type", "application/sdp") + w.Header().Set("ETag", "test_etag") + w.WriteHeader(http.StatusCreated) + w.Write([]byte(answer.SDP)) + } + }), + } + + ln, err := net.Listen("tcp", "localhost:9005") + require.NoError(t, err) + + go httpServ.Serve(ln) + defer httpServ.Shutdown(context.Background()) + + u, err := url.Parse("http://localhost:9005/my/resource") + require.NoError(t, err) + + outboundTracks := []*webrtc.OutboundTrack{{ + Caps: pwebrtc.RTPCodecCapability{ + MimeType: "audio/opus", + ClockRate: 48000, + Channels: 2, + }, + }} + + cl := &Client{ + URL: u, + HTTPClient: &http.Client{}, + BearerToken: "my_secret_token", + Log: test.NilLogger, + Publish: true, + OutboundTracks: outboundTracks, + } + err = cl.Initialize(context.Background()) + require.NoError(t, err) + defer cl.Close() //nolint:errcheck +} + +func TestClientNoTrickleICE(t *testing.T) { + pc := &webrtc.PeerConnection{ + LocalRandomUDP: true, + IPsFromInterfaces: true, + Log: test.NilLogger, + } + err := pc.Start() + require.NoError(t, err) + defer pc.Close() + + state := 0 + recv := make(chan struct{}) + + httpServ := &http.Server{ + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch state { + case 0: + require.Equal(t, http.MethodOptions, r.Method) + require.Equal(t, "/my/resource", r.URL.Path) + + w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST, DELETE") + w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type") + w.WriteHeader(http.StatusNoContent) + + case 1: + require.Equal(t, http.MethodPost, r.Method) + require.Equal(t, "/my/resource", r.URL.Path) + require.Equal(t, "application/sdp", r.Header.Get("Content-Type")) + + body, err2 := io.ReadAll(r.Body) + require.NoError(t, err2) + offer := whipOffer(body) + + require.Contains(t, offer.SDP, "a=candidate:") + + answer, err2 := pc.CreateFullAnswer(offer, false) + require.NoError(t, err2) + + w.Header().Set("Content-Type", "application/sdp") + w.Header().Set("Location", "/my/resource/sessionid") + w.WriteHeader(http.StatusCreated) + w.Write([]byte(answer.SDP)) + + go func() { + err3 := pc.WaitUntilConnected(10 * time.Second) + require.NoError(t, err3) + + err3 = pc.GatherInboundTracks(2 * time.Second) + require.NoError(t, err3) + + pc.InboundTracks()[0].OnPacketRTP = func(_ *rtp.Packet) { + close(recv) + } + + pc.StartReading() + }() + + default: + require.Equal(t, "/my/resource/sessionid", r.URL.Path) + + switch r.Method { + case http.MethodDelete: + w.WriteHeader(http.StatusOK) + + default: + t.Errorf("unexpected method: %s", r.Method) + } + } + state++ + }), + } + + ln, err := net.Listen("tcp", "localhost:9005") + require.NoError(t, err) + + go httpServ.Serve(ln) + defer httpServ.Shutdown(context.Background()) + + u, err := url.Parse("http://localhost:9005/my/resource") + require.NoError(t, err) + + outboundTracks := []*webrtc.OutboundTrack{{ + Caps: pwebrtc.RTPCodecCapability{ + MimeType: "audio/opus", + ClockRate: 48000, + Channels: 2, + }, + }} + + cl := &Client{ + URL: u, + Publish: true, + OutboundTracks: outboundTracks, + HTTPClient: &http.Client{}, + Log: test.NilLogger, + } + err = cl.Initialize(context.Background()) + require.NoError(t, err) + defer cl.Close() //nolint:errcheck + + err = outboundTracks[0].WriteRTP(&rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 111, + SequenceNumber: 1123, + Timestamp: 45343, + SSRC: 563424, + }, + Payload: []byte{5, 2}, + }) + require.NoError(t, err) + + <-recv +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/custom_limit_reader.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/custom_limit_reader.go new file mode 100644 index 0000000000000000000000000000000000000000..220f8a45ff23aafcaba80c18dc55bfa01e49b0af --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/custom_limit_reader.go @@ -0,0 +1,26 @@ +package whip + +import ( + "fmt" + "io" +) + +var errSizeExceeded = fmt.Errorf("size exceeds maximum allowed") + +// like io.LimitReader, but returns a dedicated error if the limit is exceeded. +type customLimitReader struct { + r io.Reader + n int64 +} + +func (l *customLimitReader) Read(p []byte) (n int, err error) { + if l.n <= 0 { + return 0, errSizeExceeded + } + if int64(len(p)) > l.n { + p = p[0:l.n] + } + n, err = l.r.Read(p) + l.n -= int64(n) + return +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/link_header.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/link_header.go new file mode 100644 index 0000000000000000000000000000000000000000..e6bc58294898dcad247006d3ef80c20259b80634 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/link_header.go @@ -0,0 +1,66 @@ +package whip + +import ( + "encoding/json" + "fmt" + "regexp" + + "github.com/pion/webrtc/v4" +) + +func quoteCredential(v string) string { + b, _ := json.Marshal(v) + s := string(b) + return s[1 : len(s)-1] +} + +func unquoteCredential(v string) string { + var s string + json.Unmarshal([]byte("\""+v+"\""), &s) //nolint:errcheck + return s +} + +// LinkHeaderMarshal encodes a link header. +func LinkHeaderMarshal(iceServers []webrtc.ICEServer) []string { + ret := make([]string, len(iceServers)) + + for i, server := range iceServers { + link := "<" + server.URLs[0] + ">; rel=\"ice-server\"" + if server.Username != "" { + link += "; username=\"" + quoteCredential(server.Username) + "\"" + + "; credential=\"" + quoteCredential(server.Credential.(string)) + "\"; credential-type=\"password\"" + } + ret[i] = link + } + + return ret +} + +var reLink = regexp.MustCompile(`^<(.+?)>; rel="ice-server"(; username="(.+?)"` + + `; credential="(.+?)"; credential-type="password")?`) + +// LinkHeaderUnmarshal decodes a link header. +func LinkHeaderUnmarshal(link []string) ([]webrtc.ICEServer, error) { + ret := make([]webrtc.ICEServer, len(link)) + + for i, li := range link { + m := reLink.FindStringSubmatch(li) + if m == nil { + return nil, fmt.Errorf("invalid link header: '%s'", li) + } + + s := webrtc.ICEServer{ + URLs: []string{m[1]}, + } + + if m[3] != "" { + s.Username = unquoteCredential(m[3]) + s.Credential = unquoteCredential(m[4]) + s.CredentialType = webrtc.ICECredentialTypePassword + } + + ret[i] = s + } + + return ret, nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/link_header_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/link_header_test.go new file mode 100644 index 0000000000000000000000000000000000000000..96b4e3af07de163e8b9bb79bb1c36a3355683eb6 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/link_header_test.go @@ -0,0 +1,52 @@ +package whip + +import ( + "testing" + + "github.com/pion/webrtc/v4" + "github.com/stretchr/testify/require" +) + +var linkHeaderCases = []struct { + name string + enc []string + dec []webrtc.ICEServer +}{ + { + "a", + []string{ + `; rel="ice-server"`, + `; rel="ice-server"; username="myuser\"a?2;B"; ` + + `credential="mypwd"; credential-type="password"`, + }, + []webrtc.ICEServer{ + { + URLs: []string{"stun:stun.l.google.com:19302"}, + }, + { + URLs: []string{"turns:turn.example.com"}, + Username: "myuser\"a?2;B", + Credential: "mypwd", + }, + }, + }, +} + +func TestLinkHeaderUnmarshal(t *testing.T) { + for _, ca := range linkHeaderCases { + t.Run(ca.name, func(t *testing.T) { + dec, err := LinkHeaderUnmarshal(ca.enc) + require.NoError(t, err) + require.Equal(t, ca.dec, dec) + }) + } +} + +func TestLinkHeaderMarshal(t *testing.T) { + for _, ca := range linkHeaderCases { + t.Run(ca.name, func(t *testing.T) { + enc := LinkHeaderMarshal(ca.dec) + require.Equal(t, ca.enc, enc) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/sdp_fragment.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/sdp_fragment.go new file mode 100644 index 0000000000000000000000000000000000000000..0234a156a0251259a235d837e5980bd95cd00a11 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/sdp_fragment.go @@ -0,0 +1,56 @@ +package whip + +import ( + "strings" + + "github.com/pion/sdp/v3" +) + +// SDPFragment is a SDP fragment. +// It's basically a SDP without most mandatory fields. +type SDPFragment struct { + Attributes []sdp.Attribute + Medias []*sdp.MediaDescription +} + +// Unmarshal decodes a SDP fragment. +func (f *SDPFragment) Unmarshal(buf []byte) error { + buf = append([]byte("v=0\r\no=- 0 0 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\n"), buf...) + + var sdp sdp.SessionDescription + err := sdp.Unmarshal(buf) + if err != nil { + return err + } + + f.Attributes = sdp.Attributes + f.Medias = sdp.MediaDescriptions + + return nil +} + +// Marshal encodes a SDP fragment. +func (f SDPFragment) Marshal() ([]byte, error) { + var b strings.Builder + + for _, a := range f.Attributes { + if a.Value != "" { + b.WriteString("a=" + a.Key + ":" + a.Value + "\r\n") + } else { + b.WriteString("a=" + a.Key + "\r\n") + } + } + + for _, m := range f.Medias { + b.WriteString("m=" + m.MediaName.String() + "\r\n") + for _, a := range m.Attributes { + if a.Value != "" { + b.WriteString("a=" + a.Key + ":" + a.Value + "\r\n") + } else { + b.WriteString("a=" + a.Key + "\r\n") + } + } + } + + return []byte(b.String()), nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/sdp_fragment_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/sdp_fragment_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c6046dd42d7ebd68194085c443485c41ab42b22b --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/protocols/whip/sdp_fragment_test.go @@ -0,0 +1,193 @@ +package whip + +import ( + "testing" + + "github.com/pion/sdp/v3" + "github.com/stretchr/testify/require" +) + +var sdpFragmentCases = []struct { + name string + enc string + dec *SDPFragment +}{ + { + "session-wide credentials", + "a=ice-ufrag:tUQMzoQAVLzlvBys\r\n" + + "a=ice-pwd:pimyGfJcjjRwvUjnmGOODSjtIxyDljQj\r\n" + + "m=video 9 UDP/TLS/RTP/SAVPF 96 97 98 99 100 101 102 121 127 120 125 107 108 109 123 118 45 46 116\r\n" + + "a=mid:0\r\n" + + "a=candidate:3628911098 1 udp 2130706431 192.168.3.218 49462 typ host\r\n", + &SDPFragment{ + Attributes: []sdp.Attribute{ + {Key: "ice-ufrag", Value: "tUQMzoQAVLzlvBys"}, + {Key: "ice-pwd", Value: "pimyGfJcjjRwvUjnmGOODSjtIxyDljQj"}, + }, + Medias: []*sdp.MediaDescription{{ + MediaName: sdp.MediaName{ + Media: "video", + Port: sdp.RangedPort{Value: 9}, + Protos: []string{"UDP", "TLS", "RTP", "SAVPF"}, + Formats: []string{ + "96", "97", "98", "99", "100", "101", "102", + "121", "127", "120", "125", "107", "108", "109", "123", "118", "45", "46", "116", + }, + }, + Attributes: []sdp.Attribute{ + {Key: "mid", Value: "0"}, + {Key: "candidate", Value: "3628911098 1 udp 2130706431 192.168.3.218 49462 typ host"}, + }, + }}, + }, + }, + { + "rfc9725 trickle ice patch request", + "a=group:BUNDLE 0 1\r\n" + + "m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n" + + "a=mid:0\r\n" + + "a=ice-ufrag:EsAw\r\n" + + "a=ice-pwd:P2uYro0UCOQ4zxjKXaWCBui1\r\n" + + "a=candidate:1387637174 1 udp 2122260223 192.0.2.1 61764 typ host" + + " generation 0 ufrag EsAw network-id 1\r\n" + + "a=candidate:3471623853 1 udp 2122194687 198.51.100.2 61765 typ host" + + " generation 0 ufrag EsAw network-id 2\r\n" + + "a=candidate:473322822 1 tcp 1518280447 192.0.2.1 9 typ host tcptype active" + + " generation 0 ufrag EsAw network-id 1\r\n" + + "a=candidate:2154773085 1 tcp 1518214911 198.51.100.2 9 typ host tcptype active" + + " generation 0 ufrag EsAw network-id 2\r\n" + + "a=end-of-candidates\r\n", + &SDPFragment{ + Attributes: []sdp.Attribute{ + {Key: "group", Value: "BUNDLE 0 1"}, + }, + Medias: []*sdp.MediaDescription{ + { + MediaName: sdp.MediaName{ + Media: "audio", + Port: sdp.RangedPort{Value: 9}, + Protos: []string{"UDP", "TLS", "RTP", "SAVPF"}, + Formats: []string{"111"}, + }, + Attributes: []sdp.Attribute{ + {Key: "mid", Value: "0"}, + {Key: "ice-ufrag", Value: "EsAw"}, + {Key: "ice-pwd", Value: "P2uYro0UCOQ4zxjKXaWCBui1"}, + {Key: "candidate", Value: "1387637174 1 udp 2122260223 192.0.2.1 61764 typ host" + + " generation 0 ufrag EsAw network-id 1"}, + {Key: "candidate", Value: "3471623853 1 udp 2122194687 198.51.100.2 61765 typ host" + + " generation 0 ufrag EsAw network-id 2"}, + {Key: "candidate", Value: "473322822 1 tcp 1518280447 192.0.2.1 9 typ host tcptype active" + + " generation 0 ufrag EsAw network-id 1"}, + {Key: "candidate", Value: "2154773085 1 tcp 1518214911 198.51.100.2 9 typ host tcptype active" + + " generation 0 ufrag EsAw network-id 2"}, + {Key: "end-of-candidates", Value: ""}, + }, + }, + }, + }, + }, + { + "rfc9725 ice restart patch request", + "a=ice-options:trickle ice2\r\n" + + "a=group:BUNDLE 0 1\r\n" + + "m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n" + + "a=mid:0\r\n" + + "a=ice-ufrag:ysXw\r\n" + + "a=ice-pwd:vw5LmwG4y/e6dPP/zAP9Gp5k\r\n" + + "a=candidate:1387637174 1 udp 2122260223 192.0.2.1 61764 typ host" + + " generation 0 ufrag EsAw network-id 1\r\n" + + "a=candidate:3471623853 1 udp 2122194687 198.51.100.2 61765 typ host" + + " generation 0 ufrag EsAw network-id 2\r\n" + + "a=candidate:473322822 1 tcp 1518280447 192.0.2.1 9 typ host tcptype active" + + " generation 0 ufrag EsAw network-id 1\r\n" + + "a=candidate:2154773085 1 tcp 1518214911 198.51.100.2 9 typ host tcptype active" + + " generation 0 ufrag EsAw network-id 2\r\n", + &SDPFragment{ + Attributes: []sdp.Attribute{ + {Key: "ice-options", Value: "trickle ice2"}, + {Key: "group", Value: "BUNDLE 0 1"}, + }, + Medias: []*sdp.MediaDescription{ + { + MediaName: sdp.MediaName{ + Media: "audio", + Port: sdp.RangedPort{Value: 9}, + Protos: []string{"UDP", "TLS", "RTP", "SAVPF"}, + Formats: []string{"111"}, + }, + Attributes: []sdp.Attribute{ + {Key: "mid", Value: "0"}, + {Key: "ice-ufrag", Value: "ysXw"}, + {Key: "ice-pwd", Value: "vw5LmwG4y/e6dPP/zAP9Gp5k"}, + {Key: "candidate", Value: "1387637174 1 udp 2122260223 192.0.2.1 61764 typ host" + + " generation 0 ufrag EsAw network-id 1"}, + {Key: "candidate", Value: "3471623853 1 udp 2122194687 198.51.100.2 61765 typ host" + + " generation 0 ufrag EsAw network-id 2"}, + {Key: "candidate", Value: "473322822 1 tcp 1518280447 192.0.2.1 9 typ host tcptype active" + + " generation 0 ufrag EsAw network-id 1"}, + {Key: "candidate", Value: "2154773085 1 tcp 1518214911 198.51.100.2 9 typ host tcptype active" + + " generation 0 ufrag EsAw network-id 2"}, + }, + }, + }, + }, + }, + { + "rfc9725 ice restart patch response", + "a=ice-lite\r\n" + + "a=ice-options:trickle ice2\r\n" + + "a=group:BUNDLE 0 1\r\n" + + "m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n" + + "a=mid:0\r\n" + + "a=ice-ufrag:289b31b754eaa438\r\n" + + "a=ice-pwd:0b66f472495ef0ccac7bda653ab6be49ea13114472a5d10a\r\n" + + "a=candidate:1 1 udp 2130706431 198.51.100.1 39132 typ host\r\n" + + "a=end-of-candidates\r\n", + &SDPFragment{ + Attributes: []sdp.Attribute{ + {Key: "ice-lite", Value: ""}, + {Key: "ice-options", Value: "trickle ice2"}, + {Key: "group", Value: "BUNDLE 0 1"}, + }, + Medias: []*sdp.MediaDescription{ + { + MediaName: sdp.MediaName{ + Media: "audio", + Port: sdp.RangedPort{Value: 9}, + Protos: []string{"UDP", "TLS", "RTP", "SAVPF"}, + Formats: []string{"111"}, + }, + Attributes: []sdp.Attribute{ + {Key: "mid", Value: "0"}, + {Key: "ice-ufrag", Value: "289b31b754eaa438"}, + {Key: "ice-pwd", Value: "0b66f472495ef0ccac7bda653ab6be49ea13114472a5d10a"}, + {Key: "candidate", Value: "1 1 udp 2130706431 198.51.100.1 39132 typ host"}, + {Key: "end-of-candidates", Value: ""}, + }, + }, + }, + }, + }, +} + +func TestSDPFragmentUnmarshal(t *testing.T) { + for _, ca := range sdpFragmentCases { + t.Run(ca.name, func(t *testing.T) { + frag := &SDPFragment{} + err := frag.Unmarshal([]byte(ca.enc)) + require.NoError(t, err) + require.Equal(t, ca.dec, frag) + }) + } +} + +func TestSDPFragmentMarshal(t *testing.T) { + for _, ca := range sdpFragmentCases { + t.Run(ca.name, func(t *testing.T) { + byts, err := ca.dec.Marshal() + require.NoError(t, err) + require.Equal(t, ca.enc, string(byts)) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordcleaner/cleaner.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordcleaner/cleaner.go new file mode 100644 index 0000000000000000000000000000000000000000..879eec7d782d9b324c5209c2474641b49cd100a1 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordcleaner/cleaner.go @@ -0,0 +1,151 @@ +// Package recordcleaner contains the recording cleaner. +package recordcleaner + +import ( + "context" + "io/fs" + "os" + "path/filepath" + "strings" + "time" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/recordstore" +) + +var timeNow = time.Now + +// Cleaner removes expired recording segments from disk. +type Cleaner struct { + PathConfs map[string]*conf.Path + Parent logger.Writer + + ctx context.Context + ctxCancel func() + + chReloadConf chan map[string]*conf.Path + done chan struct{} +} + +// Initialize initializes a Cleaner. +func (c *Cleaner) Initialize() { + c.ctx, c.ctxCancel = context.WithCancel(context.Background()) + c.chReloadConf = make(chan map[string]*conf.Path) + c.done = make(chan struct{}) + + go c.run() +} + +// Close closes the Cleaner. +func (c *Cleaner) Close() { + c.ctxCancel() + <-c.done +} + +// Log implements logger.Writer. +func (c *Cleaner) Log(level logger.Level, format string, args ...any) { + c.Parent.Log(level, "[record cleaner]"+format, args...) +} + +// ReloadPathConfs is called by core.Core. +func (c *Cleaner) ReloadPathConfs(pathConfs map[string]*conf.Path) { + select { + case c.chReloadConf <- pathConfs: + case <-c.ctx.Done(): + } +} + +func (c *Cleaner) run() { + defer close(c.done) + + c.doRun() //nolint:errcheck + + for { + select { + case <-time.After(c.cleanInterval()): + c.doRun() + + case cnf := <-c.chReloadConf: + c.PathConfs = cnf + + case <-c.ctx.Done(): + return + } + } +} + +func (c *Cleaner) cleanInterval() time.Duration { + interval := 30 * 60 * time.Second + + for _, e := range c.PathConfs { + if e.RecordDeleteAfter != 0 && + interval > (time.Duration(e.RecordDeleteAfter)/2) { + interval = time.Duration(e.RecordDeleteAfter) / 2 + } + } + + return interval +} + +func (c *Cleaner) doRun() { + now := timeNow() + + pathNames := recordstore.FindAllPathsWithSegments(c.PathConfs) + + for _, pathName := range pathNames { + c.processPath(now, pathName) //nolint:errcheck + } +} + +func (c *Cleaner) processPath(now time.Time, pathName string) error { + pathConf, _, err := conf.FindPathConf(c.PathConfs, pathName) + if err != nil { + return err + } + + if pathConf.RecordDeleteAfter == 0 { + return nil + } + + err = c.deleteExpiredSegments(now, pathName, pathConf) + if err != nil { + return err + } + + c.deleteEmptyDirs(pathConf) + + return nil +} + +func (c *Cleaner) deleteExpiredSegments(now time.Time, pathName string, pathConf *conf.Path) error { + end := now.Add(-time.Duration(pathConf.RecordDeleteAfter)) + segments, err := recordstore.FindSegments(pathConf, pathName, nil, &end) + if err != nil { + return err + } + + for _, seg := range segments { + c.Log(logger.Debug, "removing %s", seg.Fpath) + os.Remove(seg.Fpath) + } + + return nil +} + +func (c *Cleaner) deleteEmptyDirs(pathConf *conf.Path) { + recordPath := strings.ReplaceAll(pathConf.RecordPath, "%path", pathConf.Name) + commonPath := recordstore.CommonPath(recordPath) + + filepath.WalkDir(commonPath, func(fpath string, info fs.DirEntry, err error) error { //nolint:errcheck + if err != nil { + return err + } + + if info.IsDir() { + os.Remove(fpath) + } + + return nil + }) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordcleaner/cleaner_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordcleaner/cleaner_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3562b95c741433fe105f8b283a3c89864a70452b --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordcleaner/cleaner_test.go @@ -0,0 +1,106 @@ +package recordcleaner + +import ( + "os" + "path/filepath" + "regexp" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/stretchr/testify/require" +) + +func TestCleaner(t *testing.T) { + timeNow = func() time.Time { + return time.Date(2009, 5, 20, 22, 15, 25, 427000, time.Local) + } + + dir := t.TempDir() + + const specialChars = "_-+*?^$()[]{}|" + + err := os.Mkdir(filepath.Join(dir, specialChars+"_mypath"), 0o755) + require.NoError(t, err) + + err = os.WriteFile(filepath.Join(dir, specialChars+"_mypath", "2008-05-20_22-15-25-000125.mp4"), []byte{1}, 0o644) + require.NoError(t, err) + + err = os.WriteFile(filepath.Join(dir, specialChars+"_mypath", "2009-05-20_22-15-25-000427.mp4"), []byte{1}, 0o644) + require.NoError(t, err) + + c := &Cleaner{ + PathConfs: map[string]*conf.Path{ + "~^.*$": { + Name: "~^.*$", + Regexp: regexp.MustCompile("^.*$"), + RecordPath: filepath.Join(dir, specialChars+"_%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + RecordDeleteAfter: conf.Duration(10 * time.Second), + }, + }, + Parent: test.NilLogger, + } + c.Initialize() + defer c.Close() + + time.Sleep(500 * time.Millisecond) + + _, err = os.Stat(filepath.Join(dir, specialChars+"_mypath", "2008-05-20_22-15-25-000125.mp4")) + require.Error(t, err) + + _, err = os.Stat(filepath.Join(dir, specialChars+"_mypath", "2009-05-20_22-15-25-000427.mp4")) + require.NoError(t, err) +} + +func TestCleanerMultipleEntriesSamePath(t *testing.T) { + timeNow = func() time.Time { + return time.Date(2009, 5, 20, 22, 15, 25, 427000, time.Local) + } + + dir := t.TempDir() + + err := os.Mkdir(filepath.Join(dir, "path1"), 0o755) + require.NoError(t, err) + + err = os.Mkdir(filepath.Join(dir, "path2"), 0o755) + require.NoError(t, err) + + err = os.WriteFile(filepath.Join(dir, "path1", "2009-05-19_22-15-25-000427.mp4"), []byte{1}, 0o644) + require.NoError(t, err) + + err = os.WriteFile(filepath.Join(dir, "path2", "2009-05-19_22-15-25-000427.mp4"), []byte{1}, 0o644) + require.NoError(t, err) + + c := &Cleaner{ + PathConfs: map[string]*conf.Path{ + "path1": { + Name: "path1", + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + RecordDeleteAfter: conf.Duration(10 * time.Second), + }, + "path2": { + Name: "path2", + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + RecordDeleteAfter: conf.Duration(10 * 24 * time.Hour), + }, + }, + Parent: test.NilLogger, + } + c.Initialize() + defer c.Close() + + time.Sleep(500 * time.Millisecond) + + _, err = os.Stat(filepath.Join(dir, "path1", "2009-05-19_22-15-25-000427.mp4")) + require.Error(t, err) + + _, err = os.Stat(filepath.Join(dir, "path1")) + require.Error(t, err, "testing") + + _, err = os.Stat(filepath.Join(dir, "path2", "2009-05-19_22-15-25-000427.mp4")) + require.NoError(t, err) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format.go new file mode 100644 index 0000000000000000000000000000000000000000..890030b47b203cef7e781216fe6bae4b4949ae46 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format.go @@ -0,0 +1,6 @@ +package recorder + +type format interface { + initialize() bool + close() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4.go new file mode 100644 index 0000000000000000000000000000000000000000..688327c5a77b0b570ce22aa613f2acf2f0ef3f17 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4.go @@ -0,0 +1,958 @@ +package recorder + +import ( + "bytes" + "fmt" + "slices" + "time" + + rtspformat "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/ac3" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/av1" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/g711" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/h264" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/h265" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/jpeg" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg1audio" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4video" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/opus" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/vp9" + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + mcodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mp4/codecs" + + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/formatlabel" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/unit" +) + +var ( + av1DefaultSequenceHeader = []byte{ + 8, 0, 0, 0, 66, 167, 191, 228, 96, 13, 0, 64, + } + + h265DefaultVPS = []byte{ + 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x02, 0x20, + 0x00, 0x00, 0x03, 0x00, 0xb0, 0x00, 0x00, 0x03, + 0x00, 0x00, 0x03, 0x00, 0x7b, 0x18, 0xb0, 0x24, + } + + h265DefaultSPS = []byte{ + 0x42, 0x01, 0x01, 0x02, 0x20, 0x00, 0x00, 0x03, + 0x00, 0xb0, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, + 0x00, 0x7b, 0xa0, 0x07, 0x82, 0x00, 0x88, 0x7d, + 0xb6, 0x71, 0x8b, 0x92, 0x44, 0x80, 0x53, 0x88, + 0x88, 0x92, 0xcf, 0x24, 0xa6, 0x92, 0x72, 0xc9, + 0x12, 0x49, 0x22, 0xdc, 0x91, 0xaa, 0x48, 0xfc, + 0xa2, 0x23, 0xff, 0x00, 0x01, 0x00, 0x01, 0x6a, + 0x02, 0x02, 0x02, 0x01, + } + + h265DefaultPPS = []byte{ + 0x44, 0x01, 0xc0, 0x25, 0x2f, 0x05, 0x32, 0x40, + } + + h264DefaultSPS = []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, + } + + h264DefaultPPS = []byte{0x08, 0x06, 0x07, 0x08} + + mpeg4VideoDefaultConfig = []byte{ + 0x00, 0x00, 0x01, 0xb0, 0x01, 0x00, 0x00, 0x01, + 0xb5, 0x89, 0x13, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x01, 0x20, 0x00, 0xc4, 0x8d, 0x88, 0x00, + 0xf5, 0x3c, 0x04, 0x87, 0x14, 0x63, 0x00, 0x00, + 0x01, 0xb2, 0x4c, 0x61, 0x76, 0x63, 0x35, 0x38, + 0x2e, 0x31, 0x33, 0x34, 0x2e, 0x31, 0x30, 0x30, + } + + mpeg1VideoDefaultConfig = []byte{ + 0x00, 0x00, 0x01, 0xb3, 0x78, 0x04, 0x38, 0x35, + 0xff, 0xff, 0xe0, 0x18, 0x00, 0x00, 0x01, 0xb5, + 0x14, 0x4a, 0x00, 0x01, 0x00, 0x00, + } +) + +func mpeg1audioChannelCount(cm mpeg1audio.ChannelMode) int { + switch cm { + case mpeg1audio.ChannelModeStereo, + mpeg1audio.ChannelModeJointStereo, + mpeg1audio.ChannelModeDualChannel: + return 2 + + default: + return 1 + } +} + +func jpegExtractSize(image []byte) (int, int, error) { + l := len(image) + if l < 2 || image[0] != 0xFF || image[1] != jpeg.MarkerStartOfImage { + return 0, 0, fmt.Errorf("invalid header") + } + + image = image[2:] + + for { + if len(image) < 2 { + return 0, 0, fmt.Errorf("not enough bits") + } + + h0, h1 := image[0], image[1] + image = image[2:] + + if h0 != 0xFF { + return 0, 0, fmt.Errorf("invalid image") + } + + switch h1 { + case 0xE0, 0xE1, 0xE2, // JFIF + jpeg.MarkerDefineHuffmanTable, + jpeg.MarkerComment, + jpeg.MarkerDefineQuantizationTable, + jpeg.MarkerDefineRestartInterval: + mlen := int(image[0])<<8 | int(image[1]) + if len(image) < mlen { + return 0, 0, fmt.Errorf("not enough bits") + } + image = image[mlen:] + + case jpeg.MarkerStartOfFrame1: + mlen := int(image[0])<<8 | int(image[1]) + if len(image) < mlen { + return 0, 0, fmt.Errorf("not enough bits") + } + + var sof jpeg.StartOfFrame1 + err := sof.Unmarshal(image[2:mlen]) + if err != nil { + return 0, 0, err + } + + return sof.Width, sof.Height, nil + + case jpeg.MarkerStartOfScan: + return 0, 0, fmt.Errorf("SOF not found") + + default: + return 0, 0, fmt.Errorf("unknown marker: 0x%.2x", h1) + } + } +} + +type formatFMP4Sample struct { + *fmp4.Sample + dts int64 + ntp time.Time +} + +type formatFMP4 struct { + ri *recorderInstance + + tracks []*formatFMP4Track + hasVideo bool + currentSegment *formatFMP4Segment + nextSegmentNumber uint64 +} + +func (f *formatFMP4) initialize() bool { + nextID := 1 + + addTrack := func(format rtspformat.Format, codec mcodecs.Codec) *formatFMP4Track { + track := &formatFMP4Track{ + f: f, + id: nextID, + clockRate: uint32(format.ClockRate()), + codec: codec, + } + track.initialize() + + nextID++ + f.tracks = append(f.tracks, track) + return track + } + + outDesc := f.ri.stream.OutDescCopy() + + for i, origMedia := range f.ri.stream.OrigDesc.Medias { + for j, origFormat := range origMedia.Formats { + clockRate := origFormat.ClockRate() + + switch origFormat := origFormat.(type) { + case *rtspformat.AV1: + codec := &mcodecs.AV1{ + SequenceHeader: av1DefaultSequenceHeader, + } + track := addTrack(origFormat, codec) + + firstReceived := false + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + randomAccess := false + paramsChanged := false + + for _, obu := range u.Payload.(unit.PayloadAV1) { + typ := av1.OBUType((obu[0] >> 3) & 0b1111) + + if typ == av1.OBUTypeSequenceHeader { + if !bytes.Equal(codec.SequenceHeader, obu) { + codec.SequenceHeader = obu + paramsChanged = true + } + randomAccess = true + } + } + + if paramsChanged { + f.updateCodecParams() + } + + if !firstReceived { + if !randomAccess { + return nil + } + firstReceived = true + } + + var sampl fmp4.Sample + err := sampl.FillAV1(u.Payload.(unit.PayloadAV1)) + if err != nil { + return err + } + + return track.write(&formatFMP4Sample{ + Sample: &sampl, + dts: u.PTS, + ntp: u.NTP, + }) + }) + + case *rtspformat.VP9: + codec := &mcodecs.VP9{ + Width: 1280, + Height: 720, + Profile: 1, + BitDepth: 8, + ChromaSubsampling: 1, + ColorRange: false, + } + track := addTrack(origFormat, codec) + + firstReceived := false + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + var h vp9.Header + err := h.Unmarshal(u.Payload.(unit.PayloadVP9)) + if err != nil { + return err + } + + randomAccess := false + paramsChanged := false + + if !h.NonKeyFrame { + randomAccess = true + + if w := h.Width(); codec.Width != w { + codec.Width = w + paramsChanged = true + } + if h := h.Width(); codec.Height != h { + codec.Height = h + paramsChanged = true + } + if codec.Profile != h.Profile { + codec.Profile = h.Profile + paramsChanged = true + } + if codec.BitDepth != h.ColorConfig.BitDepth { + codec.BitDepth = h.ColorConfig.BitDepth + paramsChanged = true + } + if c := h.ChromaSubsampling(); codec.ChromaSubsampling != c { + codec.ChromaSubsampling = c + paramsChanged = true + } + if codec.ColorRange != h.ColorConfig.ColorRange { + codec.ColorRange = h.ColorConfig.ColorRange + paramsChanged = true + } + } + + if paramsChanged { + f.updateCodecParams() + } + + if !firstReceived { + if !randomAccess { + return nil + } + firstReceived = true + } + + return track.write(&formatFMP4Sample{ + Sample: &fmp4.Sample{ + IsNonSyncSample: !randomAccess, + Payload: u.Payload.(unit.PayloadVP9), + }, + dts: u.PTS, + ntp: u.NTP, + }) + }) + + case *rtspformat.VP8: + // TODO + + case *rtspformat.H265: + outFormat := outDesc.Medias[i].Formats[j].(*rtspformat.H265) + + vps := outFormat.VPS + sps := outFormat.SPS + pps := outFormat.PPS + + if vps == nil || sps == nil || pps == nil { + vps = h265DefaultVPS + sps = h265DefaultSPS + pps = h265DefaultPPS + } + + codec := &mcodecs.H265{ + VPS: vps, + SPS: sps, + PPS: pps, + } + track := addTrack(origFormat, codec) + + var dtsExtractor *h265.DTSExtractor + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + randomAccess := false + paramsChanged := false + + for _, nalu := range u.Payload.(unit.PayloadH265) { + typ := h265.NALUType((nalu[0] >> 1) & 0b111111) + + switch typ { + case h265.NALUType_VPS_NUT: + if !bytes.Equal(codec.VPS, nalu) { + codec.VPS = nalu + paramsChanged = true + } + + case h265.NALUType_SPS_NUT: + if !bytes.Equal(codec.SPS, nalu) { + codec.SPS = nalu + paramsChanged = true + } + + case h265.NALUType_PPS_NUT: + if !bytes.Equal(codec.PPS, nalu) { + codec.PPS = nalu + paramsChanged = true + } + + case h265.NALUType_IDR_W_RADL, h265.NALUType_IDR_N_LP, h265.NALUType_CRA_NUT: + randomAccess = true + } + } + + if paramsChanged { + f.updateCodecParams() + } + + if dtsExtractor == nil { + if !randomAccess { + return nil + } + dtsExtractor = &h265.DTSExtractor{} + dtsExtractor.Initialize() + } + + dts, err := dtsExtractor.Extract(u.Payload.(unit.PayloadH265), u.PTS) + if err != nil { + return err + } + + var sampl fmp4.Sample + err = sampl.FillH265(int32(u.PTS-dts), u.Payload.(unit.PayloadH265)) + if err != nil { + return err + } + + return track.write(&formatFMP4Sample{ + Sample: &sampl, + dts: dts, + ntp: u.NTP, + }) + }) + + case *rtspformat.H264: + outFormat := outDesc.Medias[i].Formats[j].(*rtspformat.H264) + + sps := outFormat.SPS + pps := outFormat.PPS + + if sps == nil || pps == nil { + sps = h264DefaultSPS + pps = h264DefaultPPS + } + + codec := &mcodecs.H264{ + SPS: sps, + PPS: pps, + } + track := addTrack(origFormat, codec) + + var dtsExtractor *h264.DTSExtractor + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + randomAccess := false + paramsChanged := false + + for _, nalu := range u.Payload.(unit.PayloadH264) { + typ := h264.NALUType(nalu[0] & 0x1F) + switch typ { + case h264.NALUTypeSPS: + if !bytes.Equal(codec.SPS, nalu) { + codec.SPS = nalu + paramsChanged = true + } + + case h264.NALUTypePPS: + if !bytes.Equal(codec.PPS, nalu) { + codec.PPS = nalu + paramsChanged = true + } + + case h264.NALUTypeIDR: + randomAccess = true + } + } + + if paramsChanged { + f.updateCodecParams() + } + + if dtsExtractor == nil { + if !randomAccess { + return nil + } + dtsExtractor = &h264.DTSExtractor{} + dtsExtractor.Initialize() + } + + dts, err := dtsExtractor.Extract(u.Payload.(unit.PayloadH264), u.PTS) + if err != nil { + return err + } + + var sampl fmp4.Sample + err = sampl.FillH264(int32(u.PTS-dts), u.Payload.(unit.PayloadH264)) + if err != nil { + return err + } + + return track.write(&formatFMP4Sample{ + Sample: &sampl, + dts: dts, + ntp: u.NTP, + }) + }) + + case *rtspformat.MPEG4Video: + outFormat := outDesc.Medias[i].Formats[j].(*rtspformat.MPEG4Video) + + config := outFormat.Config + + if config == nil { + config = mpeg4VideoDefaultConfig + } + + codec := &mcodecs.MPEG4Video{ + Config: config, + } + track := addTrack(origFormat, codec) + + firstReceived := false + var lastPTS int64 + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + randomAccess := bytes.Contains(u.Payload.(unit.PayloadMPEG4Video), + []byte{0, 0, 1, byte(mpeg4video.GroupOfVOPStartCode)}) + + if bytes.HasPrefix(u.Payload.(unit.PayloadMPEG4Video), + []byte{0, 0, 1, byte(mpeg4video.VisualObjectSequenceStartCode)}) { + end := bytes.Index(u.Payload.(unit.PayloadMPEG4Video)[4:], + []byte{0, 0, 1, byte(mpeg4video.GroupOfVOPStartCode)}) + if end >= 0 { + config2 := u.Payload.(unit.PayloadMPEG4Video)[:end+4] + + if !bytes.Equal(codec.Config, config2) { + codec.Config = config2 + f.updateCodecParams() + } + } + } + + if !firstReceived { + if !randomAccess { + return nil + } + firstReceived = true + } else if u.PTS < lastPTS { + return fmt.Errorf("MPEG-4 Video streams with B-frames are not supported (yet)") + } + lastPTS = u.PTS + + return track.write(&formatFMP4Sample{ + Sample: &fmp4.Sample{ + Payload: u.Payload.(unit.PayloadMPEG4Video), + IsNonSyncSample: !randomAccess, + }, + dts: u.PTS, + ntp: u.NTP, + }) + }) + + case *rtspformat.MPEG1Video: + codec := &mcodecs.MPEG1Video{ + Config: mpeg1VideoDefaultConfig, + } + track := addTrack(origFormat, codec) + + firstReceived := false + var lastPTS int64 + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + randomAccess := bytes.Contains(u.Payload.(unit.PayloadMPEG1Video), []byte{0, 0, 1, 0xB8}) + + if bytes.HasPrefix(u.Payload.(unit.PayloadMPEG1Video), []byte{0, 0, 1, 0xB3}) { + end := bytes.Index(u.Payload.(unit.PayloadMPEG1Video)[4:], []byte{0, 0, 1, 0xB8}) + if end >= 0 { + config := u.Payload.(unit.PayloadMPEG1Video)[:end+4] + + if !bytes.Equal(codec.Config, config) { + codec.Config = config + f.updateCodecParams() + } + } + } + + if !firstReceived { + if !randomAccess { + return nil + } + firstReceived = true + } else if u.PTS < lastPTS { + return fmt.Errorf("MPEG-1/2 Video streams with B-frames are not supported (yet)") + } + lastPTS = u.PTS + + return track.write(&formatFMP4Sample{ + Sample: &fmp4.Sample{ + Payload: u.Payload.(unit.PayloadMPEG1Video), + IsNonSyncSample: !randomAccess, + }, + dts: u.PTS, + ntp: u.NTP, + }) + }) + + case *rtspformat.MJPEG: + codec := &mcodecs.MJPEG{ + Width: 800, + Height: 600, + } + track := addTrack(origFormat, codec) + + parsed := false + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + if !parsed { + parsed = true + width, height, err := jpegExtractSize(u.Payload.(unit.PayloadMJPEG)) + if err != nil { + return err + } + codec.Width = width + codec.Height = height + f.updateCodecParams() + } + + return track.write(&formatFMP4Sample{ + Sample: &fmp4.Sample{ + Payload: u.Payload.(unit.PayloadMJPEG), + }, + dts: u.PTS, + ntp: u.NTP, + }) + }) + + case *rtspformat.Opus: + codec := &mcodecs.Opus{ + ChannelCount: origFormat.ChannelCount, + } + track := addTrack(origFormat, codec) + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + pts := u.PTS + + for _, packet := range u.Payload.(unit.PayloadOpus) { + err := track.write(&formatFMP4Sample{ + Sample: &fmp4.Sample{ + Payload: packet, + }, + dts: pts, + ntp: u.NTP.Add(timestampToDuration(pts-u.PTS, clockRate)), + }) + if err != nil { + return err + } + + pts += opus.PacketDuration2(packet) + } + + return nil + }) + + case *rtspformat.MPEG4Audio: + codec := &mcodecs.MPEG4Audio{ + Config: *origFormat.Config, + } + track := addTrack(origFormat, codec) + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + for i, au := range u.Payload.(unit.PayloadMPEG4Audio) { + pts := u.PTS + int64(i)*mpeg4audio.SamplesPerAccessUnit + + err := track.write(&formatFMP4Sample{ + Sample: &fmp4.Sample{ + Payload: au, + }, + dts: pts, + ntp: u.NTP.Add(timestampToDuration(pts-u.PTS, clockRate)), + }) + if err != nil { + return err + } + } + + return nil + }) + + case *rtspformat.MPEG4AudioLATM: + if !origFormat.CPresent { + codec := &mcodecs.MPEG4Audio{ + Config: *origFormat.StreamMuxConfig.Programs[0].Layers[0].AudioSpecificConfig, + } + track := addTrack(origFormat, codec) + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + var ame mpeg4audio.AudioMuxElement + ame.StreamMuxConfig = origFormat.StreamMuxConfig + err := ame.Unmarshal(u.Payload.(unit.PayloadMPEG4AudioLATM)) + if err != nil { + return err + } + + return track.write(&formatFMP4Sample{ + Sample: &fmp4.Sample{ + Payload: ame.Payloads[0][0][0], + }, + dts: u.PTS, + ntp: u.NTP, + }) + }) + } + + case *rtspformat.MPEG1Audio: + codec := &mcodecs.MPEG1Audio{ + SampleRate: 32000, + ChannelCount: 2, + } + track := addTrack(origFormat, codec) + + parsed := false + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + var dt time.Duration + + for _, frame := range u.Payload.(unit.PayloadMPEG1Audio) { + var h mpeg1audio.FrameHeader + err := h.Unmarshal(frame) + if err != nil { + return err + } + + if !parsed { + parsed = true + codec.SampleRate = h.SampleRate + codec.ChannelCount = mpeg1audioChannelCount(h.ChannelMode) + f.updateCodecParams() + } + + err = track.write(&formatFMP4Sample{ + Sample: &fmp4.Sample{ + Payload: frame, + }, + dts: u.PTS + u.PTS, + ntp: u.NTP, + }) + if err != nil { + return err + } + + dt += time.Duration(h.SampleCount()) * + time.Second / time.Duration(h.SampleRate) + } + + return nil + }) + + case *rtspformat.AC3: + codec := &mcodecs.AC3{ + SampleRate: origFormat.SampleRate, + ChannelCount: origFormat.ChannelCount, + Fscod: 0, + Bsid: 8, + Bsmod: 0, + Acmod: 7, + LfeOn: true, + BitRateCode: 7, + } + track := addTrack(origFormat, codec) + + parsed := false + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + for i, frame := range u.Payload.(unit.PayloadAC3) { + var syncInfo ac3.SyncInfo + err := syncInfo.Unmarshal(frame) + if err != nil { + return fmt.Errorf("invalid AC-3 frame: %w", err) + } + + var bsi ac3.BSI + err = bsi.Unmarshal(frame[5:]) + if err != nil { + return fmt.Errorf("invalid AC-3 frame: %w", err) + } + + if !parsed { + parsed = true + codec.SampleRate = syncInfo.SampleRate() + codec.ChannelCount = bsi.ChannelCount() + codec.Bsid = bsi.Bsid + codec.Bsmod = bsi.Bsmod + codec.Acmod = bsi.Acmod + codec.LfeOn = bsi.LfeOn + codec.BitRateCode = syncInfo.Frmsizecod >> 1 + f.updateCodecParams() + } + + pts := u.PTS + int64(i)*ac3.SamplesPerFrame + + err = track.write(&formatFMP4Sample{ + Sample: &fmp4.Sample{ + Payload: frame, + }, + dts: pts, + ntp: u.NTP.Add(timestampToDuration(pts-u.PTS, clockRate)), + }) + if err != nil { + return err + } + } + + return nil + }) + + case *rtspformat.G722: + // TODO + + case *rtspformat.G711: + codec := &mcodecs.LPCM{ + LittleEndian: false, + BitDepth: 16, + SampleRate: origFormat.SampleRate, + ChannelCount: origFormat.ChannelCount, + } + track := addTrack(origFormat, codec) + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + var lpcm []byte + if origFormat.MULaw { + var mu g711.Mulaw + mu.Unmarshal(u.Payload.(unit.PayloadG711)) + lpcm = mu + } else { + var al g711.Alaw + al.Unmarshal(u.Payload.(unit.PayloadG711)) + lpcm = al + } + + return track.write(&formatFMP4Sample{ + Sample: &fmp4.Sample{ + Payload: lpcm, + }, + dts: u.PTS, + ntp: u.NTP, + }) + }) + + case *rtspformat.LPCM: + codec := &mcodecs.LPCM{ + LittleEndian: false, + BitDepth: origFormat.BitDepth, + SampleRate: origFormat.SampleRate, + ChannelCount: origFormat.ChannelCount, + } + track := addTrack(origFormat, codec) + + f.ri.reader.OnData( + origMedia, + origFormat, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + return track.write(&formatFMP4Sample{ + Sample: &fmp4.Sample{ + Payload: u.Payload.(unit.PayloadLPCM), + }, + dts: u.PTS, + ntp: u.NTP, + }) + }) + } + } + } + + if len(f.tracks) == 0 { + f.ri.Log(logger.Warn, "no supported tracks found, skipping recording") + return false + } + + setuppedFormats := f.ri.reader.Formats() + + n := 1 + for _, medi := range f.ri.stream.OrigDesc.Medias { + for _, forma := range medi.Formats { + if !slices.Contains(setuppedFormats, forma) { + f.ri.Log(logger.Warn, "skipping track %d (%s)", n, formatlabel.FormatToLabel(forma)) + } + n++ + } + } + + f.ri.Log(logger.Info, "recording %s", + defs.FormatsInfo(setuppedFormats)) + + return true +} + +func (f *formatFMP4) updateCodecParams() { + f.ri.Log(logger.Debug, "codec parameters have changed") +} + +func (f *formatFMP4) close() { + if f.currentSegment != nil { + f.currentSegment.close() //nolint:errcheck + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4_part.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4_part.go new file mode 100644 index 0000000000000000000000000000000000000000..b746f4799c2f2b44cb6452aafb75755ba7ccc993 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4_part.go @@ -0,0 +1,88 @@ +package recorder + +import ( + "fmt" + "io" + "time" + + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4/seekablebuffer" + "github.com/bluenviron/mediamtx/internal/conf" +) + +func writePart( + f io.Writer, + sequenceNumber uint32, + partTracks map[*formatFMP4Track]*fmp4.PartTrack, +) error { + fmp4PartTracks := make([]*fmp4.PartTrack, len(partTracks)) + i := 0 + for _, partTrack := range partTracks { + fmp4PartTracks[i] = partTrack + i++ + } + + part := &fmp4.Part{ + SequenceNumber: sequenceNumber, + Tracks: fmp4PartTracks, + } + + var buf seekablebuffer.Buffer + err := part.Marshal(&buf) + if err != nil { + return err + } + + _, err = f.Write(buf.Bytes()) + return err +} + +type formatFMP4Part struct { + maxPartSize conf.StringSize + segmentStartDTS time.Duration + number uint32 + startDTS time.Duration + + partTracks map[*formatFMP4Track]*fmp4.PartTrack + size uint64 + endDTS time.Duration +} + +func (p *formatFMP4Part) initialize() { + p.partTracks = make(map[*formatFMP4Track]*fmp4.PartTrack) +} + +func (p *formatFMP4Part) close(w io.Writer) error { + return writePart(w, p.number, p.partTracks) +} + +func (p *formatFMP4Part) write(track *formatFMP4Track, sample *formatFMP4Sample, dts time.Duration) error { + size := uint64(len(sample.Payload)) + if (p.size + size) > uint64(p.maxPartSize) { + return fmt.Errorf("reached maximum part size") + } + p.size += size + + partTrack, ok := p.partTracks[track] + if !ok { + partTrack = &fmp4.PartTrack{ + ID: track.initTrack.ID, + BaseTime: uint64(multiplyAndDivide(int64(dts-p.segmentStartDTS), + int64(track.initTrack.TimeScale), int64(time.Second))), + } + p.partTracks[track] = partTrack + } + + partTrack.Samples = append(partTrack.Samples, sample.Sample) + + endDTS := dts + timestampToDuration(int64(sample.Duration), int(track.initTrack.TimeScale)) + if endDTS > p.endDTS { + p.endDTS = endDTS + } + + return nil +} + +func (p *formatFMP4Part) duration() time.Duration { + return p.endDTS - p.startDTS +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4_segment.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4_segment.go new file mode 100644 index 0000000000000000000000000000000000000000..cb1a3050b27aea41c86833818beefa2666f7db98 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4_segment.go @@ -0,0 +1,237 @@ +package recorder + +import ( + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "time" + + amp4 "github.com/abema/go-mp4" + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4/seekablebuffer" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/recordstore" + "github.com/google/uuid" +) + +func writeInit( + f io.Writer, + streamID uuid.UUID, + segmentNumber uint64, + dts time.Duration, + ntp time.Time, + tracks []*formatFMP4Track, +) error { + fmp4Tracks := make([]*fmp4.InitTrack, len(tracks)) + for i, track := range tracks { + fmp4Tracks[i] = track.initTrack + } + + init := fmp4.Init{ + Tracks: fmp4Tracks, + UserData: []amp4.IBox{ + &recordstore.Mtxi{ + FullBox: amp4.FullBox{ + Version: 0, + }, + StreamID: streamID, + SegmentNumber: segmentNumber, + DTS: int64(dts), + NTP: ntp.UnixNano(), + }, + }, + } + + var buf seekablebuffer.Buffer + err := init.Marshal(&buf) + if err != nil { + return err + } + + _, err = f.Write(buf.Bytes()) + return err +} + +func writeDuration(f io.ReadWriteSeeker, d time.Duration) error { + _, err := f.Seek(0, io.SeekStart) + if err != nil { + return err + } + + // check and skip ftyp header and content + + buf := make([]byte, 8) + _, err = io.ReadFull(f, buf) + if err != nil { + return err + } + + if !bytes.Equal(buf[4:], []byte{'f', 't', 'y', 'p'}) { + return fmt.Errorf("ftyp box not found") + } + + ftypSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) + + _, err = f.Seek(int64(ftypSize), io.SeekStart) + if err != nil { + return err + } + + // check and skip moov header + + _, err = io.ReadFull(f, buf) + if err != nil { + return err + } + + if !bytes.Equal(buf[4:], []byte{'m', 'o', 'o', 'v'}) { + return fmt.Errorf("moov box not found") + } + + moovSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) + + moovPos, err := f.Seek(8, io.SeekCurrent) + if err != nil { + return err + } + + var mvhd amp4.Mvhd + _, err = amp4.Unmarshal(f, uint64(moovSize-8), &mvhd, amp4.Context{}) + if err != nil { + return err + } + + mvhd.DurationV0 = uint32(d / time.Millisecond) + + _, err = f.Seek(moovPos, io.SeekStart) + if err != nil { + return err + } + + _, err = amp4.Marshal(f, &mvhd, amp4.Context{}) + if err != nil { + return err + } + + return nil +} + +type formatFMP4Segment struct { + f *formatFMP4 + startDTS time.Duration + startNTP time.Time + number uint64 + + path string + fi *os.File + curPart *formatFMP4Part + endDTS time.Duration + nextPartNumber uint32 +} + +func (s *formatFMP4Segment) initialize() { + s.endDTS = s.startDTS +} + +func (s *formatFMP4Segment) close() error { + var err error + + if s.curPart != nil { + err = s.closeCurPart() + } + + if s.fi != nil { + s.f.ri.Log(logger.Debug, "closing segment %s", s.path) + + // write overall duration in the header to speed up the playback server + duration := s.endDTS - s.startDTS + err2 := writeDuration(s.fi, duration) + if err == nil { + err = err2 + } + + err2 = s.fi.Close() + if err == nil { + err = err2 + } + + if err2 == nil { + s.f.ri.onSegmentComplete(s.path, duration) + } + } + + return err +} + +func (s *formatFMP4Segment) closeCurPart() error { + if s.fi == nil { + s.path = recordstore.Path{Start: s.startNTP}.Encode(s.f.ri.pathFormat2) + s.f.ri.Log(logger.Debug, "creating segment %s", s.path) + + err := os.MkdirAll(filepath.Dir(s.path), 0o755) + if err != nil { + return err + } + + fi, err := os.Create(s.path) + if err != nil { + return err + } + + s.f.ri.onSegmentCreate(s.path) + + err = writeInit( + fi, + s.f.ri.streamID, + s.number, + s.startDTS, + s.startNTP, + s.f.tracks) + if err != nil { + fi.Close() + return err + } + + s.fi = fi + } + + return s.curPart.close(s.fi) +} + +func (s *formatFMP4Segment) write(track *formatFMP4Track, sample *formatFMP4Sample, dts time.Duration) error { + endDTS := dts + timestampToDuration(int64(sample.Duration), int(track.initTrack.TimeScale)) + if endDTS > s.endDTS { + s.endDTS = endDTS + } + + if s.curPart == nil { + s.curPart = &formatFMP4Part{ + maxPartSize: s.f.ri.maxPartSize, + segmentStartDTS: s.startDTS, + number: s.nextPartNumber, + startDTS: dts, + } + s.curPart.initialize() + s.nextPartNumber++ + } else if s.curPart.duration() >= s.f.ri.partDuration { + err := s.closeCurPart() + s.curPart = nil + + if err != nil { + return err + } + + s.curPart = &formatFMP4Part{ + maxPartSize: s.f.ri.maxPartSize, + segmentStartDTS: s.startDTS, + number: s.nextPartNumber, + startDTS: dts, + } + s.curPart.initialize() + s.nextPartNumber++ + } + + return s.curPart.write(track, sample, dts) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4_track.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4_track.go new file mode 100644 index 0000000000000000000000000000000000000000..f8fda65be3c2d57d9b62e4d6fa51d9fc26577889 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_fmp4_track.go @@ -0,0 +1,141 @@ +package recorder + +import ( + "fmt" + "time" + + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + mcodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mp4/codecs" + "github.com/bluenviron/mediamtx/internal/logger" +) + +const ( + // this corresponds to concatenationTolerance + maxBasetime = 1 * time.Second +) + +// start next segment from the oldest next sample, in order to avoid negative basetimes (impossible) in fMP4. +// keep starting position within a certain distance from the newest next sample to avoid big basetimes. +func nextSegmentStartingPos(tracks []*formatFMP4Track) (time.Time, time.Duration) { + var maxDTS time.Duration + for _, track := range tracks { + if track.nextSample != nil { + dts := timestampToDuration(track.nextSample.dts, int(track.initTrack.TimeScale)) + if dts > maxDTS { + maxDTS = dts + } + } + } + + var oldestNTP time.Time + oldestDTS := maxDTS + + for _, track := range tracks { + if track.nextSample != nil { + dts := timestampToDuration(track.nextSample.dts, int(track.initTrack.TimeScale)) + if (maxDTS-dts) <= maxBasetime && (dts <= oldestDTS) { + oldestNTP = track.nextSample.ntp + oldestDTS = dts + } + } + } + + return oldestNTP, oldestDTS +} + +type formatFMP4Track struct { + f *formatFMP4 + id int + clockRate uint32 + codec mcodecs.Codec + + initTrack *fmp4.InitTrack + nextSample *formatFMP4Sample + startInitialized bool + startDTS time.Duration + startNTP time.Time +} + +func (t *formatFMP4Track) initialize() { + t.initTrack = &fmp4.InitTrack{ + ID: t.id, + TimeScale: t.clockRate, + Codec: t.codec, + } +} + +func (t *formatFMP4Track) write(sample *formatFMP4Sample) error { + // wait the first video sample before setting hasVideo + if t.initTrack.Codec.IsVideo() { + t.f.hasVideo = true + } + + sample, t.nextSample = t.nextSample, sample + if sample == nil { + return nil + } + + duration := t.nextSample.dts - sample.dts + if duration < 0 { + t.nextSample.dts = sample.dts + duration = 0 + } + + sample.Duration = uint32(duration) + + dts := timestampToDuration(sample.dts, int(t.initTrack.TimeScale)) + + if !t.startInitialized { + t.startDTS = dts + t.startNTP = sample.ntp + t.startInitialized = true + } else { + drift := sample.ntp.Sub(t.startNTP) - (dts - t.startDTS) + if drift < -ntpDriftTolerance || drift > ntpDriftTolerance { + return fmt.Errorf("detected drift between recording duration and absolute time, resetting") + } + } + + if t.f.currentSegment == nil { + t.f.currentSegment = &formatFMP4Segment{ + f: t.f, + startDTS: dts, + startNTP: sample.ntp, + number: t.f.nextSegmentNumber, + } + t.f.currentSegment.initialize() + t.f.nextSegmentNumber++ + } else if (dts - t.f.currentSegment.startDTS) < 0 { // BaseTime is negative, this is not supported by fMP4 + t.f.ri.Log(logger.Warn, "sample of track %d received too late, discarding", t.initTrack.ID) + return nil + } + + err := t.f.currentSegment.write(t, sample, dts) + if err != nil { + return err + } + + nextDTS := timestampToDuration(t.nextSample.dts, int(t.initTrack.TimeScale)) + + if (!t.f.hasVideo || t.initTrack.Codec.IsVideo()) && + !t.nextSample.IsNonSyncSample && + (nextDTS-t.f.currentSegment.startDTS) >= t.f.ri.segmentDuration { + err = t.f.currentSegment.close() + if err != nil { + return err + } + + oldestNTP, oldestDTS := nextSegmentStartingPos(t.f.tracks) + + t.f.currentSegment = &formatFMP4Segment{ + f: t.f, + startDTS: oldestDTS, + startNTP: oldestNTP, + number: t.f.nextSegmentNumber, + } + t.f.currentSegment.initialize() + t.f.nextSegmentNumber++ + } + + return nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_mpegts.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_mpegts.go new file mode 100644 index 0000000000000000000000000000000000000000..5bd4eb76b1782ca9a92fcdfbcc6d02825af8bc7d --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_mpegts.go @@ -0,0 +1,453 @@ +package recorder + +import ( + "bufio" + "bytes" + "fmt" + "io" + "slices" + "time" + + rtspformat "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/ac3" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/h264" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/h265" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4video" + "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts" + tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs" + + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/formatlabel" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/unit" +) + +const ( + mpegtsBufferSize = 64 * 1024 +) + +func multiplyAndDivide(v, m, d int64) int64 { + secs := v / d + dec := v % d + return (secs*m + dec*m/d) +} + +func multiplyAndDivide2(v, m, d time.Duration) time.Duration { + secs := v / d + dec := v % d + return (secs*m + dec*m/d) +} + +func timestampToDuration(t int64, clockRate int) time.Duration { + return multiplyAndDivide2(time.Duration(t), time.Second, time.Duration(clockRate)) +} + +type dynamicWriter struct { + w io.Writer +} + +func (d *dynamicWriter) Write(p []byte) (int, error) { + return d.w.Write(p) +} + +func (d *dynamicWriter) setTarget(w io.Writer) { + d.w = w +} + +type formatMPEGTS struct { + ri *recorderInstance + + dw *dynamicWriter + bw *bufio.Writer + mw *mpegts.Writer + hasVideo bool + currentSegment *formatMPEGTSSegment +} + +func (f *formatMPEGTS) initialize() bool { + var tracks []*mpegts.Track + + addTrack := func(codec tscodecs.Codec) *formatMPEGTSTrack { + track := &formatMPEGTSTrack{ + f: f, + codec: codec, + } + track.initialize() + + tracks = append(tracks, track.track) + return track + } + + for _, media := range f.ri.stream.OrigDesc.Medias { + for _, forma := range media.Formats { + clockRate := forma.ClockRate() + + switch forma := forma.(type) { + case *rtspformat.H265: //nolint:dupl + track := addTrack(&tscodecs.H265{}) + + var dtsExtractor *h265.DTSExtractor + + f.ri.reader.OnData( + media, + forma, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + randomAccess := h265.IsRandomAccess(u.Payload.(unit.PayloadH265)) + + if dtsExtractor == nil { + if !randomAccess { + return nil + } + dtsExtractor = &h265.DTSExtractor{} + dtsExtractor.Initialize() + } + + dts, err := dtsExtractor.Extract(u.Payload.(unit.PayloadH265), u.PTS) + if err != nil { + return err + } + + return track.write( + timestampToDuration(dts, clockRate), + u.NTP, + randomAccess, + func(mtrack *mpegts.Track) error { + return f.mw.WriteH265( + mtrack, + u.PTS, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + dts, + u.Payload.(unit.PayloadH265)) + }, + ) + }) + + case *rtspformat.H264: //nolint:dupl + track := addTrack(&tscodecs.H264{}) + + var dtsExtractor *h264.DTSExtractor + + f.ri.reader.OnData( + media, + forma, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + randomAccess := h264.IsRandomAccess(u.Payload.(unit.PayloadH264)) + + if dtsExtractor == nil { + if !randomAccess { + return nil + } + dtsExtractor = &h264.DTSExtractor{} + dtsExtractor.Initialize() + } + + dts, err := dtsExtractor.Extract(u.Payload.(unit.PayloadH264), u.PTS) + if err != nil { + return err + } + + return track.write( + timestampToDuration(dts, clockRate), + u.NTP, + randomAccess, + func(mtrack *mpegts.Track) error { + return f.mw.WriteH264( + mtrack, + u.PTS, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + dts, + u.Payload.(unit.PayloadH264)) + }, + ) + }) + + case *rtspformat.MPEG4Video: + track := addTrack(&tscodecs.MPEG4Video{}) + + firstReceived := false + var lastPTS int64 + + f.ri.reader.OnData( + media, + forma, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + if !firstReceived { + firstReceived = true + } else if u.PTS < lastPTS { + return fmt.Errorf("MPEG-4 Video streams with B-frames are not supported (yet)") + } + lastPTS = u.PTS + + randomAccess := bytes.Contains(u.Payload.(unit.PayloadMPEG4Video), + []byte{0, 0, 1, byte(mpeg4video.GroupOfVOPStartCode)}) + + return track.write( + timestampToDuration(u.PTS, clockRate), + u.NTP, + randomAccess, + func(mtrack *mpegts.Track) error { + return f.mw.WriteMPEG4Video( + mtrack, + u.PTS, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + u.Payload.(unit.PayloadMPEG4Video)) + }, + ) + }) + + case *rtspformat.MPEG1Video: + track := addTrack(&tscodecs.MPEG1Video{}) + + firstReceived := false + var lastPTS int64 + + f.ri.reader.OnData( + media, + forma, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + if !firstReceived { + firstReceived = true + } else if u.PTS < lastPTS { + return fmt.Errorf("MPEG-1/2 Video streams with B-frames are not supported (yet)") + } + lastPTS = u.PTS + + randomAccess := bytes.Contains(u.Payload.(unit.PayloadMPEG1Video), []byte{0, 0, 1, 0xB8}) + + return track.write( + timestampToDuration(u.PTS, clockRate), + u.NTP, + randomAccess, + func(mtrack *mpegts.Track) error { + return f.mw.WriteMPEG1Video( + mtrack, + u.PTS, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + u.Payload.(unit.PayloadMPEG1Video)) + }, + ) + }) + + case *rtspformat.Opus: + track := addTrack(&tscodecs.Opus{ + ChannelCount: forma.ChannelCount, + }) + + f.ri.reader.OnData( + media, + forma, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + return track.write( + timestampToDuration(u.PTS, clockRate), + u.NTP, + true, + func(mtrack *mpegts.Track) error { + return f.mw.WriteOpus( + mtrack, + multiplyAndDivide(u.PTS, 90000, int64(clockRate)), + u.Payload.(unit.PayloadOpus)) + }, + ) + }) + + case *rtspformat.KLV: + track := addTrack(&tscodecs.KLV{ + Synchronous: true, + }) + + f.ri.reader.OnData( + media, + forma, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + return track.write( + timestampToDuration(u.PTS, 90000), + u.NTP, + true, + func(mtrack *mpegts.Track) error { + return f.mw.WriteKLV( + mtrack, + multiplyAndDivide(u.PTS, 90000, 90000), + u.Payload.(unit.PayloadKLV)) + }, + ) + }) + + case *rtspformat.MPEG4Audio: + track := addTrack(&tscodecs.MPEG4Audio{ + Config: *forma.Config, + }) + + f.ri.reader.OnData( + media, + forma, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + return track.write( + timestampToDuration(u.PTS, clockRate), + u.NTP, + true, + func(mtrack *mpegts.Track) error { + return f.mw.WriteMPEG4Audio( + mtrack, + multiplyAndDivide(u.PTS, 90000, int64(clockRate)), + u.Payload.(unit.PayloadMPEG4Audio)) + }, + ) + }) + + case *rtspformat.MPEG4AudioLATM: + if !forma.CPresent { + track := addTrack(&tscodecs.MPEG4Audio{ + Config: *forma.StreamMuxConfig.Programs[0].Layers[0].AudioSpecificConfig, + }) + + f.ri.reader.OnData( + media, + forma, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + var ame mpeg4audio.AudioMuxElement + ame.StreamMuxConfig = forma.StreamMuxConfig + err := ame.Unmarshal(u.Payload.(unit.PayloadMPEG4AudioLATM)) + if err != nil { + return err + } + + return track.write( + timestampToDuration(u.PTS, clockRate), + u.NTP, + true, + func(mtrack *mpegts.Track) error { + return f.mw.WriteMPEG4Audio( + mtrack, + multiplyAndDivide(u.PTS, 90000, int64(clockRate)), + [][]byte{ame.Payloads[0][0][0]}) + }, + ) + }) + } + + case *rtspformat.MPEG1Audio: + track := addTrack(&tscodecs.MPEG1Audio{}) + + f.ri.reader.OnData( + media, + forma, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + return track.write( + timestampToDuration(u.PTS, clockRate), + u.NTP, + true, + func(mtrack *mpegts.Track) error { + return f.mw.WriteMPEG1Audio( + mtrack, + u.PTS, // no conversion is needed since clock rate is 90khz in both MPEG-TS and RTSP + u.Payload.(unit.PayloadMPEG1Audio)) + }, + ) + }) + + case *rtspformat.AC3: + track := addTrack(&tscodecs.AC3{}) + + f.ri.reader.OnData( + media, + forma, + func(u *unit.Unit) error { + if u.NilPayload() { + return nil + } + + return track.write( + timestampToDuration(u.PTS, clockRate), + u.NTP, + true, + func(mtrack *mpegts.Track) error { + for i, frame := range u.Payload.(unit.PayloadAC3) { + framePTS := u.PTS + int64(i)*ac3.SamplesPerFrame + + err := f.mw.WriteAC3( + mtrack, + multiplyAndDivide(framePTS, 90000, int64(clockRate)), + frame) + if err != nil { + return err + } + } + + return nil + }, + ) + }) + } + } + } + + if len(tracks) == 0 { + f.ri.Log(logger.Warn, "no supported tracks found, skipping recording") + return false + } + + setuppedFormats := f.ri.reader.Formats() + + n := 1 + for _, medi := range f.ri.stream.OrigDesc.Medias { + for _, forma := range medi.Formats { + if !slices.Contains(setuppedFormats, forma) { + f.ri.Log(logger.Warn, "skipping track %d (%s)", n, formatlabel.FormatToLabel(forma)) + } + n++ + } + } + + f.dw = &dynamicWriter{} + f.bw = bufio.NewWriterSize(f.dw, mpegtsBufferSize) + + f.mw = &mpegts.Writer{W: f.bw, Tracks: tracks} + err := f.mw.Initialize() + if err != nil { + panic(err) + } + + f.ri.Log(logger.Info, "recording %s", + defs.FormatsInfo(setuppedFormats)) + + return true +} + +func (f *formatMPEGTS) close() { + if f.currentSegment != nil { + f.currentSegment.close() //nolint:errcheck + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_mpegts_segment.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_mpegts_segment.go new file mode 100644 index 0000000000000000000000000000000000000000..09d624275d214618cb0fbf47633822a90d462373 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_mpegts_segment.go @@ -0,0 +1,72 @@ +package recorder + +import ( + "os" + "path/filepath" + "time" + + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/recordstore" +) + +type formatMPEGTSSegment struct { + pathFormat2 string + flush func() error + onSegmentCreate OnSegmentCreateFunc + onSegmentComplete OnSegmentCompleteFunc + startDTS time.Duration + startNTP time.Time + log logger.Writer + + path string + fi *os.File + lastFlush time.Duration + lastDTS time.Duration +} + +func (s *formatMPEGTSSegment) initialize() { + s.lastFlush = s.startDTS + s.lastDTS = s.startDTS +} + +func (s *formatMPEGTSSegment) close() error { + err := s.flush() + + if s.fi != nil { + s.log.Log(logger.Debug, "closing segment %s", s.path) + err2 := s.fi.Close() + if err == nil { + err = err2 + } + + if err2 == nil { + duration := s.lastDTS - s.startDTS + s.onSegmentComplete(s.path, duration) + } + } + + return err +} + +func (s *formatMPEGTSSegment) Write(p []byte) (int, error) { + if s.fi == nil { + s.path = recordstore.Path{Start: s.startNTP}.Encode(s.pathFormat2) + s.log.Log(logger.Debug, "creating segment %s", s.path) + + err := os.MkdirAll(filepath.Dir(s.path), 0o755) + if err != nil { + return 0, err + } + + fi, err := os.Create(s.path) + if err != nil { + return 0, err + } + + s.onSegmentCreate(s.path) + + s.fi = fi + } + + return s.fi.Write(p) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_mpegts_track.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_mpegts_track.go new file mode 100644 index 0000000000000000000000000000000000000000..3b6b9cde3c9e4fc09e571aaa72252329f51c4c43 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/format_mpegts_track.go @@ -0,0 +1,97 @@ +package recorder + +import ( + "fmt" + "time" + + "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts" + tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs" +) + +type formatMPEGTSTrack struct { + f *formatMPEGTS + codec tscodecs.Codec + + track *mpegts.Track + startInitialized bool + startDTS time.Duration + startNTP time.Time +} + +func (t *formatMPEGTSTrack) initialize() { + t.track = &mpegts.Track{ + Codec: t.codec, + } +} + +func (t *formatMPEGTSTrack) write( + dts time.Duration, + ntp time.Time, + randomAccess bool, + cb func(track *mpegts.Track) error, +) error { + isVideo := t.track.Codec.IsVideo() + + if isVideo { + t.f.hasVideo = true + } + + if !t.startInitialized { + t.startDTS = dts + t.startNTP = ntp + t.startInitialized = true + } else { + drift := ntp.Sub(t.startNTP) - (dts - t.startDTS) + if drift < -ntpDriftTolerance || drift > ntpDriftTolerance { + return fmt.Errorf("detected drift between recording duration and absolute time, resetting") + } + } + + switch { + case t.f.currentSegment == nil: + t.f.currentSegment = &formatMPEGTSSegment{ + pathFormat2: t.f.ri.pathFormat2, + flush: t.f.bw.Flush, + onSegmentCreate: t.f.ri.onSegmentCreate, + onSegmentComplete: t.f.ri.onSegmentComplete, + startDTS: dts, + startNTP: ntp, + log: t.f.ri, + } + t.f.currentSegment.initialize() + t.f.dw.setTarget(t.f.currentSegment) + + case (!t.f.hasVideo || isVideo) && + randomAccess && + (dts-t.f.currentSegment.startDTS) >= t.f.ri.segmentDuration: + t.f.currentSegment.lastDTS = dts + err := t.f.currentSegment.close() + if err != nil { + return err + } + + t.f.currentSegment = &formatMPEGTSSegment{ + pathFormat2: t.f.ri.pathFormat2, + flush: t.f.bw.Flush, + onSegmentCreate: t.f.ri.onSegmentCreate, + onSegmentComplete: t.f.ri.onSegmentComplete, + startDTS: dts, + startNTP: ntp, + log: t.f.ri, + } + t.f.currentSegment.initialize() + t.f.dw.setTarget(t.f.currentSegment) + + case (dts - t.f.currentSegment.lastFlush) >= t.f.ri.partDuration: + err := t.f.bw.Flush() + if err != nil { + return err + } + + t.f.currentSegment.lastFlush = dts + } + + t.f.currentSegment.lastDTS = dts + + return cb(t.track) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/recorder.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/recorder.go new file mode 100644 index 0000000000000000000000000000000000000000..a9bce9132329e6205ec3e4627708a12c9e0d9832 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/recorder.go @@ -0,0 +1,121 @@ +// Package recorder contains the recorder. +package recorder + +import ( + "time" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" +) + +const ( + ntpDriftTolerance = 5 * time.Second +) + +// OnSegmentCreateFunc is the prototype of the function passed as OnSegmentCreate +type OnSegmentCreateFunc = func(path string) + +// OnSegmentCompleteFunc is the prototype of the function passed as OnSegmentComplete +type OnSegmentCompleteFunc = func(path string, duration time.Duration) + +// Recorder writes recordings to disk. +type Recorder struct { + PathFormat string + Format conf.RecordFormat + PartDuration time.Duration + MaxPartSize conf.StringSize + SegmentDuration time.Duration + PathName string + Stream *stream.Stream + OnSegmentCreate OnSegmentCreateFunc + OnSegmentComplete OnSegmentCompleteFunc + Parent logger.Writer + + restartPause time.Duration + + currentInstance *recorderInstance + + terminate chan struct{} + done chan struct{} +} + +// Initialize initializes Recorder. +func (r *Recorder) Initialize() { + if r.OnSegmentCreate == nil { + r.OnSegmentCreate = func(string) { + } + } + if r.OnSegmentComplete == nil { + r.OnSegmentComplete = func(string, time.Duration) { + } + } + if r.restartPause == 0 { + r.restartPause = 2 * time.Second + } + + r.terminate = make(chan struct{}) + r.done = make(chan struct{}) + + r.currentInstance = &recorderInstance{ + pathFormat: r.PathFormat, + format: r.Format, + partDuration: r.PartDuration, + maxPartSize: r.MaxPartSize, + segmentDuration: r.SegmentDuration, + pathName: r.PathName, + stream: r.Stream, + onSegmentCreate: r.OnSegmentCreate, + onSegmentComplete: r.OnSegmentComplete, + parent: r, + } + r.currentInstance.initialize() + + go r.run() +} + +// Log implements logger.Writer. +func (r *Recorder) Log(level logger.Level, format string, args ...any) { + r.Parent.Log(level, "[recorder] "+format, args...) +} + +// Close closes the agent. +func (r *Recorder) Close() { + r.Log(logger.Info, "recording stopped") + close(r.terminate) + <-r.done +} + +func (r *Recorder) run() { + defer close(r.done) + + for { + select { + case <-r.currentInstance.done: + r.currentInstance.close() + case <-r.terminate: + r.currentInstance.close() + return + } + + select { + case <-time.After(r.restartPause): + case <-r.terminate: + return + } + + r.currentInstance = &recorderInstance{ + pathFormat: r.PathFormat, + format: r.Format, + partDuration: r.PartDuration, + maxPartSize: r.MaxPartSize, + segmentDuration: r.SegmentDuration, + pathName: r.PathName, + stream: r.Stream, + onSegmentCreate: r.OnSegmentCreate, + onSegmentComplete: r.OnSegmentComplete, + parent: r, + } + r.currentInstance.initialize() + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/recorder_instance.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/recorder_instance.go new file mode 100644 index 0000000000000000000000000000000000000000..044cf88c66cdd2a271810850dc4050af6fe3016b --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/recorder_instance.go @@ -0,0 +1,102 @@ +package recorder + +import ( + "strings" + "time" + + "github.com/google/uuid" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/recordstore" + "github.com/bluenviron/mediamtx/internal/stream" +) + +type recorderInstance struct { + pathFormat string + format conf.RecordFormat + partDuration time.Duration + maxPartSize conf.StringSize + segmentDuration time.Duration + pathName string + stream *stream.Stream + onSegmentCreate OnSegmentCreateFunc + onSegmentComplete OnSegmentCompleteFunc + parent logger.Writer + + streamID uuid.UUID + pathFormat2 string + format2 format + skip bool + reader *stream.Reader + + terminate chan struct{} + done chan struct{} +} + +// Log implements logger.Writer. +func (ri *recorderInstance) Log(level logger.Level, format string, args ...any) { + ri.parent.Log(level, format, args...) +} + +func (ri *recorderInstance) initialize() { + ri.streamID = uuid.New() + ri.pathFormat2 = ri.pathFormat + ri.pathFormat2 = recordstore.PathAddExtension( + strings.ReplaceAll(ri.pathFormat2, "%path", ri.pathName), + ri.format, + ) + ri.reader = &stream.Reader{ + SkipOutboundBytes: true, + Parent: ri, + } + + ri.terminate = make(chan struct{}) + ri.done = make(chan struct{}) + + switch ri.format { + case conf.RecordFormatMPEGTS: + ri.format2 = &formatMPEGTS{ + ri: ri, + } + ok := ri.format2.initialize() + ri.skip = !ok + + default: + ri.format2 = &formatFMP4{ + ri: ri, + } + ok := ri.format2.initialize() + ri.skip = !ok + } + + if !ri.skip { + ri.stream.AddReader(ri.reader) + } + + go ri.run() +} + +func (ri *recorderInstance) close() { + close(ri.terminate) + <-ri.done +} + +func (ri *recorderInstance) run() { + defer close(ri.done) + + if !ri.skip { + select { + case err := <-ri.reader.Error(): + ri.Log(logger.Error, err.Error()) + + case <-ri.terminate: + } + + ri.stream.RemoveReader(ri.reader) + } else { + <-ri.terminate + } + + ri.format2.close() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/recorder_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/recorder_test.go new file mode 100644 index 0000000000000000000000000000000000000000..742ce83655618911c81363a5b04309adb1bc9643 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recorder/recorder_test.go @@ -0,0 +1,1073 @@ +package recorder + +import ( + "fmt" + "os" + "path/filepath" + "testing" + "time" + + amp4 "github.com/abema/go-mp4" + "github.com/bluenviron/gortsplib/v5/pkg/description" + rtspformat "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" + mcodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mp4/codecs" + "github.com/stretchr/testify/require" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/recordstore" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/bluenviron/mediamtx/internal/unit" +) + +func TestRecorder(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []rtspformat.Format{&rtspformat.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + }}, + }, + { + Type: description.MediaTypeVideo, + Formats: []rtspformat.Format{&rtspformat.H265{ + PayloadTyp: 96, + }}, + }, + { + Type: description.MediaTypeAudio, + Formats: []rtspformat.Format{&rtspformat.MPEG4Audio{ + PayloadTyp: 96, + Config: &mpeg4audio.AudioSpecificConfig{ + Type: 2, + SampleRate: 44100, + ChannelCount: 2, + }, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + }}, + }, + { + Type: description.MediaTypeAudio, + Formats: []rtspformat.Format{&rtspformat.G711{ + PayloadTyp: 8, + MULaw: false, + SampleRate: 8000, + ChannelCount: 1, + }}, + }, + { + Type: description.MediaTypeAudio, + Formats: []rtspformat.Format{&rtspformat.LPCM{ + PayloadTyp: 96, + BitDepth: 16, + SampleRate: 44100, + ChannelCount: 2, + }}, + }, + }} + + writeToStream := func(subStream *stream.SubStream, startDTS int64, startNTP time.Time) { + for i := range 2 { + pts := startDTS + int64(i)*100*90000/1000 + ntp := startNTP.Add(time.Duration(i*100) * time.Millisecond) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: pts, + NTP: ntp, + Payload: unit.PayloadH264{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5}, // IDR + }, + }) + + subStream.WriteUnit(desc.Medias[1], desc.Medias[1].Formats[0], &unit.Unit{ + PTS: pts, + Payload: unit.PayloadH265{ + { + 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x01, 0x60, + 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, + 0x00, 0x00, 0x03, 0x00, 0x78, 0xba, 0x02, 0x40, + }, + { + 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, + 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, + 0x00, 0x78, 0xa0, 0x03, 0xc0, 0x80, 0x11, 0x07, + 0xcb, 0x96, 0xe9, 0x29, 0x30, 0xbc, 0x05, 0xa0, + 0x20, 0x00, 0x00, 0x03, 0x00, 0x20, 0x00, 0x00, + 0x03, 0x03, 0xc1, + }, + { + 0x44, 0x01, 0xc0, 0x73, 0xc1, 0x89, + }, + {0x26, 0x1, 0xaf, 0x8, 0x42, 0x23, 0x48, 0x8a, 0x43, 0xe2}, + }, + }) + + subStream.WriteUnit(desc.Medias[2], desc.Medias[2].Formats[0], &unit.Unit{ + PTS: pts * int64(desc.Medias[2].Formats[0].ClockRate()) / 90000, + Payload: unit.PayloadMPEG4Audio{{1, 2, 3, 4}}, + }) + + subStream.WriteUnit(desc.Medias[3], desc.Medias[3].Formats[0], &unit.Unit{ + PTS: pts * int64(desc.Medias[3].Formats[0].ClockRate()) / 90000, + Payload: unit.PayloadG711{1, 2, 3, 4}, + }) + + subStream.WriteUnit(desc.Medias[4], desc.Medias[4].Formats[0], &unit.Unit{ + PTS: pts * int64(desc.Medias[4].Formats[0].ClockRate()) / 90000, + Payload: unit.PayloadLPCM{1, 2, 3, 4}, + }) + } + } + + for _, ca := range []string{"fmp4", "mpegts"} { + t.Run(ca, func(t *testing.T) { + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + defer strm.Close() + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + dir := t.TempDir() + + recordPath := filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f") + + segCreated := make(chan struct{}, 4) + segDone := make(chan struct{}, 4) + + var f conf.RecordFormat + if ca == "fmp4" { + f = conf.RecordFormatFMP4 + } else { + f = conf.RecordFormatMPEGTS + } + + var ext string + if ca == "fmp4" { + ext = "mp4" + } else { + ext = "ts" + } + + n := 0 + + w := &Recorder{ + PathFormat: recordPath, + Format: f, + PartDuration: 100 * time.Millisecond, + MaxPartSize: 50 * 1024 * 1024, + SegmentDuration: 1 * time.Second, + PathName: "mypath", + Stream: strm, + OnSegmentCreate: func(segPath string) { + switch n { + case 0: + require.Equal(t, filepath.Join(dir, "mypath", "2008-05-20_22-15-25-000000."+ext), segPath) + case 1: + require.Equal(t, filepath.Join(dir, "mypath", "2008-05-20_22-15-27-000000."+ext), segPath) + default: + require.Equal(t, filepath.Join(dir, "mypath", "2010-05-20_22-15-25-000000."+ext), segPath) + } + segCreated <- struct{}{} + }, + OnSegmentComplete: func(segPath string, du time.Duration) { + switch n { + case 0: + require.Equal(t, filepath.Join(dir, "mypath", "2008-05-20_22-15-25-000000."+ext), segPath) + require.Equal(t, 2*time.Second, du) + case 1: + require.Equal(t, filepath.Join(dir, "mypath", "2008-05-20_22-15-27-000000."+ext), segPath) + require.Equal(t, 100*time.Millisecond, du) + default: + require.Equal(t, filepath.Join(dir, "mypath", "2010-05-20_22-15-25-000000."+ext), segPath) + require.Equal(t, 100*time.Millisecond, du) + } + n++ + segDone <- struct{}{} + }, + Parent: test.NilLogger, + restartPause: 1 * time.Millisecond, + } + w.Initialize() + + writeToStream(subStream, + 50*90000, + time.Date(2008, 5, 20, 22, 15, 25, 0, time.UTC)) + + writeToStream(subStream, + 52*90000, + time.Date(2008, 5, 20, 22, 15, 27, 0, time.UTC)) + + // simulate a write error + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: 0, + Payload: unit.PayloadH264{ + {5}, // IDR + }, + }) + + for range 2 { + <-segCreated + <-segDone + } + + if ca == "fmp4" { + var init fmp4.Init + + func() { + f, err2 := os.Open(filepath.Join(dir, "mypath", "2008-05-20_22-15-25-000000."+ext)) + require.NoError(t, err2) + defer f.Close() + + err2 = init.Unmarshal(f) + require.NoError(t, err2) + }() + + require.Equal(t, fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + { + ID: 2, + TimeScale: 90000, + Codec: &mcodecs.H265{ + VPS: []byte{ + 0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x01, 0x60, + 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, + 0x00, 0x00, 0x03, 0x00, 0x78, 0xba, 0x02, 0x40, + }, + SPS: []byte{ + 0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, + 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, + 0x00, 0x78, 0xa0, 0x03, 0xc0, 0x80, 0x11, 0x07, + 0xcb, 0x96, 0xe9, 0x29, 0x30, 0xbc, 0x05, 0xa0, + 0x20, 0x00, 0x00, 0x03, 0x00, 0x20, 0x00, 0x00, + 0x03, 0x03, 0xc1, + }, + PPS: []byte{ + 0x44, 0x01, 0xc0, 0x73, 0xc1, 0x89, + }, + }, + }, + { + ID: 3, + TimeScale: 44100, + Codec: &mcodecs.MPEG4Audio{ + Config: mpeg4audio.AudioSpecificConfig{ + Type: 2, + SampleRate: 44100, + ChannelCount: 2, + ChannelConfig: 2, + }, + }, + }, + { + ID: 4, + TimeScale: 8000, + Codec: &mcodecs.LPCM{ + BitDepth: 16, + SampleRate: 8000, + ChannelCount: 1, + }, + }, + { + ID: 5, + TimeScale: 44100, + Codec: &mcodecs.LPCM{ + BitDepth: 16, + SampleRate: 44100, + ChannelCount: 2, + }, + }, + }, + UserData: []amp4.IBox{ + &recordstore.Mtxi{ + StreamID: init.UserData[0].(*recordstore.Mtxi).StreamID, + DTS: 50000000000, + NTP: 1211321725000000000, + }, + }, + }, init) + + _, err = os.Stat(filepath.Join(dir, "mypath", "2008-05-20_22-15-27-000000."+ext)) + require.NoError(t, err) + } else { + _, err = os.Stat(filepath.Join(dir, "mypath", "2008-05-20_22-15-25-000000."+ext)) + require.NoError(t, err) + + _, err = os.Stat(filepath.Join(dir, "mypath", "2008-05-20_22-15-27-000000."+ext)) + require.NoError(t, err) + } + + time.Sleep(50 * time.Millisecond) + + writeToStream(subStream, + 300*90000, + time.Date(2010, 5, 20, 22, 15, 25, 0, time.UTC)) + + time.Sleep(50 * time.Millisecond) + + w.Close() + + <-segCreated + <-segDone + + _, err = os.Stat(filepath.Join(dir, "mypath", "2010-05-20_22-15-25-000000."+ext)) + require.NoError(t, err) + + if ca == "fmp4" { + var byts []byte + byts, err = os.ReadFile(filepath.Join(dir, "mypath", "2008-05-20_22-15-25-000000.mp4")) + require.NoError(t, err) + + var parts fmp4.Parts + err = parts.Unmarshal(byts) + require.NoError(t, err) + + for _, part := range parts { + for _, track := range part.Tracks { + track.Samples = nil + } + } + + require.Equal(t, fmp4.Parts{ + { + Tracks: []*fmp4.PartTrack{{ + ID: 1, + }}, + }, + { + SequenceNumber: 1, + Tracks: []*fmp4.PartTrack{{ + ID: 2, + }}, + }, + { + SequenceNumber: 2, + Tracks: []*fmp4.PartTrack{{ + ID: 3, + }}, + }, + { + SequenceNumber: 3, + Tracks: []*fmp4.PartTrack{{ + ID: 4, + }}, + }, + { + SequenceNumber: 4, + Tracks: []*fmp4.PartTrack{{ + ID: 5, + }}, + }, + { + SequenceNumber: 5, + Tracks: []*fmp4.PartTrack{{ + ID: 1, + BaseTime: 9000, + }}, + }, + }, parts) + } + }) + } +} + +func TestRecorderFMP4NegativeInitialDTS(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []rtspformat.Format{&rtspformat.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + }}, + }, + { + Type: description.MediaTypeAudio, + Formats: []rtspformat.Format{&rtspformat.MPEG4Audio{ + PayloadTyp: 96, + Config: &mpeg4audio.AudioSpecificConfig{ + Type: 2, + SampleRate: 44100, + ChannelCount: 2, + }, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + }}, + }, + }} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + defer strm.Close() + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + dir := t.TempDir() + + recordPath := filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f") + + w := &Recorder{ + PathFormat: recordPath, + Format: conf.RecordFormatFMP4, + PartDuration: 100 * time.Millisecond, + MaxPartSize: 50 * 1024 * 1024, + SegmentDuration: 1 * time.Second, + PathName: "mypath", + Stream: strm, + Parent: test.NilLogger, + } + w.Initialize() + + for i := range 3 { + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: -50*90000/1000 + (int64(i) * 200 * 90000 / 1000), + NTP: time.Date(2008, 5, 20, 22, 15, 25, 0, time.UTC), + Payload: unit.PayloadH264{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5}, // IDR + }, + }) + + subStream.WriteUnit(desc.Medias[1], desc.Medias[1].Formats[0], &unit.Unit{ + PTS: -100*44100/1000 + (int64(i) * 200 * 44100 / 1000), + Payload: unit.PayloadMPEG4Audio{{1, 2, 3, 4}}, + }) + } + + time.Sleep(50 * time.Millisecond) + + w.Close() + + byts, err := os.ReadFile(filepath.Join(dir, "mypath", "2008-05-20_22-15-25-000000.mp4")) + require.NoError(t, err) + + var parts fmp4.Parts + err = parts.Unmarshal(byts) + require.NoError(t, err) + + found := false + + for _, part := range parts { + for _, track := range part.Tracks { + if track.ID == 2 { + require.Equal(t, uint64(6615), track.BaseTime) + found = true + } + } + } + + require.True(t, found) +} + +func TestRecorderFMP4NegativeDTSDiff(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []rtspformat.Format{&rtspformat.MPEG4Audio{ + PayloadTyp: 96, + Config: &mpeg4audio.AudioSpecificConfig{ + Type: 2, + SampleRate: 44100, + ChannelCount: 2, + }, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + }}, + }, + }} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + defer strm.Close() + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + dir := t.TempDir() + + recordPath := filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f") + + w := &Recorder{ + PathFormat: recordPath, + Format: conf.RecordFormatFMP4, + PartDuration: 100 * time.Millisecond, + MaxPartSize: 50 * 1024 * 1024, + SegmentDuration: 2 * time.Second, + PathName: "mypath", + Stream: strm, + Parent: test.NilLogger, + } + w.Initialize() + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: 44100, + NTP: time.Date(2008, 5, 20, 22, 15, 25, 0, time.UTC), + Payload: unit.PayloadMPEG4Audio{{1, 2}}, + }) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: 3 * 44100, + NTP: time.Date(2008, 5, 20, 22, 15, 25, 0, time.UTC), + Payload: unit.PayloadMPEG4Audio{{1, 2}}, + }) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: 2 * 44100, + NTP: time.Date(2008, 5, 20, 22, 15, 25, 0, time.UTC), + Payload: unit.PayloadMPEG4Audio{{1, 2}}, + }) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: 4 * 44100, + NTP: time.Date(2008, 5, 20, 22, 15, 25, 0, time.UTC), + Payload: unit.PayloadMPEG4Audio{{1, 2}}, + }) + + time.Sleep(50 * time.Millisecond) + + w.Close() + + byts, err := os.ReadFile(filepath.Join(dir, "mypath", "2008-05-20_22-15-25-000000.mp4")) + require.NoError(t, err) + + var parts fmp4.Parts + err = parts.Unmarshal(byts) + require.NoError(t, err) + + require.Equal(t, fmp4.Parts{{ + Tracks: []*fmp4.PartTrack{{ + ID: 1, + Samples: []*fmp4.Sample{ + { + Payload: []byte{1, 2}, + }, + { + Duration: 44100, + Payload: []byte{1, 2}, + }, + }, + }}, + }}, parts) +} + +func TestRecorderSkipTracksPartial(t *testing.T) { + for _, ca := range []string{"fmp4", "mpegts"} { + t.Run(ca, func(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []rtspformat.Format{&rtspformat.H264{PacketizationMode: 1}}, + }, + { + Type: description.MediaTypeVideo, + Formats: []rtspformat.Format{&rtspformat.VP8{}}, + }, + }} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + defer strm.Close() + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + dir := t.TempDir() + + recordPath := filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f") + + n := 0 + + l := test.Logger(func(l logger.Level, format string, args ...any) { + if n == 0 { + require.Equal(t, logger.Warn, l) + require.Equal(t, "[recorder] skipping track 2 (VP8)", fmt.Sprintf(format, args...)) + } + n++ + }) + + var fo conf.RecordFormat + if ca == "fmp4" { + fo = conf.RecordFormatFMP4 + } else { + fo = conf.RecordFormatMPEGTS + } + + w := &Recorder{ + PathFormat: recordPath, + Format: fo, + PartDuration: 100 * time.Millisecond, + MaxPartSize: 50 * 1024 * 1024, + SegmentDuration: 1 * time.Second, + PathName: "mypath", + Stream: strm, + Parent: l, + } + w.Initialize() + defer w.Close() + + require.Equal(t, 2, n) + }) + } +} + +func TestRecorderSkipTracksFull(t *testing.T) { + for _, ca := range []string{"fmp4", "mpegts"} { + t.Run(ca, func(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []rtspformat.Format{&rtspformat.VP8{}}, + }, + }} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + defer strm.Close() + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + dir := t.TempDir() + + recordPath := filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f") + + n := 0 + + l := test.Logger(func(l logger.Level, format string, args ...any) { + if n == 0 { + require.Equal(t, logger.Warn, l) + require.Equal(t, "[recorder] no supported tracks found, skipping recording", fmt.Sprintf(format, args...)) + } + n++ + }) + + var fo conf.RecordFormat + if ca == "fmp4" { + fo = conf.RecordFormatFMP4 + } else { + fo = conf.RecordFormatMPEGTS + } + + w := &Recorder{ + PathFormat: recordPath, + Format: fo, + PartDuration: 100 * time.Millisecond, + MaxPartSize: 50 * 1024 * 1024, + SegmentDuration: 1 * time.Second, + PathName: "mypath", + Stream: strm, + Parent: l, + } + w.Initialize() + defer w.Close() + + require.Equal(t, 1, n) + }) + } +} + +func TestRecorderFMP4SegmentSwitch(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []rtspformat.Format{test.FormatH264}, + }, + { + Type: description.MediaTypeAudio, + Formats: []rtspformat.Format{test.FormatMPEG4Audio}, + }, + }} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + defer strm.Close() + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + dir := t.TempDir() + + n := 0 + + w := &Recorder{ + PathFormat: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + Format: conf.RecordFormatFMP4, + PartDuration: 100 * time.Millisecond, + MaxPartSize: 50 * 1024 * 1024, + SegmentDuration: 1 * time.Second, + PathName: "mypath", + Stream: strm, + Parent: test.NilLogger, + OnSegmentCreate: func(segPath string) { + switch n { + case 0: + require.Equal(t, filepath.Join(dir, "mypath", "2008-05-20_22-15-25-000000.mp4"), segPath) + case 1: + require.Equal(t, filepath.Join(dir, "mypath", "2008-05-20_22-15-25-700000.mp4"), segPath) // +0.7s + } + n++ + }, + } + w.Initialize() + + pts := 50 * time.Second + ntp := time.Date(2008, 5, 20, 22, 15, 25, 0, time.UTC) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: int64(pts) * 90000 / int64(time.Second), + NTP: ntp, + Payload: unit.PayloadH264{ + {5}, // IDR + }, + }) + + pts += 700 * time.Millisecond + ntp = ntp.Add(700 * time.Millisecond) + + subStream.WriteUnit(desc.Medias[1], desc.Medias[1].Formats[0], &unit.Unit{ // segment switch should happen here + PTS: int64(pts) * 44100 / int64(time.Second), + NTP: ntp, + Payload: unit.PayloadMPEG4Audio{{1, 2}}, + }) + + pts += 400 * time.Millisecond + ntp = ntp.Add(400 * time.Millisecond) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: int64(pts) * 90000 / int64(time.Second), + NTP: ntp, + Payload: unit.PayloadH264{ + {5}, // IDR + }, + }) + + pts += 100 * time.Millisecond + ntp = ntp.Add(100 * time.Millisecond) + + subStream.WriteUnit(desc.Medias[1], desc.Medias[1].Formats[0], &unit.Unit{ + PTS: int64(pts) * 44100 / int64(time.Second), + NTP: ntp, + Payload: unit.PayloadMPEG4Audio{{3, 4}}, + }) + + pts += 400 * time.Millisecond + ntp = ntp.Add(400 * time.Millisecond) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: int64(pts) * 90000 / int64(time.Second), + NTP: ntp, + Payload: unit.PayloadH264{ + {5}, // IDR + }, + }) + + time.Sleep(100 * time.Millisecond) + + w.Close() + + require.Equal(t, 2, n) +} + +func TestRecorderTimeDriftDetector(t *testing.T) { + for _, ca := range []string{"fmp4", "mpegts"} { + t.Run(ca, func(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + { + Type: description.MediaTypeVideo, + Formats: []rtspformat.Format{&rtspformat.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + }}, + }, + { + Type: description.MediaTypeAudio, + Formats: []rtspformat.Format{&rtspformat.MPEG4Audio{ + PayloadTyp: 96, + Config: &mpeg4audio.AudioSpecificConfig{ + Type: 2, + SampleRate: 44100, + ChannelCount: 2, + }, + SizeLength: 13, + IndexLength: 3, + IndexDeltaLength: 3, + }}, + }, + }} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + defer strm.Close() + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + dir := t.TempDir() + + recordPath := filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f") + + var ext string + if ca == "fmp4" { + ext = "mp4" + } else { + ext = "ts" + } + + segCreated := make(chan struct{}, 10) + segDone := make(chan struct{}, 10) + + var f conf.RecordFormat + if ca == "fmp4" { + f = conf.RecordFormatFMP4 + } else { + f = conf.RecordFormatMPEGTS + } + + w := &Recorder{ + PathFormat: recordPath, + Format: f, + PartDuration: 100 * time.Millisecond, + MaxPartSize: 50 * 1024 * 1024, + SegmentDuration: 1 * time.Second, + PathName: "mypath", + Stream: strm, + OnSegmentCreate: func(_ string) { + select { + case segCreated <- struct{}{}: + default: + } + }, + OnSegmentComplete: func(_ string, _ time.Duration) { + select { + case segDone <- struct{}{}: + default: + } + }, + Parent: test.NilLogger, + restartPause: 10 * time.Millisecond, + } + w.Initialize() + + // Write initial samples with correct timing + startDTS := int64(50 * 90000) + startNTP := time.Date(2008, 5, 20, 22, 15, 25, 0, time.UTC) + + for i := range 3 { + pts := startDTS + int64(i)*100*90000/1000 + ntp := startNTP.Add(time.Duration(i*100) * time.Millisecond) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: pts, + NTP: ntp, + Payload: unit.PayloadH264{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5}, // IDR + }, + }) + + subStream.WriteUnit(desc.Medias[1], desc.Medias[1].Formats[0], &unit.Unit{ + PTS: pts * int64(desc.Medias[1].Formats[0].ClockRate()) / 90000, + NTP: ntp, + Payload: unit.PayloadMPEG4Audio{{1, 2, 3, 4}}, + }) + } + + // Wait for first segment to be created + select { + case <-segCreated: + case <-time.After(2 * time.Second): + t.Fatal("timeout waiting for first segment") + } + + // Write more samples to ensure segment has data + for i := 3; i < 15; i++ { + pts := startDTS + int64(i)*100*90000/1000 + ntp := startNTP.Add(time.Duration(i*100) * time.Millisecond) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: pts, + NTP: ntp, + Payload: unit.PayloadH264{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5}, // IDR + }, + }) + + subStream.WriteUnit(desc.Medias[1], desc.Medias[1].Formats[0], &unit.Unit{ + PTS: pts * int64(desc.Medias[1].Formats[0].ClockRate()) / 90000, + NTP: ntp, + Payload: unit.PayloadMPEG4Audio{{1, 2, 3, 4}}, + }) + } + + // Simulate a time drift by advancing NTP time by more than 5 seconds + // while keeping DTS progression normal (only 100ms forward) + driftedPTS := startDTS + 15*100*90000/1000 + driftedNTP := startNTP.Add(15*100*time.Millisecond + 6*time.Second) // 6 second drift + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: driftedPTS, + NTP: driftedNTP, + Payload: unit.PayloadH264{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5}, // IDR + }, + }) + + // Wait for the recorder to detect the drift, complete the segment, and restart + select { + case <-segDone: + case <-time.After(2 * time.Second): + t.Fatal("timeout waiting for segment completion after drift") + } + + // Give the recorder time to restart + time.Sleep(100 * time.Millisecond) + + // Write samples after restart with corrected timing + restartDTS := int64(60 * 90000) + restartNTP := time.Date(2008, 5, 20, 22, 15, 35, 0, time.UTC) + + for i := range 3 { + pts := restartDTS + int64(i)*100*90000/1000 + ntp := restartNTP.Add(time.Duration(i*100) * time.Millisecond) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: pts, + NTP: ntp, + Payload: unit.PayloadH264{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5}, // IDR + }, + }) + + subStream.WriteUnit(desc.Medias[1], desc.Medias[1].Formats[0], &unit.Unit{ + PTS: pts * int64(desc.Medias[1].Formats[0].ClockRate()) / 90000, + NTP: ntp, + Payload: unit.PayloadMPEG4Audio{{1, 2, 3, 4}}, + }) + } + + // Wait for second segment to be created after restart + select { + case <-segCreated: + case <-time.After(2 * time.Second): + t.Fatal("timeout waiting for segment after restart") + } + + time.Sleep(50 * time.Millisecond) + + w.Close() + + // Wait for final segment to complete + select { + case <-segDone: + case <-time.After(2 * time.Second): + // This is not fatal as the final segment may complete during Close() + } + + // Verify that files were created + entries, err := os.ReadDir(filepath.Join(dir, "mypath")) + require.NoError(t, err) + require.GreaterOrEqual(t, len(entries), 2, "expected at least 2 segments (before and after drift)") + + // Verify files have the expected extension + for _, entry := range entries { + require.Equal(t, "."+ext, filepath.Ext(entry.Name())) + } + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/mp4_boxes.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/mp4_boxes.go new file mode 100644 index 0000000000000000000000000000000000000000..1c1a86b5e4a18efb7baaf2553426070127576119 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/mp4_boxes.go @@ -0,0 +1,25 @@ +package recordstore + +import ( + amp4 "github.com/abema/go-mp4" +) + +func boxTypeMtxi() amp4.BoxType { return amp4.StrToBoxType("mtxi") } + +func init() { //nolint:gochecknoinits + amp4.AddBoxDef(&Mtxi{}, 0) +} + +// Mtxi is a MediaMTX segment info. +type Mtxi struct { + amp4.FullBox `mp4:"0,extend"` + StreamID [16]byte `mp4:"1,size=8"` + SegmentNumber uint64 `mp4:"2,size=64"` + DTS int64 `mp4:"3,size=64"` + NTP int64 `mp4:"4,size=64"` +} + +// GetType implements amp4.IBox. +func (*Mtxi) GetType() amp4.BoxType { + return boxTypeMtxi() +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/path.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/path.go new file mode 100644 index 0000000000000000000000000000000000000000..9d3c1d823777c890452ca074a27878e1602eda49 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/path.go @@ -0,0 +1,262 @@ +package recordstore + +import ( + "regexp" + "strconv" + "strings" + "time" + + "github.com/bluenviron/mediamtx/internal/conf" +) + +func leadingZeros(v int, size int) string { + out := strconv.FormatInt(int64(v), 10) + if len(out) >= size { + return out + } + + out2 := "" + for i := 0; i < (size - len(out)); i++ { + out2 += "0" + } + + return out2 + out +} + +func timeLocationEncode(t time.Time) string { + _, off := t.Zone() + + if off == 0 { + return "Z" + } + + var ret string + + if off > 0 { + ret = "+" + } else { + ret = "-" + off = -off + } + + ret += leadingZeros(off/60/60, 2) + ret += leadingZeros((off/60)%60, 2) + + return ret +} + +func timeLocationDecode(s string) *time.Location { + if s == "Z" { + return time.UTC + } + + var sign int + if s[0] == '+' { + sign = 1 + } else { + sign = -1 + } + + v1, _ := strconv.ParseInt(s[1:3], 10, 64) + v2, _ := strconv.ParseInt(s[3:5], 10, 64) + + off := sign*int(v1)*3600 + int(v2)*3600 + + return time.FixedZone("myzone", off) +} + +// PathAddExtension adds the file extension to the path. +func PathAddExtension(path string, format conf.RecordFormat) string { + switch format { + case conf.RecordFormatMPEGTS: + return path + ".ts" + + default: + return path + ".mp4" + } +} + +// CommonPath returns the common path between all segments with given recording path. +func CommonPath(v string) string { + common := "" + remaining := v + + for { + i := strings.IndexAny(remaining, "\\/") + if i < 0 { + break + } + + var part string + part, remaining = remaining[:i+1], remaining[i+1:] + + if strings.Contains(part, "%") { + break + } + + common += part + } + + if len(common) > 0 { + common = common[:len(common)-1] + } + + return common +} + +// Path is a path of a recording segment. +type Path struct { + Start time.Time + Path string +} + +// Decode decodes a Path. +func (p *Path) Decode(format string, v string) bool { + re := format + + for _, ch := range []uint8{ + '\\', + '.', + '+', + '*', + '?', + '^', + '$', + '(', + ')', + '[', + ']', + '{', + '}', + '|', + } { + re = strings.ReplaceAll(re, string(ch), "\\"+string(ch)) + } + + re = strings.ReplaceAll(re, "%path", "(.*?)") + re = strings.ReplaceAll(re, "%Y", "([0-9]{4})") + re = strings.ReplaceAll(re, "%m", "([0-9]{2})") + re = strings.ReplaceAll(re, "%d", "([0-9]{2})") + re = strings.ReplaceAll(re, "%H", "([0-9]{2})") + re = strings.ReplaceAll(re, "%M", "([0-9]{2})") + re = strings.ReplaceAll(re, "%S", "([0-9]{2})") + re = strings.ReplaceAll(re, "%f", "([0-9]{6})") + re = strings.ReplaceAll(re, "%z", "(Z|\\+[0-9]{4}|-[0-9]{4})") + re = strings.ReplaceAll(re, "%s", "([0-9]{10})") + r := regexp.MustCompile(re) + + var groupMapping []string + cur := format + for { + i := strings.Index(cur, "%") + if i < 0 { + break + } + + cur = cur[i:] + + for _, va := range []string{ + "%path", + "%Y", + "%m", + "%d", + "%H", + "%M", + "%S", + "%f", + "%z", + "%s", + } { + if strings.HasPrefix(cur, va) { + groupMapping = append(groupMapping, va) + } + } + + cur = cur[1:] + } + + matches := r.FindStringSubmatch(v) + if matches == nil { + return false + } + + values := make(map[string]string) + + for i, match := range matches[1:] { + values[groupMapping[i]] = match + } + + var year int + var month time.Month = 1 + day := 1 + var hour int + var minute int + var second int + var micros int + var unixSec int64 = -1 + loc := time.Local + + for k, v := range values { + switch k { + case "%path": + p.Path = v + + case "%Y": + tmp, _ := strconv.ParseInt(v, 10, 64) + year = int(tmp) + + case "%m": + tmp, _ := strconv.ParseInt(v, 10, 64) + month = time.Month(int(tmp)) + + case "%d": + tmp, _ := strconv.ParseInt(v, 10, 64) + day = int(tmp) + + case "%H": + tmp, _ := strconv.ParseInt(v, 10, 64) + hour = int(tmp) + + case "%M": + tmp, _ := strconv.ParseInt(v, 10, 64) + minute = int(tmp) + + case "%S": + tmp, _ := strconv.ParseInt(v, 10, 64) + second = int(tmp) + + case "%f": + tmp, _ := strconv.ParseInt(v, 10, 64) + micros = int(tmp) + + case "%z": + loc = timeLocationDecode(v) + + case "%s": + unixSec, _ = strconv.ParseInt(v, 10, 64) + } + } + + if unixSec > 0 { + p.Start = time.Unix(unixSec, int64(micros)*1000) + } else { + p.Start = time.Date(year, month, day, hour, minute, second, micros*1000, loc) + } + + return true +} + +// Encode encodes a path. +func (p Path) Encode(format string) string { + format = strings.ReplaceAll(format, "%path", p.Path) + format = strings.ReplaceAll(format, "%Y", strconv.FormatInt(int64(p.Start.Year()), 10)) + format = strings.ReplaceAll(format, "%m", leadingZeros(int(p.Start.Month()), 2)) + format = strings.ReplaceAll(format, "%d", leadingZeros(p.Start.Day(), 2)) + format = strings.ReplaceAll(format, "%H", leadingZeros(p.Start.Hour(), 2)) + format = strings.ReplaceAll(format, "%M", leadingZeros(p.Start.Minute(), 2)) + format = strings.ReplaceAll(format, "%S", leadingZeros(p.Start.Second(), 2)) + format = strings.ReplaceAll(format, "%f", leadingZeros(p.Start.Nanosecond()/1000, 6)) + format = strings.ReplaceAll(format, "%z", timeLocationEncode(p.Start)) + format = strings.ReplaceAll(format, "%s", strconv.FormatInt(p.Start.Unix(), 10)) + return format +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/path_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/path_test.go new file mode 100644 index 0000000000000000000000000000000000000000..897ff2997233ffd162bae81910d65e5f6ffbf916 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/path_test.go @@ -0,0 +1,89 @@ +package recordstore + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +var pathCases = []struct { + name string + format string + dec Path + enc string +}{ + { + "standard", + "%path/%Y-%m-%d_%H-%M-%S-%f.mp4", + Path{ + Start: time.Date(2008, 11, 7, 11, 22, 4, 123456000, time.Local), + Path: "mypath", + }, + "mypath/2008-11-07_11-22-04-123456.mp4", + }, + { + "unix seconds", + "%path/%s.mp4", + Path{ + Start: time.Date(2021, 12, 2, 12, 15, 23, 0, time.UTC).Local(), + Path: "mypath", + }, + "mypath/1638447323.mp4", + }, + { + "unix microseconds", + "%path/%s.%f.mp4", + Path{ + Start: time.Date(2021, 12, 2, 12, 15, 23, 567324000, time.UTC).Local(), + Path: "mypath", + }, + "mypath/1638447323.567324.mp4", + }, + { + "timezone utc", + "%path/%Y-%m-%d_%H-%M-%S-%f_%z.mp4", + Path{ + Start: time.Date(2021, 12, 2, 12, 15, 23, 567324000, time.UTC), + Path: "mypath", + }, + "mypath/2021-12-02_12-15-23-567324_Z.mp4", + }, + { + "timezone plus", + "%path/%Y-%m-%d_%H-%M-%S-%f_%z.mp4", + Path{ + Start: time.Date(2021, 12, 2, 12, 15, 23, 567324000, time.FixedZone("myzone", 7200)), + Path: "mypath", + }, + "mypath/2021-12-02_12-15-23-567324_+0200.mp4", + }, + { + "timezone minus", + "%path/%Y-%m-%d_%H-%M-%S-%f_%z.mp4", + Path{ + Start: time.Date(2021, 12, 2, 12, 15, 23, 567324000, time.FixedZone("myzone", -7200)), + Path: "mypath", + }, + "mypath/2021-12-02_12-15-23-567324_-0200.mp4", + }, +} + +func TestPathDecode(t *testing.T) { + for _, ca := range pathCases { + t.Run(ca.name, func(t *testing.T) { + var dec Path + ok := dec.Decode(ca.format, ca.enc) + require.Equal(t, true, ok) + require.Equal(t, ca.dec, dec) + }) + } +} + +func TestPathEncode(t *testing.T) { + for _, ca := range pathCases { + t.Run(ca.name, func(t *testing.T) { + require.Equal(t, ca.enc, ca.dec.Encode(ca.format)) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/recordstore.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/recordstore.go new file mode 100644 index 0000000000000000000000000000000000000000..da35b37aaad5cea50ab030cc32e42de7100895dc --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/recordstore.go @@ -0,0 +1,2 @@ +// Package recordstore contains utilities to store/retrieve recordings to/from disk. +package recordstore diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/segment.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/segment.go new file mode 100644 index 0000000000000000000000000000000000000000..bf153c0c9323328bfa58fcc684a74607684f3df3 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/segment.go @@ -0,0 +1,205 @@ +package recordstore + +import ( + "errors" + "fmt" + "io/fs" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/bluenviron/mediamtx/internal/conf" +) + +// ErrNoSegmentsFound is returned when no recording segments have been found. +var ErrNoSegmentsFound = errors.New("no recording segments found") + +var errFound = errors.New("found") + +// Segment is a recording segment. +type Segment struct { + Fpath string + Start time.Time +} + +func fixedPathHasSegments(pathConf *conf.Path) bool { + recordPath := 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 := CommonPath(recordPath) + + err := filepath.WalkDir(commonPath, func(fpath string, info fs.DirEntry, err error) error { + if err != nil { + return err + } + + if !info.IsDir() { + var pa 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 regexpPathFindPathsWithSegments(pathConf *conf.Path) map[string]struct{} { + recordPath := 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 := CommonPath(recordPath) + + ret := make(map[string]struct{}) + + filepath.WalkDir(commonPath, func(fpath string, info fs.DirEntry, err error) error { //nolint:errcheck + if err != nil { + return err + } + + if !info.IsDir() { + var pa Path + if ok := pa.Decode(recordPath, fpath); ok { + if err = conf.IsValidPathName(pa.Path); err == nil { + if pathConf.Regexp.FindStringSubmatch(pa.Path) != nil { + ret[pa.Path] = struct{}{} + } + } + } + } + + return nil + }) + + return ret +} + +// FindAllPathsWithSegments returns all paths that have at least one segment. +func FindAllPathsWithSegments(pathConfs map[string]*conf.Path) []string { + pathNames := make(map[string]struct{}) + + for _, pathConf := range pathConfs { + if pathConf.Regexp == nil { + if fixedPathHasSegments(pathConf) { + pathNames[pathConf.Name] = struct{}{} + } + } else { + for name := range regexpPathFindPathsWithSegments(pathConf) { + pathNames[name] = struct{}{} + } + } + } + + out := make([]string, len(pathNames)) + n := 0 + for k := range pathNames { + out[n] = k + n++ + } + sort.Strings(out) + + return out +} + +// FindSegments returns all segments of a path. +// Segments can be filtered by start date and end date. +func FindSegments( + pathConf *conf.Path, + pathName string, + start *time.Time, + end *time.Time, +) ([]*Segment, error) { + // double protection against directory traversal attacks + if err := conf.IsValidPathName(pathName); err != nil { + return nil, fmt.Errorf("invalid path name: %w (%s)", err, pathName) + } + + recordPath := 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 := CommonPath(recordPath) + var segments []*Segment + + err := filepath.WalkDir(commonPath, func(fpath string, info fs.DirEntry, err error) error { + if err != nil { + return err + } + + if !info.IsDir() { + var pa Path + ok := pa.Decode(recordPath, fpath) + + // gather all segments that start before the end of the playback + if ok && (end == nil || !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) + }) + + if start != nil { + if start.Before(segments[0].Start) { + return segments, nil + } + + // 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 +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/segment_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/segment_test.go new file mode 100644 index 0000000000000000000000000000000000000000..395f885dbef2f934bedd2c335aff0662868db69d --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/recordstore/segment_test.go @@ -0,0 +1,133 @@ +package recordstore + +import ( + "os" + "path/filepath" + "regexp" + "testing" + "time" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/stretchr/testify/require" +) + +func TestFindAllPathsWithSegments(t *testing.T) { + dir := t.TempDir() + + err := os.Mkdir(filepath.Join(dir, "path1"), 0o755) + require.NoError(t, err) + + err = os.Mkdir(filepath.Join(dir, "path2"), 0o755) + require.NoError(t, err) + + err = os.WriteFile(filepath.Join(dir, "path1", "2015-05-19_22-15-25-000427.mp4"), []byte{1}, 0o644) + require.NoError(t, err) + + err = os.WriteFile(filepath.Join(dir, "path2", "2015-07-19_22-15-25-000427.mp4"), []byte{1}, 0o644) + require.NoError(t, err) + + paths := FindAllPathsWithSegments(map[string]*conf.Path{ + "~^.*$": { + Name: "~^.*$", + Regexp: regexp.MustCompile("^.*$"), + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + "path2": { + Name: "path2", + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + }) + require.Equal(t, []string{"path1", "path2"}, paths) +} + +func TestFindAllPathsWithSegmentsInvalidPath(t *testing.T) { + dir := t.TempDir() + + err := os.WriteFile(filepath.Join(dir, "_2015-05-19_22-15-25-000427.mp4"), []byte{1}, 0o644) + require.NoError(t, err) + + paths := FindAllPathsWithSegments(map[string]*conf.Path{ + "~^.*$": { + Name: "~^.*$", + Regexp: regexp.MustCompile("^.*$"), + RecordPath: filepath.Join(dir, "%path_%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + }) + require.Equal(t, []string{}, paths) +} + +func TestFindSegments(t *testing.T) { + for _, ca := range []string{ + "no filtering", + "filtering", + "start before first", + } { + t.Run(ca, func(t *testing.T) { + dir := t.TempDir() + + err := os.Mkdir(filepath.Join(dir, "path1"), 0o755) + require.NoError(t, err) + + err = os.Mkdir(filepath.Join(dir, "path2"), 0o755) + require.NoError(t, err) + + err = os.WriteFile(filepath.Join(dir, "path1", "2015-05-19_22-15-25-000427.mp4"), []byte{1}, 0o644) + require.NoError(t, err) + + err = os.WriteFile(filepath.Join(dir, "path1", "2016-05-19_22-15-25-000427.mp4"), []byte{1}, 0o644) + require.NoError(t, err) + + var start *time.Time + var end *time.Time + + switch ca { + case "no filtering": + + case "filtering": + start = new(time.Date(2015, 5, 19, 22, 18, 25, 427000, time.Local)) + end = new(start.Add(60 * time.Minute)) + + case "start before first": + start = new(time.Date(2014, 5, 19, 22, 18, 25, 427000, time.Local)) + } + + segments, err := FindSegments( + &conf.Path{ + Name: "~^.*$", + Regexp: regexp.MustCompile("^.*$"), + RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), + RecordFormat: conf.RecordFormatFMP4, + }, + "path1", + start, + end, + ) + require.NoError(t, err) + + switch ca { + case "no filtering", "start before first": + require.Equal(t, []*Segment{ + { + Fpath: filepath.Join(dir, "path1", "2015-05-19_22-15-25-000427.mp4"), + Start: time.Date(2015, 5, 19, 22, 15, 25, 427000, time.Local), + }, + { + Fpath: filepath.Join(dir, "path1", "2016-05-19_22-15-25-000427.mp4"), + Start: time.Date(2016, 5, 19, 22, 15, 25, 427000, time.Local), + }, + }, segments) + + case "filtering": + require.Equal(t, []*Segment{ + { + Fpath: filepath.Join(dir, "path1", "2015-05-19_22-15-25-000427.mp4"), + Start: time.Date(2015, 5, 19, 22, 15, 25, 427000, time.Local), + }, + }, segments) + } + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/restrictnetwork/restrict_network.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/restrictnetwork/restrict_network.go new file mode 100644 index 0000000000000000000000000000000000000000..5d29b8adab150bb332f1fa880757f61f5c4d4907 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/restrictnetwork/restrict_network.go @@ -0,0 +1,18 @@ +// Package restrictnetwork contains Restrict(). +package restrictnetwork + +import ( + "net" +) + +// Restrict prevents listening on IPv6 when address is 0.0.0.0. +func Restrict(network string, address string) (string, string) { + host, _, err := net.SplitHostPort(address) + if err == nil { + if host == "0.0.0.0" { + return network + "4", address + } + } + + return network, address +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/rlimit/rlimit.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/rlimit/rlimit.go new file mode 100644 index 0000000000000000000000000000000000000000..211556c2904ff952e85fd738c3e97b72ea10fc6e --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/rlimit/rlimit.go @@ -0,0 +1,30 @@ +//go:build !windows + +// Package rlimit contains a function to raise rlimit. +package rlimit + +import ( + "syscall" +) + +// Raise raises the number of file descriptors that can be opened. +func Raise() error { + var rlim syscall.Rlimit + err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlim) + if err != nil { + return err + } + + rlim.Cur = 999999 + err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlim) + if err != nil { + return err + } + + err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlim) + if err != nil { + return err + } + + return nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/rlimit/rlimit_windows.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/rlimit/rlimit_windows.go new file mode 100644 index 0000000000000000000000000000000000000000..98fe0e1417a1d50d7bd5a0c27f472ede07f1b800 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/rlimit/rlimit_windows.go @@ -0,0 +1,5 @@ +package rlimit + +func Raise() error { + return nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/HASH b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/HASH new file mode 100644 index 0000000000000000000000000000000000000000..626e20e4007dd81fda946abdfa8b92f46433c7b9 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/HASH @@ -0,0 +1 @@ +09c827969e702e82be694da80dbf16dbdf5ff6819c33a374b1757e1bc0adb458 diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/VERSION b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/VERSION new file mode 100644 index 0000000000000000000000000000000000000000..b0fbe9e7b1033c94f580f2ebf3a1551d11bbd9eb --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/VERSION @@ -0,0 +1 @@ +v1.6.16 diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/custom_limit_reader.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/custom_limit_reader.go new file mode 100644 index 0000000000000000000000000000000000000000..d6899c355e22354aeb9f3131676ecd0e3fb5e5b0 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/custom_limit_reader.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "io" +) + +var errSizeExceeded = fmt.Errorf("size exceeds maximum allowed") + +// like io.LimitReader, but returns a dedicated error if the limit is exceeded. +type customLimitReader struct { + r io.Reader + n int64 +} + +func (l *customLimitReader) Read(p []byte) (n int, err error) { + if l.n <= 0 { + return 0, errSizeExceeded + } + if int64(len(p)) > l.n { + p = p[0:l.n] + } + n, err = l.r.Read(p) + l.n -= int64(n) + return +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/main.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/main.go new file mode 100644 index 0000000000000000000000000000000000000000..d121cc32493b2c037c2d9bb97b7c5f964c0eb262 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/hlsjsdownloader/main.go @@ -0,0 +1,85 @@ +// Package main contains an utility to download hls.js +package main + +import ( + "archive/zip" + "bytes" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "io/fs" + "log" + "net/http" + "os" + "strings" +) + +const ( + maxInboundHLSJSSize = 10 * 1024 * 1024 +) + +func do() error { + buf, err := os.ReadFile("./hlsjsdownloader/VERSION") + if err != nil { + return err + } + version := strings.TrimSpace(string(buf)) + + log.Printf("downloading hls.js %s...", version) + + res, err := http.Get("https://github.com/video-dev/hls.js/releases/download/" + version + "/release.zip") + if err != nil { + return err + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + return fmt.Errorf("bad status code: %v", res.StatusCode) + } + + zipBuf, err := io.ReadAll(&customLimitReader{res.Body, maxInboundHLSJSSize}) + if err != nil { + return err + } + + buf, err = os.ReadFile("./hlsjsdownloader/HASH") + if err != nil { + return err + } + str := strings.TrimSpace(string(buf)) + + hash, err := hex.DecodeString(str) + if err != nil { + return err + } + + if sum := sha256.Sum256(zipBuf); !bytes.Equal(sum[:], hash) { + return fmt.Errorf("hash mismatch") + } + + z, err := zip.NewReader(bytes.NewReader(zipBuf), int64(len(zipBuf))) + if err != nil { + return err + } + + hls, err := fs.ReadFile(z, "dist/hls.min.js") + if err != nil { + return err + } + + if err = os.WriteFile("hls.min.js", hls, 0o644); err != nil { + return err + } + + log.Println("ok") + return nil +} + +func main() { + err := do() + if err != nil { + log.Printf("ERR: %v", err) + os.Exit(1) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/http_server.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/http_server.go new file mode 100644 index 0000000000000000000000000000000000000000..979ffe383183646f1a2852b33450287e39bb144c --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/http_server.go @@ -0,0 +1,427 @@ +package hls + +import ( + _ "embed" + "errors" + "fmt" + "net" + "net/http" + "path" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/httpp" +) + +//go:generate go run ./hlsjsdownloader + +//go:embed index.html +var hlsIndex []byte + +//go:embed hls.min.js +var hlsMinJS []byte + +func trailingSlashLocation(rawPath string, rawQuery string) string { + res := path.Clean(rawPath) + res = strings.TrimLeft(res, "/\\") + res = "/" + res + "/" + + if rawQuery != "" { + res += "?" + rawQuery + } + + return res +} + +func sanitizeLocation(rawPath string, rawQuery string) string { + res := path.Clean(rawPath) + res = strings.TrimLeft(res, "/\\") + res = "/" + res + + if rawQuery != "" { + res += "?" + rawQuery + } + + return res +} + +func isIOS(userAgent string) bool { + return strings.Contains(userAgent, "iPad") || + strings.Contains(userAgent, "iPhone") || + strings.Contains(userAgent, "iPod") +} + +type httpServer struct { + address string + dumpPackets bool + encryption bool + serverKey string + serverCert string + allowOrigins []string + trustedProxies conf.IPNetworks + readTimeout conf.Duration + writeTimeout conf.Duration + cdnSecret string + pathManager serverPathManager + parent *Server + + inner *httpp.Server +} + +func (s *httpServer) initialize() error { + router := gin.New() + router.SetTrustedProxies(s.trustedProxies.ToTrustedProxies()) //nolint:errcheck + router.Use(s.middlewarePreflightRequests) + router.Use(s.onRequest) + + var proto string + if s.encryption { + proto = "hlss" + } else { + proto = "hls" + } + + s.inner = &httpp.Server{ + Address: s.address, + AllowOrigins: s.allowOrigins, + DumpPackets: s.dumpPackets, + DumpPacketsPrefix: proto + "_server_conn", + ReadTimeout: time.Duration(s.readTimeout), + WriteTimeout: time.Duration(s.writeTimeout), + Encryption: s.encryption, + ServerCert: s.serverCert, + ServerKey: s.serverKey, + Handler: router, + Parent: s, + } + err := s.inner.Initialize() + if err != nil { + return err + } + + return nil +} + +// Log implements logger.Writer. +func (s *httpServer) Log(level logger.Level, format string, args ...any) { + s.parent.Log(level, format, args...) +} + +func (s *httpServer) close() { + s.inner.Close() +} + +func (s *httpServer) middlewarePreflightRequests(ctx *gin.Context) { + if ctx.Request.Method == http.MethodOptions && + ctx.Request.Header.Get("Access-Control-Request-Method") != "" { + ctx.Header("Access-Control-Allow-Methods", "OPTIONS, GET") + ctx.Header("Access-Control-Allow-Headers", "Authorization, Range") + ctx.AbortWithStatus(http.StatusNoContent) + return + } +} + +func (s *httpServer) writeErrorNoLog(ctx *gin.Context, status int, err error) { + ctx.AbortWithStatusJSON(status, &defs.APIError{ + Status: defs.APIErrorStatusError, + Error: err.Error(), + }) +} + +func (s *httpServer) onRequest(ctx *gin.Context) { + if ctx.Request.Method != http.MethodGet { + return + } + + // remove leading prefix + pa := ctx.Request.URL.Path[1:] + + var dir string + var fname string + + type contentType int + + const ( + index contentType = iota + multivariantPlaylist + mediaPlaylist + segment + ) + + var contentTyp contentType + + switch { + case strings.HasSuffix(pa, "/hls.min.js"): + ctx.Header("Cache-Control", "max-age=3600") + ctx.Header("Content-Type", "application/javascript") + ctx.Writer.WriteHeader(http.StatusOK) + ctx.Writer.Write(hlsMinJS) + return + + case pa == "", pa == "favicon.ico", strings.HasSuffix(pa, "/hls.min.js.map"): + return + + case strings.HasSuffix(pa, ".m3u8"): + dir, fname = path.Dir(pa), path.Base(pa) + + if fname == "index.m3u8" { + contentTyp = multivariantPlaylist + } else { + contentTyp = mediaPlaylist + } + + case strings.HasSuffix(pa, ".ts") || + strings.HasSuffix(pa, ".mp4") || + strings.HasSuffix(pa, ".mp"): + dir, fname = path.Dir(pa), path.Base(pa) + + if strings.HasSuffix(fname, ".mp") { + fname += "4" + } + + contentTyp = segment + + default: + dir = pa + + if !strings.HasSuffix(dir, "/") { + ctx.Header("Location", trailingSlashLocation(ctx.Request.URL.Path, ctx.Request.URL.RawQuery)) + ctx.Writer.WriteHeader(http.StatusFound) + return + } + + dir = dir[:len(dir)-1] + contentTyp = index + } + + isCDN := (s.cdnSecret != "" && ctx.Request.Header.Get("Authorization") == "Bearer "+s.cdnSecret) + + switch contentTyp { + case index: + _, err := s.pathManager.FindPathConf(defs.PathFindPathConfReq{ + AccessRequest: defs.PathAccessRequest{ + Name: dir, + Query: ctx.Request.URL.RawQuery, + Publish: false, + Proto: auth.ProtocolHLS, + Credentials: httpp.Credentials(ctx.Request), + IP: net.ParseIP(ctx.ClientIP()), + }, + }) + if err != nil { + if terr, ok := errors.AsType[*auth.Error](err); ok { + if terr.AskCredentials { + ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`) + s.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return + } + + s.Log(logger.Info, "connection %v failed to authenticate: %v", httpp.RemoteAddr(ctx), terr.Wrapped) + + s.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return + } + + s.writeErrorNoLog(ctx, http.StatusInternalServerError, err) + return + } + + ctx.Header("Cache-Control", "max-age=3600") + ctx.Header("Content-Type", "text/html") + ctx.Writer.WriteHeader(http.StatusOK) + ctx.Writer.Write(hlsIndex) + + case multivariantPlaylist: + if isCDN { + if existingMuxer, err := s.parent.getMuxer(serverGetMuxerReq{path: dir, create: false}); err == nil { + if sx := existingMuxer.getCDNSession(); sx != nil { + sx.lastRequestTime.Store(time.Now().UnixNano()) + + ctx.Writer = &responseWriterCounter{ + ResponseWriter: ctx.Writer, + bytesSent: &sx.bytesSent, + } + ctx.Request.URL.Path = fname + + err = existingMuxer.handleRequest(ctx, isCDN) + if err != nil { + s.writeErrorNoLog(ctx, http.StatusInternalServerError, err) + } + return + } + } + + sx := &session{ + isCDN: true, + remoteAddr: httpp.RemoteAddr(ctx), + pathName: dir, + externalCmdPool: s.parent.ExternalCmdPool, + pathManager: s.pathManager, + server: s.parent, + } + err := sx.initialize(ctx) + if err != nil { + if _, ok := errors.AsType[*defs.PathNoStreamAvailableError](err); ok { + s.writeErrorNoLog(ctx, http.StatusNotFound, err) + return + } + + s.writeErrorNoLog(ctx, http.StatusInternalServerError, err) + return + } + + ctx.Writer = &responseWriterCounter{ + ResponseWriter: ctx.Writer, + bytesSent: &sx.bytesSent, + } + ctx.Request.URL.Path = fname + + err = sx.muxer.handleRequest(ctx, isCDN) + if err != nil { + s.writeErrorNoLog(ctx, http.StatusInternalServerError, err) + } + return + } + + if ctx.Request.URL.Query().Get("cookieCheck") != "1" { + http.SetCookie(ctx.Writer, &http.Cookie{ + Name: "cookieCheck", + Value: "1", + }) + + http.SetCookie(ctx.Writer, &http.Cookie{ + Name: "cookieCheck", + Value: "1", + SameSite: http.SameSiteNoneMode, + Secure: true, + Partitioned: true, + HttpOnly: true, + }) + + q := ctx.Request.URL.Query() + q.Set("cookieCheck", "1") + ctx.Request.URL.RawQuery = q.Encode() + ctx.Writer.Header().Set("Location", sanitizeLocation(ctx.Request.URL.Path, ctx.Request.URL.RawQuery)) + + ctx.Writer.WriteHeader(http.StatusFound) + return + } + + if _, err := ctx.Request.Cookie("cookieCheck"); err != nil && isIOS(ctx.Request.UserAgent()) { + s.writeErrorNoLog(ctx, http.StatusBadRequest, fmt.Errorf("HLS on iOS requires the server to set and read cookies")) + return + } + + q := ctx.Request.URL.Query() + q.Del("cookieCheck") + ctx.Request.URL.RawQuery = q.Encode() + + sx := &session{ + remoteAddr: httpp.RemoteAddr(ctx), + pathName: dir, + externalCmdPool: s.parent.ExternalCmdPool, + pathManager: s.pathManager, + server: s.parent, + } + err := sx.initialize(ctx) + if err != nil { + if terr, ok := errors.AsType[*auth.Error](err); ok { + if terr.AskCredentials { + ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`) + s.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return + } + + s.Log(logger.Info, "connection %v failed to authenticate: %v", httpp.RemoteAddr(ctx), terr.Wrapped) + + s.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return + } + + if _, ok := errors.AsType[*defs.PathNoStreamAvailableError](err); ok { + s.writeErrorNoLog(ctx, http.StatusNotFound, err) + return + } + + s.writeErrorNoLog(ctx, http.StatusInternalServerError, err) + return + } + + if cookie, err2 := ctx.Request.Cookie("cookieCheck"); err2 == nil && cookie.Value == "1" { + http.SetCookie(ctx.Writer, &http.Cookie{ + Name: sessionCookieName, + Value: sx.secret.String(), + }) + + http.SetCookie(ctx.Writer, &http.Cookie{ + Name: sessionCookieName, + Value: sx.secret.String(), + SameSite: http.SameSiteNoneMode, + Secure: true, + Partitioned: true, + HttpOnly: true, + }) + } else { + q = ctx.Request.URL.Query() + q.Set(sessionQueryParamName, sx.secret.String()) + ctx.Request.URL.RawQuery = q.Encode() + } + + ctx.Writer = &responseWriterCounter{ + ResponseWriter: ctx.Writer, + bytesSent: &sx.bytesSent, + } + + ctx.Request.URL.Path = fname + + err = sx.muxer.handleRequest(ctx, isCDN) + if err != nil { + s.writeErrorNoLog(ctx, http.StatusInternalServerError, err) + return + } + + default: + muxer, err := s.parent.getMuxer(serverGetMuxerReq{ + path: dir, + create: false, + }) + if err != nil { + s.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return + } + + var sx *session + if isCDN { + sx = muxer.getCDNSession() + } else { + sx = muxer.findSession(ctx) + } + if sx == nil { + s.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return + } + + if isCDN { + sx.lastRequestTime.Store(time.Now().UnixNano()) + } + + ctx.Writer = &responseWriterCounter{ + ResponseWriter: ctx.Writer, + bytesSent: &sx.bytesSent, + } + + ctx.Request.URL.Path = fname + + err = muxer.handleRequest(ctx, isCDN) + if err != nil { + s.writeErrorNoLog(ctx, http.StatusInternalServerError, err) + return + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/index.html b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/index.html new file mode 100644 index 0000000000000000000000000000000000000000..355d8b724866ad4ccca90e864c505537a60107e9 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/index.html @@ -0,0 +1,203 @@ + + + + + + + + + +
+
+ + + + + + diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/muxer.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/muxer.go new file mode 100644 index 0000000000000000000000000000000000000000..9e45b456b54b2cc43ddeeacc3d79688c50958d00 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/muxer.go @@ -0,0 +1,462 @@ +package hls + +import ( + "context" + "errors" + "fmt" + "sync" + "sync/atomic" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/hls" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +const ( + recreateInstancePause = 10 * time.Second +) + +func emptyTimer() *time.Timer { + t := time.NewTimer(0) + <-t.C + return t +} + +type muxerCloseInstanceReq struct { + instance *muxerInstance + err error +} + +type muxer struct { + parentCtx context.Context + remoteAddr string + variant conf.HLSVariant + segmentCount int + segmentDuration conf.Duration + partDuration conf.Duration + segmentMaxSize conf.StringSize + directory string + closeAfter conf.Duration + wg *sync.WaitGroup + pathName string + pathManager serverPathManager + parent *Server + query string + + ctx context.Context + ctxCancel func() + created time.Time + path defs.Path + lastRequestTime atomic.Int64 + bytesSent atomic.Uint64 + + mutex sync.RWMutex + instance *muxerInstance + cumulatedOutboundFramesDiscarded uint64 + sessionsBySecret map[uuid.UUID]*session + cdnSession *session + + chCloseInstance chan muxerCloseInstanceReq +} + +func (m *muxer) initialize() { + ctx, ctxCancel := context.WithCancel(m.parentCtx) + + m.ctx = ctx + m.ctxCancel = ctxCancel + m.created = time.Now() + m.lastRequestTime.Store(time.Now().UnixNano()) + m.sessionsBySecret = make(map[uuid.UUID]*session) + m.chCloseInstance = make(chan muxerCloseInstanceReq) + + m.Log(logger.Info, "created %s", func() string { + if m.remoteAddr == "" { + return "automatically" + } + return "(requested by " + m.remoteAddr + ")" + }()) + + // block first request to getInstance() until the first instance is available + m.mutex.Lock() + + m.wg.Add(1) + go m.run() +} + +func (m *muxer) Close() { + m.ctxCancel() +} + +// Log implements logger.Writer. +func (m *muxer) Log(level logger.Level, format string, args ...any) { + m.parent.Log(level, "[muxer %s] "+format, append([]any{m.pathName}, args...)...) +} + +// PathName returns the path name. +func (m *muxer) PathName() string { + return m.pathName +} + +func (m *muxer) run() { + defer m.wg.Done() + + err := m.runInner() + + m.ctxCancel() + + if m.instance != nil { + m.instance.close() + } + + m.mutex.Lock() + + m.instance = nil + + for _, sx := range m.sessionsBySecret { + sx.close2(fmt.Errorf("muxer destroyed")) + } + + if m.cdnSession != nil { + m.cdnSession.close2(fmt.Errorf("muxer destroyed")) + m.cdnSession = nil + } + + m.mutex.Unlock() + + m.Log(logger.Info, "destroyed: %v", err) + + m.parent.closeMuxer(m) +} + +func (m *muxer) runInner() error { + res, err := m.pathManager.AddReader(defs.PathAddReaderReq{ + Author: m, + AccessRequest: defs.PathAccessRequest{ + Name: m.pathName, + Query: m.query, + SkipAuth: true, + }, + }) + if err != nil { + m.mutex.Unlock() + return err + } + + m.path = res.Path + + defer m.path.RemoveReader(defs.PathRemoveReaderReq{Author: m}) + + tmp, err := m.createInstance(res.Stream) + if err != nil { + if m.remoteAddr != "" || errors.Is(err, hls.ErrNoSupportedCodecs) { + m.mutex.Unlock() + return err + } + + m.Log(logger.Error, "muxer instance crashed: %v", err) + } + + m.instance = tmp + m.mutex.Unlock() + + var recreateInstanceTimer *time.Timer + + if m.instance != nil { + recreateInstanceTimer = emptyTimer() + } else { + recreateInstanceTimer = time.NewTimer(recreateInstancePause) + } + + defer func() { + recreateInstanceTimer.Stop() + }() + + sessionCleanupTicker := time.NewTicker(sessionCleanupPeriod) + defer sessionCleanupTicker.Stop() + + var activityCheckTimer *time.Timer + if m.remoteAddr != "" { + activityCheckTimer = time.NewTimer(max(time.Duration(m.closeAfter)/3, 1*time.Second)) + } else { + activityCheckTimer = emptyTimer() + } + + defer func() { + activityCheckTimer.Stop() + }() + + for { + select { + case req := <-m.chCloseInstance: + if m.instance != req.instance { + continue + } + + m.mutex.Lock() + m.cumulatedOutboundFramesDiscarded += m.instance.reader.OutboundFramesDiscarded() + m.instance = nil + m.mutex.Unlock() + + if m.remoteAddr != "" { + return req.err + } else { + m.mutex.Lock() + for _, sx := range m.sessionsBySecret { + sx.close2(fmt.Errorf("muxer instance crashed")) + } + m.sessionsBySecret = make(map[uuid.UUID]*session) + if m.cdnSession != nil { + m.cdnSession.close2(fmt.Errorf("muxer instance crashed")) + m.cdnSession = nil + } + m.mutex.Unlock() + + m.Log(logger.Error, "muxer instance crashed: %v", req.err) + } + + recreateInstanceTimer = time.NewTimer(recreateInstancePause) + + case <-recreateInstanceTimer.C: + tmp, err = m.createInstance(res.Stream) + if err != nil { + m.Log(logger.Error, "muxer instance crashed: %v", err) + recreateInstanceTimer = time.NewTimer(recreateInstancePause) + continue + } + + m.mutex.Lock() + m.instance = tmp + m.mutex.Unlock() + + case <-sessionCleanupTicker.C: + now := time.Now() + + m.mutex.Lock() + for secret, sx := range m.sessionsBySecret { + lastRequest := time.Unix(0, sx.lastRequestTime.Load()) + + if now.Sub(lastRequest) >= sessionCloseAfter { + delete(m.sessionsBySecret, secret) + sx.close2(fmt.Errorf("inactive")) + } + } + if m.cdnSession != nil { + lastRequest := time.Unix(0, m.cdnSession.lastRequestTime.Load()) + if now.Sub(lastRequest) >= sessionCloseAfter { + m.cdnSession.close2(fmt.Errorf("inactive")) + m.cdnSession = nil + } + } + m.mutex.Unlock() + + case <-activityCheckTimer.C: + t := time.Unix(0, m.lastRequestTime.Load()) + if time.Since(t) >= time.Duration(m.closeAfter) { + return fmt.Errorf("not used anymore") + } + activityCheckTimer = time.NewTimer(max(time.Duration(m.closeAfter)/3, 1*time.Second)) + + case <-m.ctx.Done(): + return errors.New("terminated") + } + } +} + +func (m *muxer) createInstance(strm *stream.Stream) (*muxerInstance, error) { + mi := &muxerInstance{ + variant: m.variant, + segmentCount: m.segmentCount, + segmentDuration: m.segmentDuration, + partDuration: m.partDuration, + segmentMaxSize: m.segmentMaxSize, + directory: m.directory, + pathName: m.pathName, + bytesSent: &m.bytesSent, + wg: m.wg, + stream: strm, + server: m.parent, + parent: m, + } + err := mi.initialize() + if err != nil { + return nil, err + } + return mi, nil +} + +func (m *muxer) closeInstance(mi *muxerInstance, err error) { + select { + case m.chCloseInstance <- muxerCloseInstanceReq{instance: mi, err: err}: + case <-m.ctx.Done(): + } +} + +// APIReaderDescribe implements reader. +func (m *muxer) APIReaderDescribe() *defs.APIPathReader { + return &defs.APIPathReader{ + Type: defs.APIPathReaderTypeHidden, + ID: "", + } +} + +func (m *muxer) addSession(sx *session) ([]format.Format, error) { + m.mutex.Lock() + defer m.mutex.Unlock() + + if m.instance == nil { + return nil, fmt.Errorf("muxer instance not available") + } + + if sx.isCDN { + if m.cdnSession != nil { + m.cdnSession.close2(fmt.Errorf("replaced by new CDN session")) + } + m.cdnSession = sx + } else { + m.sessionsBySecret[sx.secret] = sx + } + + return m.instance.reader.Formats(), nil +} + +func (m *muxer) getCDNSession() *session { + m.mutex.RLock() + defer m.mutex.RUnlock() + return m.cdnSession +} + +func (m *muxer) findSession(ctx *gin.Context) *session { + var rawSecret string + if cookie, err := ctx.Request.Cookie(sessionCookieName); err == nil { + rawSecret = cookie.Value + } else { + q := ctx.Request.URL.Query() + rawSecret = q.Get(sessionQueryParamName) + } + + secret, err := uuid.Parse(rawSecret) + if err != nil { + return nil + } + + m.mutex.RLock() + defer m.mutex.RUnlock() + + sx, ok := m.sessionsBySecret[secret] + if !ok { + return nil + } + + if ctx.ClientIP() != sx.ip { + return nil + } + + sx.lastRequestTime.Store(time.Now().UnixNano()) + + return sx +} + +func (m *muxer) handleRequest(ctx *gin.Context, isCDN bool) error { + m.lastRequestTime.Store(time.Now().UnixNano()) + + m.mutex.RLock() + instance := m.instance + m.mutex.RUnlock() + + if instance == nil { + return fmt.Errorf("muxer instance not available") + } + + instance.handleRequest(ctx, isCDN) + return nil +} + +func (m *muxer) apiItem() *defs.APIHLSMuxer { + m.mutex.RLock() + instance := m.instance + cumulatedOutboundFramesDiscarded := m.cumulatedOutboundFramesDiscarded + m.mutex.RUnlock() + + outboundFramesDiscarded := cumulatedOutboundFramesDiscarded + if instance != nil { + outboundFramesDiscarded += instance.reader.OutboundFramesDiscarded() + } + + return &defs.APIHLSMuxer{ + Path: m.pathName, + Created: m.created, + LastRequest: time.Unix(0, m.lastRequestTime.Load()), + OutboundBytes: m.bytesSent.Load(), + OutboundFramesDiscarded: outboundFramesDiscarded, + BytesSent: m.bytesSent.Load(), + } +} + +func (m *muxer) apiSessionsList() []defs.APIHLSSession { + m.mutex.RLock() + defer m.mutex.RUnlock() + + sessions := make([]defs.APIHLSSession, 0, len(m.sessionsBySecret)) + + for _, sx := range m.sessionsBySecret { + sessions = append(sessions, *sx.apiItem()) + } + + if m.cdnSession != nil { + sessions = append(sessions, *m.cdnSession.apiItem()) + } + + return sessions +} + +func (m *muxer) findSessionByUUID(uuid uuid.UUID) *session { + for _, sx := range m.sessionsBySecret { + if sx.uuid == uuid { + return sx + } + } + return nil +} + +func (m *muxer) apiSessionsGet(uuid uuid.UUID) (*defs.APIHLSSession, bool) { + m.mutex.RLock() + defer m.mutex.RUnlock() + + if m.cdnSession != nil && m.cdnSession.uuid == uuid { + return m.cdnSession.apiItem(), true + } + + sx := m.findSessionByUUID(uuid) + if sx == nil { + return nil, false + } + + return sx.apiItem(), true +} + +func (m *muxer) apiSessionsKick(uuid uuid.UUID) bool { + m.mutex.Lock() + defer m.mutex.Unlock() + + if m.cdnSession != nil && m.cdnSession.uuid == uuid { + m.cdnSession.close2(fmt.Errorf("kicked")) + m.cdnSession = nil + return true + } + + sx := m.findSessionByUUID(uuid) + if sx == nil { + return false + } + + sx.close2(fmt.Errorf("kicked")) + delete(m.sessionsBySecret, sx.secret) + + return true +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/muxer_instance.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/muxer_instance.go new file mode 100644 index 0000000000000000000000000000000000000000..7777cbfd72949ab9bac588c55fca2bff88963a9e --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/muxer_instance.go @@ -0,0 +1,160 @@ +package hls + +import ( + "context" + "fmt" + "os" + "path/filepath" + "sync" + "sync/atomic" + "time" + + "github.com/bluenviron/gohlslib/v2" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/hls" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/gin-gonic/gin" +) + +const ( + sessionCookieName = "hlsSession" + sessionQueryParamName = "session" + sessionCloseAfter = 30 * time.Second + sessionCleanupPeriod = sessionCloseAfter / 3 +) + +type instanceParent interface { + logger.Writer + closeInstance(*muxerInstance, error) +} + +type muxerInstance struct { + variant conf.HLSVariant + segmentCount int + segmentDuration conf.Duration + partDuration conf.Duration + segmentMaxSize conf.StringSize + directory string + pathName string + bytesSent *atomic.Uint64 + wg *sync.WaitGroup + stream *stream.Stream + server logger.Writer + parent instanceParent + + ctx context.Context + ctxCancel func() + hmuxer *gohlslib.Muxer + reader *stream.Reader +} + +func (mi *muxerInstance) initialize() error { + mi.Log(logger.Debug, "instance created") + + var muxerDirectory string + if mi.directory != "" { + muxerDirectory = filepath.Join(mi.directory, mi.pathName) + os.MkdirAll(muxerDirectory, 0o755) + } + + mi.hmuxer = &gohlslib.Muxer{ + Variant: gohlslib.MuxerVariant(mi.variant), + SegmentCount: mi.segmentCount, + SegmentMinDuration: time.Duration(mi.segmentDuration), + PartMinDuration: time.Duration(mi.partDuration), + SegmentMaxSize: uint64(mi.segmentMaxSize), + Directory: muxerDirectory, + OnEncodeError: func(err error) { + mi.Log(logger.Warn, err.Error()) + }, + } + + mi.reader = &stream.Reader{ + SkipOutboundBytes: true, + Parent: mi, + } + + err := hls.FromStream( + mi.stream.OrigDesc, + mi.stream.OutDescCopy(), + mi.reader, + mi.hmuxer) + if err != nil { + return err + } + + err = mi.hmuxer.Start() + if err != nil { + return err + } + + mi.Log(logger.Info, "is converting into HLS, %s", + defs.FormatsInfo(mi.reader.Formats())) + + mi.stream.AddReader(mi.reader) + + mi.ctx, mi.ctxCancel = context.WithCancel(context.Background()) + + mi.wg.Add(1) + go mi.run() + + return nil +} + +// Log implements logger.Writer. +func (mi *muxerInstance) Log(level logger.Level, format string, args ...any) { + mi.parent.Log(level, format, args...) +} + +func (mi *muxerInstance) close() { + mi.ctxCancel() +} + +func (mi *muxerInstance) run() { + defer mi.wg.Done() + + err := mi.runInner() + + mi.ctxCancel() + + mi.stream.RemoveReader(mi.reader) + + mi.hmuxer.Close() + + if mi.hmuxer.Directory != "" { + os.Remove(mi.hmuxer.Directory) + } + + mi.Log(logger.Debug, "instance destroyed: %v", err) + + mi.parent.closeInstance(mi, err) +} + +func (mi *muxerInstance) runInner() error { + for { + select { + case <-mi.ctx.Done(): + return fmt.Errorf("terminated") + + case err := <-mi.reader.Error(): + return err + } + } +} + +func (mi *muxerInstance) handleRequest(ctx *gin.Context, isCDN bool) { + w := ctx.Writer + + if !isCDN { + w = &responseWriterNoCache{ResponseWriter: w} + } + + w = &responseWriterCounter{ + ResponseWriter: w, + bytesSent: mi.bytesSent, + } + + mi.hmuxer.Handle(w, ctx.Request) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/response_writer_counter.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/response_writer_counter.go new file mode 100644 index 0000000000000000000000000000000000000000..183a2ce8d7c813955e4622bf70d0fe1b86cde308 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/response_writer_counter.go @@ -0,0 +1,18 @@ +package hls + +import ( + "sync/atomic" + + "github.com/gin-gonic/gin" +) + +type responseWriterCounter struct { + gin.ResponseWriter + bytesSent *atomic.Uint64 +} + +func (w *responseWriterCounter) Write(p []byte) (int, error) { + n, err := w.ResponseWriter.Write(p) + w.bytesSent.Add(uint64(n)) + return n, err +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/response_writer_no_cache.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/response_writer_no_cache.go new file mode 100644 index 0000000000000000000000000000000000000000..5a226e5b8d327c6723029c2aaee1ca096798c4cf --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/response_writer_no_cache.go @@ -0,0 +1,19 @@ +package hls + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +type responseWriterNoCache struct { + gin.ResponseWriter +} + +func (w *responseWriterNoCache) WriteHeader(statusCode int) { + if statusCode == http.StatusOK { + w.ResponseWriter.Header().Set("Cache-Control", "private, no-cache") + } + + w.ResponseWriter.WriteHeader(statusCode) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/server.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/server.go new file mode 100644 index 0000000000000000000000000000000000000000..f78773565b1656f9bffe11fbc6bc8c4b1e0a4643 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/server.go @@ -0,0 +1,483 @@ +// Package hls contains a HLS server. +package hls + +import ( + "context" + "errors" + "fmt" + "reflect" + "sort" + "sync" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/google/uuid" +) + +// ErrMuxerNotFound is returned when a muxer is not found. +var ErrMuxerNotFound = errors.New("muxer not found") + +// ErrSessionNotFound is returned when a session is not found. +var ErrSessionNotFound = errors.New("session not found") + +func interfaceIsEmpty(i any) bool { + return reflect.ValueOf(i).Kind() != reflect.Pointer || reflect.ValueOf(i).IsNil() +} + +type serverGetMuxerRes struct { + muxer *muxer + err error +} + +type serverGetMuxerReq struct { + path string + create bool + remoteAddr string // only if create == true + query string // only if create == true + sourceOnDemand bool // only if create == true + res chan serverGetMuxerRes +} + +type serverAPIMuxersListRes struct { + data *defs.APIHLSMuxerList + err error +} + +type serverAPIMuxersListReq struct { + res chan serverAPIMuxersListRes +} + +type serverAPIMuxersGetRes struct { + data *defs.APIHLSMuxer + err error +} + +type serverAPIMuxersGetReq struct { + name string + res chan serverAPIMuxersGetRes +} + +type serverAPISessionsListRes struct { + data *defs.APIHLSSessionList + err error +} + +type serverAPISessionsListReq struct { + res chan serverAPISessionsListRes +} + +type serverAPISessionsGetRes struct { + data *defs.APIHLSSession + err error +} + +type serverAPISessionsGetReq struct { + uuid uuid.UUID + res chan serverAPISessionsGetRes +} + +type serverAPISessionsKickRes struct { + err error +} + +type serverAPISessionsKickReq struct { + uuid uuid.UUID + res chan serverAPISessionsKickRes +} + +type serverMetrics interface { + SetHLSServer(defs.APIHLSServer) +} + +type serverPathManager interface { + SetHLSServer(*Server) []defs.Path + FindPathConf(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) + AddReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) +} + +type serverParent interface { + logger.Writer +} + +// Server is a HLS server. +type Server struct { + Address string + DumpPackets bool + Encryption bool + ServerKey string + ServerCert string + AllowOrigins []string + TrustedProxies conf.IPNetworks + AlwaysRemux bool + Variant conf.HLSVariant + SegmentCount int + SegmentDuration conf.Duration + PartDuration conf.Duration + SegmentMaxSize conf.StringSize + Directory string + CDNSecret string + ReadTimeout conf.Duration + WriteTimeout conf.Duration + MuxerCloseAfter conf.Duration + ExternalCmdPool *externalcmd.Pool + Metrics serverMetrics + PathManager serverPathManager + Parent serverParent + + ctx context.Context + ctxCancel func() + wg sync.WaitGroup + httpServer *httpServer + muxers map[string]*muxer + + // in + chPathReady chan defs.Path + chPathNotReady chan defs.Path + chGetMuxer chan serverGetMuxerReq + chCloseMuxer chan *muxer + chAPIMuxerList chan serverAPIMuxersListReq + chAPIMuxerGet chan serverAPIMuxersGetReq + chAPISessionsList chan serverAPISessionsListReq + chAPISessionsGet chan serverAPISessionsGetReq + chAPISessionsKick chan serverAPISessionsKickReq +} + +// Initialize initializes the server. +func (s *Server) Initialize() error { + ctx, ctxCancel := context.WithCancel(context.Background()) + + s.ctx = ctx + s.ctxCancel = ctxCancel + s.muxers = make(map[string]*muxer) + s.chPathReady = make(chan defs.Path) + s.chPathNotReady = make(chan defs.Path) + s.chGetMuxer = make(chan serverGetMuxerReq) + s.chCloseMuxer = make(chan *muxer) + s.chAPIMuxerList = make(chan serverAPIMuxersListReq) + s.chAPIMuxerGet = make(chan serverAPIMuxersGetReq) + s.chAPISessionsList = make(chan serverAPISessionsListReq) + s.chAPISessionsGet = make(chan serverAPISessionsGetReq) + s.chAPISessionsKick = make(chan serverAPISessionsKickReq) + + s.httpServer = &httpServer{ + address: s.Address, + dumpPackets: s.DumpPackets, + encryption: s.Encryption, + serverKey: s.ServerKey, + serverCert: s.ServerCert, + allowOrigins: s.AllowOrigins, + trustedProxies: s.TrustedProxies, + readTimeout: s.ReadTimeout, + writeTimeout: s.WriteTimeout, + cdnSecret: s.CDNSecret, + pathManager: s.PathManager, + parent: s, + } + err := s.httpServer.initialize() + if err != nil { + ctxCancel() + return err + } + + str := "started with listener on " + s.Address + if !s.Encryption { + str += " (TCP/HTTP)" + } else { + str += " (TCP/HTTPS)" + } + s.Log(logger.Info, str) + + s.wg.Add(1) + go s.run() + + if !interfaceIsEmpty(s.Metrics) { + s.Metrics.SetHLSServer(s) + } + + return nil +} + +// Log implements logger.Writer. +func (s *Server) Log(level logger.Level, format string, args ...any) { + s.Parent.Log(level, "[HLS] "+format, args...) +} + +// Close closes the server. +func (s *Server) Close() { + s.Log(logger.Info, "closing") + + if !interfaceIsEmpty(s.Metrics) { + s.Metrics.SetHLSServer(nil) + } + + s.ctxCancel() + s.wg.Wait() +} + +func (s *Server) run() { + defer s.wg.Done() + + readyPaths := s.PathManager.SetHLSServer(s) + defer s.PathManager.SetHLSServer(nil) + + if s.AlwaysRemux { + for _, pa := range readyPaths { + if !pa.SafeConf().SourceOnDemand { + if _, ok := s.muxers[pa.Name()]; !ok { + s.createMuxer(pa.Name(), "", "") + } + } + } + } + +outer: + for { + select { + case pa := <-s.chPathReady: + if s.AlwaysRemux && !pa.SafeConf().SourceOnDemand { + if _, ok := s.muxers[pa.Name()]; !ok { + s.createMuxer(pa.Name(), "", "") + } + } + + case pa := <-s.chPathNotReady: + c, ok := s.muxers[pa.Name()] + if ok && c.remoteAddr == "" { // created with "always remux" + c.Close() + delete(s.muxers, pa.Name()) + } + + case req := <-s.chGetMuxer: + mux, ok := s.muxers[req.path] + switch { + case ok: + req.res <- serverGetMuxerRes{muxer: mux} + case !req.create: + req.res <- serverGetMuxerRes{err: fmt.Errorf("muxer not found")} + case s.AlwaysRemux && !req.sourceOnDemand: + req.res <- serverGetMuxerRes{err: fmt.Errorf("muxer is waiting to be created")} + default: + req.res <- serverGetMuxerRes{muxer: s.createMuxer(req.path, req.remoteAddr, req.query)} + } + + case c := <-s.chCloseMuxer: + if c2, ok := s.muxers[c.PathName()]; ok && c2 == c { + delete(s.muxers, c.PathName()) + } + + case req := <-s.chAPIMuxerList: + data := &defs.APIHLSMuxerList{ + Items: []defs.APIHLSMuxer{}, + } + + for _, muxer := range s.muxers { + data.Items = append(data.Items, *muxer.apiItem()) + } + + sort.Slice(data.Items, func(i, j int) bool { + return data.Items[i].Created.Before(data.Items[j].Created) + }) + + req.res <- serverAPIMuxersListRes{ + data: data, + } + + case req := <-s.chAPIMuxerGet: + muxer, ok := s.muxers[req.name] + if !ok { + req.res <- serverAPIMuxersGetRes{err: ErrMuxerNotFound} + continue + } + + req.res <- serverAPIMuxersGetRes{data: muxer.apiItem()} + + case req := <-s.chAPISessionsList: + data := &defs.APIHLSSessionList{ + Items: []defs.APIHLSSession{}, + } + + for _, muxer := range s.muxers { + data.Items = append(data.Items, muxer.apiSessionsList()...) + } + + sort.Slice(data.Items, func(i, j int) bool { + return data.Items[i].Created.Before(data.Items[j].Created) + }) + + req.res <- serverAPISessionsListRes{data: data} + + case req := <-s.chAPISessionsGet: + for _, muxer := range s.muxers { + session, ok := muxer.apiSessionsGet(req.uuid) + if ok { + req.res <- serverAPISessionsGetRes{data: session} + continue outer + } + } + + req.res <- serverAPISessionsGetRes{err: ErrSessionNotFound} + + case req := <-s.chAPISessionsKick: + for _, muxer := range s.muxers { + ok := muxer.apiSessionsKick(req.uuid) + if ok { + req.res <- serverAPISessionsKickRes{} + continue outer + } + } + + req.res <- serverAPISessionsKickRes{err: ErrSessionNotFound} + + case <-s.ctx.Done(): + break outer + } + } + + s.ctxCancel() + + s.httpServer.close() +} + +func (s *Server) createMuxer(pathName string, remoteAddr string, query string) *muxer { + r := &muxer{ + parentCtx: s.ctx, + remoteAddr: remoteAddr, + variant: s.Variant, + segmentCount: s.SegmentCount, + segmentDuration: s.SegmentDuration, + partDuration: s.PartDuration, + segmentMaxSize: s.SegmentMaxSize, + directory: s.Directory, + wg: &s.wg, + pathName: pathName, + pathManager: s.PathManager, + parent: s, + query: query, + closeAfter: s.MuxerCloseAfter, + } + r.initialize() + s.muxers[pathName] = r + return r +} + +// closeMuxer is called by muxer. +func (s *Server) closeMuxer(c *muxer) { + select { + case s.chCloseMuxer <- c: + case <-s.ctx.Done(): + } +} + +func (s *Server) getMuxer(req serverGetMuxerReq) (*muxer, error) { + req.res = make(chan serverGetMuxerRes) + + select { + case s.chGetMuxer <- req: + res := <-req.res + return res.muxer, res.err + + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// PathReady is called by pathManager. +func (s *Server) PathReady(pa defs.Path) { + select { + case s.chPathReady <- pa: + case <-s.ctx.Done(): + } +} + +// PathNotReady is called by pathManager. +func (s *Server) PathNotReady(pa defs.Path) { + select { + case s.chPathNotReady <- pa: + case <-s.ctx.Done(): + } +} + +// APIMuxersList implements defs.APIHLSServer. +func (s *Server) APIMuxersList() (*defs.APIHLSMuxerList, error) { + req := serverAPIMuxersListReq{ + res: make(chan serverAPIMuxersListRes), + } + + select { + case s.chAPIMuxerList <- req: + res := <-req.res + return res.data, res.err + + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// APIMuxersGet implements defs.APIHLSServer. +func (s *Server) APIMuxersGet(name string) (*defs.APIHLSMuxer, error) { + req := serverAPIMuxersGetReq{ + name: name, + res: make(chan serverAPIMuxersGetRes), + } + + select { + case s.chAPIMuxerGet <- req: + res := <-req.res + return res.data, res.err + + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// APISessionsList implements defs.APIHLSServer. +func (s *Server) APISessionsList() (*defs.APIHLSSessionList, error) { + req := serverAPISessionsListReq{ + res: make(chan serverAPISessionsListRes), + } + + select { + case s.chAPISessionsList <- req: + res := <-req.res + return res.data, res.err + + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// APISessionsGet implements defs.APIHLSServer. +func (s *Server) APISessionsGet(uuid uuid.UUID) (*defs.APIHLSSession, error) { + req := serverAPISessionsGetReq{ + uuid: uuid, + res: make(chan serverAPISessionsGetRes), + } + + select { + case s.chAPISessionsGet <- req: + res := <-req.res + return res.data, res.err + + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// APISessionsKick implements defs.APIHLSServer. +func (s *Server) APISessionsKick(uuid uuid.UUID) error { + req := serverAPISessionsKickReq{ + uuid: uuid, + res: make(chan serverAPISessionsKickRes), + } + + select { + case s.chAPISessionsKick <- req: + res := <-req.res + return res.err + + case <-s.ctx.Done(): + return fmt.Errorf("terminated") + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/server_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..37d5d95d3d575e4628609933c97c9af527c22e69 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/server_test.go @@ -0,0 +1,781 @@ +package hls + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "testing" + "time" + + "github.com/bluenviron/gohlslib/v2" + "github.com/bluenviron/gohlslib/v2/pkg/codecs" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/mediacommon/v2/pkg/codecs/mpeg4audio" + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/stretchr/testify/require" +) + +type dummyPathManager struct { + setHLSServerImpl func() []defs.Path + findPathConfImpl func(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) + addReaderImpl func(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) +} + +func (pm *dummyPathManager) SetHLSServer(*Server) []defs.Path { + if pm.setHLSServerImpl != nil { + return pm.setHLSServerImpl() + } + return nil +} + +func (pm *dummyPathManager) FindPathConf(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) { + return pm.findPathConfImpl(req) +} + +func (pm *dummyPathManager) AddReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + return pm.addReaderImpl(req) +} + +type dummyPath struct{} + +func (pa *dummyPath) Name() string { + return "teststream" +} + +func (pa *dummyPath) SafeConf() *conf.Path { + return &conf.Path{} +} + +func (pa *dummyPath) ExternalCmdEnv() externalcmd.Environment { + return nil +} + +func (pa *dummyPath) RemovePublisher(_ defs.PathRemovePublisherReq) { +} + +func (pa *dummyPath) RemoveReader(_ defs.PathRemoveReaderReq) { +} + +func TestServerPreflightRequest(t *testing.T) { + s := &Server{ + Address: "127.0.0.1:8888", + AllowOrigins: []string{"*"}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: &dummyPathManager{}, + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + req, err := http.NewRequest(http.MethodOptions, "http://localhost:8888", nil) + require.NoError(t, err) + + req.Header.Add("Access-Control-Request-Method", "GET") + + res, err := hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusNoContent, res.StatusCode) + + byts, err := io.ReadAll(res.Body) + require.NoError(t, err) + + require.Equal(t, "*", res.Header.Get("Access-Control-Allow-Origin")) + require.Equal(t, "true", res.Header.Get("Access-Control-Allow-Credentials")) + require.Equal(t, "OPTIONS, GET", res.Header.Get("Access-Control-Allow-Methods")) + require.Equal(t, "Authorization, Range", res.Header.Get("Access-Control-Allow-Headers")) + require.Equal(t, byts, []byte{}) +} + +func TestServerIndexNotConfigured(t *testing.T) { + pm := &dummyPathManager{ + findPathConfImpl: func(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) { + require.Equal(t, "nonconfigured", req.AccessRequest.Name) + return nil, fmt.Errorf("path is not configured") + }, + } + + s := &Server{ + Address: "127.0.0.1:8888", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: pm, + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8888/nonconfigured/", nil) + require.NoError(t, err) + + res, err := http.DefaultClient.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusInternalServerError, res.StatusCode) + require.Contains(t, res.Header.Get("Content-Type"), "application/json") + + byts, err := io.ReadAll(res.Body) + require.NoError(t, err) + + var payload defs.APIError + err = json.Unmarshal(byts, &payload) + require.NoError(t, err) + require.Equal(t, defs.APIError{ + Status: defs.APIErrorStatusError, + Error: "path is not configured", + }, payload) +} + +func TestServerIndexRedirect(t *testing.T) { + s := &Server{ + Address: "127.0.0.1:8888", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: &dummyPathManager{}, + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + client := &http.Client{ + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { + return http.ErrUseLastResponse + }, + } + + res, err := client.Get("http://127.0.0.1:8888/stream") + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusFound, res.StatusCode) + require.Equal(t, "/stream/", res.Header.Get("Location")) +} + +func TestServerIndexRedirectNoXSS(t *testing.T) { + for _, ca := range []struct { + name string + path string + expected string + }{ + {"double slash", "//double/slash", "/double/slash/"}, + {"protocol-relative open redirect", "//evil.com", "/evil.com/"}, + {"backslash bypass", "/%5Cevil.com", "/evil.com/"}, + } { + t.Run(ca.name, func(t *testing.T) { + pm := &dummyPathManager{ + findPathConfImpl: func(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) { + return &defs.PathFindPathConfRes{Conf: &conf.Path{}, User: req.AccessRequest.Credentials.User}, nil + }, + } + + s := &Server{ + Address: "127.0.0.1:8888", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: pm, + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{ + Transport: tr, + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { + return http.ErrUseLastResponse + }, + } + + req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8888"+ca.path, nil) + require.NoError(t, err) + + res, err := hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusFound, res.StatusCode) + require.Equal(t, ca.expected, res.Header.Get("Location")) + }) + } +} + +func TestServerNotFound(t *testing.T) { + for _, ca := range []string{ + "always remux off", + "always remux on", + } { + t.Run(ca, func(t *testing.T) { + pm := &dummyPathManager{ + findPathConfImpl: func(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) { + require.Equal(t, "nonexisting", req.AccessRequest.Name) + return &defs.PathFindPathConfRes{Conf: &conf.Path{}, User: req.AccessRequest.Credentials.User}, nil + }, + addReaderImpl: func(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + require.Equal(t, "nonexisting", req.AccessRequest.Name) + return nil, &defs.PathNoStreamAvailableError{} + }, + } + + s := &Server{ + Address: "127.0.0.1:8888", + Encryption: false, + ServerKey: "", + ServerCert: "", + AlwaysRemux: ca == "always remux on", + Variant: conf.HLSVariant(gohlslib.MuxerVariantMPEGTS), + SegmentCount: 7, + SegmentDuration: conf.Duration(1 * time.Second), + PartDuration: conf.Duration(200 * time.Millisecond), + SegmentMaxSize: 50 * 1024 * 1024, + TrustedProxies: conf.IPNetworks{}, + Directory: "", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: pm, + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + tr := &http.Transport{} + defer tr.CloseIdleConnections() + hc := &http.Client{Transport: tr} + + func() { + var req *http.Request + req, err = http.NewRequest(http.MethodGet, "http://myuser:mypass@127.0.0.1:8888/nonexisting/", nil) + require.NoError(t, err) + + var res *http.Response + res, err = hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + require.Equal(t, http.StatusOK, res.StatusCode) + }() + + func() { + var req *http.Request + req, err = http.NewRequest(http.MethodGet, "http://myuser:mypass@127.0.0.1:8888/nonexisting/index.m3u8", nil) + require.NoError(t, err) + + var res *http.Response + res, err = hc.Do(req) + require.NoError(t, err) + defer res.Body.Close() + require.Equal(t, http.StatusNotFound, res.StatusCode) + }() + }) + } +} + +type cdnRoundTripper struct { + secret string + base http.RoundTripper +} + +func (t *cdnRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + req = req.Clone(req.Context()) + req.Header.Set("Authorization", "Bearer "+t.secret) + return t.base.RoundTrip(req) +} + +func TestServerRead(t *testing.T) { + for _, cdn := range []string{ + "no cdn", + "cdn", + } { + for _, ca := range []string{ + "always remux off", + "always remux on", + } { + t.Run(cdn+"/"+ca, func(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{ + test.MediaH264, + test.MediaMPEG4Audio, + }} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + ReplaceNTP: false, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + pm := &dummyPathManager{ + addReaderImpl: func(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + + switch req.Author.(type) { + case *muxer: + if cdn != "no cdn" || ca == "always remux on" { + require.Equal(t, "", req.AccessRequest.Query) + } else { + require.Equal(t, "param=value", req.AccessRequest.Query) + } + + case *session: + if cdn != "no cdn" { + require.True(t, req.AccessRequest.SkipAuth) + require.Nil(t, req.AccessRequest.Credentials) + require.Equal(t, "", req.AccessRequest.Query) + } else { + require.Equal(t, "param=value", req.AccessRequest.Query) + } + + default: + t.Errorf("should not happen") + } + + return &defs.PathAddReaderRes{Path: &dummyPath{}, Stream: strm}, nil + }, + } + + s := &Server{ + Address: "127.0.0.1:8888", + AlwaysRemux: ca == "always remux on", + Variant: conf.HLSVariant(gohlslib.MuxerVariantMPEGTS), + SegmentCount: 7, + SegmentDuration: conf.Duration(1 * time.Second), + PartDuration: conf.Duration(200 * time.Millisecond), + SegmentMaxSize: 50 * 1024 * 1024, + TrustedProxies: conf.IPNetworks{}, + CDNSecret: "myCDNSecret", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: pm, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + recv1 := make(chan struct{}) + recv2 := make(chan struct{}) + + newClient := func() *gohlslib.Client { + c := &gohlslib.Client{StartDistance: 1} + c.OnTracks = func(tracks []*gohlslib.Track) error { + require.Equal(t, []*gohlslib.Track{ + { + Codec: &codecs.H264{}, + ClockRate: 90000, + }, + { + Codec: &codecs.MPEG4Audio{ + Config: mpeg4audio.AudioSpecificConfig{ + Type: 2, + ChannelCount: 2, + ChannelConfig: 2, + SampleRate: 44100, + }, + }, + ClockRate: 90000, + }, + }, tracks) + + c.OnDataH26x(tracks[0], func(pts, dts int64, au [][]byte) { + require.Equal(t, int64(0), pts) + require.Equal(t, int64(0), dts) + require.Equal(t, [][]byte{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5, 1}, + }, au) + close(recv1) + }) + + c.OnDataMPEG4Audio(tracks[1], func(pts int64, aus [][]byte) { + require.Equal(t, int64(0), pts) + require.Equal(t, [][]byte{{1, 2}}, aus) + close(recv2) + }) + + return nil + } + if cdn != "no cdn" { + c.URI = "http://127.0.0.1:8888/teststream/index.m3u8" + c.HTTPClient = &http.Client{ + Transport: &cdnRoundTripper{ + secret: "myCDNSecret", + base: &http.Transport{}, + }, + } + } else { + c.URI = "http://myuser:mypass@127.0.0.1:8888/teststream/index.m3u8?param=value" + } + return c + } + + writeData := func() { + for i := range 2 { + subStream.WriteUnit(test.MediaH264, test.FormatH264, &unit.Unit{ + NTP: time.Time{}, + PTS: int64(i) * 90000, + Payload: unit.PayloadH264{ + {5, 1}, // IDR + }, + }) + subStream.WriteUnit(test.MediaMPEG4Audio, test.FormatMPEG4Audio, &unit.Unit{ + NTP: time.Time{}, + PTS: int64(i) * 44100, + Payload: unit.PayloadMPEG4Audio{{1, 2}}, + }) + } + } + + if ca == "always remux off" { + c := newClient() + err = c.Start() + require.NoError(t, err) + defer c.Close() + + strm.WaitForReaders() + writeData() + } else { + s.PathReady(&dummyPath{}) + strm.WaitForReaders() + writeData() + + c := newClient() + err = c.Start() + require.NoError(t, err) + defer c.Close() + } + + <-recv1 + <-recv2 + }) + } + } +} + +func TestServerDirectory(t *testing.T) { + dir := t.TempDir() + + desc := &description.Session{Medias: []*description.Media{test.MediaH264}} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + pm := &dummyPathManager{ + addReaderImpl: func(_ defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + return &defs.PathAddReaderRes{Path: &dummyPath{}, Stream: strm}, nil + }, + } + + s := &Server{ + Address: "127.0.0.1:8888", + Encryption: false, + ServerKey: "", + ServerCert: "", + AlwaysRemux: true, + Variant: conf.HLSVariant(gohlslib.MuxerVariantMPEGTS), + SegmentCount: 7, + SegmentDuration: conf.Duration(1 * time.Second), + PartDuration: conf.Duration(200 * time.Millisecond), + SegmentMaxSize: 50 * 1024 * 1024, + TrustedProxies: conf.IPNetworks{}, + Directory: filepath.Join(dir, "mydir"), + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: pm, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + s.PathReady(&dummyPath{}) + + time.Sleep(100 * time.Millisecond) + + _, err = os.Stat(filepath.Join(dir, "mydir", "teststream")) + require.NoError(t, err) +} + +func TestServerDynamicAlwaysRemux(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{test.MediaH264}} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + done := make(chan struct{}) + + pm := &dummyPathManager{ + setHLSServerImpl: func() []defs.Path { + return []defs.Path{&dummyPath{}} + }, + addReaderImpl: func(_ defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + close(done) + return &defs.PathAddReaderRes{Path: &dummyPath{}, Stream: strm}, nil + }, + } + + s := &Server{ + Address: "127.0.0.1:8888", + Encryption: false, + ServerKey: "", + ServerCert: "", + AlwaysRemux: true, + Variant: conf.HLSVariant(gohlslib.MuxerVariantMPEGTS), + SegmentCount: 7, + SegmentDuration: conf.Duration(1 * time.Second), + PartDuration: conf.Duration(200 * time.Millisecond), + SegmentMaxSize: 50 * 1024 * 1024, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: pm, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + <-done +} + +func TestAuthError(t *testing.T) { + n := 0 + + s := &Server{ + Address: "127.0.0.1:8888", + Encryption: false, + ServerKey: "", + ServerCert: "", + AlwaysRemux: true, + Variant: conf.HLSVariant(gohlslib.MuxerVariantMPEGTS), + SegmentCount: 7, + SegmentDuration: conf.Duration(1 * time.Second), + PartDuration: conf.Duration(200 * time.Millisecond), + SegmentMaxSize: 50 * 1024 * 1024, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: &dummyPathManager{ + addReaderImpl: func(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + if req.AccessRequest.Credentials.User == "" && req.AccessRequest.Credentials.Pass == "" { + return nil, &auth.Error{AskCredentials: true, Wrapped: fmt.Errorf("auth error")} + } + + return nil, &auth.Error{Wrapped: fmt.Errorf("auth error")} + }, + }, + Parent: test.Logger(func(l logger.Level, s string, i ...any) { + if l == logger.Info { + if n == 1 { + require.Regexp(t, "failed to authenticate: auth error$", fmt.Sprintf(s, i...)) + } + n++ + } + }), + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8888/stream/index.m3u8", nil) + require.NoError(t, err) + + res, err := http.DefaultClient.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusUnauthorized, res.StatusCode) + require.Equal(t, `Basic realm="mediamtx"`, res.Header.Get("WWW-Authenticate")) + + req, err = http.NewRequest(http.MethodGet, "http://myuser:mypass@127.0.0.1:8888/stream/index.m3u8", nil) + require.NoError(t, err) + + res, err = http.DefaultClient.Do(req) + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusUnauthorized, res.StatusCode) + + require.Equal(t, 2, n) +} + +func TestAuthQueryPreservedAcrossRedirect(t *testing.T) { + s := &Server{ + Address: "127.0.0.1:8888", + Encryption: false, + ServerKey: "", + ServerCert: "", + AlwaysRemux: true, + Variant: conf.HLSVariant(gohlslib.MuxerVariantMPEGTS), + SegmentCount: 7, + SegmentDuration: conf.Duration(1 * time.Second), + PartDuration: conf.Duration(200 * time.Millisecond), + SegmentMaxSize: 50 * 1024 * 1024, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: &dummyPathManager{ + findPathConfImpl: func(_ defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) { + return nil, &auth.Error{AskCredentials: true, Wrapped: fmt.Errorf("auth error")} + }, + }, + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + client := &http.Client{ + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { + return http.ErrUseLastResponse + }, + } + + res, err := client.Get("http://127.0.0.1:8888/stream/index.m3u8?jwt=mytoken") + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusFound, res.StatusCode) + require.Equal(t, "/stream/index.m3u8?cookieCheck=1&jwt=mytoken", res.Header.Get("Location")) +} + +func TestServerNoSupportedCodecs(t *testing.T) { + for _, ca := range []string{ + "always remux off", + "always remux on", + } { + t.Run(ca, func(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.VP8{}}, + }}} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + pm := &dummyPathManager{ + addReaderImpl: func(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + return &defs.PathAddReaderRes{Path: &dummyPath{}, Stream: strm}, nil + }, + } + + s := &Server{ + Address: "127.0.0.1:8888", + AlwaysRemux: (ca == "always remux on"), + Variant: conf.HLSVariant(gohlslib.MuxerVariantMPEGTS), + SegmentCount: 7, + SegmentDuration: conf.Duration(1 * time.Second), + PartDuration: conf.Duration(200 * time.Millisecond), + SegmentMaxSize: 50 * 1024 * 1024, + TrustedProxies: conf.IPNetworks{}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: pm, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + client := &http.Client{ + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { + return http.ErrUseLastResponse + }, + } + + res, err := client.Get("http://127.0.0.1:8888/teststream/index.m3u8") + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusFound, res.StatusCode) + require.Equal(t, "/teststream/index.m3u8?cookieCheck=1", res.Header.Get("Location")) + + res, err = client.Get("http://127.0.0.1:8888/teststream/index.m3u8?cookieCheck=1") + require.NoError(t, err) + defer res.Body.Close() + + require.Equal(t, http.StatusInternalServerError, res.StatusCode) + require.Contains(t, res.Header.Get("Content-Type"), "application/json") + + byts, err := io.ReadAll(res.Body) + require.NoError(t, err) + + var payload defs.APIError + err = json.Unmarshal(byts, &payload) + require.NoError(t, err) + + if ca == "always remux off" { + require.Equal(t, defs.APIError{ + Status: defs.APIErrorStatusError, + Error: "muxer instance not available", + }, payload) + } else { + require.Equal(t, defs.APIError{ + Status: defs.APIErrorStatusError, + Error: "muxer is waiting to be created", + }, payload) + } + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/session.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/session.go new file mode 100644 index 0000000000000000000000000000000000000000..36ea3b1fe7a729f77db4157f8a2cb40180c8ee0c --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/hls/session.go @@ -0,0 +1,185 @@ +package hls + +import ( + "encoding/hex" + "net" + "slices" + "sync/atomic" + "time" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/hooks" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/httpp" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +type sessionServer interface { + logger.Writer + getMuxer(serverGetMuxerReq) (*muxer, error) +} + +type session struct { + remoteAddr string + pathName string + isCDN bool + externalCmdPool *externalcmd.Pool + pathManager serverPathManager + server sessionServer + + uuid uuid.UUID + secret uuid.UUID + ip string + created time.Time + query string + user string + userAgent string + lastRequestTime atomic.Int64 + bytesSent atomic.Uint64 + path defs.Path + stream *stream.Stream + muxer *muxer + reader *stream.Reader + onUnreadHook func() +} + +func (s *session) initialize(ctx *gin.Context) error { + s.uuid = uuid.New() + s.secret = uuid.New() + s.ip, _, _ = net.SplitHostPort(s.remoteAddr) + s.created = time.Now() + s.query = ctx.Request.URL.RawQuery + s.userAgent = ctx.Request.UserAgent() + s.lastRequestTime.Store(time.Now().UnixNano()) + + accessReq := defs.PathAccessRequest{ + Name: s.pathName, + Query: s.query, + Publish: false, + UserAgent: s.userAgent, + Proto: auth.ProtocolHLS, + ID: &s.uuid, + IP: net.ParseIP(ctx.ClientIP()), + } + if s.isCDN { + accessReq.SkipAuth = true + } else { + accessReq.Credentials = httpp.Credentials(ctx.Request) + } + + res, err := s.pathManager.AddReader(defs.PathAddReaderReq{ + Author: s, + AccessRequest: accessReq, + }) + if err != nil { + return err + } + + s.path = res.Path + s.stream = res.Stream + s.user = res.User + + muxer, err := s.server.getMuxer(serverGetMuxerReq{ + path: s.pathName, + create: true, + remoteAddr: s.remoteAddr, + query: s.query, + sourceOnDemand: res.Path.SafeConf().SourceOnDemand, + }) + if err != nil { + s.path.RemoveReader(defs.PathRemoveReaderReq{Author: s}) + return err + } + + s.muxer = muxer + + muxerFormats, err := s.muxer.addSession(s) + if err != nil { + s.path.RemoveReader(defs.PathRemoveReaderReq{Author: s}) + return err + } + + s.reader = &stream.Reader{ + Parent: s, + } + + // this is needed to increase stream outbound bytes for every HLS session, + // even if HLS sessions are not directly attached to streams (they are through muxers). + for _, medi := range res.Stream.OrigDesc.Medias { + for _, forma := range medi.Formats { + if slices.Contains(muxerFormats, forma) { + s.reader.OnData(medi, forma, func(_ *unit.Unit) error { + return nil + }) + } + } + } + + res.Stream.AddReader(s.reader) + + if s.isCDN { + s.Log(logger.Info, "created by %s (CDN), reading from muxer '%s'", s.remoteAddr, s.pathName) + } else { + s.Log(logger.Info, "created by %s, reading from muxer '%s'", s.remoteAddr, s.pathName) + } + + s.onUnreadHook = hooks.OnRead(hooks.OnReadParams{ + Logger: s, + ExternalCmdPool: s.externalCmdPool, + Conf: res.Path.SafeConf(), + ExternalCmdEnv: res.Path.ExternalCmdEnv(), + Reader: *s.APIReaderDescribe(), + Query: s.query, + }) + + return nil +} + +// called by path or path manager. +// not implemented since closing the Muxer is enough to close every associated session. +func (s *session) Close() { +} + +func (s *session) close2(err error) { + s.stream.RemoveReader(s.reader) + + s.path.RemoveReader(defs.PathRemoveReaderReq{Author: s}) + + s.onUnreadHook() + + s.Log(logger.Info, "closed: %v", err) +} + +// Log implements logger.Writer. +func (s *session) Log(level logger.Level, format string, args ...any) { + id := hex.EncodeToString(s.uuid[:4]) + s.server.Log(level, "[session %v] "+format, append([]any{id}, args...)...) +} + +func (s *session) apiItem() *defs.APIHLSSession { + outboundBytes := s.bytesSent.Load() + + return &defs.APIHLSSession{ + ID: s.uuid, + Created: s.created, + RemoteAddr: s.remoteAddr, + Path: s.pathName, + Query: s.query, + User: s.user, + UserAgent: s.userAgent, + IsCDN: s.isCDN, + OutboundBytes: outboundBytes, + } +} + +func (s *session) APIReaderDescribe() *defs.APIPathReader { + return &defs.APIPathReader{ + Type: defs.APIPathReaderTypeHLSSession, + ID: s.uuid.String(), + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/http_server.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/http_server.go new file mode 100644 index 0000000000000000000000000000000000000000..30d8a3fcde8dfa1b4ad7c5df44b99d5e44ac4810 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/http_server.go @@ -0,0 +1,338 @@ +package moq + +import ( + "crypto/sha256" + "crypto/tls" + _ "embed" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "net" + "net/http" + "path" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/httpp" + "github.com/bluenviron/mediamtx/internal/protocols/httpp3" +) + +//go:embed publish_index.html +var publishIndex []byte + +//go:embed read_index.html +var readIndex []byte + +//go:embed reader.js +var readerJS []byte + +//go:embed publisher.js +var publisherJS []byte + +const ( + moqtVersion = "moqt-18" + wtProtocolHeader = "WT-Protocol" + wtAvailableProtocolsHeader = "WT-Available-Protocols" +) + +type ginUnwrapper interface { + Unwrap() http.ResponseWriter +} + +func containsMoqtVersion(header string) bool { + for item := range strings.SplitSeq(header, ",") { + item = strings.TrimSpace(item) + if i := strings.IndexByte(item, ';'); i >= 0 { + item = item[:i] + } + item = strings.Trim(strings.TrimSpace(item), `"`) + if item == moqtVersion { + return true + } + } + return false +} + +func trailingSlashLocation(rawPath string, rawQuery string) string { + res := path.Clean(rawPath) + res = strings.TrimLeft(res, "/\\") + res = "/" + res + "/" + + if rawQuery != "" { + res += "?" + rawQuery + } + + return res +} + +func certFingerprint(cert *tls.Certificate) (string, error) { + if len(cert.Certificate) == 0 { + return "", fmt.Errorf("empty certificate") + } + sum := sha256.Sum256(cert.Certificate[0]) + return hex.EncodeToString(sum[:]), nil +} + +type httpServerParent interface { + newSession(req newSessionReq) newSessionRes + logger.Writer +} + +type httpServer struct { + http2Address string + http3Address string + serverCert string + serverKey string + allowOrigins []string + trustedProxies conf.IPNetworks + udpReadBufferSize uint + readTimeout conf.Duration + writeTimeout conf.Duration + pathManager serverPathManager + parent httpServerParent + + innerHTTP2 *httpp.Server + innerHTTP3 *httpp3.Server +} + +func (s *httpServer) initialize() error { + routerHTTP2 := gin.New() + routerHTTP2.SetTrustedProxies(s.trustedProxies.ToTrustedProxies()) //nolint:errcheck + routerHTTP2.Use(s.middlewarePreflightRequests) + routerHTTP2.Use(s.onRequestHTTPS2) + + s.innerHTTP2 = &httpp.Server{ + Address: s.http2Address, + AllowOrigins: s.allowOrigins, + ReadTimeout: time.Duration(s.readTimeout), + WriteTimeout: time.Duration(s.writeTimeout), + Encryption: true, + ServerKey: s.serverKey, + ServerCert: s.serverCert, + AllowAutoCert: true, + Handler: routerHTTP2, + Parent: s, + } + err := s.innerHTTP2.Initialize() + if err != nil { + return err + } + + routerHTTP3 := gin.New() + routerHTTP3.Use(s.onRequestHTTPS3) + + s.innerHTTP3 = &httpp3.Server{ + Address: s.http3Address, + UDPReadBufferSize: s.udpReadBufferSize, + EnableWebTransport: true, + Handler: routerHTTP3, + Parent: s, + } + err = s.innerHTTP3.Initialize() + if err != nil { + s.innerHTTP2.Close() + return err + } + + return nil +} + +// Log implements logger.Writer. +func (s *httpServer) Log(level logger.Level, format string, args ...any) { + s.parent.Log(level, format, args...) +} + +func (s *httpServer) close() { + s.innerHTTP3.Close() + s.innerHTTP2.Close() +} + +func (s *httpServer) middlewarePreflightRequests(ctx *gin.Context) { + if ctx.Request.Method == http.MethodOptions && + ctx.Request.Header.Get("Access-Control-Request-Method") != "" { + ctx.Header("Access-Control-Allow-Methods", "OPTIONS, GET, POST") + ctx.AbortWithStatus(http.StatusNoContent) + return + } +} + +func (s *httpServer) writeErrorNoLog(ctx *gin.Context, status int, err error) { + ctx.AbortWithStatusJSON(status, &defs.APIError{ + Status: defs.APIErrorStatusError, + Error: err.Error(), + }) +} + +func (s *httpServer) checkAuthOutsideSession(ctx *gin.Context, pathName string, publish bool) bool { + _, err := s.pathManager.FindPathConf(defs.PathFindPathConfReq{ + AccessRequest: defs.PathAccessRequest{ + Name: pathName, + Query: ctx.Request.URL.RawQuery, + Publish: publish, + Proto: auth.ProtocolMoQ, + Credentials: httpp.Credentials(ctx.Request), + IP: net.ParseIP(ctx.ClientIP()), + }, + }) + if err != nil { + if terr, ok := errors.AsType[*auth.Error](err); ok { + if terr.AskCredentials { + ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`) + s.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return false + } + + s.Log(logger.Info, "connection %v failed to authenticate: %v", httpp.RemoteAddr(ctx), terr.Wrapped) + + s.writeErrorNoLog(ctx, http.StatusUnauthorized, fmt.Errorf("authentication error")) + return false + } + + s.writeErrorNoLog(ctx, http.StatusInternalServerError, err) + return false + } + + return true +} + +func (s *httpServer) onPage(ctx *gin.Context, pathName string, publish bool) { + if !s.checkAuthOutsideSession(ctx, pathName, publish) { + return + } + + ctx.Header("Content-Type", "text/html") + ctx.Writer.WriteHeader(http.StatusOK) + + if publish { + ctx.Writer.Write(publishIndex) + } else { + ctx.Writer.Write(readIndex) + } +} + +func (s *httpServer) onAuthMirror(ctx *gin.Context) { + if !strings.HasPrefix(ctx.Request.Header.Get("Authorization"), "Basic ") { + s.writeErrorNoLog(ctx, http.StatusBadRequest, fmt.Errorf("missing basic auth header")) + return + } + + creds, err := base64.StdEncoding.DecodeString(ctx.Request.Header.Get("Authorization")[len("Basic "):]) + if err != nil { + s.writeErrorNoLog(ctx, http.StatusBadRequest, fmt.Errorf("invalid basic auth header: %w", err)) + return + } + + parts := strings.SplitN(string(creds), ":", 2) + if len(parts) != 2 { + s.writeErrorNoLog(ctx, http.StatusBadRequest, fmt.Errorf("invalid basic auth header: missing colon")) + return + } + + ctx.JSON(http.StatusOK, struct { + User string `json:"user"` + Pass string `json:"pass"` + }{ + User: parts[0], + Pass: parts[1], + }) +} + +func (s *httpServer) onFingerprint(ctx *gin.Context) { + fp, err := certFingerprint(s.innerHTTP3.Certificate()) + if err != nil { + s.writeErrorNoLog(ctx, http.StatusInternalServerError, err) + return + } + + ctx.String(http.StatusOK, fp) +} + +func (s *httpServer) onRequestHTTPS2(ctx *gin.Context) { + if ctx.Request.Method == http.MethodGet { + switch { + case strings.HasSuffix(ctx.Request.URL.Path, "/authmirror"): + s.onAuthMirror(ctx) + + case strings.HasSuffix(ctx.Request.URL.Path, "/fingerprint"): + s.onFingerprint(ctx) + + case strings.HasSuffix(ctx.Request.URL.Path, "/reader.js"): + ctx.Header("Cache-Control", "max-age=3600") + ctx.Header("Content-Type", "application/javascript") + ctx.Writer.WriteHeader(http.StatusOK) + ctx.Writer.Write(readerJS) + + case strings.HasSuffix(ctx.Request.URL.Path, "/publisher.js"): + ctx.Header("Cache-Control", "max-age=3600") + ctx.Header("Content-Type", "application/javascript") + ctx.Writer.WriteHeader(http.StatusOK) + ctx.Writer.Write(publisherJS) + + case ctx.Request.URL.Path == "/favicon.ico": + + case len(ctx.Request.URL.Path) >= 2: + switch { + case len(ctx.Request.URL.Path) > len("/publish") && strings.HasSuffix(ctx.Request.URL.Path, "/publish"): + s.onPage(ctx, ctx.Request.URL.Path[1:len(ctx.Request.URL.Path)-len("/publish")], true) + + case ctx.Request.URL.Path[len(ctx.Request.URL.Path)-1] != '/': + ctx.Header("Location", trailingSlashLocation(ctx.Request.URL.Path, ctx.Request.URL.RawQuery)) + ctx.Writer.WriteHeader(http.StatusFound) + + default: + s.onPage(ctx, ctx.Request.URL.Path[1:len(ctx.Request.URL.Path)-1], false) + } + } + } +} + +func (s *httpServer) onRequestHTTPS3(ctx *gin.Context) { + if ctx.Request.Method != http.MethodConnect || + !strings.HasSuffix(ctx.Request.URL.Path, "/moq") || + len(ctx.Request.URL.Path) <= len("/moq") { + return + } + + pathName := ctx.Request.URL.Path[1 : len(ctx.Request.URL.Path)-len("/moq")] + if len(pathName) == 0 { + return + } + + if offered := ctx.Request.Header.Get(wtAvailableProtocolsHeader); offered != "" { + if !containsMoqtVersion(offered) { + s.writeErrorNoLog(ctx, http.StatusBadRequest, + fmt.Errorf("no supported MoQ version in %s", wtAvailableProtocolsHeader)) + return + } + } + + w := ctx.Writer.(ginUnwrapper).Unwrap() + + if offered := ctx.Request.Header.Get(wtAvailableProtocolsHeader); offered != "" { + w.Header().Set(wtProtocolHeader, `"`+moqtVersion+`"`) + } + + wt, err := s.innerHTTP3.Upgrade(w, ctx.Request) + if err != nil { + s.writeErrorNoLog(ctx, http.StatusBadRequest, fmt.Errorf("webtransport upgrade failed: %w", err)) + return + } + + res := s.parent.newSession(newSessionReq{ + pathName: pathName, + query: ctx.Request.URL.RawQuery, + userAgent: ctx.Request.Header.Get("User-Agent"), + wt: wt, + }) + if res.err != nil { + wt.CloseWithError(0, res.err.Error()) //nolint:errcheck + return + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/inbound_track.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/inbound_track.go new file mode 100644 index 0000000000000000000000000000000000000000..92f24ea3e6272a146cbf0032ab60f50d226f728c --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/inbound_track.go @@ -0,0 +1,38 @@ +package moq + +import ( + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/moq/reorderer" + "github.com/bluenviron/mediamtx/internal/protocols/moq/subgroup" +) + +type inboundTrack struct { + onSubGroup func(sg *subgroup.SubGroup) error + parent logger.Writer + + reorderer *reorderer.Reorderer +} + +func (t *inboundTrack) initialize() { + t.reorderer = &reorderer.Reorderer{ + MaxReordered: maxReorderedSubGroups, + Parent: t.parent, + } + t.reorderer.Initialize() +} + +func (t *inboundTrack) push(sg *subgroup.SubGroup) error { + sgs, err := t.reorderer.Push(sg) + if err != nil { + return err + } + + for _, s := range sgs { + err = t.onSubGroup(s) + if err != nil { + return err + } + } + + return nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/publish_index.html b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/publish_index.html new file mode 100644 index 0000000000000000000000000000000000000000..ae5644eb982bd5b74b7eb4ba6a50a7aaf1f3d070 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/publish_index.html @@ -0,0 +1,480 @@ + + + + + + + + + + + +
+
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ +
+ +
+
+
+ +
+ +
+
+ +
+ + + + diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/publisher.js b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/publisher.js new file mode 100644 index 0000000000000000000000000000000000000000..2b4c292c309c0484e709c15fe0c8141c32c8f418 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/publisher.js @@ -0,0 +1,822 @@ +"use strict"; + +/** + * @callback OnError + * @param {string} err - error. + */ + +/** + * @callback OnConnected + */ + +/** + * @typedef Conf + * @type {object} + * @property {string} fingerprintUrl - URL to fetch the server certificate fingerprint. + * @property {string} url - WebTransport URL to connect to. + * @property {string} user - username. + * @property {string} pass - password. + * @property {string} token - token. + * @property {MediaStream} stream - media stream to publish. + * @property {string} videoCodec - video codec string (e.g., "avc3.640028"). + * @property {number} videoBitrate - video bitrate in kbps. + * @property {number} videoFramerate - video framerate. + * @property {number} videoKeyframeInterval - video keyframe interval in seconds. + * @property {number} videoWidth - video width. + * @property {number} videoHeight - video height. + * @property {string} audioCodec - audio codec string (e.g., "opus"). + * @property {number} audioBitrate - audio bitrate in kbps. + * @property {OnError} onError - called when there's an error. + * @property {OnConnected} onConnected - called when publishing has started. + */ + +/** Media-over-QUIC publisher. */ +class MediaMTXMoQPublisher { + static #RETRY_PAUSE = 2000; + + static #MOQT_VERSION = "moqt-18"; + + static #SETUP_TYPE = 0x2f00n; + static #MSG_PUBLISH = 0x1dn; + static #MSG_REQUEST_OK = 0x07n; + static #MSG_REQUEST_ERROR = 0x05n; + static #SUBGROUP_TYPE = 0x30n; + static #SUBGROUP_TYPE_WITH_PROPS = 0x31n; + static #PARAM_AUTH_TOKEN = 0x03n; + static #USE_VALUE = 3n; + + static #NAMESPACE = "stream"; + + #conf; + #state = "running"; + #restartTimeout = null; + #wt = null; + #fingerprint = null; + #uniStreamsQueue = []; + #uniStreamsListeners = []; + #videoEncoder = null; + #audioEncoder = null; + + /** + * Create a MediaMTXMoQPublisher. + * @param {Conf} conf - configuration. + */ + constructor(conf) { + this.#conf = conf; + this.#start(); + } + + /** + * Close the publisher and all its resources. + */ + close() { + this.#state = "closed"; + this.#cleanup(); + if (this.#restartTimeout !== null) { + clearTimeout(this.#restartTimeout); + } + } + + #cleanup() { + if (this.#wt !== null) { + this.#wt.close(); + this.#wt = null; + } + + if (this.#videoEncoder !== null) { + try { + this.#videoEncoder.close(); + } catch (e) {} + this.#videoEncoder = null; + } + + if (this.#audioEncoder !== null) { + try { + this.#audioEncoder.close(); + } catch (e) {} + this.#audioEncoder = null; + } + + this.#uniStreamsQueue = []; + for (const w of this.#uniStreamsListeners) { + w.reject(new Error("restarting")); + } + this.#uniStreamsListeners = []; + } + + #handleError(err) { + if (this.#state === "running") { + this.#state = "restarting"; + + this.#cleanup(); + + this.#restartTimeout = window.setTimeout( + () => this.#restart(), + MediaMTXMoQPublisher.#RETRY_PAUSE, + ); + + if (this.#conf.onError !== undefined) { + this.#conf.onError(`${err}, retrying in some seconds`); + } + } + } + + #restart() { + this.#restartTimeout = null; + this.#state = "running"; + this.#start(); + } + + #start() { + this.#fetchFingerprint() + .then(() => this.#connect()) + .then(() => this.#setup()) + .then(() => this.#publishAllTracks()) + .catch((err) => this.#handleError(err.message)); + } + + async #fetchFingerprint() { + const hex = await fetch(this.#conf.fingerprintUrl, { + headers: this.#authHeader(), + }).then((r) => r.text()); + this.#fingerprint = new Uint8Array(hex.length / 2); + for (let i = 0; i < this.#fingerprint.length; i++) + this.#fingerprint[i] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); + } + + #authHeader() { + if (this.#conf.user !== undefined && this.#conf.user !== "") { + const credentials = btoa(`${this.#conf.user}:${this.#conf.pass}`); + return { Authorization: `Basic ${credentials}` }; + } + if (this.#conf.token !== undefined && this.#conf.token !== "") { + return { Authorization: `Bearer ${this.#conf.token}` }; + } + return {}; + } + + #encodeAuthParams() { + let tokenValue = null; + if (this.#conf.user !== undefined && this.#conf.user !== "") { + const credentials = btoa(`${this.#conf.user}:${this.#conf.pass}`); + tokenValue = new TextEncoder().encode(`Basic ${credentials}`); + } else if (this.#conf.token !== undefined && this.#conf.token !== "") { + tokenValue = new TextEncoder().encode(`Bearer ${this.#conf.token}`); + } + + if (tokenValue === null) { + return MediaMTXMoQPublisher.#encodeVarint(0); + } + + const tokenStruct = MediaMTXMoQPublisher.#concat( + MediaMTXMoQPublisher.#encodeVarint(MediaMTXMoQPublisher.#USE_VALUE), + MediaMTXMoQPublisher.#encodeVarint(0), // Token Type (out-of-band) + tokenValue, + ); + + const param = MediaMTXMoQPublisher.#concat( + MediaMTXMoQPublisher.#encodeVarint( + MediaMTXMoQPublisher.#PARAM_AUTH_TOKEN, + ), + MediaMTXMoQPublisher.#encodeVarint(tokenStruct.length), + tokenStruct, + ); + return MediaMTXMoQPublisher.#concat( + MediaMTXMoQPublisher.#encodeVarint(1), + param, + ); + } + + async #connect() { + this.#wt = new WebTransport(this.#conf.url, { + serverCertificateHashes: [ + { algorithm: "sha-256", value: this.#fingerprint.buffer }, + ], + protocols: [MediaMTXMoQPublisher.#MOQT_VERSION], + }); + await this.#wt.ready; + console.log("connected"); + + this.#wt.closed + .then(() => this.#handleError("connection closed")) + .catch((err) => this.#handleError(err.message)); + + this.#acceptUniStreams().catch((err) => this.#handleError(err.message)); + } + + async #acceptUniStreams() { + const reader = this.#wt.incomingUnidirectionalStreams.getReader(); + for (;;) { + const { value, done } = await reader.read(); + if (done) { + break; + } + if (this.#uniStreamsListeners.length > 0) { + this.#uniStreamsListeners.shift().resolve(value); + } else { + this.#uniStreamsQueue.push(value); + } + } + } + + #nextUni() { + return new Promise((resolve, reject) => { + if (this.#uniStreamsQueue.length > 0) { + resolve(this.#uniStreamsQueue.shift()); + } else { + this.#uniStreamsListeners.push({ resolve, reject }); + } + }); + } + + async #setup() { + const tx = await this.#wt.createUnidirectionalStream(); + const w = tx.getWriter(); + await w.write( + MediaMTXMoQPublisher.#encodeVarint(MediaMTXMoQPublisher.#SETUP_TYPE), + ); + await w.write(new Uint8Array([0x00, 0x00])); + w.releaseLock(); + + const rx = new MediaMTXMoQPublisher.#StreamReader(await this.#nextUni()); + const t = await rx.readVarint(); + if (t !== MediaMTXMoQPublisher.#SETUP_TYPE) { + throw new Error("unexpected setup type 0x" + t.toString(16)); + } + await rx.readBytes(await rx.readU16()); + console.log("setup ok"); + } + + #buildCatalog() { + const tracks = []; + let trackIdx = 0; + + const videoTracks = this.#conf.stream.getVideoTracks(); + if (videoTracks.length > 0) { + tracks.push({ + name: String(trackIdx), + packaging: "loc", + isLive: true, + codec: this.#conf.videoCodec, + clockrate: 90000, + }); + trackIdx++; + } + + const audioTracks = this.#conf.stream.getAudioTracks(); + if (audioTracks.length > 0) { + const audioSettings = audioTracks[0].getSettings(); + tracks.push({ + name: String(trackIdx), + packaging: "loc", + isLive: true, + codec: this.#conf.audioCodec, + clockrate: audioSettings.sampleRate || 48000, + samplerate: audioSettings.sampleRate || 48000, + channels: audioSettings.channelCount || 1, + }); + } + + return { version: 1, tracks }; + } + + async #publishAllTracks() { + const catalog = this.#buildCatalog(); + const catalogJSON = JSON.stringify(catalog); + console.log("catalog:", catalog); + + await Promise.all([ + this.#publish(0n, ".catalog", 0n), + this.#writeCatalog(catalogJSON, 0n), + ]); + + await Promise.all( + catalog.tracks.map((track, idx) => + this.#publish(BigInt((idx + 1) * 2), track.name, BigInt(idx + 1)), + ), + ); + + if (this.#conf.onConnected !== undefined) { + this.#conf.onConnected(); + } + + const promises = []; + let alias = 1n; + + const videoTracks = this.#conf.stream.getVideoTracks(); + if (videoTracks.length > 0) { + promises.push(this.#encodeVideo(videoTracks[0], alias)); + alias++; + } + + const audioTracks = this.#conf.stream.getAudioTracks(); + if (audioTracks.length > 0) { + promises.push(this.#encodeAudio(audioTracks[0], alias)); + alias++; + } + + await Promise.all(promises); + } + + async #publish(requestId, trackName, trackAlias) { + const bidi = await this.#wt.createBidirectionalStream(); + const w = bidi.writable.getWriter(); + const r = new MediaMTXMoQPublisher.#StreamReader(bidi.readable); + + await w.write( + MediaMTXMoQPublisher.#encodeMsg( + MediaMTXMoQPublisher.#MSG_PUBLISH, + MediaMTXMoQPublisher.#concat( + MediaMTXMoQPublisher.#encodeVarint(requestId), + MediaMTXMoQPublisher.#encodeNamespace( + MediaMTXMoQPublisher.#NAMESPACE, + ), + MediaMTXMoQPublisher.#encodeString(trackName), + MediaMTXMoQPublisher.#encodeVarint(trackAlias), + this.#encodeAuthParams(), + ), + ), + ); + w.releaseLock(); + + const t = await r.readVarint(); + const payload = await r.readBytes(await r.readU16()); + switch (t) { + case MediaMTXMoQPublisher.#MSG_REQUEST_ERROR: + throw new Error(MediaMTXMoQPublisher.#requestErrorReason(payload)); + case MediaMTXMoQPublisher.#MSG_REQUEST_OK: + break; + default: + throw new Error("expected REQUEST_OK (0x7), got 0x" + t.toString(16)); + } + console.log("REQUEST_OK for track", trackName); + } + + async #encodeVideo(mediaTrack, trackAlias) { + const isAvc = this.#conf.videoCodec.startsWith("avc3"); + const isHvc = this.#conf.videoCodec.startsWith("hev1"); + const processor = new MediaStreamTrackProcessor({ track: mediaTrack }); + const frameReader = processor.readable.getReader(); + + let groupId = 0n; + let vps = null; + let sps = null; + let pps = null; + + this.#videoEncoder = new VideoEncoder({ + output: (chunk, metadata) => { + if (isAvc && metadata?.decoderConfig?.description !== undefined) { + [sps, pps] = MediaMTXMoQPublisher.#parseAvcC( + metadata.decoderConfig.description, + ); + } else if ( + isHvc && + metadata?.decoderConfig?.description !== undefined + ) { + [vps, sps, pps] = MediaMTXMoQPublisher.#parseHvcC( + metadata.decoderConfig.description, + ); + } + + let data = new Uint8Array(chunk.byteLength); + chunk.copyTo(data); + + if (isAvc && chunk.type === "key" && sps !== null && pps !== null) { + data = MediaMTXMoQPublisher.#concat( + MediaMTXMoQPublisher.#avccLen(sps.length), + sps, + MediaMTXMoQPublisher.#avccLen(pps.length), + pps, + data, + ); + } else if ( + isHvc && + chunk.type === "key" && + vps !== null && + sps !== null && + pps !== null + ) { + data = MediaMTXMoQPublisher.#concat( + MediaMTXMoQPublisher.#avccLen(vps.length), + vps, + MediaMTXMoQPublisher.#avccLen(sps.length), + sps, + MediaMTXMoQPublisher.#avccLen(pps.length), + pps, + data, + ); + } + + this.#writeData( + trackAlias, + groupId++, + chunk.timestamp, + 90000, + data, + ).catch((err) => this.#handleError(err.message)); + }, + error: (err) => console.error(err.message), + }); + + const videoConfig = { + codec: this.#conf.videoCodec, + bitrate: this.#conf.videoBitrate * 1000, + framerate: this.#conf.videoFramerate, + width: this.#conf.videoWidth, + height: this.#conf.videoHeight, + latencyMode: "realtime", + }; + this.#videoEncoder.configure(videoConfig); + + let frameCount = 0n; + + for (;;) { + const { value: frame, done } = await frameReader.read(); + if (done) break; + if (this.#state !== "running") { + frame.close(); + break; + } + this.#videoEncoder.encode(frame, { + keyFrame: frameCount % BigInt(this.#conf.videoKeyframeInterval) === 0n, + }); + frame.close(); + frameCount++; + } + } + + async #encodeAudio(mediaTrack, trackAlias) { + const processor = new MediaStreamTrackProcessor({ track: mediaTrack }); + const frameReader = processor.readable.getReader(); + const audioSettings = mediaTrack.getSettings(); + const sampleRate = audioSettings.sampleRate || 48000; + const channelCount = audioSettings.channelCount || 1; + + let groupId = 0n; + + this.#audioEncoder = new AudioEncoder({ + output: (chunk) => { + const data = new Uint8Array(chunk.byteLength); + chunk.copyTo(data); + this.#writeData( + trackAlias, + groupId++, + chunk.timestamp, + sampleRate, + data, + ).catch((err) => this.#handleError(err.message)); + }, + error: (err) => console.error(err.message), + }); + + this.#audioEncoder.configure({ + codec: this.#conf.audioCodec, + sampleRate: sampleRate, + numberOfChannels: channelCount, + bitrate: (this.#conf.audioBitrate || 128) * 1000, + }); + + for (;;) { + const { value: frame, done } = await frameReader.read(); + if (done) break; + if (this.#state !== "running" || this.#audioEncoder === null) { + frame.close(); + break; + } + this.#audioEncoder.encode(frame); + frame.close(); + } + } + + async #writeCatalog(catalogJSON, trackAlias) { + const payload = new TextEncoder().encode(catalogJSON); + const uniStream = await this.#wt.createUnidirectionalStream(); + const w = uniStream.getWriter(); + await w.write( + MediaMTXMoQPublisher.#concat( + MediaMTXMoQPublisher.#encodeVarint(MediaMTXMoQPublisher.#SUBGROUP_TYPE), + MediaMTXMoQPublisher.#encodeVarint(trackAlias), + MediaMTXMoQPublisher.#encodeVarint(0), + MediaMTXMoQPublisher.#encodeVarint(0), + MediaMTXMoQPublisher.#encodeVarint(payload.length), + payload, + new Uint8Array([0x00, 0x00, 0x03]), + ), + ); + await w.close(); + console.log("catalog sent"); + } + + async #writeData(trackAlias, groupId, timestamp, clockrate, payload) { + const tsType = MediaMTXMoQPublisher.#encodeVarint(0x06n); + const tsValue = MediaMTXMoQPublisher.#encodeVarint( + BigInt(Math.round((timestamp * clockrate) / 1000000)), + ); + const kv = MediaMTXMoQPublisher.#concat(tsType, tsValue); + const propsBlock = MediaMTXMoQPublisher.#concat( + MediaMTXMoQPublisher.#encodeVarint(kv.length), + kv, + ); + + const uniStream = await this.#wt.createUnidirectionalStream(); + const w = uniStream.getWriter(); + await w.write( + MediaMTXMoQPublisher.#concat( + MediaMTXMoQPublisher.#encodeVarint( + MediaMTXMoQPublisher.#SUBGROUP_TYPE_WITH_PROPS, + ), + MediaMTXMoQPublisher.#encodeVarint(trackAlias), + MediaMTXMoQPublisher.#encodeVarint(groupId), + MediaMTXMoQPublisher.#encodeVarint(0), + propsBlock, + MediaMTXMoQPublisher.#encodeVarint(payload.length), + payload, + new Uint8Array([0x00, 0x00, 0x00, 0x03]), + ), + ); + await w.close(); + } + + static #readVarintFromBytes(bytes, offset) { + const b = bytes[offset]; + if ((b & 0x80) === 0) return { value: BigInt(b), size: 1 }; + if ((b & 0xc0) === 0x80) + return { value: BigInt(((b & 0x3f) << 8) | bytes[offset + 1]), size: 2 }; + if ((b & 0xe0) === 0xc0) + return { + value: BigInt( + ((b & 0x1f) << 16) | (bytes[offset + 1] << 8) | bytes[offset + 2], + ), + size: 3, + }; + if ((b & 0xf0) === 0xe0) + return { + value: BigInt( + ((b & 0x0f) << 24) | + (bytes[offset + 1] << 16) | + (bytes[offset + 2] << 8) | + bytes[offset + 3], + ), + size: 4, + }; + throw new Error("varint too long"); + } + + static #requestErrorReason(payload) { + let off = 0; + let v = MediaMTXMoQPublisher.#readVarintFromBytes(payload, off); + off += v.size; // skip error code + v = MediaMTXMoQPublisher.#readVarintFromBytes(payload, off); + off += v.size; // skip retry interval + v = MediaMTXMoQPublisher.#readVarintFromBytes(payload, off); + off += v.size; // reason length + return new TextDecoder().decode(payload.slice(off, off + Number(v.value))); + } + + static #avccLen(l) { + return new Uint8Array([ + (l >> 24) & 0xff, + (l >> 16) & 0xff, + (l >> 8) & 0xff, + l & 0xff, + ]); + } + + static #parseAvcC(description) { + let sps = null; + let pps = null; + const desc = new Uint8Array(description); + let off = 5; + const numSPS = desc[off++] & 0x1f; + for (let i = 0; i < numSPS; i++) { + const len = (desc[off] << 8) | desc[off + 1]; + off += 2; + sps = desc.slice(off, off + len); + off += len; + } + const numPPS = desc[off++]; + for (let i = 0; i < numPPS; i++) { + const len = (desc[off] << 8) | desc[off + 1]; + off += 2; + pps = desc.slice(off, off + len); + off += len; + } + return [sps, pps]; + } + + static #parseHvcC(description) { + let vps = null; + let sps = null; + let pps = null; + const desc = new Uint8Array(description); + let off = 22; // skip 22-byte fixed header + const numArrays = desc[off++]; + for (let i = 0; i < numArrays; i++) { + const naluType = desc[off++] & 0x3f; + const numNalus = (desc[off] << 8) | desc[off + 1]; + off += 2; + for (let j = 0; j < numNalus; j++) { + const len = (desc[off] << 8) | desc[off + 1]; + off += 2; + const nalu = desc.slice(off, off + len); + off += len; + if (naluType === 32) vps = nalu; + else if (naluType === 33) sps = nalu; + else if (naluType === 34) pps = nalu; + } + } + return [vps, sps, pps]; + } + + static #encodeVarint(value) { + const v = BigInt(value); + if (v < 128n) { + return new Uint8Array([Number(v)]); + } + if (v < 16384n) { + return new Uint8Array([0x80 | Number(v >> 8n), Number(v & 0xffn)]); + } + if (v < 2097152n) { + return new Uint8Array([ + 0xc0 | Number(v >> 16n), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + if (v < 268435456n) { + return new Uint8Array([ + 0xe0 | Number(v >> 24n), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + if (v < 34359738368n) { + return new Uint8Array([ + 0xf0 | Number(v >> 32n), + Number((v >> 24n) & 0xffn), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + if (v < 4398046511104n) { + return new Uint8Array([ + 0xf8 | Number(v >> 40n), + Number((v >> 32n) & 0xffn), + Number((v >> 24n) & 0xffn), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + if (v < 562949953421312n) { + return new Uint8Array([ + 0xfc | Number(v >> 48n), + Number((v >> 40n) & 0xffn), + Number((v >> 32n) & 0xffn), + Number((v >> 24n) & 0xffn), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + if (v < 72057594037927936n) { + return new Uint8Array([ + 0xfe, + Number((v >> 48n) & 0xffn), + Number((v >> 40n) & 0xffn), + Number((v >> 32n) & 0xffn), + Number((v >> 24n) & 0xffn), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + return new Uint8Array([ + 0xff, + Number((v >> 56n) & 0xffn), + Number((v >> 48n) & 0xffn), + Number((v >> 40n) & 0xffn), + Number((v >> 32n) & 0xffn), + Number((v >> 24n) & 0xffn), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + + static #concat(...arrays) { + const total = arrays.reduce((n, a) => n + a.length, 0); + const out = new Uint8Array(total); + let pos = 0; + for (const a of arrays) { + out.set(a, pos); + pos += a.length; + } + return out; + } + + static #encodeString(s) { + const b = new TextEncoder().encode(s); + return MediaMTXMoQPublisher.#concat( + MediaMTXMoQPublisher.#encodeVarint(b.length), + b, + ); + } + + static #encodeNamespace(parts) { + let b = MediaMTXMoQPublisher.#encodeVarint(parts.length); + for (const p of parts) + b = MediaMTXMoQPublisher.#concat( + b, + MediaMTXMoQPublisher.#encodeString(p), + ); + return b; + } + + static #encodeMsg(type, payload) { + return MediaMTXMoQPublisher.#concat( + MediaMTXMoQPublisher.#encodeVarint(type), + new Uint8Array([(payload.length >> 8) & 0xff, payload.length & 0xff]), + payload, + ); + } + + static #StreamReader = class { + #reader = null; + #buf = new Uint8Array(0); + + constructor(src) { + this.#reader = src.getReader(); + } + + async #fill() { + if (!this.#reader) { + throw new Error("stream ended"); + } + const { value, done } = await this.#reader.read(); + if (done) { + throw new Error("stream ended"); + } + const next = new Uint8Array(this.#buf.length + value.length); + next.set(this.#buf); + next.set(value, this.#buf.length); + this.#buf = next; + } + + async readBytes(n) { + while (this.#buf.length < n) await this.#fill(); + const out = this.#buf.slice(0, n); + this.#buf = this.#buf.slice(n); + return out; + } + + async readVarint() { + while (this.#buf.length < 1) await this.#fill(); + const b = this.#buf[0]; + let size; + if ((b & 0x80) === 0) { + size = 1; + } else if ((b & 0xc0) === 0x80) { + size = 2; + } else if ((b & 0xe0) === 0xc0) { + size = 3; + } else if ((b & 0xf0) === 0xe0) { + size = 4; + } else if ((b & 0xf8) === 0xf0) { + size = 5; + } else { + throw new Error("unsupported varint: 0x" + b.toString(16)); + } + const d = await this.readBytes(size); + switch (size) { + case 1: + return BigInt(d[0]); + case 2: + return BigInt(((d[0] & 0x3f) << 8) | d[1]); + case 3: + return BigInt(((d[0] & 0x1f) << 16) | (d[1] << 8) | d[2]); + case 4: + return BigInt( + ((d[0] & 0x0f) << 24) | (d[1] << 16) | (d[2] << 8) | d[3], + ); + case 5: + return ( + (BigInt(d[0] & 0x07) << 32n) | + (BigInt(d[1]) << 24n) | + (BigInt(d[2]) << 16n) | + (BigInt(d[3]) << 8n) | + BigInt(d[4]) + ); + } + } + + async readU16() { + const d = await this.readBytes(2); + return (d[0] << 8) | d[1]; + } + }; +} + +window.MediaMTXMoQPublisher = MediaMTXMoQPublisher; diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/read_index.html b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/read_index.html new file mode 100644 index 0000000000000000000000000000000000000000..7528e756c718695ba876c8288c216a1f2231b7bb --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/read_index.html @@ -0,0 +1,111 @@ + + + + + + + + + +
+
+
+ + + + diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/reader.js b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/reader.js new file mode 100644 index 0000000000000000000000000000000000000000..578906532979c7468db9ebddfaf0533f4f17cbd7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/reader.js @@ -0,0 +1,1263 @@ +"use strict"; + +/** + * @callback OnError + * @param {string} err - error. + */ + +/** + * @callback OnSubscribed + * @param {boolean} hasAudio - whether an audio track was subscribed. + */ + +/** + * @callback OnAudioMuted + * @param {boolean} muted - whether the audio is muted. + */ + +/** + * @typedef Conf + * @type {object} + * @property {string} fingerprintUrl - URL to fetch the server certificate fingerprint. + * @property {string} url - WebTransport URL to connect to. + * @property {string} user - username. + * @property {string} pass - password. + * @property {string} token - token. + * @property {HTMLElement} videoElement - element where the video canvas will be appended. + * @property {OnError} onError - called when there's an error. + * @property {OnSubscribed} onSubscribed - called when track subscription is successful. + * @property {OnAudioMuted} onAudioMuted - called when audio is muted or unmuted. + */ + +/** Media-over-QUIC reader. */ +class MediaMTXMoQReader { + static #RETRY_PAUSE = 2000; + + static #MOQT_VERSION = "moqt-18"; + + static #SETUP_TYPE = 0x2f00n; + static #MSG_SUBSCRIBE = 0x03n; + static #MSG_SUBSCRIBE_OK = 0x04n; + static #MSG_REQUEST_ERROR = 0x05n; + static #SUBGROUP_TYPE_MASK = 0x90n; + static #SUBGROUP_TYPE_BITS = 0x10n; + static #SUBGROUP_PROPS_BIT = 0x01n; + static #PARAM_AUTH_TOKEN = 0x03n; + static #USE_VALUE = 3n; + + static #NAMESPACE = "stream"; + static #VIDEO_REQUEST_ID = BigInt(10); + static #AUDIO_REQUEST_ID = BigInt(11); + + static #MAX_VIDEO_REORDERED_SUBGROUPS = 30; + static #MAX_VIDEO_FRAMES_IN_DECODER = 10; + + static #MAX_AUDIO_REORDERED_SUBGROUPS = 50; + static #MAX_AUDIO_FRAMES_IN_DECODER = 10; + static #AUDIO_START_LATENCY_SECS = 0.0; + static #AUDIO_MAX_LATENCY_SECS = 0.5; + + #conf; + #state = "running"; + #restartTimeout = null; + #wt = null; + #fingerprint = null; + #catalog = null; + #uniStreamsQueue = []; + #uniStreamsListeners = []; + #videoTrack = null; + #videoParams = null; + #videoCanvas = null; + #videoDecoder = null; + #videoReorderer = null; + #audioTrack = null; + #audioCtx = null; + #audioDecoder = null; + #audioReorderer = null; + + /** + * Create a MediaMTXMoQReader. + * @param {Conf} conf - configuration. + */ + constructor(conf) { + this.#conf = conf; + this.#start(); + } + + /** + * Unmute the reader. + */ + unmute() { + if (this.#audioCtx !== null) { + this.#audioCtx.resume().then(() => { + if (this.#conf.onAudioMuted !== undefined) { + this.#conf.onAudioMuted(false); + } + }); + } + } + + #start() { + this.#fetchFingerprint() + .then(() => this.#connect()) + .then(() => this.#setup()) + .then(() => this.#subscribeCatalog()) + .then(() => this.#subscribeAllTracks()) + .then(() => this.#drainDataStreams()) + .catch((err) => this.#handleError(err.message)); + } + + /** @param {string} err */ + #handleError(err) { + if (this.#state === "running") { + this.#state = "restarting"; + + if (this.#wt !== null) { + this.#wt.close(); + this.#wt = null; + } + + if (this.#videoDecoder !== null) { + try { + this.#videoDecoder.close(); + } catch (e) {} + this.#videoDecoder = null; + } + + if (this.#videoCanvas !== null) { + this.#videoCanvas.remove(); + this.#videoCanvas = null; + } + + if (this.#audioDecoder !== null) { + try { + this.#audioDecoder.close(); + } catch (e) {} + this.#audioDecoder = null; + } + + if (this.#audioCtx !== null) { + this.#audioCtx.close(); + this.#audioCtx = null; + } + + this.#uniStreamsQueue = []; + for (const w of this.#uniStreamsListeners) { + w.reject(new Error("restarting")); + } + this.#uniStreamsListeners = []; + this.#videoTrack = null; + this.#videoParams = null; + this.#videoReorderer = null; + this.#audioTrack = null; + this.#audioReorderer = null; + + this.#restartTimeout = window.setTimeout( + () => this.#restart(), + MediaMTXMoQReader.#RETRY_PAUSE, + ); + + if (this.#conf.onAudioMuted !== undefined) { + this.#conf.onAudioMuted(false); + } + + if (this.#conf.onError !== undefined) { + this.#conf.onError(`${err}, retrying in some seconds`); + } + } + } + + #restart() { + this.#restartTimeout = null; + this.#state = "running"; + this.#start(); + } + + async #fetchFingerprint() { + const hex = await fetch(this.#conf.fingerprintUrl, { + headers: this.#authHeader(), + }).then((r) => r.text()); + this.#fingerprint = new Uint8Array(hex.length / 2); + for (let i = 0; i < this.#fingerprint.length; i++) + this.#fingerprint[i] = parseInt(hex.slice(2 * i, 2 * i + 2), 16); + } + + #authHeader() { + if (this.#conf.user !== undefined && this.#conf.user !== "") { + const credentials = btoa(`${this.#conf.user}:${this.#conf.pass}`); + return { Authorization: `Basic ${credentials}` }; + } + if (this.#conf.token !== undefined && this.#conf.token !== "") { + return { Authorization: `Bearer ${this.#conf.token}` }; + } + return {}; + } + + #encodeAuthParams() { + let tokenValue = null; + if (this.#conf.user !== undefined && this.#conf.user !== "") { + const credentials = btoa(`${this.#conf.user}:${this.#conf.pass}`); + tokenValue = new TextEncoder().encode(`Basic ${credentials}`); + } else if (this.#conf.token !== undefined && this.#conf.token !== "") { + tokenValue = new TextEncoder().encode(`Bearer ${this.#conf.token}`); + } + + if (tokenValue === null) { + return MediaMTXMoQReader.#encodeVarint(0); + } + + const tokenStruct = MediaMTXMoQReader.#concat( + MediaMTXMoQReader.#encodeVarint(MediaMTXMoQReader.#USE_VALUE), + MediaMTXMoQReader.#encodeVarint(0), // Token Type (out-of-band) + tokenValue, + ); + + const param = MediaMTXMoQReader.#concat( + MediaMTXMoQReader.#encodeVarint(MediaMTXMoQReader.#PARAM_AUTH_TOKEN), + MediaMTXMoQReader.#encodeVarint(tokenStruct.length), + tokenStruct, + ); + return MediaMTXMoQReader.#concat(MediaMTXMoQReader.#encodeVarint(1), param); + } + + async #connect() { + this.#wt = new WebTransport(this.#conf.url, { + serverCertificateHashes: [ + { algorithm: "sha-256", value: this.#fingerprint.buffer }, + ], + protocols: [MediaMTXMoQReader.#MOQT_VERSION], + }); + await this.#wt.ready; + console.log("connected"); + + this.#wt.closed + .then(() => this.#handleError("connection closed")) + .catch((err) => this.#handleError(err.message)); + + this.#acceptUniStreams().catch((err) => this.#handleError(err.message)); + } + + async #acceptUniStreams() { + const reader = this.#wt.incomingUnidirectionalStreams.getReader(); + for (;;) { + const { value, done } = await reader.read(); + if (done) { + break; + } + if (this.#uniStreamsListeners.length > 0) { + this.#uniStreamsListeners.shift().resolve(value); + } else { + this.#uniStreamsQueue.push(value); + } + } + } + + #nextUni() { + return new Promise((resolve, reject) => { + if (this.#uniStreamsQueue.length > 0) { + resolve(this.#uniStreamsQueue.shift()); + } else { + this.#uniStreamsListeners.push({ resolve, reject }); + } + }); + } + + async #setup() { + const tx = await this.#wt.createUnidirectionalStream(); + const w = tx.getWriter(); + await w.write( + MediaMTXMoQReader.#encodeVarint(MediaMTXMoQReader.#SETUP_TYPE), + ); + await w.write(new Uint8Array([0x00, 0x00])); + w.releaseLock(); + + const rx = new MediaMTXMoQReader.#StreamReader(await this.#nextUni()); + const t = await rx.readVarint(); + if (t !== MediaMTXMoQReader.#SETUP_TYPE) { + throw new Error("unexpected setup type 0x" + t.toString(16)); + } + await rx.readBytes(await rx.readU16()); + console.log("setup ok"); + } + + async #subscribeCatalog() { + const bidi = await this.#wt.createBidirectionalStream(); + const w = bidi.writable.getWriter(); + const r = new MediaMTXMoQReader.#StreamReader(bidi.readable); + + await w.write( + MediaMTXMoQReader.#encodeMsg( + MediaMTXMoQReader.#MSG_SUBSCRIBE, + MediaMTXMoQReader.#concat( + MediaMTXMoQReader.#encodeVarint(0), + MediaMTXMoQReader.#encodeNamespace(MediaMTXMoQReader.#NAMESPACE), + MediaMTXMoQReader.#encodeString(".catalog"), + this.#encodeAuthParams(), + ), + ), + ); + w.releaseLock(); + + const t = await r.readVarint(); + switch (t) { + case MediaMTXMoQReader.#MSG_REQUEST_ERROR: { + const errPayload = await r.readBytes(await r.readU16()); + throw new Error(MediaMTXMoQReader.#requestErrorReason(errPayload)); + } + case MediaMTXMoQReader.#MSG_SUBSCRIBE_OK: + break; + default: + throw new Error("expected SUBSCRIBE_OK, got 0x" + t.toString(16)); + } + await r.readBytes(await r.readU16()); + + const { data } = await this.#readSubGroup(await this.#nextUni()); + this.#catalog = JSON.parse(new TextDecoder().decode(data)); + + console.log("catalog:", this.#catalog); + } + + static #readVarintFromBytes(bytes, offset) { + const b = bytes[offset]; + if ((b & 0x80) === 0) return { value: BigInt(b), size: 1 }; + if ((b & 0xc0) === 0x80) + return { value: BigInt(((b & 0x3f) << 8) | bytes[offset + 1]), size: 2 }; + if ((b & 0xe0) === 0xc0) + return { + value: BigInt( + ((b & 0x1f) << 16) | (bytes[offset + 1] << 8) | bytes[offset + 2], + ), + size: 3, + }; + if ((b & 0xf0) === 0xe0) + return { + value: BigInt( + ((b & 0x0f) << 24) | + (bytes[offset + 1] << 16) | + (bytes[offset + 2] << 8) | + bytes[offset + 3], + ), + size: 4, + }; + if ((b & 0xf8) === 0xf0) + return { + value: + (BigInt(b & 0x07) << 32n) | + (BigInt(bytes[offset + 1]) << 24n) | + (BigInt(bytes[offset + 2]) << 16n) | + (BigInt(bytes[offset + 3]) << 8n) | + BigInt(bytes[offset + 4]), + size: 5, + }; + if ((b & 0xfc) === 0xf8) + return { + value: + (BigInt(b & 0x03) << 40n) | + (BigInt(bytes[offset + 1]) << 32n) | + (BigInt(bytes[offset + 2]) << 24n) | + (BigInt(bytes[offset + 3]) << 16n) | + (BigInt(bytes[offset + 4]) << 8n) | + BigInt(bytes[offset + 5]), + size: 6, + }; + if ((b & 0xfe) === 0xfc) + return { + value: + (BigInt(b & 0x01) << 48n) | + (BigInt(bytes[offset + 1]) << 40n) | + (BigInt(bytes[offset + 2]) << 32n) | + (BigInt(bytes[offset + 3]) << 24n) | + (BigInt(bytes[offset + 4]) << 16n) | + (BigInt(bytes[offset + 5]) << 8n) | + BigInt(bytes[offset + 6]), + size: 7, + }; + if (b === 0xfe) + return { + value: + (BigInt(bytes[offset + 1]) << 48n) | + (BigInt(bytes[offset + 2]) << 40n) | + (BigInt(bytes[offset + 3]) << 32n) | + (BigInt(bytes[offset + 4]) << 24n) | + (BigInt(bytes[offset + 5]) << 16n) | + (BigInt(bytes[offset + 6]) << 8n) | + BigInt(bytes[offset + 7]), + size: 8, + }; + return { + value: + (BigInt(bytes[offset + 1]) << 56n) | + (BigInt(bytes[offset + 2]) << 48n) | + (BigInt(bytes[offset + 3]) << 40n) | + (BigInt(bytes[offset + 4]) << 32n) | + (BigInt(bytes[offset + 5]) << 24n) | + (BigInt(bytes[offset + 6]) << 16n) | + (BigInt(bytes[offset + 7]) << 8n) | + BigInt(bytes[offset + 8]), + size: 9, + }; + } + + static #requestErrorReason(payload) { + let off = 0; + let v = MediaMTXMoQReader.#readVarintFromBytes(payload, off); + off += v.size; + v = MediaMTXMoQReader.#readVarintFromBytes(payload, off); + off += v.size; + v = MediaMTXMoQReader.#readVarintFromBytes(payload, off); + off += v.size; + return new TextDecoder().decode(payload.slice(off, off + Number(v.value))); + } + + async #readSubGroup(readable) { + const r = new MediaMTXMoQReader.#StreamReader(readable); + const streamType = await r.readVarint(); + if ( + (streamType & MediaMTXMoQReader.#SUBGROUP_TYPE_MASK) !== + MediaMTXMoQReader.#SUBGROUP_TYPE_BITS + ) { + throw new Error("not a subgroup stream"); + } + const withProps = + (streamType & MediaMTXMoQReader.#SUBGROUP_PROPS_BIT) !== 0n; + + const trackAlias = await r.readVarint(); + const groupId = await r.readVarint(); + + await r.readVarint(); // idDelta + if (withProps) { + const propsLen = await r.readVarint(); + if (propsLen > 0n) await r.readBytes(Number(propsLen)); + } + const len = await r.readVarint(); + if (len === 0n) { + throw new Error("first object has zero length"); + } + const data = await r.readBytes(Number(len)); + + await r.readVarint(); // idDelta + if (withProps) { + const propsLen = await r.readVarint(); + if (propsLen > 0n) await r.readBytes(Number(propsLen)); + } + const endLen = await r.readVarint(); + if (endLen !== 0n) { + throw new Error("end chunk has non-zero length"); + } + + return { data, trackAlias, groupId }; + } + + async #subscribeAllTracks() { + const promises = []; + + for (let i = 0; i < this.#catalog.tracks.length; i++) { + const track = this.#catalog.tracks[i]; + + if (/^(avc3|hev1|av01|vp09|vp8)/.test(track.codec)) { + if (this.#videoTrack === null) { + this.#videoTrack = track; + promises.push( + this.#subscribeTrack(MediaMTXMoQReader.#VIDEO_REQUEST_ID, track), + ); + } + } else if (/^(opus|mp4a|flac|pcm)/.test(track.codec)) { + if (this.#audioTrack === null) { + this.#audioTrack = track; + promises.push( + this.#subscribeTrack(MediaMTXMoQReader.#AUDIO_REQUEST_ID, track), + ); + } + } else { + throw new Error("unsupported codec: " + track.codec); + } + } + + await Promise.all(promises); + + if (this.#conf.onSubscribed !== undefined) { + this.#conf.onSubscribed(this.#audioTrack !== null); + } + } + + async #subscribeTrack(requestId, track) { + const bidi = await this.#wt.createBidirectionalStream(); + const w = bidi.writable.getWriter(); + const r = new MediaMTXMoQReader.#StreamReader(bidi.readable); + + await w.write( + MediaMTXMoQReader.#encodeMsg( + MediaMTXMoQReader.#MSG_SUBSCRIBE, + MediaMTXMoQReader.#concat( + MediaMTXMoQReader.#encodeVarint(requestId), + MediaMTXMoQReader.#encodeNamespace(MediaMTXMoQReader.#NAMESPACE), + MediaMTXMoQReader.#encodeString(track.name), + this.#encodeAuthParams(), + ), + ), + ); + w.releaseLock(); + + const t = await r.readVarint(); + if (t !== MediaMTXMoQReader.#MSG_SUBSCRIBE_OK) { + throw new Error("expected SUBSCRIBE_OK, got 0x" + t.toString(16)); + } + await r.readBytes(await r.readU16()); + + if (requestId === MediaMTXMoQReader.#VIDEO_REQUEST_ID) { + this.#videoCanvas = document.createElement("canvas"); + this.#conf.videoElement.appendChild(this.#videoCanvas); + + const ctxGL = this.#videoCanvas.getContext("webgl2", { + desynchronized: true, + powerPreference: "high-performance", + }); + + let ctx2D = null; + if (ctxGL === null) { + console.log("video renderer: 2D canvas"); + + ctx2D = this.#videoCanvas.getContext("2d"); + } else { + console.log("video renderer: WebGL2"); + + const vert = ctxGL.createShader(ctxGL.VERTEX_SHADER); + ctxGL.shaderSource( + vert, + `#version 300 es + in vec2 a_pos; + out vec2 v_uv; + void main() { + v_uv = vec2(a_pos.x * 0.5 + 0.5, 0.5 - a_pos.y * 0.5); + gl_Position = vec4(a_pos, 0, 1); + } + `, + ); + ctxGL.compileShader(vert); + + const frag = ctxGL.createShader(ctxGL.FRAGMENT_SHADER); + ctxGL.shaderSource( + frag, + `#version 300 es + precision mediump float; + uniform sampler2D u_tex; + in vec2 v_uv; + out vec4 color; + void main() { color = texture(u_tex, v_uv); } + `, + ); + ctxGL.compileShader(frag); + + const prog = ctxGL.createProgram(); + ctxGL.attachShader(prog, vert); + ctxGL.attachShader(prog, frag); + ctxGL.linkProgram(prog); + ctxGL.useProgram(prog); + + const buf = ctxGL.createBuffer(); + ctxGL.bindBuffer(ctxGL.ARRAY_BUFFER, buf); + ctxGL.bufferData( + ctxGL.ARRAY_BUFFER, + new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), + ctxGL.STATIC_DRAW, + ); + const loc = ctxGL.getAttribLocation(prog, "a_pos"); + ctxGL.enableVertexAttribArray(loc); + ctxGL.vertexAttribPointer(loc, 2, ctxGL.FLOAT, false, 0, 0); + + const tex = ctxGL.createTexture(); + ctxGL.bindTexture(ctxGL.TEXTURE_2D, tex); + ctxGL.texParameteri( + ctxGL.TEXTURE_2D, + ctxGL.TEXTURE_MIN_FILTER, + ctxGL.LINEAR, + ); + ctxGL.texParameteri( + ctxGL.TEXTURE_2D, + ctxGL.TEXTURE_MAG_FILTER, + ctxGL.LINEAR, + ); + ctxGL.texParameteri( + ctxGL.TEXTURE_2D, + ctxGL.TEXTURE_WRAP_S, + ctxGL.CLAMP_TO_EDGE, + ); + ctxGL.texParameteri( + ctxGL.TEXTURE_2D, + ctxGL.TEXTURE_WRAP_T, + ctxGL.CLAMP_TO_EDGE, + ); + ctxGL.uniform1i(ctxGL.getUniformLocation(prog, "u_tex"), 0); + } + + this.#videoDecoder = new VideoDecoder({ + output: (frame) => { + if ( + this.#videoCanvas.width !== frame.displayWidth || + this.#videoCanvas.height !== frame.displayHeight + ) { + this.#videoCanvas.width = frame.displayWidth; + this.#videoCanvas.height = frame.displayHeight; + + if (ctxGL !== null) { + ctxGL.viewport( + 0, + 0, + this.#videoCanvas.width, + this.#videoCanvas.height, + ); + } + } + + if (ctxGL !== null) { + ctxGL.texImage2D( + ctxGL.TEXTURE_2D, + 0, + ctxGL.RGBA, + ctxGL.RGBA, + ctxGL.UNSIGNED_BYTE, + frame, + ); + ctxGL.drawArrays(ctxGL.TRIANGLE_STRIP, 0, 4); + } else { + ctx2D.drawImage(frame, 0, 0); + } + + frame.close(); + }, + error: (err) => console.error(err.message), + }); + + const config = { + codec: track.codec, + optimizeForLatency: true, + }; + + const supported = await VideoDecoder.isConfigSupported(config); + if (!supported.supported) { + throw new Error( + "the browser you are using does not support video codec " + + track.codec, + ); + } + + this.#videoDecoder.configure(config); + + this.#videoReorderer = new MediaMTXMoQReader.#Reorderer( + MediaMTXMoQReader.#MAX_VIDEO_REORDERED_SUBGROUPS, + ); + } else { + this.#audioCtx = new AudioContext(); + + if ( + this.#audioCtx.state === "suspended" && + this.#conf.onAudioMuted !== undefined + ) { + this.#conf.onAudioMuted(true); + } + + let playbackTime = null; + + this.#audioDecoder = new AudioDecoder({ + output: async (data) => { + try { + if (this.#audioCtx.state === "running") { + const buf = this.#audioCtx.createBuffer( + data.numberOfChannels, + data.numberOfFrames, + data.sampleRate, + ); + + for (let ch = 0; ch < data.numberOfChannels; ch++) { + data.copyTo(buf.getChannelData(ch), { + planeIndex: ch, + format: "f32-planar", + }); + } + + const src = this.#audioCtx.createBufferSource(); + src.buffer = buf; + src.connect(this.#audioCtx.destination); + + if ( + playbackTime === null || + playbackTime < this.#audioCtx.currentTime || + playbackTime > + this.#audioCtx.currentTime + + MediaMTXMoQReader.#AUDIO_MAX_LATENCY_SECS + ) { + if (playbackTime !== null) { + console.info( + "audio desync detected (currentTime=" + + this.#audioCtx.currentTime.toFixed(3) + + " playbackTime=" + + playbackTime.toFixed(3) + + ") - resetting playback time", + ); + } + playbackTime = + this.#audioCtx.currentTime + + MediaMTXMoQReader.#AUDIO_START_LATENCY_SECS; + } + + src.start(playbackTime); + + playbackTime += buf.duration; + } + } finally { + data.close(); + } + }, + error: (err) => console.error(err.message), + }); + + const config = { + codec: track.codec, + sampleRate: track.samplerate, + numberOfChannels: track.channels, + }; + if (track.initData) { + config.description = MediaMTXMoQReader.#base64ToBuffer(track.initData); + } + + this.#audioDecoder.configure(config); + + this.#audioReorderer = new MediaMTXMoQReader.#Reorderer( + MediaMTXMoQReader.#MAX_AUDIO_REORDERED_SUBGROUPS, + ); + } + + console.log("subscribed track " + track.name + " (" + track.codec + ")"); + } + + async #drainDataStreams() { + for (;;) { + const stream = await this.#nextUni(); + this.#onDataTrack(stream).catch((err) => this.#handleError(err.message)); + } + } + + async #onDataTrack(readable) { + const { data, trackAlias, groupId } = await this.#readSubGroup(readable); + if (data.length === 0) { + return; + } + + if (trackAlias === MediaMTXMoQReader.#VIDEO_REQUEST_ID) { + const sgs = this.#videoReorderer.push(data, groupId); + + for (const sg of sgs) { + this.#decodeVideo(sg.data, sg.groupId); + } + } else { + const sgs = this.#audioReorderer.push(data, groupId); + + for (const sg of sgs) { + this.#decodeAudio(sg.data, sg.groupId); + } + } + } + + #decodeVideo(data, groupId) { + // this happens when the screen is off + if ( + this.#videoDecoder.decodeQueueSize >= + MediaMTXMoQReader.#MAX_VIDEO_FRAMES_IN_DECODER + ) { + console.log("skipping video frame, decode queue is full"); + return; + } + + if (/^(avc3)/.test(this.#videoTrack.codec)) { + let sps = null; + let pps = null; + for (const nalu of MediaMTXMoQReader.#splitAVCC(data)) { + const naluType = nalu[0] & 0x1f; + if (naluType === 7) { + sps = nalu; + } else if (naluType === 8) { + pps = nalu; + } + } + + if ( + sps !== null && + pps !== null && + (this.#videoParams === null || + !MediaMTXMoQReader.#bytesEqual(this.#videoParams.sps, sps) || + !MediaMTXMoQReader.#bytesEqual(this.#videoParams.pps, pps)) + ) { + this.#videoParams = { sps, pps }; + this.#videoDecoder.configure({ + codec: this.#videoTrack.codec, + optimizeForLatency: true, + description: MediaMTXMoQReader.#makeAvcC(sps, pps), + }); + console.log("video params updated"); + } + } else if (/^(hev1)/.test(this.#videoTrack.codec)) { + let vps = null; + let sps = null; + let pps = null; + for (const nalu of MediaMTXMoQReader.#splitAVCC(data)) { + const naluType = (nalu[0] >> 1) & 0x3f; + if (naluType === 32) { + vps = nalu; + } else if (naluType === 33) { + sps = nalu; + } else if (naluType === 34) { + pps = nalu; + } + } + + if ( + vps !== null && + sps !== null && + pps !== null && + (this.#videoParams === null || + !MediaMTXMoQReader.#bytesEqual(this.#videoParams.vps, vps) || + !MediaMTXMoQReader.#bytesEqual(this.#videoParams.sps, sps) || + !MediaMTXMoQReader.#bytesEqual(this.#videoParams.pps, pps)) + ) { + this.#videoParams = { vps, sps, pps }; + this.#videoDecoder.configure({ + codec: this.#videoTrack.codec, + optimizeForLatency: true, + description: MediaMTXMoQReader.#makeHvcC(vps, sps, pps), + }); + console.log("video params updated"); + } + } + + const timestamp = performance.now() * 1000; + this.#videoDecoder.decode( + new EncodedVideoChunk({ type: "key", timestamp, data }), + ); + } + + #decodeAudio(data, groupId) { + // this happens when the screen is off + if ( + this.#audioDecoder.decodeQueueSize >= + MediaMTXMoQReader.#MAX_AUDIO_FRAMES_IN_DECODER + ) { + console.log("skipping audio frame, decode queue is full"); + return; + } + + const timestamp = Number(groupId); + this.#audioDecoder.decode( + new EncodedAudioChunk({ type: "key", timestamp, data }), + ); + } + + static #makeAvcC(sps, pps) { + const avcC = new Uint8Array(11 + sps.length + pps.length); + let off = 0; + avcC[off++] = 0x01; // configurationVersion + avcC[off++] = sps[1]; // AVCProfileIndication + avcC[off++] = sps[2]; // profile_compatibility + avcC[off++] = sps[3]; // AVCLevelIndication + avcC[off++] = 0xff; // reserved + lengthSizeMinusOne=3 + avcC[off++] = 0xe1; // reserved + numSPS=1 + avcC[off++] = (sps.length >> 8) & 0xff; + avcC[off++] = sps.length & 0xff; + avcC.set(sps, off); + off += sps.length; + avcC[off++] = 0x01; // numPPS=1 + avcC[off++] = (pps.length >> 8) & 0xff; + avcC[off++] = pps.length & 0xff; + avcC.set(pps, off); + return avcC; + } + + static #makeHvcC(vps, sps, pps) { + // Extract profile/level from SPS NALU: + // bytes 0-1: NALU header + // byte 2: sps_vps_id(4) | sps_max_sub_layers_minus1(3) | sps_temporal_id_nesting_flag(1) + // bytes 3-14: profile_tier_level general portion (12 bytes) + const numTemporalLayers = ((sps[2] >> 1) & 0x7) + 1; + const temporalIdNested = sps[2] & 0x1; + const arrays = [ + { type: 32, nalu: vps }, // VPS + { type: 33, nalu: sps }, // SPS + { type: 34, nalu: pps }, // PPS + ]; + const totalSize = 23 + arrays.reduce((n, a) => n + 5 + a.nalu.length, 0); + const hvcC = new Uint8Array(totalSize); + let off = 0; + hvcC[off++] = 0x01; // configurationVersion + hvcC[off++] = sps[3]; // general_profile_space(2)|general_tier_flag(1)|general_profile_idc(5) + hvcC[off++] = sps[4]; // general_profile_compatibility_flags + hvcC[off++] = sps[5]; + hvcC[off++] = sps[6]; + hvcC[off++] = sps[7]; + hvcC[off++] = sps[8]; // general_constraint_indicator_flags + hvcC[off++] = sps[9]; + hvcC[off++] = sps[10]; + hvcC[off++] = sps[11]; + hvcC[off++] = sps[12]; + hvcC[off++] = sps[13]; + hvcC[off++] = sps[14]; // general_level_idc + hvcC[off++] = 0xf0; // reserved(4) | min_spatial_segmentation_idc[11:8] + hvcC[off++] = 0x00; // min_spatial_segmentation_idc[7:0] + hvcC[off++] = 0xfc; // reserved(6) | parallelismType(2) + hvcC[off++] = 0xfd; // reserved(6) | chromaFormat=1 (4:2:0) + hvcC[off++] = 0xf8; // reserved(5) | bitDepthLumaMinus8=0 + hvcC[off++] = 0xf8; // reserved(5) | bitDepthChromaMinus8=0 + hvcC[off++] = 0x00; // avgFrameRate + hvcC[off++] = 0x00; + // constantFrameRate(2)=0 | numTemporalLayers(3) | temporalIdNested(1) | lengthSizeMinusOne(2)=3 + hvcC[off++] = + ((numTemporalLayers & 0x7) << 3) | ((temporalIdNested & 0x1) << 2) | 0x03; + hvcC[off++] = arrays.length; // numOfArrays + for (const { type, nalu } of arrays) { + hvcC[off++] = 0x80 | (type & 0x3f); // array_completeness=1 | reserved | NAL_unit_type + hvcC[off++] = 0x00; // numNalus high + hvcC[off++] = 0x01; // numNalus low = 1 + hvcC[off++] = (nalu.length >> 8) & 0xff; + hvcC[off++] = nalu.length & 0xff; + hvcC.set(nalu, off); + off += nalu.length; + } + return hvcC; + } + + static #encodeVarint(value) { + const v = BigInt(value); + if (v < 128n) { + return new Uint8Array([Number(v)]); + } + if (v < 16384n) { + return new Uint8Array([0x80 | Number(v >> 8n), Number(v & 0xffn)]); + } + if (v < 2097152n) { + return new Uint8Array([ + 0xc0 | Number(v >> 16n), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + if (v < 268435456n) { + return new Uint8Array([ + 0xe0 | Number(v >> 24n), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + if (v < 34359738368n) { + return new Uint8Array([ + 0xf0 | Number(v >> 32n), + Number((v >> 24n) & 0xffn), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + if (v < 4398046511104n) { + return new Uint8Array([ + 0xf8 | Number(v >> 40n), + Number((v >> 32n) & 0xffn), + Number((v >> 24n) & 0xffn), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + if (v < 562949953421312n) { + return new Uint8Array([ + 0xfc | Number(v >> 48n), + Number((v >> 40n) & 0xffn), + Number((v >> 32n) & 0xffn), + Number((v >> 24n) & 0xffn), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + if (v < 72057594037927936n) { + return new Uint8Array([ + 0xfe, + Number((v >> 48n) & 0xffn), + Number((v >> 40n) & 0xffn), + Number((v >> 32n) & 0xffn), + Number((v >> 24n) & 0xffn), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + return new Uint8Array([ + 0xff, + Number((v >> 56n) & 0xffn), + Number((v >> 48n) & 0xffn), + Number((v >> 40n) & 0xffn), + Number((v >> 32n) & 0xffn), + Number((v >> 24n) & 0xffn), + Number((v >> 16n) & 0xffn), + Number((v >> 8n) & 0xffn), + Number(v & 0xffn), + ]); + } + + static #concat(...arrays) { + const total = arrays.reduce((n, a) => n + a.length, 0); + const out = new Uint8Array(total); + let pos = 0; + for (const a of arrays) { + out.set(a, pos); + pos += a.length; + } + return out; + } + + static #encodeString(s) { + const b = new TextEncoder().encode(s); + return MediaMTXMoQReader.#concat( + MediaMTXMoQReader.#encodeVarint(b.length), + b, + ); + } + + static #encodeNamespace(parts) { + let b = MediaMTXMoQReader.#encodeVarint(parts.length); + for (const p of parts) + b = MediaMTXMoQReader.#concat(b, MediaMTXMoQReader.#encodeString(p)); + return b; + } + + static #encodeMsg(type, payload) { + return MediaMTXMoQReader.#concat( + MediaMTXMoQReader.#encodeVarint(type), + new Uint8Array([(payload.length >> 8) & 0xff, payload.length & 0xff]), + payload, + ); + } + + static #splitAVCC(data) { + const nalus = []; + let i = 0; + while (i + 4 <= data.length) { + const len = + (data[i] << 24) | + (data[i + 1] << 16) | + (data[i + 2] << 8) | + data[i + 3]; + i += 4; + if (len <= 0 || i + len > data.length) break; + nalus.push(data.slice(i, i + len)); + i += len; + } + return nalus; + } + + static #base64ToBuffer(b64) { + const bin = atob(b64); + const buf = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i); + return buf; + } + + static #bytesEqual(a, b) { + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + } + + static #Reorderer = class { + #maxReorderered; + #curGroupId = null; + #pending = new Map(); + + constructor(maxReorderered) { + this.#maxReorderered = maxReorderered; + } + + push(data, groupId) { + if (this.#curGroupId === null) { + this.#curGroupId = groupId; + return [{ data, groupId }]; + } else if (groupId <= this.#curGroupId) { + console.log("skipping out-of-order subgroup"); + } else if ( + groupId === this.#curGroupId + 1n && + this.#pending.size === 0 + ) { + this.#curGroupId = groupId; + return [{ data, groupId }]; + } else { + this.#pending.set(groupId, data); + + const diff = groupId - this.#curGroupId; + + let countInRange = 0n; + for (const id of this.#pending.keys()) { + if (id <= groupId) { + countInRange++; + } + } + + if (countInRange === diff) { + return this.#flushUpTo(groupId); + } else if (this.#pending.size > this.#maxReorderered) { + console.log("too many reordered subgroups, flushing"); + return this.#flushUpTo(groupId); + } + } + return []; + } + + // Flushes pending items from curGroupId+1 through maxGroupId (skipping + // gaps), advances curGroupId, then drains any further consecutive items + // already in pending so they are not stranded. + #flushUpTo(maxGroupId) { + const out = []; + for (let i = this.#curGroupId + 1n; i <= maxGroupId; i++) { + const d = this.#pending.get(i); + if (d !== undefined) { + out.push({ data: d, groupId: i }); + this.#pending.delete(i); + } + } + this.#curGroupId = maxGroupId; + for (;;) { + const next = this.#pending.get(this.#curGroupId + 1n); + if (next === undefined) break; + this.#curGroupId += 1n; + out.push({ data: next, groupId: this.#curGroupId }); + this.#pending.delete(this.#curGroupId); + } + return out; + } + }; + + static #StreamReader = class { + #reader = null; + #buf = new Uint8Array(0); + + constructor(src) { + this.#reader = src.getReader(); + } + + async #fill() { + if (!this.#reader) { + throw new Error("stream ended"); + } + const { value, done } = await this.#reader.read(); + if (done) { + throw new Error("stream ended"); + } + const next = new Uint8Array(this.#buf.length + value.length); + next.set(this.#buf); + next.set(value, this.#buf.length); + this.#buf = next; + } + + async readBytes(n) { + while (this.#buf.length < n) await this.#fill(); + const out = this.#buf.slice(0, n); + this.#buf = this.#buf.slice(n); + return out; + } + + async readVarint() { + while (this.#buf.length < 1) await this.#fill(); + const b = this.#buf[0]; + let size; + if ((b & 0x80) === 0) { + size = 1; + } else if ((b & 0xc0) === 0x80) { + size = 2; + } else if ((b & 0xe0) === 0xc0) { + size = 3; + } else if ((b & 0xf0) === 0xe0) { + size = 4; + } else if ((b & 0xf8) === 0xf0) { + size = 5; + } else if ((b & 0xfc) === 0xf8) { + size = 6; + } else if ((b & 0xfe) === 0xfc) { + size = 7; + } else if (b === 0xfe) { + size = 8; + } else { + size = 9; // b === 0xff + } + const d = await this.readBytes(size); + switch (size) { + case 1: + return BigInt(d[0]); + case 2: + return BigInt(((d[0] & 0x3f) << 8) | d[1]); + case 3: + return BigInt(((d[0] & 0x1f) << 16) | (d[1] << 8) | d[2]); + case 4: + return BigInt( + ((d[0] & 0x0f) << 24) | (d[1] << 16) | (d[2] << 8) | d[3], + ); + case 5: + return ( + (BigInt(d[0] & 0x07) << 32n) | + (BigInt(d[1]) << 24n) | + (BigInt(d[2]) << 16n) | + (BigInt(d[3]) << 8n) | + BigInt(d[4]) + ); + case 6: + return ( + (BigInt(d[0] & 0x03) << 40n) | + (BigInt(d[1]) << 32n) | + (BigInt(d[2]) << 24n) | + (BigInt(d[3]) << 16n) | + (BigInt(d[4]) << 8n) | + BigInt(d[5]) + ); + case 7: + return ( + (BigInt(d[0] & 0x01) << 48n) | + (BigInt(d[1]) << 40n) | + (BigInt(d[2]) << 32n) | + (BigInt(d[3]) << 24n) | + (BigInt(d[4]) << 16n) | + (BigInt(d[5]) << 8n) | + BigInt(d[6]) + ); + case 8: + return ( + (BigInt(d[1]) << 48n) | + (BigInt(d[2]) << 40n) | + (BigInt(d[3]) << 32n) | + (BigInt(d[4]) << 24n) | + (BigInt(d[5]) << 16n) | + (BigInt(d[6]) << 8n) | + BigInt(d[7]) + ); + default: // 9 + return ( + (BigInt(d[1]) << 56n) | + (BigInt(d[2]) << 48n) | + (BigInt(d[3]) << 40n) | + (BigInt(d[4]) << 32n) | + (BigInt(d[5]) << 24n) | + (BigInt(d[6]) << 16n) | + (BigInt(d[7]) << 8n) | + BigInt(d[8]) + ); + } + } + + async readU16() { + const d = await this.readBytes(2); + return (d[0] << 8) | d[1]; + } + }; +} + +window.MediaMTXMoQReader = MediaMTXMoQReader; diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/server.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/server.go new file mode 100644 index 0000000000000000000000000000000000000000..4cc95bc6dff1638dd24ecba1018eb86cac094826 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/server.go @@ -0,0 +1,304 @@ +// Package moq contains a Media over QUIC server. +package moq + +import ( + "context" + "errors" + "fmt" + "reflect" + "sync" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/google/uuid" + "github.com/quic-go/webtransport-go" +) + +// ErrSessionNotFound is returned when a session is not found. +var ErrSessionNotFound = errors.New("session not found") + +func interfaceIsEmpty(i any) bool { + return reflect.ValueOf(i).Kind() != reflect.Pointer || reflect.ValueOf(i).IsNil() +} + +type serverPathManager interface { + FindPathConf(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) + AddReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) + AddPublisher(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) +} + +type newSessionRes struct { + sx *session + err error +} + +type newSessionReq struct { + pathName string + query string + userAgent string + wt *webtransport.Session + res chan newSessionRes +} + +type serverAPISessionsListRes struct { + data *defs.APIMoQSessionList +} + +type serverAPISessionsListReq struct { + res chan serverAPISessionsListRes +} + +type serverAPISessionsGetRes struct { + data *defs.APIMoQSession + err error +} + +type serverAPISessionsGetReq struct { + uuid uuid.UUID + res chan serverAPISessionsGetRes +} + +type serverAPISessionsKickRes struct { + err error +} + +type serverAPISessionsKickReq struct { + uuid uuid.UUID + res chan serverAPISessionsKickRes +} + +type serverParent interface { + logger.Writer +} + +type serverMetrics interface { + SetMoQServer(defs.APIMoQServer) +} + +// Server is a Media over QUIC server. +type Server struct { + HTTP2Address string + HTTP3Address string + ServerKey string + ServerCert string + AllowOrigins []string + UDPReadBufferSize uint + TrustedProxies conf.IPNetworks + ReadTimeout conf.Duration + WriteTimeout conf.Duration + PathManager serverPathManager + Metrics serverMetrics + Parent serverParent + + ctx context.Context + ctxCancel context.CancelFunc + httpServer *httpServer + sessions map[*session]struct{} + + chNewSession chan newSessionReq + chCloseSession chan *session + chAPISessionsList chan serverAPISessionsListReq + chAPISessionsGet chan serverAPISessionsGetReq + chAPISessionsKick chan serverAPISessionsKickReq + done chan struct{} +} + +// Initialize initializes the server. +func (s *Server) Initialize() error { + s.httpServer = &httpServer{ + http2Address: s.HTTP2Address, + http3Address: s.HTTP3Address, + serverKey: s.ServerKey, + serverCert: s.ServerCert, + allowOrigins: s.AllowOrigins, + trustedProxies: s.TrustedProxies, + udpReadBufferSize: s.UDPReadBufferSize, + readTimeout: s.ReadTimeout, + writeTimeout: s.WriteTimeout, + pathManager: s.PathManager, + parent: s, + } + err := s.httpServer.initialize() + if err != nil { + return err + } + + s.ctx, s.ctxCancel = context.WithCancel(context.Background()) + s.sessions = make(map[*session]struct{}) + s.chNewSession = make(chan newSessionReq) + s.chCloseSession = make(chan *session) + s.chAPISessionsList = make(chan serverAPISessionsListReq) + s.chAPISessionsGet = make(chan serverAPISessionsGetReq) + s.chAPISessionsKick = make(chan serverAPISessionsKickReq) + s.done = make(chan struct{}) + + s.Log(logger.Info, "started with listeners on %s (TCP/HTTP2), %s (UDP/HTTP3)", s.HTTP2Address, s.HTTP3Address) + + go s.run() + + if !interfaceIsEmpty(s.Metrics) { + s.Metrics.SetMoQServer(s) + } + + return nil +} + +// Log implements logger.Writer. +func (s *Server) Log(level logger.Level, format string, args ...any) { + s.Parent.Log(level, "[MoQ] "+format, args...) +} + +// Close closes the server. +func (s *Server) Close() { + s.Log(logger.Info, "closing") + + if !interfaceIsEmpty(s.Metrics) { + s.Metrics.SetMoQServer(nil) + } + + s.ctxCancel() + <-s.done +} + +func (s *Server) run() { + defer close(s.done) + + var wg sync.WaitGroup + +outer: + for { + select { + case req := <-s.chNewSession: + sx := &session{ + wt: req.wt, + wg: &wg, + pathName: req.pathName, + query: req.query, + userAgent: req.userAgent, + pathManager: s.PathManager, + parent: s, + } + sx.initialize() + s.sessions[sx] = struct{}{} + req.res <- newSessionRes{sx: sx} + + case sx := <-s.chCloseSession: + delete(s.sessions, sx) + + case req := <-s.chAPISessionsList: + data := &defs.APIMoQSessionList{ + Items: []defs.APIMoQSession{}, + } + for sx := range s.sessions { + data.Items = append(data.Items, sx.apiItem()) + } + req.res <- serverAPISessionsListRes{data: data} + + case req := <-s.chAPISessionsGet: + var found *session + for sx := range s.sessions { + if sx.uuid == req.uuid { + found = sx + break + } + } + if found == nil { + req.res <- serverAPISessionsGetRes{err: ErrSessionNotFound} + } else { + item := found.apiItem() + req.res <- serverAPISessionsGetRes{data: &item} + } + + case req := <-s.chAPISessionsKick: + var found *session + for sx := range s.sessions { + if sx.uuid == req.uuid { + found = sx + break + } + } + if found == nil { + req.res <- serverAPISessionsKickRes{err: ErrSessionNotFound} + } else { + found.Close() + req.res <- serverAPISessionsKickRes{} + } + + case <-s.ctx.Done(): + break outer + } + } + + // close sessions before closing UDP packet listener + for sx := range s.sessions { + sx.Close() + } + + s.httpServer.close() + + wg.Wait() +} + +func (s *Server) newSession(req newSessionReq) newSessionRes { + req.res = make(chan newSessionRes) + + select { + case s.chNewSession <- req: + return <-req.res + case <-s.ctx.Done(): + return newSessionRes{err: fmt.Errorf("terminated")} + } +} + +// closeSession is called by session. +func (s *Server) closeSession(sx *session) { + select { + case s.chCloseSession <- sx: + case <-s.ctx.Done(): + } +} + +// APISessionsList implements defs.APIMoQServer. +func (s *Server) APISessionsList() (*defs.APIMoQSessionList, error) { + req := serverAPISessionsListReq{ + res: make(chan serverAPISessionsListRes), + } + select { + case s.chAPISessionsList <- req: + res := <-req.res + return res.data, nil + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// APISessionsGet implements defs.APIMoQServer. +func (s *Server) APISessionsGet(id uuid.UUID) (*defs.APIMoQSession, error) { + req := serverAPISessionsGetReq{ + uuid: id, + res: make(chan serverAPISessionsGetRes), + } + select { + case s.chAPISessionsGet <- req: + res := <-req.res + return res.data, res.err + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// APISessionsKick implements defs.APIMoQServer. +func (s *Server) APISessionsKick(id uuid.UUID) error { + req := serverAPISessionsKickReq{ + uuid: id, + res: make(chan serverAPISessionsKickRes), + } + select { + case s.chAPISessionsKick <- req: + res := <-req.res + return res.err + case <-s.ctx.Done(): + return fmt.Errorf("terminated") + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/server_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..93dd8b1c637c2408aaf610e80b9962c3afd62fa0 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/server_test.go @@ -0,0 +1,178 @@ +package moq + +import ( + "context" + "crypto/tls" + "encoding/json" + "testing" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + mch264 "github.com/bluenviron/mediacommon/v2/pkg/codecs/h264" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/protocols/moq/catalog" + "github.com/bluenviron/mediamtx/internal/protocols/moq/controlmessage" + "github.com/bluenviron/mediamtx/internal/protocols/moq/subgroup" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/quic-go/quic-go" + "github.com/quic-go/webtransport-go" + "github.com/stretchr/testify/require" +) + +type serverDummyPath struct{} + +func (p *serverDummyPath) Name() string { return "teststream" } +func (p *serverDummyPath) SafeConf() *conf.Path { return &conf.Path{} } +func (p *serverDummyPath) ExternalCmdEnv() externalcmd.Environment { return externalcmd.Environment{} } +func (p *serverDummyPath) RemovePublisher(_ defs.PathRemovePublisherReq) {} +func (p *serverDummyPath) RemoveReader(_ defs.PathRemoveReaderReq) {} + +func TestServer(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}} + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + defer strm.Close() + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + pm := &test.PathManager{ + FindPathConfImpl: func(_ defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) { + return &defs.PathFindPathConfRes{Conf: &conf.Path{}}, nil + }, + AddReaderImpl: func(_ defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + return &defs.PathAddReaderRes{Path: &serverDummyPath{}, Stream: strm}, nil + }, + } + + serverCertFile := test.CreateTempFile(t, test.TLSCertPub) + serverKeyFile := test.CreateTempFile(t, test.TLSCertKey) + + s := &Server{ + HTTP2Address: "127.0.0.1:19895", + HTTP3Address: "127.0.0.1:19896", + ServerCert: serverCertFile, + ServerKey: serverKeyFile, + AllowOrigins: []string{"*"}, + TrustedProxies: conf.IPNetworks{}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + PathManager: pm, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + d := &webtransport.Dialer{ + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: true, //nolint:gosec + }, + QUICConfig: &quic.Config{ + EnableDatagrams: true, + EnableStreamResetPartialDelivery: true, + }, + ApplicationProtocols: []string{"moqt-18"}, + } + defer d.Close() //nolint:errcheck + + res, sx, err := d.Dial(ctx, "https://127.0.0.1:19896/teststream/moq", nil) + require.NoError(t, err) + defer sx.CloseWithError(0, "") //nolint:errcheck + defer res.Body.Close() //nolint:errcheck + + setupStream, err := sx.AcceptUniStream(ctx) + require.NoError(t, err) + setupMsg, err := controlmessage.Read(setupStream) + require.NoError(t, err) + _, ok := setupMsg.(*controlmessage.Setup) + require.True(t, ok) + + clientSetup, err := sx.OpenUniStreamSync(ctx) + require.NoError(t, err) + _, err = clientSetup.Write(controlmessage.Setup{}.Marshal()) + require.NoError(t, err) + + catalogBidi, err := sx.OpenStreamSync(ctx) + require.NoError(t, err) + _, err = catalogBidi.Write(controlmessage.Subscribe{ + RequestID: 1, + TrackName: ".catalog", + }.Marshal()) + require.NoError(t, err) + + catalogOkMsg, err := controlmessage.Read(catalogBidi) + require.NoError(t, err) + catalogOk, ok := catalogOkMsg.(*controlmessage.SubscribeOk) + require.True(t, ok) + require.Equal(t, uint64(1), catalogOk.TrackAlias) + + catalogDataStream, err := sx.AcceptUniStream(ctx) + require.NoError(t, err) + var catalogSG subgroup.SubGroup + err = catalogSG.Read(catalogDataStream) + require.NoError(t, err) + + var cat catalog.Catalog + err = json.Unmarshal(catalogSG.Objects[0].Payload, &cat) + require.NoError(t, err) + + require.Equal(t, catalog.Catalog{ + Version: 1, + Tracks: []catalog.Track{{ + Name: "0", + Packaging: "loc", + IsLive: true, + Codec: "avc3.640028", + }}, + }, cat) + + trackBidi, err := sx.OpenStreamSync(ctx) + require.NoError(t, err) + _, err = trackBidi.Write(controlmessage.Subscribe{ + RequestID: 2, + TrackName: "0", + }.Marshal()) + require.NoError(t, err) + + trackOkMsg, err := controlmessage.Read(trackBidi) + require.NoError(t, err) + trackOk, ok := trackOkMsg.(*controlmessage.SubscribeOk) + require.True(t, ok) + require.Equal(t, uint64(2), trackOk.TrackAlias) + + go func() { + time.Sleep(200 * time.Millisecond) + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + PTS: 0, + Payload: unit.PayloadH264{{5, 1}}, + }) + }() + + frameStream, err := sx.AcceptUniStream(ctx) + require.NoError(t, err) + var frameSG subgroup.SubGroup + err = frameSG.Read(frameStream) + require.NoError(t, err) + + expectedPayload, err2 := mch264.AVCC([][]byte{test.FormatH264.SPS, test.FormatH264.PPS, {5, 1}}).Marshal() + require.NoError(t, err2) + require.Equal(t, expectedPayload, frameSG.Objects[0].Payload) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/session.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/session.go new file mode 100644 index 0000000000000000000000000000000000000000..60a597f5d68df3e9362a3df03c79488b4f06bfee --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/moq/session.go @@ -0,0 +1,734 @@ +package moq + +import ( + "bufio" + "context" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/moq" + "github.com/bluenviron/mediamtx/internal/protocols/moq/catalog" + "github.com/bluenviron/mediamtx/internal/protocols/moq/controlmessage" + "github.com/bluenviron/mediamtx/internal/protocols/moq/parameter" + "github.com/bluenviron/mediamtx/internal/protocols/moq/property" + "github.com/bluenviron/mediamtx/internal/protocols/moq/subgroup" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/google/uuid" + "github.com/quic-go/webtransport-go" + "golang.org/x/sync/errgroup" +) + +const maxReorderedSubGroups = 50 + +func findAuthorizationToken(parameters []parameter.Parameter) *parameter.AuthorizationToken { + for _, pa := range parameters { + if auth, ok := pa.(*parameter.AuthorizationToken); ok { + return auth + } + } + return nil +} + +func credentialsFromAuthorizationToken(authorization *parameter.AuthorizationToken) *auth.Credentials { + if authorization != nil { + if s, ok := strings.CutPrefix(string(authorization.TokenValue), "Basic "); ok { + decoded, err := base64.StdEncoding.DecodeString(s) + if err != nil { + return &auth.Credentials{} + } + var user, pass string + user, pass, ok = strings.Cut(string(decoded), ":") + if !ok { + return &auth.Credentials{} + } + return &auth.Credentials{ + User: user, + Pass: pass, + } + } + + if s, ok := strings.CutPrefix(string(authorization.TokenValue), "Bearer "); ok { + return &auth.Credentials{ + Token: s, + } + } + } + + return &auth.Credentials{} +} + +func tracksToCatalog(tracks []*moq.Track) (catalog.Catalog, error) { + cat := catalog.Catalog{ + Version: 1, + Tracks: make([]catalog.Track, len(tracks)), + } + + for i, track := range tracks { + ct := catalog.Track{ + Name: strconv.Itoa(i), + Packaging: "loc", + IsLive: true, + Codec: track.Codec, + Samplerate: track.Samplerate, + Channels: track.Channels, + InitData: track.InitData, + } + cat.Tracks[i] = ct + } + + return cat, nil +} + +func isSubGroupStream(b byte) bool { + return (b & 0x90) == 0x10 +} + +type sessionParent interface { + closeSession(sx *session) + logger.Writer +} +type session struct { + wt *webtransport.Session + wg *sync.WaitGroup + pathName string + query string + userAgent string + pathManager serverPathManager + parent sessionParent + + ctx context.Context + ctxCancel context.CancelFunc + created time.Time + uuid uuid.UUID + mutex sync.Mutex + state defs.APIMoQSessionState + path defs.Path + stream *stream.Stream // read only + tracks []*moq.Track // read only + trackSubscriptions map[int]struct{} // read only + catalogReceived chan []byte // publish only + publishReady chan struct{} // publish only + inboundTracks map[uint64]*inboundTrack // publish only + + inboundBytes atomic.Uint64 + outboundBytes atomic.Uint64 + + setupReceived chan struct{} + done chan struct{} +} + +func (s *session) initialize() { + s.ctx, s.ctxCancel = context.WithCancel(context.Background()) + s.created = time.Now() + s.uuid = uuid.New() + s.state = defs.APIMoQSessionStateIdle + s.trackSubscriptions = make(map[int]struct{}) + + s.catalogReceived = make(chan []byte, 1) + s.publishReady = make(chan struct{}) + + s.setupReceived = make(chan struct{}) + s.done = make(chan struct{}) + + s.Log(logger.Info, "created by %s", s.wt.RemoteAddr()) + + s.wg.Add(1) + go s.run() +} + +// Log implements logger.Writer. +func (s *session) Log(level logger.Level, format string, args ...any) { + id := hex.EncodeToString(s.uuid[:4]) + s.parent.Log(level, "[session %v] "+format, append([]any{id}, args...)...) +} + +// Close implements defs.Reader. +func (s *session) Close() { + s.ctxCancel() +} + +func (s *session) run() { + defer s.wg.Done() + defer close(s.done) + + err := s.runInner() + + switch s.state { + case defs.APIMoQSessionStatePublish: + if s.path != nil { + s.path.RemovePublisher(defs.PathRemovePublisherReq{Author: s}) + } + + case defs.APIMoQSessionStateRead: + if s.path != nil { + s.path.RemoveReader(defs.PathRemoveReaderReq{Author: s}) + } + } + + s.parent.closeSession(s) + + s.Log(logger.Info, "closed: %v", err) +} + +func (s *session) runInner() error { + errGroup, errGroupCtx := errgroup.WithContext(context.Background()) + + errGroup.Go(func() error { + return s.runUniStreamAcceptor(errGroup) + }) + + errGroup.Go(func() error { + return s.runBidiStreamAcceptor(errGroup) + }) + + errGroup.Go(func() error { + return s.runSetupWriter() + }) + + select { + case <-s.ctx.Done(): + s.wt.CloseWithError(0, "") //nolint:errcheck + errGroup.Wait() //nolint:errcheck + return fmt.Errorf("terminated") + + case <-errGroupCtx.Done(): + s.ctxCancel() + s.wt.CloseWithError(0, "") //nolint:errcheck + return errGroup.Wait() + } +} + +func (s *session) runSetupWriter() error { + wstream, err := s.wt.OpenUniStreamSync(context.Background()) + if err != nil { + return err + } + + _, err = wstream.Write(controlmessage.Setup{}.Marshal()) + if err != nil { + return err + } + + return nil +} + +func (s *session) runUniStreamAcceptor(errGroup *errgroup.Group) error { + for { + stream, err := s.wt.AcceptUniStream(context.Background()) + if err != nil { + return fmt.Errorf("AcceptUniStream returned: %w", err) + } + + errGroup.Go(func() error { + return s.runUniStream(stream) + }) + } +} + +func (s *session) runBidiStreamAcceptor(errGroup *errgroup.Group) error { + for { + stream, err := s.wt.AcceptStream(context.Background()) + if err != nil { + return fmt.Errorf("AcceptStream returned: %w", err) + } + + errGroup.Go(func() error { + return s.runBidiStream(stream) + }) + } +} + +func (s *session) runUniStream(wstream *webtransport.ReceiveStream) error { + br := bufio.NewReader(wstream) + firstByte, err := br.Peek(1) + if err != nil { + return err + } + + if isSubGroupStream(firstByte[0]) { + return s.onUniSubGroup(br) + } + + return s.onUniMessage(br) +} + +func (s *session) onUniMessage(r io.Reader) error { + msg, err := controlmessage.Read(r) + if err != nil { + return err + } + + switch msg.(type) { + case *controlmessage.Setup: + err = func() error { + s.mutex.Lock() + defer s.mutex.Unlock() + + select { + case <-s.setupReceived: + return fmt.Errorf("SETUP stream is already present") + default: + close(s.setupReceived) + return nil + } + }() + if err != nil { + return err + } + + io.Copy(io.Discard, r) + return fmt.Errorf("SETUP stream closed") + + default: + return fmt.Errorf("unsupported stream type: %T", msg) + } +} + +func (s *session) runBidiStream(wstream *webtransport.Stream) error { + select { + case <-s.setupReceived: + case <-s.ctx.Done(): + return fmt.Errorf("terminated") + } + + msg, err := controlmessage.Read(wstream) + if err != nil { + return err + } + + switch m := msg.(type) { + case *controlmessage.Subscribe: + s.Log(logger.Debug, "SUBSCRIBE track=%s", m.TrackName) + + if m.TrackName == ".catalog" { + return s.onSubscribeCatalog(wstream, m) + } + + return s.onSubscribeTrack(wstream, m) + + case *controlmessage.Publish: + s.Log(logger.Debug, "PUBLISH track=%s alias=%d", m.TrackName, m.TrackAlias) + + if m.TrackName == ".catalog" { + return s.onPublishCatalog(wstream, m) + } + + return s.onPublishTrack(wstream) + + default: + return fmt.Errorf("unsupported message type: %T", msg) + } +} + +func (s *session) onSubscribeCatalog(wstream *webtransport.Stream, m *controlmessage.Subscribe) error { + s.mutex.Lock() + if s.state != defs.APIMoQSessionStateIdle { + s.mutex.Unlock() + return fmt.Errorf("unexpected SUBSCRIBE in state %s", s.state) + } + s.state = defs.APIMoQSessionStateRead + s.mutex.Unlock() + + remoteHost, _, _ := net.SplitHostPort(s.wt.RemoteAddr().String()) + addRes, err := s.pathManager.AddReader(defs.PathAddReaderReq{ + Author: s, + AccessRequest: defs.PathAccessRequest{ + Name: s.pathName, + Query: s.query, + Proto: auth.ProtocolMoQ, + ID: &s.uuid, + Credentials: credentialsFromAuthorizationToken(findAuthorizationToken(m.Parameters)), + IP: net.ParseIP(remoteHost), + UserAgent: s.userAgent, + }, + }) + if err != nil { + var code controlmessage.RequestErrorCode + if _, ok := errors.AsType[*auth.Error](err); ok { + code = controlmessage.RequestErrorCodeUnauthorized + } else if _, ok = errors.AsType[*defs.PathNoStreamAvailableError](err); ok { + code = controlmessage.RequestErrorCodeDoesNotExist + } else { + code = controlmessage.RequestErrorCodeNotSupported + } + + wstream.Write(controlmessage.RequestError{ //nolint:errcheck + Code: code, + Reason: err.Error(), + }.Marshal()) + + // wait for the client to read the error + io.Copy(io.Discard, wstream) + + return err + } + + tracks, err := moq.FromStream( + addRes.Stream.OrigDesc, + ) + if err != nil { + addRes.Path.RemoveReader(defs.PathRemoveReaderReq{Author: s}) + return err + } + + s.mutex.Lock() + s.path = addRes.Path + s.stream = addRes.Stream + s.tracks = tracks + s.mutex.Unlock() + + s.Log(logger.Info, "is reading from path %s", s.pathName) + + _, err = wstream.Write(controlmessage.SubscribeOk{TrackAlias: m.RequestID}.Marshal()) + if err != nil { + return err + } + + cat, err := tracksToCatalog(tracks) + if err != nil { + return err + } + + enc, err := json.Marshal(cat) + if err != nil { + return err + } + + dataWStream, err := s.wt.OpenUniStreamSync(context.Background()) + if err != nil { + return err + } + defer dataWStream.Close() //nolint:errcheck + + sg := &subgroup.SubGroup{ + Header: subgroup.Header{ + Properties: false, + FirstObject: true, + TrackAlias: m.RequestID, + GroupID: 0, + }, + Objects: []subgroup.Object{{ + Payload: enc, + }}, + } + buf := sg.Marshal() + + _, err = dataWStream.Write(buf) + if err != nil { + return err + } + + io.Copy(io.Discard, wstream) + return fmt.Errorf("SUBSCRIBE catalog stream closed") +} + +func (s *session) onSubscribeTrack(wstream *webtransport.Stream, m *controlmessage.Subscribe) error { + trackID, err := strconv.Atoi(m.TrackName) + if err != nil || trackID < 0 { + return fmt.Errorf("invalid track name: %s", m.TrackName) + } + + err = func() error { + s.mutex.Lock() + defer s.mutex.Unlock() + + if s.state != defs.APIMoQSessionStateRead { + return fmt.Errorf("unexpected SUBSCRIBE in state %s", s.state) + } + + if s.stream == nil { + return fmt.Errorf("stream not ready") + } + + if trackID >= len(s.tracks) { + return fmt.Errorf("track index %d out of range", trackID) + } + + _, ok := s.trackSubscriptions[trackID] + if ok { + return fmt.Errorf("already subscribed to track %d", trackID) + } + + s.trackSubscriptions[trackID] = struct{}{} + + return nil + }() + if err != nil { + return err + } + + r := &stream.Reader{Parent: s} + + track := s.tracks[trackID] + groupID := uint64(0) + + wrapped := func(payload []byte, pts int64) error { + wstream, err2 := s.wt.OpenUniStreamSync(context.Background()) + if err2 != nil { + return err2 + } + defer wstream.Close() //nolint:errcheck + + sg := &subgroup.SubGroup{ + Header: subgroup.Header{ + Properties: true, + FirstObject: true, + TrackAlias: m.RequestID, + GroupID: groupID, + }, + Objects: []subgroup.Object{{ + Properties: property.Properties{ + new(property.Timestamp(pts)), + }, + Payload: payload, + }}, + } + buf := sg.Marshal() + groupID++ + + _, err2 = wstream.Write(buf) + if err2 == nil { + s.outboundBytes.Add(uint64(len(payload))) + } + return err2 + } + + r.OnData(track.Media, track.Format, func(u *unit.Unit) error { + return track.OnData(u, wrapped) + }) + + s.stream.AddReader(r) + defer s.stream.RemoveReader(r) + + _, err = wstream.Write(controlmessage.SubscribeOk{TrackAlias: m.RequestID}.Marshal()) + if err != nil { + return err + } + + streamClosed := make(chan struct{}) + go func() { + io.Copy(io.Discard, wstream) + close(streamClosed) + }() + + select { + case err = <-r.Error(): + return err + case <-streamClosed: + return fmt.Errorf("SUBSCRIBE track stream closed") + case <-s.ctx.Done(): + return fmt.Errorf("terminated") + } +} + +func (s *session) onPublishCatalog(wstream *webtransport.Stream, m *controlmessage.Publish) error { + s.mutex.Lock() + if s.state != defs.APIMoQSessionStateIdle { + s.mutex.Unlock() + return fmt.Errorf("unexpected PUBLISH in state %s", s.state) + } + s.state = defs.APIMoQSessionStatePublish + s.mutex.Unlock() + + select { + case catalogData := <-s.catalogReceived: + var cat catalog.Catalog + err := json.Unmarshal(catalogData, &cat) + if err != nil { + return fmt.Errorf("failed to parse catalog JSON: %w", err) + } + + var subStream *stream.SubStream + + medias, writeFuncs, err := moq.ToStream(&cat, &subStream) + if err != nil { + return err + } + + s.inboundTracks = make(map[uint64]*inboundTrack) + + for i := range cat.Tracks { + trackAlias := uint64(i + 1) + tr := &inboundTrack{ + onSubGroup: writeFuncs[trackAlias], + parent: s, + } + tr.initialize() + s.inboundTracks[trackAlias] = tr + } + + remoteHost, _, _ := net.SplitHostPort(s.wt.RemoteAddr().String()) + addRes, err := s.pathManager.AddPublisher(defs.PathAddPublisherReq{ + Author: s, + Desc: &description.Session{Medias: medias}, + UseRTPPackets: false, + ReplaceNTP: true, + AccessRequest: defs.PathAccessRequest{ + Name: s.pathName, + Query: s.query, + Publish: true, + Proto: auth.ProtocolMoQ, + ID: &s.uuid, + Credentials: credentialsFromAuthorizationToken(findAuthorizationToken(m.Parameters)), + IP: net.ParseIP(remoteHost), + UserAgent: s.userAgent, + }, + }) + if err != nil { + var code controlmessage.RequestErrorCode + if _, ok := errors.AsType[*auth.Error](err); ok { + code = controlmessage.RequestErrorCodeUnauthorized + } else { + code = controlmessage.RequestErrorCodeUninterested + } + + wstream.Write(controlmessage.RequestError{ //nolint:errcheck + Code: code, + Reason: err.Error(), + }.Marshal()) //nolint:errcheck + + // wait for the client to read the error + io.Copy(io.Discard, wstream) + + return err + } + + s.mutex.Lock() + s.path = addRes.Path + s.mutex.Unlock() + + subStream = addRes.SubStream + + close(s.publishReady) + + case <-s.publishReady: + return fmt.Errorf("catalog already received") + + case <-s.ctx.Done(): + return fmt.Errorf("terminated") + } + + _, err := wstream.Write(controlmessage.RequestOk{}.Marshal()) + if err != nil { + return err + } + + io.Copy(io.Discard, wstream) + return fmt.Errorf("PUBLISH catalog stream closed") +} + +func (s *session) onPublishTrack(wstream *webtransport.Stream) error { + s.mutex.Lock() + if s.state != defs.APIMoQSessionStatePublish { + s.mutex.Unlock() + return fmt.Errorf("unexpected PUBLISH in state %s", s.state) + } + s.mutex.Unlock() + + _, err := wstream.Write(controlmessage.RequestOk{}.Marshal()) + if err != nil { + return err + } + + io.Copy(io.Discard, wstream) + return fmt.Errorf("PUBLISH track stream closed") +} + +func (s *session) onUniSubGroup(r io.Reader) error { + var sg subgroup.SubGroup + err := sg.Read(r) + if err != nil { + return err + } + + if sg.Header.TrackAlias == 0 { + return s.onDataCatalog(r, &sg) + } + + return s.onDataTrack(r, &sg) +} + +func (s *session) onDataCatalog(r io.Reader, sg *subgroup.SubGroup) error { + select { + case s.catalogReceived <- sg.Objects[0].Payload: + default: + return fmt.Errorf("catalog already received") + } + + io.Copy(io.Discard, r) + return nil +} + +func (s *session) onDataTrack(r io.Reader, sg *subgroup.SubGroup) error { + select { + case <-s.publishReady: + case <-s.ctx.Done(): + return fmt.Errorf("terminated") + } + + track, ok := s.inboundTracks[sg.Header.TrackAlias] + if !ok { + return fmt.Errorf("track %d not found", sg.Header.TrackAlias) + } + + for _, obj := range sg.Objects { + s.inboundBytes.Add(uint64(len(obj.Payload))) + } + + err := track.push(sg) + if err != nil { + return err + } + + io.Copy(io.Discard, r) + return nil +} + +func (s *session) apiItem() defs.APIMoQSession { + s.mutex.Lock() + state := s.state + s.mutex.Unlock() + + return defs.APIMoQSession{ + ID: s.uuid, + Created: s.created, + RemoteAddr: s.wt.RemoteAddr().String(), + State: state, + Path: s.pathName, + Query: s.query, + UserAgent: s.userAgent, + InboundBytes: s.inboundBytes.Load(), + OutboundBytes: s.outboundBytes.Load(), + } +} + +// APIReaderDescribe implements defs.Reader. +func (s *session) APIReaderDescribe() *defs.APIPathReader { + return &defs.APIPathReader{ + Type: defs.APIPathReaderTypeMoQSession, + ID: s.uuid.String(), + } +} + +// APISourceDescribe implements defs.Source. +func (s *session) APISourceDescribe() *defs.APIPathSource { + return &defs.APIPathSource{ + Type: defs.APIPathSourceTypeMoQSession, + ID: s.uuid.String(), + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/conn.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/conn.go new file mode 100644 index 0000000000000000000000000000000000000000..11f88437a0f2e6fd0f151c7ed6e0bf70b2fbc6f4 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/conn.go @@ -0,0 +1,352 @@ +package rtmp + +import ( + "context" + "errors" + "fmt" + "net" + "strings" + "sync" + "time" + + "github.com/bluenviron/gortmplib" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/google/uuid" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/hooks" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/rtmp" + "github.com/bluenviron/mediamtx/internal/stream" +) + +type conn struct { + parentCtx context.Context + encryption bool + rtspAddress string + readTimeout conf.Duration + writeTimeout conf.Duration + runOnConnect string + runOnConnectRestart bool + runOnDisconnect string + wg *sync.WaitGroup + nconn net.Conn + externalCmdPool *externalcmd.Pool + pathManager serverPathManager + parent *Server + + ctx context.Context + ctxCancel func() + uuid uuid.UUID + created time.Time + mutex sync.RWMutex + rconn *gortmplib.ServerConn + state defs.APIRTMPConnState + pathName string + query string + user string + userAgent string + reader *stream.Reader +} + +func (c *conn) initialize() { + c.ctx, c.ctxCancel = context.WithCancel(c.parentCtx) + + c.uuid = uuid.New() + c.created = time.Now() + c.state = defs.APIRTMPConnStateIdle + + c.Log(logger.Info, "opened") + + c.wg.Add(1) + go c.run() +} + +func (c *conn) Close() { + c.ctxCancel() +} + +func (c *conn) remoteAddr() net.Addr { + return c.nconn.RemoteAddr() +} + +// Log implements logger.Writer. +func (c *conn) Log(level logger.Level, format string, args ...any) { + c.parent.Log(level, "[conn %v] "+format, append([]any{c.nconn.RemoteAddr()}, args...)...) +} + +func (c *conn) ip() net.IP { + return c.nconn.RemoteAddr().(*net.TCPAddr).IP +} + +func (c *conn) run() { //nolint:dupl + defer c.wg.Done() + + onDisconnectHook := hooks.OnConnect(hooks.OnConnectParams{ + Logger: c, + ExternalCmdPool: c.externalCmdPool, + RunOnConnect: c.runOnConnect, + RunOnConnectRestart: c.runOnConnectRestart, + RunOnDisconnect: c.runOnDisconnect, + RTSPAddress: c.rtspAddress, + Desc: *c.APIReaderDescribe(), + }) + defer onDisconnectHook() + + err := c.runInner() + + c.ctxCancel() + + c.parent.closeConn(c) + + c.Log(logger.Info, "closed: %v", err) +} + +func (c *conn) runInner() error { + readerErr := make(chan error) + go func() { + readerErr <- c.runReader() + }() + + select { + case err := <-readerErr: + c.nconn.Close() + return err + + case <-c.ctx.Done(): + c.nconn.Close() + <-readerErr + return errors.New("terminated") + } +} + +func (c *conn) runReader() error { + c.nconn.SetReadDeadline(time.Now().Add(time.Duration(c.readTimeout))) + c.nconn.SetWriteDeadline(time.Now().Add(time.Duration(c.writeTimeout))) + + conn := &gortmplib.ServerConn{ + RW: c.nconn, + } + err := conn.Initialize() + if err != nil { + return err + } + + err = conn.Accept() + if err != nil { + return err + } + + c.mutex.Lock() + c.rconn = conn + c.userAgent = conn.FlashVer + c.mutex.Unlock() + + if !conn.Publish { + return c.runRead() + } + return c.runPublish() +} + +func (c *conn) runRead() error { + pathName := strings.TrimLeft(c.rconn.URL.Path, "/") + query := c.rconn.URL.Query() + + res, err := c.pathManager.AddReader(defs.PathAddReaderReq{ + Author: c, + AccessRequest: defs.PathAccessRequest{ + Name: pathName, + Query: c.rconn.URL.RawQuery, + UserAgent: c.userAgent, + Proto: auth.ProtocolRTMP, + ID: &c.uuid, + Credentials: &auth.Credentials{ + User: query.Get("user"), + Pass: query.Get("pass"), + }, + IP: c.ip(), + }, + }) + if err != nil { + return err + } + + defer res.Path.RemoveReader(defs.PathRemoveReaderReq{Author: c}) + + c.mutex.Lock() + c.state = defs.APIRTMPConnStateRead + c.pathName = pathName + c.query = c.rconn.URL.RawQuery + c.user = res.User + c.mutex.Unlock() + + r := &stream.Reader{Parent: c} + + err = rtmp.FromStream( + res.Stream.OrigDesc, + res.Stream.OutDescCopy(), + r, + c.rconn, + c.nconn, + time.Duration(c.writeTimeout)) + if err != nil { + return err + } + + c.Log(logger.Info, "is reading from path '%s', %s", + res.Path.Name(), defs.FormatsInfo(r.Formats())) + + onUnreadHook := hooks.OnRead(hooks.OnReadParams{ + Logger: c, + ExternalCmdPool: c.externalCmdPool, + Conf: res.Path.SafeConf(), + ExternalCmdEnv: res.Path.ExternalCmdEnv(), + Reader: *c.APIReaderDescribe(), + Query: c.rconn.URL.RawQuery, + }) + defer onUnreadHook() + + c.nconn.SetReadDeadline(time.Time{}) + + res.Stream.AddReader(r) + defer res.Stream.RemoveReader(r) + + c.mutex.Lock() + c.reader = r + c.mutex.Unlock() + + select { + case <-c.ctx.Done(): + return fmt.Errorf("terminated") + + case err = <-r.Error(): + return err + } +} + +func (c *conn) runPublish() error { + pathName := strings.TrimLeft(c.rconn.URL.Path, "/") + query := c.rconn.URL.Query() + + r := &gortmplib.Reader{ + Conn: c.rconn, + } + err := r.Initialize() + if err != nil { + return err + } + + var subStream *stream.SubStream + + medias, err := rtmp.ToStream(r, &subStream) + if err != nil { + return err + } + + res, err := c.pathManager.AddPublisher(defs.PathAddPublisherReq{ + Author: c, + Desc: &description.Session{Medias: medias}, + UseRTPPackets: false, + ReplaceNTP: true, + AccessRequest: defs.PathAccessRequest{ + Name: pathName, + Query: c.rconn.URL.RawQuery, + Publish: true, + UserAgent: c.userAgent, + Proto: auth.ProtocolRTMP, + ID: &c.uuid, + Credentials: &auth.Credentials{ + User: query.Get("user"), + Pass: query.Get("pass"), + }, + IP: c.ip(), + }, + }) + if err != nil { + return err + } + + defer res.Path.RemovePublisher(defs.PathRemovePublisherReq{Author: c}) + + subStream = res.SubStream + + c.mutex.Lock() + c.state = defs.APIRTMPConnStatePublish + c.pathName = pathName + c.query = c.rconn.URL.RawQuery + c.user = res.User + c.mutex.Unlock() + + c.nconn.SetWriteDeadline(time.Time{}) + + for { + c.nconn.SetReadDeadline(time.Now().Add(time.Duration(c.readTimeout))) + err = r.Read() + if err != nil { + return err + } + } +} + +// APIReaderDescribe implements reader. +func (c *conn) APIReaderDescribe() *defs.APIPathReader { + return &defs.APIPathReader{ + Type: func() defs.APIPathReaderType { + if c.encryption { + return defs.APIPathReaderTypeRTMPSConn + } + return defs.APIPathReaderTypeRTMPConn + }(), + ID: c.uuid.String(), + } +} + +// APISourceDescribe implements source. +func (c *conn) APISourceDescribe() *defs.APIPathSource { + return &defs.APIPathSource{ + Type: func() defs.APIPathSourceType { + if c.encryption { + return defs.APIPathSourceTypeRTMPSConn + } + return defs.APIPathSourceTypeRTMPConn + }(), + ID: c.uuid.String(), + } +} + +func (c *conn) apiItem() *defs.APIRTMPConn { + c.mutex.RLock() + defer c.mutex.RUnlock() + + bytesReceived := uint64(0) + bytesSent := uint64(0) + outboundFramesDiscarded := uint64(0) + + if c.rconn != nil { + bytesReceived = c.rconn.BytesReceived() + bytesSent = c.rconn.BytesSent() + } + + if c.reader != nil { + outboundFramesDiscarded = c.reader.OutboundFramesDiscarded() + } + + return &defs.APIRTMPConn{ + ID: c.uuid, + Created: c.created, + RemoteAddr: c.remoteAddr().String(), + State: c.state, + Path: c.pathName, + Query: c.query, + User: c.user, + UserAgent: c.userAgent, + InboundBytes: bytesReceived, + OutboundBytes: bytesSent, + BytesReceived: bytesReceived, + BytesSent: bytesSent, + OutboundFramesDiscarded: outboundFramesDiscarded, + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/listener.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/listener.go new file mode 100644 index 0000000000000000000000000000000000000000..033121d8734cf63f44ef32a345a7530f8cdc671c --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/listener.go @@ -0,0 +1,36 @@ +package rtmp + +import ( + "net" + "sync" +) + +type listener struct { + ln net.Listener + wg *sync.WaitGroup + parent *Server +} + +func (l *listener) initialize() { + l.wg.Add(1) + go l.run() +} + +func (l *listener) run() { + defer l.wg.Done() + + err := l.runInner() + + l.parent.acceptError(err) +} + +func (l *listener) runInner() error { + for { + conn, err := l.ln.Accept() + if err != nil { + return err + } + + l.parent.newConn(conn) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/server.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/server.go new file mode 100644 index 0000000000000000000000000000000000000000..74465030f09c4df394ddcd430babb65dc35c8065 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/server.go @@ -0,0 +1,415 @@ +// Package rtmp contains a RTMP server. +package rtmp + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "net" + "reflect" + "sort" + "sync" + + "github.com/google/uuid" + + "github.com/bluenviron/mediamtx/internal/certloader" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/packetdumper" + "github.com/bluenviron/mediamtx/internal/protocols/proxy" + "github.com/bluenviron/mediamtx/internal/restrictnetwork" +) + +// ErrConnNotFound is returned when a connection is not found. +var ErrConnNotFound = errors.New("connection not found") + +func interfaceIsEmpty(i any) bool { + return reflect.ValueOf(i).Kind() != reflect.Pointer || reflect.ValueOf(i).IsNil() +} + +type serverAPIConnsListRes struct { + data *defs.APIRTMPConnList + err error +} + +type serverAPIConnsListReq struct { + res chan serverAPIConnsListRes +} + +type serverAPIConnsGetRes struct { + data *defs.APIRTMPConn + err error +} + +type serverAPIConnsGetReq struct { + uuid uuid.UUID + res chan serverAPIConnsGetRes +} + +type serverAPIConnsKickRes struct { + err error +} + +type serverAPIConnsKickReq struct { + uuid uuid.UUID + res chan serverAPIConnsKickRes +} + +type serverMetrics interface { + SetRTMPSServer(defs.APIRTMPServer) + SetRTMPServer(defs.APIRTMPServer) +} + +type serverPathManager interface { + AddPublisher(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) + AddReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) +} + +type serverParent interface { + logger.Writer +} + +// Server is a RTMP server. +type Server struct { + Address string + DumpPackets bool + ReadTimeout conf.Duration + WriteTimeout conf.Duration + Encryption bool + ServerCert string + ServerKey string + RTSPAddress string + TrustedProxies conf.IPNetworks + RunOnConnect string + RunOnConnectRestart bool + RunOnDisconnect string + ExternalCmdPool *externalcmd.Pool + Metrics serverMetrics + PathManager serverPathManager + Parent serverParent + + ctx context.Context + ctxCancel func() + wg sync.WaitGroup + ln net.Listener + conns map[*conn]struct{} + loader *certloader.CertLoader + + // in + chNewConn chan net.Conn + chAcceptErr chan error + chCloseConn chan *conn + chAPIConnsList chan serverAPIConnsListReq + chAPIConnsGet chan serverAPIConnsGetReq + chAPIConnsKick chan serverAPIConnsKickReq +} + +// Initialize initializes the server. +func (s *Server) Initialize() error { + listen := func(network, address string) (net.Listener, error) { + ln, err := net.Listen(network, address) + if err != nil { + return nil, err + } + + if s.DumpPackets { + var proto string + if s.Encryption { + proto = "rtmps" + } else { + proto = "rtmp" + } + + ln = &packetdumper.Listener{ + Wrapped: ln, + Prefix: proto + "_server_conn", + } + } + + if len(s.TrustedProxies) > 0 { + pl := &proxy.Listener{ + Wrapped: ln, + TrustedProxies: s.TrustedProxies, + } + pl.Initialize() + ln = pl + } + + return ln, nil + } + + tlsListen := func(network string, laddr string, config *tls.Config) (net.Listener, error) { + ln, err := listen(network, laddr) + if err != nil { + return nil, err + } + + if s.DumpPackets { + ln = &packetdumper.TLSListener{ + Wrapped: ln, + TLSConfig: config, + } + } else { + ln = tls.NewListener(ln, config) + } + + return ln, nil + } + + if s.Encryption { + s.loader = &certloader.CertLoader{ + CertPath: s.ServerCert, + KeyPath: s.ServerKey, + Parent: s.Parent, + } + err := s.loader.Initialize() + if err != nil { + return err + } + + net, addr := restrictnetwork.Restrict("tcp", s.Address) + s.ln, err = tlsListen(net, addr, &tls.Config{GetCertificate: s.loader.GetCertificate()}) + if err != nil { + return err + } + } else { + var err error + s.ln, err = listen(restrictnetwork.Restrict("tcp", s.Address)) + if err != nil { + return err + } + } + + s.ctx, s.ctxCancel = context.WithCancel(context.Background()) + + s.conns = make(map[*conn]struct{}) + s.chNewConn = make(chan net.Conn) + s.chAcceptErr = make(chan error) + s.chCloseConn = make(chan *conn) + s.chAPIConnsList = make(chan serverAPIConnsListReq) + s.chAPIConnsGet = make(chan serverAPIConnsGetReq) + s.chAPIConnsKick = make(chan serverAPIConnsKickReq) + + str := "started with listener on " + s.Address + if s.Encryption { + str += " (TCP/RTMPS)" + } else { + str += " (TCP/RTMP)" + } + s.Log(logger.Info, str) + + l := &listener{ + ln: s.ln, + wg: &s.wg, + parent: s, + } + l.initialize() + + s.wg.Add(1) + go s.run() + + if !interfaceIsEmpty(s.Metrics) { + if s.Encryption { + s.Metrics.SetRTMPSServer(s) + } else { + s.Metrics.SetRTMPServer(s) + } + } + + return nil +} + +// Log implements logger.Writer. +func (s *Server) Log(level logger.Level, format string, args ...any) { + label := func() string { + if s.Encryption { + return "RTMPS" + } + return "RTMP" + }() + s.Parent.Log(level, "[%s] "+format, append([]any{label}, args...)...) +} + +// Close closes the server. +func (s *Server) Close() { + s.Log(logger.Info, "closing") + + if !interfaceIsEmpty((s.Metrics)) { + if s.Encryption { + s.Metrics.SetRTMPSServer(nil) + } else { + s.Metrics.SetRTMPServer(nil) + } + } + + s.ctxCancel() + s.wg.Wait() + + if s.loader != nil { + s.loader.Close() + } +} + +func (s *Server) run() { + defer s.wg.Done() + +outer: + for { + select { + case err := <-s.chAcceptErr: + s.Log(logger.Error, "%s", err) + break outer + + case nconn := <-s.chNewConn: + c := &conn{ + parentCtx: s.ctx, + encryption: s.Encryption, + rtspAddress: s.RTSPAddress, + readTimeout: s.ReadTimeout, + writeTimeout: s.WriteTimeout, + runOnConnect: s.RunOnConnect, + runOnConnectRestart: s.RunOnConnectRestart, + runOnDisconnect: s.RunOnDisconnect, + wg: &s.wg, + nconn: nconn, + externalCmdPool: s.ExternalCmdPool, + pathManager: s.PathManager, + parent: s, + } + c.initialize() + s.conns[c] = struct{}{} + + case c := <-s.chCloseConn: + delete(s.conns, c) + + case req := <-s.chAPIConnsList: + data := &defs.APIRTMPConnList{ + Items: []defs.APIRTMPConn{}, + } + + for c := range s.conns { + data.Items = append(data.Items, *c.apiItem()) + } + + sort.Slice(data.Items, func(i, j int) bool { + return data.Items[i].Created.Before(data.Items[j].Created) + }) + + req.res <- serverAPIConnsListRes{data: data} + + case req := <-s.chAPIConnsGet: + c := s.findConnByUUID(req.uuid) + if c == nil { + req.res <- serverAPIConnsGetRes{err: ErrConnNotFound} + continue + } + + req.res <- serverAPIConnsGetRes{data: c.apiItem()} + + case req := <-s.chAPIConnsKick: + c := s.findConnByUUID(req.uuid) + if c == nil { + req.res <- serverAPIConnsKickRes{err: ErrConnNotFound} + continue + } + + delete(s.conns, c) + c.Close() + req.res <- serverAPIConnsKickRes{} + + case <-s.ctx.Done(): + break outer + } + } + + s.ctxCancel() + + s.ln.Close() +} + +func (s *Server) findConnByUUID(uuid uuid.UUID) *conn { + for c := range s.conns { + if c.uuid == uuid { + return c + } + } + return nil +} + +// newConn is called by rtmpListener. +func (s *Server) newConn(conn net.Conn) { + select { + case s.chNewConn <- conn: + case <-s.ctx.Done(): + conn.Close() + } +} + +// acceptError is called by rtmpListener. +func (s *Server) acceptError(err error) { + select { + case s.chAcceptErr <- err: + case <-s.ctx.Done(): + } +} + +// closeConn is called by conn. +func (s *Server) closeConn(c *conn) { + select { + case s.chCloseConn <- c: + case <-s.ctx.Done(): + } +} + +// APIConnsList implements defs.APIRTMPServer. +func (s *Server) APIConnsList() (*defs.APIRTMPConnList, error) { + req := serverAPIConnsListReq{ + res: make(chan serverAPIConnsListRes), + } + + select { + case s.chAPIConnsList <- req: + res := <-req.res + return res.data, res.err + + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// APIConnsGet implements defs.APIRTMPServer. +func (s *Server) APIConnsGet(uuid uuid.UUID) (*defs.APIRTMPConn, error) { + req := serverAPIConnsGetReq{ + uuid: uuid, + res: make(chan serverAPIConnsGetRes), + } + + select { + case s.chAPIConnsGet <- req: + res := <-req.res + return res.data, res.err + + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// APIConnsKick implements defs.APIRTMPServer. +func (s *Server) APIConnsKick(uuid uuid.UUID) error { + req := serverAPIConnsKickReq{ + uuid: uuid, + res: make(chan serverAPIConnsKickRes), + } + + select { + case s.chAPIConnsKick <- req: + res := <-req.res + return res.err + + case <-s.ctx.Done(): + return fmt.Errorf("terminated") + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/server_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..0f4a002016bf60a2c925a9c660e4f4234df4739d --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtmp/server_test.go @@ -0,0 +1,402 @@ +package rtmp + +import ( + "context" + "crypto/tls" + "net" + "net/url" + "testing" + "time" + + "github.com/bluenviron/gortmplib" + "github.com/bluenviron/gortmplib/pkg/codecs" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/pires/go-proxyproto" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/stretchr/testify/require" +) + +type dummyPath struct{} + +func (p *dummyPath) Name() string { + return "teststream" +} + +func (p *dummyPath) SafeConf() *conf.Path { + return &conf.Path{} +} + +func (p *dummyPath) ExternalCmdEnv() externalcmd.Environment { + return externalcmd.Environment{} +} + +func (p *dummyPath) RemovePublisher(_ defs.PathRemovePublisherReq) { +} + +func (p *dummyPath) RemoveReader(_ defs.PathRemoveReaderReq) { +} + +func TestServerPublish(t *testing.T) { + for _, encrypt := range []string{ + "plain", + "tls", + } { + for _, proxy := range []string{ + "no_proxy", + "proxy", + } { + t.Run(encrypt+"_"+proxy, func(t *testing.T) { + var serverCertFpath string + var serverKeyFpath string + + if encrypt == "tls" { + serverCertFpath = test.CreateTempFile(t, test.TLSCertPub) + serverKeyFpath = test.CreateTempFile(t, test.TLSCertKey) + } + + _, ipnet, err := net.ParseCIDR("127.0.0.1/32") + require.NoError(t, err) + trustedProxies := conf.IPNetworks{conf.IPNetwork(*ipnet)} + + var strm *stream.Stream + var reader *stream.Reader + defer func() { + strm.RemoveReader(reader) + }() + dataReceived := make(chan struct{}) + n := 0 + + pathManager := &test.PathManager{ + AddPublisherImpl: func(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + require.Equal(t, "user=myuser&pass=mypass¶m=value", req.AccessRequest.Query) + require.Equal(t, "myuser", req.AccessRequest.Credentials.User) + require.Equal(t, "mypass", req.AccessRequest.Credentials.Pass) + + strm = &stream.Stream{ + OrigDesc: req.Desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err2 := strm.Initialize() + require.NoError(t, err2) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err2 = subStream.Initialize() + require.NoError(t, err2) + + reader = &stream.Reader{Parent: test.NilLogger} + + reader.OnData( + strm.OrigDesc.Medias[0], + strm.OrigDesc.Medias[0].Formats[0], + func(u *unit.Unit) error { + switch n { + case 0: + require.Equal(t, unit.PayloadH264(nil), u.Payload) + + case 1: + require.Equal(t, unit.PayloadH264{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5, 2, 3, 4}, + }, u.Payload) + close(dataReceived) + + default: + t.Errorf("should not happen") + } + n++ + return nil + }) + + strm.AddReader(reader) + + return &defs.PathAddPublisherRes{ + Path: &dummyPath{}, + User: req.AccessRequest.Credentials.User, + SubStream: subStream, + }, nil + }, + } + + s := &Server{ + Address: "127.0.0.1:1939", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + Encryption: encrypt == "tls", + ServerCert: serverCertFpath, + ServerKey: serverKeyFpath, + RTSPAddress: "", + TrustedProxies: trustedProxies, + RunOnConnect: "", + RunOnConnectRestart: false, + RunOnDisconnect: "", + ExternalCmdPool: nil, + PathManager: pathManager, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + var rawURL string + + if encrypt == "tls" { + rawURL += "rtmps://" + } else { + rawURL += "rtmp://" + } + + rawURL += "127.0.0.1:1939/teststream?user=myuser&pass=mypass¶m=value" + + u, err := url.Parse(rawURL) + require.NoError(t, err) + + var dialContext func(ctx context.Context, network, address string) (net.Conn, error) + if proxy == "proxy" { + dialContext = func(ctx context.Context, network, address string) (net.Conn, error) { + c, err2 := (&net.Dialer{}).DialContext(ctx, network, address) + if err2 != nil { + return nil, err2 + } + header := &proxyproto.Header{ + Version: 1, + Command: proxyproto.PROXY, + TransportProtocol: proxyproto.TCPv4, + SourceAddr: &net.TCPAddr{IP: net.ParseIP("192.168.1.100"), Port: 1234}, + DestinationAddr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 1939}, + } + _, err2 = header.WriteTo(c) + if err2 != nil { + return nil, err2 + } + return c, nil + } + } + + conn := &gortmplib.Client{ + URL: u, + TLSConfig: &tls.Config{InsecureSkipVerify: true}, + Publish: true, + DialContext: dialContext, + } + err = conn.Initialize(context.Background()) + require.NoError(t, err) + defer conn.Close() + + w := &gortmplib.Writer{ + Conn: conn, + Tracks: []*gortmplib.Track{ + {Codec: &codecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }}, + {Codec: &codecs.MPEG4Audio{ + Config: test.FormatMPEG4Audio.Config, + }}, + }, + } + err = w.Initialize() + require.NoError(t, err) + + err = w.WriteH264( + w.Tracks[0], + 2*time.Second, 2*time.Second, [][]byte{ + {5, 2, 3, 4}, + }) + require.NoError(t, err) + + <-dataReceived + + list, err := s.APIConnsList() + require.NoError(t, err) + require.Equal(t, &defs.APIRTMPConnList{ + Items: []defs.APIRTMPConn{ + { + ID: list.Items[0].ID, + Created: list.Items[0].Created, + RemoteAddr: list.Items[0].RemoteAddr, + State: "publish", + Path: "teststream", + Query: "user=myuser&pass=mypass¶m=value", + User: "myuser", + UserAgent: list.Items[0].UserAgent, + InboundBytes: list.Items[0].InboundBytes, + OutboundBytes: list.Items[0].OutboundBytes, + OutboundFramesDiscarded: list.Items[0].OutboundFramesDiscarded, + BytesReceived: list.Items[0].BytesReceived, + BytesSent: list.Items[0].BytesSent, + }, + }, + }, list) + }) + } + } +} + +func TestServerRead(t *testing.T) { + for _, encrypt := range []string{ + "plain", + "tls", + } { + t.Run(encrypt, func(t *testing.T) { + var serverCertFpath string + var serverKeyFpath string + + if encrypt == "tls" { + serverCertFpath = test.CreateTempFile(t, test.TLSCertPub) + serverKeyFpath = test.CreateTempFile(t, test.TLSCertKey) + } + desc := &description.Session{Medias: []*description.Media{test.MediaH264}} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + pathManager := &test.PathManager{ + AddReaderImpl: func(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + require.Equal(t, "user=myuser&pass=mypass¶m=value", req.AccessRequest.Query) + require.Equal(t, "myuser", req.AccessRequest.Credentials.User) + require.Equal(t, "mypass", req.AccessRequest.Credentials.Pass) + return &defs.PathAddReaderRes{Path: &dummyPath{}, User: req.AccessRequest.Credentials.User, Stream: strm}, nil + }, + } + + s := &Server{ + Address: "127.0.0.1:1939", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + Encryption: encrypt == "tls", + ServerCert: serverCertFpath, + ServerKey: serverKeyFpath, + RTSPAddress: "", + RunOnConnect: "", + RunOnConnectRestart: false, + RunOnDisconnect: "", + ExternalCmdPool: nil, + PathManager: pathManager, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + var rawURL string + + if encrypt == "tls" { + rawURL += "rtmps://" + } else { + rawURL += "rtmp://" + } + + rawURL += "127.0.0.1:1939/teststream?user=myuser&pass=mypass¶m=value" + + u, err := url.Parse(rawURL) + require.NoError(t, err) + + conn := &gortmplib.Client{ + URL: u, + TLSConfig: &tls.Config{InsecureSkipVerify: true}, + Publish: false, + } + err = conn.Initialize(context.Background()) + require.NoError(t, err) + defer conn.Close() + + strm.WaitForReaders() + + go func() { + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + NTP: time.Time{}, + Payload: unit.PayloadH264{ + {5, 2, 3, 4}, // IDR + }, + }) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + NTP: time.Time{}, + PTS: 2 * 90000, + Payload: unit.PayloadH264{ + {5, 2, 3, 4}, // IDR + }, + }) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + NTP: time.Time{}, + PTS: 3 * 90000, + Payload: unit.PayloadH264{ + {5, 2, 3, 4}, // IDR + }, + }) + }() + + r := &gortmplib.Reader{ + Conn: conn, + } + err = r.Initialize() + require.NoError(t, err) + + tracks := r.Tracks() + require.Len(t, tracks, 1) + _, ok := tracks[0].Codec.(*codecs.H264) + require.True(t, ok) + + r.OnDataH264(tracks[0], func(_ time.Duration, _ time.Duration, au [][]byte) { + require.Equal(t, [][]byte{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5, 2, 3, 4}, + }, au) + }) + + err = r.Read() + require.NoError(t, err) + + list, err := s.APIConnsList() + require.NoError(t, err) + require.Equal(t, &defs.APIRTMPConnList{ + Items: []defs.APIRTMPConn{ + { + ID: list.Items[0].ID, + Created: list.Items[0].Created, + RemoteAddr: list.Items[0].RemoteAddr, + State: "read", + Path: "teststream", + Query: "user=myuser&pass=mypass¶m=value", + User: "myuser", + UserAgent: list.Items[0].UserAgent, + InboundBytes: list.Items[0].InboundBytes, + OutboundBytes: list.Items[0].OutboundBytes, + OutboundFramesDiscarded: list.Items[0].OutboundFramesDiscarded, + BytesReceived: list.Items[0].BytesReceived, + BytesSent: list.Items[0].BytesSent, + }, + }, + }, list) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/conn.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/conn.go new file mode 100644 index 0000000000000000000000000000000000000000..7bbe9976b20336e87b426c505c1fc74f2d2054c4 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/conn.go @@ -0,0 +1,241 @@ +package rtsp + +import ( + "errors" + "fmt" + "net" + "slices" + "strings" + "time" + + "github.com/bluenviron/gortsplib/v5" + rtspauth "github.com/bluenviron/gortsplib/v5/pkg/auth" + "github.com/bluenviron/gortsplib/v5/pkg/base" + "github.com/bluenviron/gortsplib/v5/pkg/liberrors" + "github.com/google/uuid" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/hooks" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/rtsp" +) + +func absoluteURL(req *base.Request, v string) string { + if strings.HasPrefix(v, "/") { + ur := base.URL{ + Scheme: req.URL.Scheme, + Host: req.URL.Host, + Path: v, + } + return ur.String() + } + + return v +} + +func tunnelLabel(t gortsplib.Tunnel) string { + switch t { + case gortsplib.TunnelHTTP: + return "http" + case gortsplib.TunnelWebSocket: + return "websocket" + case gortsplib.TunnelNone: + return "none" + } + return "unknown" +} + +type connParent interface { + logger.Writer + getSessionByRSessionUnsafe(rsession *gortsplib.ServerSession) *session +} + +type conn struct { + encryption bool + rtspAddress string + authMethods []rtspauth.VerifyMethod + readTimeout conf.Duration + runOnConnect string + runOnConnectRestart bool + runOnDisconnect string + externalCmdPool *externalcmd.Pool + pathManager serverPathManager + rconn *gortsplib.ServerConn + rserver *gortsplib.Server + parent connParent + + uuid uuid.UUID + created time.Time + onDisconnectHook func() +} + +func (c *conn) initialize() { + c.uuid = uuid.New() + c.created = time.Now() + + c.Log(logger.Info, "opened") + + c.onDisconnectHook = hooks.OnConnect(hooks.OnConnectParams{ + Logger: c, + ExternalCmdPool: c.externalCmdPool, + RunOnConnect: c.runOnConnect, + RunOnConnectRestart: c.runOnConnectRestart, + RunOnDisconnect: c.runOnDisconnect, + RTSPAddress: c.rtspAddress, + Desc: defs.APIPathReader{ + Type: func() defs.APIPathReaderType { + if c.encryption { + return defs.APIPathReaderTypeRTSPSConn + } + return defs.APIPathReaderTypeRTSPConn + }(), + ID: c.uuid.String(), + }, + }) +} + +// Log implements logger.Writer. +func (c *conn) Log(level logger.Level, format string, args ...any) { + c.parent.Log(level, "[conn %v] "+format, append([]any{c.rconn.NetConn().RemoteAddr()}, args...)...) +} + +// Conn returns the RTSP connection. +func (c *conn) Conn() *gortsplib.ServerConn { + return c.rconn +} + +func (c *conn) remoteAddr() net.Addr { + return c.rconn.NetConn().RemoteAddr() +} + +func (c *conn) ip() net.IP { + return c.rconn.NetConn().RemoteAddr().(*net.TCPAddr).IP +} + +// onClose is called by rtspServer. +func (c *conn) onClose(err error) { + c.Log(logger.Info, "closed: %v", err) + + c.onDisconnectHook() +} + +// onRequest is called by rtspServer. +func (c *conn) onRequest(req *base.Request) { + c.Log(logger.Debug, "[c->s] %v", req) +} + +// OnResponse is called by rtspServer. +func (c *conn) OnResponse(res *base.Response) { + c.Log(logger.Debug, "[s->c] %v", res) +} + +// onDescribe is called by rtspServer. +func (c *conn) onDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx, +) (*base.Response, *gortsplib.ServerStream, error) { + if len(ctx.Path) == 0 || ctx.Path[0] != '/' { + return &base.Response{ + StatusCode: base.StatusBadRequest, + }, nil, fmt.Errorf("invalid path") + } + ctx.Path = ctx.Path[1:] + + // CustomVerifyFunc prevents hashed credentials from working. + // Use it only when strictly needed. + var customVerifyFunc func(expectedUser, expectedPass string) bool + if slices.Contains(c.authMethods, rtspauth.VerifyMethodDigestMD5) { + customVerifyFunc = func(expectedUser, expectedPass string) bool { + return c.rconn.VerifyCredentials(ctx.Request, expectedUser, expectedPass) + } + } + + res, err := c.pathManager.Describe(defs.PathDescribeReq{ + AccessRequest: defs.PathAccessRequest{ + Name: ctx.Path, + Query: ctx.Query, + Proto: auth.ProtocolRTSP, + ID: &c.uuid, + Credentials: rtsp.Credentials(ctx.Request), + IP: c.ip(), + CustomVerifyFunc: customVerifyFunc, + }, + }) + if err != nil { + if terr, ok := errors.AsType[*auth.Error](err); ok { + res, err2 := c.handleAuthError(terr) + return res, nil, err2 + } + + if _, ok := errors.AsType[*defs.PathNoStreamAvailableError](err); ok { + return &base.Response{ + StatusCode: base.StatusNotFound, + }, nil, err + } + + return &base.Response{ + StatusCode: base.StatusBadRequest, + }, nil, err + } + + if res.Redirect != "" { + return &base.Response{ + StatusCode: base.StatusFound, + Header: base.Header{ + "Location": base.HeaderValue{absoluteURL(ctx.Request, res.Redirect)}, + }, + }, nil, nil + } + + var strm *gortsplib.ServerStream + if !c.encryption { + strm, err = res.Stream.RTSPStream(c.rserver) + } else { + strm, err = res.Stream.RTSPSStream(c.rserver) + } + + if err != nil { + return &base.Response{ + StatusCode: base.StatusBadRequest, + }, nil, err + } + + return &base.Response{ + StatusCode: base.StatusOK, + }, strm, nil +} + +func (c *conn) handleAuthError(err *auth.Error) (*base.Response, error) { + if err.AskCredentials { + return &base.Response{ + StatusCode: base.StatusUnauthorized, + }, liberrors.ErrServerAuth{} + } + + return &base.Response{ + StatusCode: base.StatusUnauthorized, + }, err +} + +func (c *conn) apiItem() *defs.APIRTSPConn { + stats := c.rconn.Stats() + + return &defs.APIRTSPConn{ + ID: c.uuid, + Created: c.created, + RemoteAddr: c.remoteAddr().String(), + Session: func() *uuid.UUID { + sx := c.parent.getSessionByRSessionUnsafe(c.rconn.Session()) + if sx != nil { + return &sx.uuid + } + return nil + }(), + Tunnel: tunnelLabel(c.rconn.Transport().Tunnel), + InboundBytes: stats.InboundBytes, + OutboundBytes: stats.OutboundBytes, + BytesReceived: stats.InboundBytes, + BytesSent: stats.OutboundBytes, + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/mpegts_demuxer.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/mpegts_demuxer.go new file mode 100644 index 0000000000000000000000000000000000000000..6bc018540fc1698e34054bb0f39cca94c0aff877 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/mpegts_demuxer.go @@ -0,0 +1,124 @@ +package rtsp + +import ( + "errors" + "fmt" + "io" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/pion/rtp" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/errordumper" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/mpegts" + "github.com/bluenviron/mediamtx/internal/stream" +) + +// mpegtsDemuxer demuxes an MPEG-TS stream received via RTP into component streams. +type mpegtsDemuxer struct { + session *session + pathManager serverPathManager + pathConf *conf.Path + mpegtsMedia *description.Media + mpegtsFormat *format.MPEGTS + decodeErrors *errordumper.Dumper + pathName string + query string + + pipeWriter *io.PipeWriter +} + +func (d *mpegtsDemuxer) initialize() error { + decoder, err := d.mpegtsFormat.CreateDecoder() + if err != nil { + return fmt.Errorf("failed to create MPEG-TS decoder: %w", err) + } + + pr, pw := io.Pipe() + d.pipeWriter = pw + + d.session.rsession.OnPacketRTP(d.mpegtsMedia, d.mpegtsFormat, func(pkt *rtp.Packet) { + tsData, decErr := decoder.Decode(pkt) + if decErr != nil { + d.decodeErrors.Add(decErr) + return + } + + for _, data := range tsData { + _, err = pw.Write(data) + if err != nil { + d.session.Log(logger.Warn, "demuxer pipe write error: %v", err) + return + } + } + }) + + go d.run(pr) + + return nil +} + +func (d *mpegtsDemuxer) close() { + d.pipeWriter.CloseWithError(io.EOF) +} + +func (d *mpegtsDemuxer) run(pr *io.PipeReader) { + err := d.doRun(pr) + if err != nil { + d.session.Log(logger.Error, "MPEG-TS demuxer error: %v", err) + d.session.Close() + } +} + +func (d *mpegtsDemuxer) doRun(pr *io.PipeReader) error { + r := &mpegts.EnhancedReader{R: pr} + err := r.Initialize() + if err != nil { + return fmt.Errorf("failed to initialize MPEG-TS reader: %w", err) + } + + r.OnDecodeError(func(err error) { + d.decodeErrors.Add(err) + }) + + var subStream *stream.SubStream + + medias, err := mpegts.ToStream(r, &subStream, d.session) + if err != nil { + return fmt.Errorf("failed to map MPEG-TS to stream: %w", err) + } + + res, err := d.pathManager.AddPublisher(defs.PathAddPublisherReq{ + Author: d.session, + Desc: &description.Session{Medias: medias}, + UseRTPPackets: false, + ReplaceNTP: true, + ConfToCompare: d.pathConf, + AccessRequest: defs.PathAccessRequest{ + Name: d.pathName, + Query: d.query, + Publish: true, + SkipAuth: true, + }, + }) + if err != nil { + return fmt.Errorf("failed to add publisher: %w", err) + } + + defer res.Path.RemovePublisher(defs.PathRemovePublisherReq{Author: d.session}) + + subStream = res.SubStream + + for { + err = r.Read() + if err != nil { + if !errors.Is(err, io.EOF) { + return err + } + return nil + } + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/server.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/server.go new file mode 100644 index 0000000000000000000000000000000000000000..86c1b109642e400563734e04bcef4da081ed5e53 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/server.go @@ -0,0 +1,596 @@ +// Package rtsp contains a RTSP server. +package rtsp + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "net" + "reflect" + "sort" + "strings" + "sync" + "time" + + "github.com/bluenviron/gortsplib/v5" + "github.com/bluenviron/gortsplib/v5/pkg/auth" + "github.com/bluenviron/gortsplib/v5/pkg/base" + "github.com/bluenviron/gortsplib/v5/pkg/liberrors" + "github.com/google/uuid" + + "github.com/bluenviron/mediamtx/internal/certloader" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/packetdumper" + "github.com/bluenviron/mediamtx/internal/protocols/proxy" +) + +// ErrConnNotFound is returned when a connection is not found. +var ErrConnNotFound = errors.New("connection not found") + +// ErrSessionNotFound is returned when a session is not found. +var ErrSessionNotFound = errors.New("session not found") + +func interfaceIsEmpty(i any) bool { + return reflect.ValueOf(i).Kind() != reflect.Pointer || reflect.ValueOf(i).IsNil() +} + +func printAddresses(srv *gortsplib.Server) string { + var ret []string + + tmp := srv.RTSPAddress + if srv.TLSConfig == nil { + tmp += " (TCP/RTSP)" + } else { + tmp += " (TCP/RTSPS)" + } + ret = append(ret, tmp) + + if srv.UDPRTPAddress != "" { + tmp = srv.UDPRTPAddress + if srv.TLSConfig == nil { + tmp += " (UDP/RTP)" + } else { + tmp += " (UDP/SRTP)" + } + ret = append(ret, tmp) + } + + if srv.UDPRTCPAddress != "" { + tmp = srv.UDPRTCPAddress + if srv.TLSConfig == nil { + tmp += " (UDP/RTCP)" + } else { + tmp += " (UDP/SRTCP)" + } + ret = append(ret, tmp) + } + + return strings.Join(ret, ", ") +} + +type serverMetrics interface { + SetRTSPSServer(defs.APIRTSPServer) + SetRTSPServer(defs.APIRTSPServer) +} + +type serverPathManager interface { + FindPathConf(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) + Describe(req defs.PathDescribeReq) (*defs.PathDescribeRes, error) + AddPublisher(_ defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) + AddReader(_ defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) +} + +type serverParent interface { + logger.Writer +} + +// Server is a RTSP server. +type Server struct { + Address string + AuthMethods []auth.VerifyMethod + DumpPackets bool + UDPReadBufferSize uint + ReadTimeout conf.Duration + WriteTimeout conf.Duration + WriteQueueSize int + RTSPTransports conf.RTSPTransports + RTPAddress string + RTCPAddress string + MulticastIPRange string + MulticastRTPPort int + MulticastRTCPPort int + Encryption bool + ServerCert string + ServerKey string + RTSPAddress string + TrustedProxies conf.IPNetworks + Transports conf.RTSPTransports + RunOnConnect string + RunOnConnectRestart bool + RunOnDisconnect string + ExternalCmdPool *externalcmd.Pool + Metrics serverMetrics + PathManager serverPathManager + Parent serverParent + + ctx context.Context + ctxCancel func() + wg sync.WaitGroup + srv *gortsplib.Server + mutex sync.RWMutex + conns map[*gortsplib.ServerConn]*conn + sessions map[*gortsplib.ServerSession]*session + loader *certloader.CertLoader +} + +// Initialize initializes the server. +func (s *Server) Initialize() error { + s.ctx, s.ctxCancel = context.WithCancel(context.Background()) + + s.conns = make(map[*gortsplib.ServerConn]*conn) + s.sessions = make(map[*gortsplib.ServerSession]*session) + + s.srv = &gortsplib.Server{ + Handler: s, + ReadTimeout: time.Duration(s.ReadTimeout), + WriteTimeout: time.Duration(s.WriteTimeout), + UDPReadBufferSize: int(s.UDPReadBufferSize), + WriteQueueSize: s.WriteQueueSize, + RTSPAddress: s.Address, + AuthMethods: s.AuthMethods, + } + + if _, ok := s.RTSPTransports[gortsplib.ProtocolUDP]; ok { + s.srv.UDPRTPAddress = s.RTPAddress + s.srv.UDPRTCPAddress = s.RTCPAddress + } + + if _, ok := s.RTSPTransports[gortsplib.ProtocolUDPMulticast]; ok { + s.srv.MulticastIPRange = s.MulticastIPRange + s.srv.MulticastRTPPort = s.MulticastRTPPort + s.srv.MulticastRTCPPort = s.MulticastRTCPPort + } + + if s.Encryption { + s.loader = &certloader.CertLoader{ + CertPath: s.ServerCert, + KeyPath: s.ServerKey, + Parent: s.Parent, + } + err := s.loader.Initialize() + if err != nil { + return err + } + + s.srv.TLSConfig = &tls.Config{GetCertificate: s.loader.GetCertificate()} + } + + s.srv.Listen = func(network, address string) (net.Listener, error) { + ln, err := net.Listen(network, address) + if err != nil { + return nil, err + } + + if s.DumpPackets { + var proto string + if s.Encryption { + proto = "rtsps" + } else { + proto = "rtsp" + } + + ln = &packetdumper.Listener{ + Wrapped: ln, + Prefix: proto + "_server_conn", + } + } + + if len(s.TrustedProxies) > 0 { + pl := &proxy.Listener{ + Wrapped: ln, + TrustedProxies: s.TrustedProxies, + } + pl.Initialize() + ln = pl + } + + return ln, nil + } + + s.srv.TLSListen = func(network, laddr string, config *tls.Config) (net.Listener, error) { + ln, err := s.srv.Listen(network, laddr) + if err != nil { + return nil, err + } + + if s.DumpPackets { + ln = &packetdumper.TLSListener{ + Wrapped: ln, + TLSConfig: config, + } + } else { + ln = tls.NewListener(ln, config) + } + + return ln, nil + } + + s.srv.ListenPacket = func(network, address string) (net.PacketConn, error) { + pc, err := net.ListenPacket(network, address) + if err != nil { + return nil, err + } + + if s.DumpPackets { + var proto string + if s.Encryption { + proto = "rtsps" + } else { + proto = "rtsp" + } + + pc2 := &packetdumper.PacketConn{ + Wrapped: pc, + Prefix: proto + "_server_packet_conn", + } + err = pc2.Initialize() + if err != nil { + pc.Close() //nolint:errcheck + return nil, err + } + + pc = pc2 + } + + return pc, nil + } + + err := s.srv.Start() + if err != nil { + return err + } + + s.Log(logger.Info, "started with listeners on %s", printAddresses(s.srv)) + + s.wg.Add(1) + go s.run() + + if !interfaceIsEmpty(s.Metrics) { + if s.Encryption { + s.Metrics.SetRTSPSServer(s) + } else { + s.Metrics.SetRTSPServer(s) + } + } + + return nil +} + +// Log implements logger.Writer. +func (s *Server) Log(level logger.Level, format string, args ...any) { + label := func() string { + if s.Encryption { + return "RTSPS" + } + return "RTSP" + }() + s.Parent.Log(level, "[%s] "+format, append([]any{label}, args...)...) +} + +// Close closes the server. +func (s *Server) Close() { + s.Log(logger.Info, "closing") + + if !interfaceIsEmpty(s.Metrics) { + if s.Encryption { + s.Metrics.SetRTSPSServer(nil) + } else { + s.Metrics.SetRTSPServer(nil) + } + } + + s.ctxCancel() + s.wg.Wait() + + if s.loader != nil { + s.loader.Close() + } +} + +func (s *Server) run() { + defer s.wg.Done() + + serverErr := make(chan error) + go func() { + serverErr <- s.srv.Wait() + }() + +outer: + select { + case err := <-serverErr: + s.Log(logger.Error, "%s", err) + break outer + + case <-s.ctx.Done(): + s.srv.Close() + <-serverErr + break outer + } + + s.ctxCancel() +} + +// OnConnOpen implements gortsplib.ServerHandlerOnConnOpen. +func (s *Server) OnConnOpen(ctx *gortsplib.ServerHandlerOnConnOpenCtx) { + c := &conn{ + encryption: s.Encryption, + rtspAddress: s.RTSPAddress, + authMethods: s.AuthMethods, + readTimeout: s.ReadTimeout, + runOnConnect: s.RunOnConnect, + runOnConnectRestart: s.RunOnConnectRestart, + runOnDisconnect: s.RunOnDisconnect, + externalCmdPool: s.ExternalCmdPool, + pathManager: s.PathManager, + rconn: ctx.Conn, + rserver: s.srv, + parent: s, + } + c.initialize() + s.mutex.Lock() + s.conns[ctx.Conn] = c + s.mutex.Unlock() + + ctx.Conn.SetUserData(c) +} + +// OnConnClose implements gortsplib.ServerHandlerOnConnClose. +func (s *Server) OnConnClose(ctx *gortsplib.ServerHandlerOnConnCloseCtx) { + s.mutex.Lock() + c := s.conns[ctx.Conn] + delete(s.conns, ctx.Conn) + s.mutex.Unlock() + c.onClose(ctx.Error) +} + +// OnRequest implements gortsplib.ServerHandlerOnRequest. +func (s *Server) OnRequest(sc *gortsplib.ServerConn, req *base.Request) { + c := sc.UserData().(*conn) + c.onRequest(req) +} + +// OnResponse implements gortsplib.ServerHandlerOnResponse. +func (s *Server) OnResponse(sc *gortsplib.ServerConn, res *base.Response) { + c := sc.UserData().(*conn) + c.OnResponse(res) +} + +// OnSessionOpen implements gortsplib.ServerHandlerOnSessionOpen. +func (s *Server) OnSessionOpen(ctx *gortsplib.ServerHandlerOnSessionOpenCtx) { + se := &session{ + encryption: s.Encryption, + transports: s.Transports, + rsession: ctx.Session, + rconn: ctx.Conn, + rserver: s.srv, + externalCmdPool: s.ExternalCmdPool, + pathManager: s.PathManager, + parent: s, + } + se.initialize() + s.mutex.Lock() + s.sessions[ctx.Session] = se + s.mutex.Unlock() + ctx.Session.SetUserData(se) +} + +// OnSessionClose implements gortsplib.ServerHandlerOnSessionClose. +func (s *Server) OnSessionClose(ctx *gortsplib.ServerHandlerOnSessionCloseCtx) { + s.mutex.Lock() + se := s.sessions[ctx.Session] + delete(s.sessions, ctx.Session) + s.mutex.Unlock() + + if se != nil { + se.onClose(ctx.Error) + } +} + +// OnDescribe implements gortsplib.ServerHandlerOnDescribe. +func (s *Server) OnDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx, +) (*base.Response, *gortsplib.ServerStream, error) { + c := ctx.Conn.UserData().(*conn) + return c.onDescribe(ctx) +} + +// OnAnnounce implements gortsplib.ServerHandlerOnAnnounce. +func (s *Server) OnAnnounce(ctx *gortsplib.ServerHandlerOnAnnounceCtx) (*base.Response, error) { + c := ctx.Conn.UserData().(*conn) + se := ctx.Session.UserData().(*session) + return se.onAnnounce(c, ctx) +} + +// OnSetup implements gortsplib.ServerHandlerOnSetup. +func (s *Server) OnSetup(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) { + c := ctx.Conn.UserData().(*conn) + se := ctx.Session.UserData().(*session) + return se.onSetup(c, ctx) +} + +// OnPlay implements gortsplib.ServerHandlerOnPlay. +func (s *Server) OnPlay(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) { + se := ctx.Session.UserData().(*session) + return se.onPlay(ctx) +} + +// OnRecord implements gortsplib.ServerHandlerOnRecord. +func (s *Server) OnRecord(ctx *gortsplib.ServerHandlerOnRecordCtx) (*base.Response, error) { + se := ctx.Session.UserData().(*session) + return se.onRecord(ctx) +} + +// OnPause implements gortsplib.ServerHandlerOnPause. +func (s *Server) OnPause(ctx *gortsplib.ServerHandlerOnPauseCtx) (*base.Response, error) { + se := ctx.Session.UserData().(*session) + return se.onPause(ctx) +} + +// OnPacketsLost implements gortsplib.ServerHandlerOnPacketsLost. +func (s *Server) OnPacketsLost(ctx *gortsplib.ServerHandlerOnPacketsLostCtx) { + se := ctx.Session.UserData().(*session) + se.onPacketsLost(ctx) +} + +// OnDecodeError implements gortsplib.ServerHandlerOnDecodeError. +func (s *Server) OnDecodeError(ctx *gortsplib.ServerHandlerOnDecodeErrorCtx) { + se := ctx.Session.UserData().(*session) + se.onDecodeError(ctx) +} + +// OnStreamWriteError implements gortsplib.ServerHandlerOnStreamWriteError. +func (s *Server) OnStreamWriteError(ctx *gortsplib.ServerHandlerOnStreamWriteErrorCtx) { + se := ctx.Session.UserData().(*session) + se.onStreamWriteError(ctx) +} + +func (s *Server) findConnByUUID(uuid uuid.UUID) *conn { + for _, c := range s.conns { + if c.uuid == uuid { + return c + } + } + return nil +} + +func (s *Server) findSessionByUUID(uuid uuid.UUID) (*gortsplib.ServerSession, *session) { + for key, sx := range s.sessions { + if sx.uuid == uuid { + return key, sx + } + } + return nil, nil +} + +func (s *Server) getConnByRConnUnsafe(rconn *gortsplib.ServerConn) *conn { + return s.conns[rconn] +} + +func (s *Server) getSessionByRSessionUnsafe(rsession *gortsplib.ServerSession) *session { + return s.sessions[rsession] +} + +// APIConnsList implements defs.APIRTSPServer. +func (s *Server) APIConnsList() (*defs.APIRTSPConnsList, error) { + select { + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + default: + } + + s.mutex.RLock() + defer s.mutex.RUnlock() + + data := &defs.APIRTSPConnsList{ + Items: []defs.APIRTSPConn{}, + } + + for _, c := range s.conns { + data.Items = append(data.Items, *c.apiItem()) + } + + sort.Slice(data.Items, func(i, j int) bool { + return data.Items[i].Created.Before(data.Items[j].Created) + }) + + return data, nil +} + +// APIConnsGet implements defs.APIRTSPServer. +func (s *Server) APIConnsGet(uuid uuid.UUID) (*defs.APIRTSPConn, error) { + select { + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + default: + } + + s.mutex.RLock() + defer s.mutex.RUnlock() + + conn := s.findConnByUUID(uuid) + if conn == nil { + return nil, ErrConnNotFound + } + + return conn.apiItem(), nil +} + +// APISessionsList implements defs.APIRTSPServer. +func (s *Server) APISessionsList() (*defs.APIRTSPSessionList, error) { + select { + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + default: + } + + s.mutex.RLock() + defer s.mutex.RUnlock() + + data := &defs.APIRTSPSessionList{ + Items: []defs.APIRTSPSession{}, + } + + for _, s := range s.sessions { + data.Items = append(data.Items, *s.apiItem()) + } + + sort.Slice(data.Items, func(i, j int) bool { + return data.Items[i].Created.Before(data.Items[j].Created) + }) + + return data, nil +} + +// APISessionsGet implements defs.APIRTSPServer. +func (s *Server) APISessionsGet(uuid uuid.UUID) (*defs.APIRTSPSession, error) { + select { + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + default: + } + + s.mutex.RLock() + defer s.mutex.RUnlock() + + _, sx := s.findSessionByUUID(uuid) + if sx == nil { + return nil, ErrSessionNotFound + } + + return sx.apiItem(), nil +} + +// APISessionsKick implements defs.APIRTSPServer. +func (s *Server) APISessionsKick(uuid uuid.UUID) error { + select { + case <-s.ctx.Done(): + return fmt.Errorf("terminated") + default: + } + + s.mutex.RLock() + defer s.mutex.RUnlock() + + key, sx := s.findSessionByUUID(uuid) + if sx == nil { + return ErrSessionNotFound + } + + sx.Close() + delete(s.sessions, key) + sx.onClose(liberrors.ErrServerTerminated{}) + return nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/server_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..079d637d2602c12c47621e284522e44b93f5f56a --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/server_test.go @@ -0,0 +1,727 @@ +package rtsp + +import ( + "bufio" + "bytes" + "context" + "crypto/tls" + "fmt" + "net" + "sync/atomic" + "testing" + "time" + + "github.com/bluenviron/gortsplib/v5" + rtspauth "github.com/bluenviron/gortsplib/v5/pkg/auth" + "github.com/bluenviron/gortsplib/v5/pkg/base" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + mpegts "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts" + tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs" + "github.com/pires/go-proxyproto" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/bluenviron/mediamtx/internal/unit" + "github.com/pion/rtp" + "github.com/stretchr/testify/require" +) + +type dummyPath struct{} + +func (p *dummyPath) Name() string { + return "teststream" +} + +func (p *dummyPath) SafeConf() *conf.Path { + return &conf.Path{} +} + +func (p *dummyPath) ExternalCmdEnv() externalcmd.Environment { + return externalcmd.Environment{} +} + +func (p *dummyPath) RemovePublisher(_ defs.PathRemovePublisherReq) { +} + +func (p *dummyPath) RemoveReader(_ defs.PathRemoveReaderReq) { +} + +func TestServerPublish(t *testing.T) { + for _, ca := range []string{"basic", "digest", "basic+digest"} { + for _, encrypt := range []string{"plain", "tls"} { + for _, proxy := range []string{"no_proxy", "proxy"} { + t.Run(ca+"_"+encrypt+"_"+proxy, func(t *testing.T) { + var serverCertFpath string + var serverKeyFpath string + + if encrypt == "tls" { + serverCertFpath = test.CreateTempFile(t, test.TLSCertPub) + serverKeyFpath = test.CreateTempFile(t, test.TLSCertKey) + } + + _, ipnet, err := net.ParseCIDR("127.0.0.1/32") + require.NoError(t, err) + trustedProxies := conf.IPNetworks{conf.IPNetwork(*ipnet)} + + var strm *stream.Stream + var reader *stream.Reader + defer func() { + strm.RemoveReader(reader) + }() + dataReceived := make(chan struct{}) + + n := 0 + + pathManager := &test.PathManager{ + FindPathConfImpl: func(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + require.Equal(t, "param=value", req.AccessRequest.Query) + + if ca == "basic" { + require.Nil(t, req.AccessRequest.CustomVerifyFunc) + + if req.AccessRequest.Credentials.User == "" && req.AccessRequest.Credentials.Pass == "" { + return nil, &auth.Error{AskCredentials: true, Wrapped: fmt.Errorf("auth error")} + } + + require.Equal(t, "myuser", req.AccessRequest.Credentials.User) + require.Equal(t, "mypass", req.AccessRequest.Credentials.Pass) + } else { + ok := req.AccessRequest.CustomVerifyFunc("myuser", "mypass") + if n == 0 { + require.False(t, ok) + n++ + return nil, &auth.Error{AskCredentials: true, Wrapped: fmt.Errorf("auth error")} + } + require.True(t, ok) + } + + return &defs.PathFindPathConfRes{Conf: &conf.Path{}, User: req.AccessRequest.Credentials.User}, nil + }, + AddPublisherImpl: func(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + require.Equal(t, "param=value", req.AccessRequest.Query) + require.True(t, req.AccessRequest.SkipAuth) + + strm = &stream.Stream{ + OrigDesc: req.Desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err2 := strm.Initialize() + require.NoError(t, err2) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: true, + } + err2 = subStream.Initialize() + require.NoError(t, err2) + + reader = &stream.Reader{Parent: test.NilLogger} + + reader.OnData( + strm.OrigDesc.Medias[0], + strm.OrigDesc.Medias[0].Formats[0], + func(u *unit.Unit) error { + require.Equal(t, unit.PayloadH264{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5, 2, 3, 4}, + }, u.Payload) + close(dataReceived) + return nil + }) + + strm.AddReader(reader) + + return &defs.PathAddPublisherRes{Path: &dummyPath{}, SubStream: subStream}, nil + }, + } + + var authMethods []rtspauth.VerifyMethod + switch ca { + case "basic": + authMethods = []rtspauth.VerifyMethod{rtspauth.VerifyMethodBasic} + case "digest": + authMethods = []rtspauth.VerifyMethod{rtspauth.VerifyMethodDigestMD5} + default: + authMethods = []rtspauth.VerifyMethod{rtspauth.VerifyMethodBasic, rtspauth.VerifyMethodDigestMD5} + } + + s := &Server{ + Address: "127.0.0.1:8557", + AuthMethods: authMethods, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + WriteQueueSize: 512, + Transports: conf.RTSPTransports{gortsplib.ProtocolTCP: {}}, + Encryption: encrypt == "tls", + ServerCert: serverCertFpath, + ServerKey: serverKeyFpath, + TrustedProxies: trustedProxies, + PathManager: pathManager, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + var scheme string + if encrypt == "tls" { + scheme = "rtsps" + } else { + scheme = "rtsp" + } + + var dialContext func(ctx context.Context, network, address string) (net.Conn, error) + if proxy == "proxy" { + dialContext = func(ctx context.Context, network, address string) (net.Conn, error) { + c, err2 := (&net.Dialer{}).DialContext(ctx, network, address) + if err2 != nil { + return nil, err2 + } + header := &proxyproto.Header{ + Version: 1, + Command: proxyproto.PROXY, + TransportProtocol: proxyproto.TCPv4, + SourceAddr: &net.TCPAddr{IP: net.ParseIP("192.168.1.100"), Port: 1234}, + DestinationAddr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8557}, + } + _, err2 = header.WriteTo(c) + if err2 != nil { + return nil, err2 + } + return c, nil + } + } + + source := gortsplib.Client{ + TLSConfig: &tls.Config{InsecureSkipVerify: true}, + DialContext: dialContext, + } + + media0 := test.UniqueMediaH264() + + err = source.StartRecording( + scheme+"://myuser:mypass@127.0.0.1:8557/teststream?param=value", + &description.Session{Medias: []*description.Media{media0}}) + require.NoError(t, err) + defer source.Close() + + err = source.WritePacketRTP(media0, &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 96, + SequenceNumber: 123, + Timestamp: 45343, + SSRC: 563423, + }, + Payload: []byte{5, 2, 3, 4}, + }) + require.NoError(t, err) + + <-dataReceived + + list, err := s.APISessionsList() + require.NoError(t, err) + require.Equal(t, &defs.APIRTSPSessionList{ + Items: []defs.APIRTSPSession{ + { + ID: list.Items[0].ID, + Created: list.Items[0].Created, + RemoteAddr: list.Items[0].RemoteAddr, + State: "publish", + Path: "teststream", + Query: "param=value", + User: "myuser", + UserAgent: list.Items[0].UserAgent, + InboundBytes: list.Items[0].InboundBytes, + InboundRTPPackets: list.Items[0].InboundRTPPackets, + OutboundBytes: list.Items[0].OutboundBytes, + BytesReceived: list.Items[0].BytesReceived, + BytesSent: list.Items[0].BytesSent, + Conns: list.Items[0].Conns, + RTPPacketsReceived: list.Items[0].RTPPacketsReceived, + Transport: new("TCP"), + Profile: func() *string { + if encrypt == "tls" { + return new("SAVP") + } + return new("AVP") + }(), + }, + }, + }, list) + }) + } + } + } +} + +func TestServerPublishMPEGTS(t *testing.T) { + var strm *stream.Stream + var reader *stream.Reader + defer func() { + if strm != nil && reader != nil { + strm.RemoveReader(reader) + } + }() + + dataReceived := make(chan struct{}) + + pathConf := &conf.Path{RTSPDemuxMpegts: true} + + pathManager := &test.PathManager{ + FindPathConfImpl: func(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + require.Equal(t, "param=value", req.AccessRequest.Query) + return &defs.PathFindPathConfRes{Conf: pathConf}, nil + }, + AddPublisherImpl: func(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + require.Equal(t, "param=value", req.AccessRequest.Query) + require.True(t, req.AccessRequest.SkipAuth) + require.False(t, req.UseRTPPackets) + require.True(t, req.ReplaceNTP) + require.Same(t, pathConf, req.ConfToCompare) + require.Equal(t, &description.Session{Medias: []*description.Media{{ + Type: description.MediaTypeVideo, + Formats: []format.Format{&format.H264{ + PayloadTyp: 96, + PacketizationMode: 1, + }}, + }}}, req.Desc) + + strm = &stream.Stream{ + OrigDesc: req.Desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + reader = &stream.Reader{Parent: test.NilLogger} + n := 0 + + reader.OnData( + strm.OrigDesc.Medias[0], + strm.OrigDesc.Medias[0].Formats[0], + func(u *unit.Unit) error { + if n == 0 { + require.Equal(t, unit.PayloadH264{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5, 1}, + }, u.Payload) + close(dataReceived) + } + n++ + return nil + }) + + strm.AddReader(reader) + + return &defs.PathAddPublisherRes{Path: &dummyPath{}, SubStream: subStream}, nil + }, + } + + s := &Server{ + Address: "127.0.0.1:8557", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + WriteQueueSize: 512, + Transports: conf.RTSPTransports{gortsplib.ProtocolTCP: {}}, + PathManager: pathManager, + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + source := gortsplib.Client{} + + media0 := &description.Media{ + Type: description.MediaTypeApplication, + Formats: []format.Format{&format.MPEGTS{}}, + } + + err = source.StartRecording( + "rtsp://127.0.0.1:8557/teststream?param=value", + &description.Session{Medias: []*description.Media{media0}}) + require.NoError(t, err) + defer source.Close() + + track := &mpegts.Track{Codec: &tscodecs.H264{}} + + var buf bytes.Buffer + bw := bufio.NewWriter(&buf) + w := &mpegts.Writer{W: bw, Tracks: []*mpegts.Track{track}} + err = w.Initialize() + require.NoError(t, err) + + // the MPEG-TS muxer needs two PES packets in order to write the first one + err = w.WriteH264(track, 0, 0, [][]byte{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5, 1}, + }) + require.NoError(t, err) + + err = w.WriteH264(track, 0, 0, [][]byte{{5, 2}}) + require.NoError(t, err) + + err = bw.Flush() + require.NoError(t, err) + + raw := buf.Bytes() + require.NotEmpty(t, raw) + require.Zero(t, len(raw)%188) + + tsPackets := make([][]byte, 0, len(raw)/188) + for len(raw) > 0 { + tsPackets = append(tsPackets, raw[:188:188]) + raw = raw[188:] + } + + encoder, err := media0.Formats[0].(*format.MPEGTS).CreateEncoder() + require.NoError(t, err) + + rtpPackets, err := encoder.Encode(tsPackets) + require.NoError(t, err) + + for _, pkt := range rtpPackets { + err = source.WritePacketRTP(media0, pkt) + require.NoError(t, err) + } + + <-dataReceived +} + +func TestServerRead(t *testing.T) { + for _, ca := range []string{"basic", "digest", "basic+digest"} { + t.Run(ca, func(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{test.MediaH264}} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + n := 0 + + pathManager := &test.PathManager{ + DescribeImpl: func(req defs.PathDescribeReq) (*defs.PathDescribeRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + require.Equal(t, "param=value", req.AccessRequest.Query) + + if ca == "basic" { + require.Nil(t, req.AccessRequest.CustomVerifyFunc) + + if req.AccessRequest.Credentials.User == "" && req.AccessRequest.Credentials.Pass == "" { + return nil, &auth.Error{AskCredentials: true, Wrapped: fmt.Errorf("auth error")} + } + + require.Equal(t, "myuser", req.AccessRequest.Credentials.User) + require.Equal(t, "mypass", req.AccessRequest.Credentials.Pass) + } else { + ok := req.AccessRequest.CustomVerifyFunc("myuser", "mypass") + if n == 0 { + require.False(t, ok) + n++ + return nil, &auth.Error{AskCredentials: true, Wrapped: fmt.Errorf("auth error")} + } + require.True(t, ok) + } + + return &defs.PathDescribeRes{ + Path: &dummyPath{}, + Stream: strm, + }, nil + }, + AddReaderImpl: func(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + require.Equal(t, "param=value", req.AccessRequest.Query) + + if ca == "basic" { + require.Nil(t, req.AccessRequest.CustomVerifyFunc) + require.Equal(t, "myuser", req.AccessRequest.Credentials.User) + require.Equal(t, "mypass", req.AccessRequest.Credentials.Pass) + } else { + ok := req.AccessRequest.CustomVerifyFunc("myuser", "mypass") + require.True(t, ok) + } + + return &defs.PathAddReaderRes{Path: &dummyPath{}, User: req.AccessRequest.Credentials.User, Stream: strm}, nil + }, + } + + var authMethods []rtspauth.VerifyMethod + switch ca { + case "basic": + authMethods = []rtspauth.VerifyMethod{rtspauth.VerifyMethodBasic} + case "digest": + authMethods = []rtspauth.VerifyMethod{rtspauth.VerifyMethodDigestMD5} + default: + authMethods = []rtspauth.VerifyMethod{rtspauth.VerifyMethodBasic, rtspauth.VerifyMethodDigestMD5} + } + + s := &Server{ + Address: "127.0.0.1:8557", + AuthMethods: authMethods, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + WriteQueueSize: 512, + Transports: conf.RTSPTransports{gortsplib.ProtocolTCP: {}}, + PathManager: pathManager, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + u, err := base.ParseURL("rtsp://myuser:mypass@127.0.0.1:8557/teststream?param=value") + require.NoError(t, err) + + reader := gortsplib.Client{ + Scheme: u.Scheme, + Host: u.Host, + } + + err = reader.Start() + require.NoError(t, err) + defer reader.Close() + + desc2, _, err := reader.Describe(u) + require.NoError(t, err) + + err = reader.SetupAll(desc2.BaseURL, desc2.Medias) + require.NoError(t, err) + + recv := make(chan struct{}) + + reader.OnPacketRTPAny(func(_ *description.Media, _ format.Format, p *rtp.Packet) { + require.Equal(t, &rtp.Packet{ + Header: rtp.Header{ + Version: 2, + Marker: true, + PayloadType: 96, + SequenceNumber: p.SequenceNumber, + Timestamp: p.Timestamp, + SSRC: p.SSRC, + }, + Payload: []byte{ + 0x18, 0x00, 0x19, 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, 0x00, 0x04, 0x08, 0x06, + 0x07, 0x08, 0x00, 0x04, 0x05, 0x02, 0x03, 0x04, + }, + }, p) + close(recv) + }) + + _, err = reader.Play(nil) + require.NoError(t, err) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + NTP: time.Time{}, + Payload: unit.PayloadH264{ + {5, 2, 3, 4}, // IDR + }, + }) + + <-recv + + list, err := s.APISessionsList() + require.NoError(t, err) + require.Equal(t, &defs.APIRTSPSessionList{ + Items: []defs.APIRTSPSession{ + { + ID: list.Items[0].ID, + Created: list.Items[0].Created, + RemoteAddr: list.Items[0].RemoteAddr, + State: "read", + Path: "teststream", + Query: "param=value", + User: "myuser", + UserAgent: list.Items[0].UserAgent, + InboundBytes: list.Items[0].InboundBytes, + InboundRTPPackets: list.Items[0].InboundRTPPackets, + OutboundBytes: list.Items[0].OutboundBytes, + OutboundRTPPackets: list.Items[0].OutboundRTPPackets, + BytesReceived: list.Items[0].BytesReceived, + BytesSent: list.Items[0].BytesSent, + Conns: list.Items[0].Conns, + RTPPacketsReceived: list.Items[0].RTPPacketsReceived, + RTPPacketsSent: list.Items[0].RTPPacketsSent, + Transport: new("TCP"), + Profile: new("AVP"), + }, + }, + }, list) + }) + } +} + +func TestServerRedirect(t *testing.T) { + for _, ca := range []string{"relative", "absolute"} { + t.Run(ca, func(t *testing.T) { + desc := &description.Session{Medias: []*description.Media{test.MediaH264}} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: true, + } + err = subStream.Initialize() + require.NoError(t, err) + + pathManager := &test.PathManager{ + DescribeImpl: func(req defs.PathDescribeReq) (*defs.PathDescribeRes, error) { + if req.AccessRequest.Name == "path1" { + if ca == "relative" { + return &defs.PathDescribeRes{ + Redirect: "/path2", + }, nil + } + return &defs.PathDescribeRes{ + Redirect: "rtsp://localhost:8557/path2", + }, nil + } + + if req.AccessRequest.Credentials.User == "" && req.AccessRequest.Credentials.Pass == "" { + return nil, &auth.Error{AskCredentials: true, Wrapped: fmt.Errorf("auth error")} + } + + require.Equal(t, "path2", req.AccessRequest.Name) + require.Equal(t, "", req.AccessRequest.Query) + require.Equal(t, "myuser", req.AccessRequest.Credentials.User) + require.Equal(t, "mypass", req.AccessRequest.Credentials.Pass) + + return &defs.PathDescribeRes{ + Path: &dummyPath{}, + Stream: strm, + }, nil + }, + } + + s := &Server{ + Address: "127.0.0.1:8557", + AuthMethods: []rtspauth.VerifyMethod{rtspauth.VerifyMethodBasic}, + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + WriteQueueSize: 512, + Transports: conf.RTSPTransports{gortsplib.ProtocolTCP: {}}, + PathManager: pathManager, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + u, err := base.ParseURL("rtsp://myuser:mypass@127.0.0.1:8557/path1?param=value") + require.NoError(t, err) + + reader := gortsplib.Client{ + Scheme: u.Scheme, + Host: u.Host, + } + + err = reader.Start() + require.NoError(t, err) + defer reader.Close() + + desc2, _, err := reader.Describe(u) + require.NoError(t, err) + + require.Equal(t, desc.Medias[0].Formats, desc2.Medias[0].Formats) + }) + } +} + +func TestAuthError(t *testing.T) { + pathManager := &test.PathManager{ + DescribeImpl: func(req defs.PathDescribeReq) (*defs.PathDescribeRes, error) { + if req.AccessRequest.Credentials.User == "" && req.AccessRequest.Credentials.Pass == "" { + return nil, &auth.Error{AskCredentials: true, Wrapped: fmt.Errorf("auth error")} + } + + return nil, &auth.Error{Wrapped: fmt.Errorf("auth error")} + }, + } + + var n atomic.Int64 + done := make(chan struct{}) + + s := &Server{ + Address: "127.0.0.1:8557", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + WriteQueueSize: 512, + PathManager: pathManager, + Parent: test.Logger(func(l logger.Level, s string, i ...any) { + if l == logger.Info { + if n.Add(1) == 3 { + require.Regexp(t, "authentication failed: auth error$", fmt.Sprintf(s, i...)) + close(done) + } + } + }), + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + u, err := base.ParseURL("rtsp://myuser:mypass@127.0.0.1:8557/teststream?param=value") + require.NoError(t, err) + + reader := gortsplib.Client{ + Scheme: u.Scheme, + Host: u.Host, + } + + err = reader.Start() + require.NoError(t, err) + defer reader.Close() + + _, _, err = reader.Describe(u) + require.EqualError(t, err, "bad status code: 401 (Unauthorized)") + + <-done +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/session.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/session.go new file mode 100644 index 0000000000000000000000000000000000000000..257043beec4dc7ebac7d6d5e46687dcdab72bfa7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/rtsp/session.go @@ -0,0 +1,586 @@ +package rtsp + +import ( + "encoding/hex" + "errors" + "fmt" + "net" + "slices" + "sync" + "time" + + "github.com/bluenviron/gortsplib/v5" + rtspauth "github.com/bluenviron/gortsplib/v5/pkg/auth" + "github.com/bluenviron/gortsplib/v5/pkg/base" + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/gortsplib/v5/pkg/format" + "github.com/bluenviron/gortsplib/v5/pkg/headers" + "github.com/google/uuid" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/counterdumper" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/errordumper" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/hooks" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/rtsp" + "github.com/bluenviron/mediamtx/internal/stream" +) + +func profileLabel(p headers.TransportProfile) string { + switch p { + case headers.TransportProfileSAVP: + return "SAVP" + case headers.TransportProfileAVP: + return "AVP" + } + return "unknown" +} + +func findSingleMPEGTSFormat(desc *description.Session) (*description.Media, *format.MPEGTS) { + if len(desc.Medias) != 1 || len(desc.Medias[0].Formats) != 1 { + return nil, nil + } + + forma := desc.Medias[0].Formats[0] + if forma, ok := forma.(*format.MPEGTS); ok { + return desc.Medias[0], forma + } + + return nil, nil +} + +type sessionParent interface { + logger.Writer + getConnByRConnUnsafe(rconn *gortsplib.ServerConn) *conn +} + +type session struct { + encryption bool + transports conf.RTSPTransports + rsession *gortsplib.ServerSession + rconn *gortsplib.ServerConn + rserver *gortsplib.Server + externalCmdPool *externalcmd.Pool + pathManager serverPathManager + parent sessionParent + + uuid uuid.UUID + created time.Time + pathConf *conf.Path // record only + path defs.Path + stream *stream.Stream + rtspStream *gortsplib.ServerStream + subStream *stream.SubStream + onUnreadHook func() + inboundRTPPacketsLost *counterdumper.Dumper + inboundRTPPacketsInError *errordumper.Dumper + outboundRTPPacketsDiscarded *counterdumper.Dumper + mutex sync.RWMutex + user string + userAgent string + mpegtsDemuxer *mpegtsDemuxer +} + +func (s *session) initialize() { + s.uuid = uuid.New() + s.created = time.Now() + + s.inboundRTPPacketsLost = &counterdumper.Dumper{ + OnReport: func(val uint64) { + s.Log(logger.Warn, "%d RTP %s lost", + val, + func() string { + if val == 1 { + return "packet" + } + return "packets" + }()) + }, + } + s.inboundRTPPacketsLost.Start() + + s.inboundRTPPacketsInError = &errordumper.Dumper{ + OnReport: func(val uint64, last error) { + if val == 1 { + s.Log(logger.Warn, "decode error: %v", last) + } else { + s.Log(logger.Warn, "%d decode errors, last was: %v", val, last) + } + }, + } + s.inboundRTPPacketsInError.Start() + + s.outboundRTPPacketsDiscarded = &counterdumper.Dumper{ + OnReport: func(val uint64) { + s.Log(logger.Warn, "reader is too slow, discarding %d %s", + val, + func() string { + if val == 1 { + return "frame" + } + return "frames" + }()) + }, + } + s.outboundRTPPacketsDiscarded.Start() + + s.Log(logger.Info, "created by %v", s.rconn.NetConn().RemoteAddr()) +} + +// Close closes a Session. +// this is not always called, so things that need to be released +// must go in onClose(). +func (s *session) Close() { + s.rsession.Close() +} + +func (s *session) remoteAddr() net.Addr { + return s.rconn.NetConn().RemoteAddr() +} + +// Log implements logger.Writer. +func (s *session) Log(level logger.Level, format string, args ...any) { + id := hex.EncodeToString(s.uuid[:4]) + s.parent.Log(level, "[session %s] "+format, append([]any{id}, args...)...) +} + +// onClose is called by rtspServer. +func (s *session) onClose(err error) { + if s.rsession.State() == gortsplib.ServerSessionStatePlay { + s.onUnreadHook() + } + + if s.mpegtsDemuxer != nil { + s.mpegtsDemuxer.close() + } + + switch s.rsession.State() { + case gortsplib.ServerSessionStatePrePlay, gortsplib.ServerSessionStatePlay: + s.path.RemoveReader(defs.PathRemoveReaderReq{Author: s}) + + case gortsplib.ServerSessionStateRecord: + if s.path != nil { + s.path.RemovePublisher(defs.PathRemovePublisherReq{Author: s}) + } + } + + s.path = nil + s.stream = nil + s.subStream = nil + + s.outboundRTPPacketsDiscarded.Stop() + s.inboundRTPPacketsInError.Stop() + s.inboundRTPPacketsLost.Stop() + + s.Log(logger.Info, "destroyed: %v", err) +} + +// onAnnounce is called by rtspServer. +func (s *session) onAnnounce(c *conn, ctx *gortsplib.ServerHandlerOnAnnounceCtx) (*base.Response, error) { + if len(ctx.Path) == 0 || ctx.Path[0] != '/' { + return &base.Response{ + StatusCode: base.StatusBadRequest, + }, fmt.Errorf("invalid path") + } + ctx.Path = ctx.Path[1:] + + // CustomVerifyFunc prevents hashed credentials from working. + // Use it only when strictly needed. + var customVerifyFunc func(expectedUser, expectedPass string) bool + if slices.Contains(c.authMethods, rtspauth.VerifyMethodDigestMD5) { + customVerifyFunc = func(expectedUser, expectedPass string) bool { + return c.rconn.VerifyCredentials(ctx.Request, expectedUser, expectedPass) + } + } + + var userAgent string + if ua, ok := ctx.Request.Header["User-Agent"]; ok && len(ua) > 0 { + userAgent = ua[0] + } + + res, err := s.pathManager.FindPathConf(defs.PathFindPathConfReq{ + AccessRequest: defs.PathAccessRequest{ + Name: ctx.Path, + Query: ctx.Query, + Publish: true, + UserAgent: userAgent, + Proto: auth.ProtocolRTSP, + ID: &c.uuid, + Credentials: rtsp.Credentials(ctx.Request), + IP: c.ip(), + CustomVerifyFunc: customVerifyFunc, + }, + }) + if err != nil { + if terr, ok := errors.AsType[*auth.Error](err); ok { + return c.handleAuthError(terr) + } + + return &base.Response{ + StatusCode: base.StatusBadRequest, + }, err + } + + s.pathConf = res.Conf + + s.mutex.Lock() + s.user = res.User + s.userAgent = userAgent + s.mutex.Unlock() + + return &base.Response{ + StatusCode: base.StatusOK, + }, nil +} + +// onSetup is called by rtspServer. +func (s *session) onSetup(c *conn, ctx *gortsplib.ServerHandlerOnSetupCtx, +) (*base.Response, *gortsplib.ServerStream, error) { + if len(ctx.Path) == 0 || ctx.Path[0] != '/' { + return &base.Response{ + StatusCode: base.StatusBadRequest, + }, nil, fmt.Errorf("invalid path") + } + ctx.Path = ctx.Path[1:] + + // in case the client is setupping a stream with UDP or UDP-multicast, and these + // transport protocols are disabled, gortsplib already blocks the request. + // we only have to handle the case in which the transport protocol is TCP + // and it is disabled. + if ctx.Transport.Protocol == gortsplib.ProtocolTCP { + if _, ok := s.transports[gortsplib.ProtocolTCP]; !ok { + return &base.Response{ + StatusCode: base.StatusUnsupportedTransport, + }, nil, nil + } + } + + // CustomVerifyFunc prevents hashed credentials from working. + // Use it only when strictly needed. + var customVerifyFunc func(expectedUser, expectedPass string) bool + if slices.Contains(c.authMethods, rtspauth.VerifyMethodDigestMD5) { + customVerifyFunc = func(expectedUser, expectedPass string) bool { + return c.rconn.VerifyCredentials(ctx.Request, expectedUser, expectedPass) + } + } + + var userAgent string + if ua, ok := ctx.Request.Header["User-Agent"]; ok && len(ua) > 0 { + userAgent = ua[0] + } + + switch s.rsession.State() { + case gortsplib.ServerSessionStateInitial: // play + res, err := s.pathManager.AddReader(defs.PathAddReaderReq{ + Author: s, + AccessRequest: defs.PathAccessRequest{ + Name: ctx.Path, + Query: ctx.Query, + UserAgent: userAgent, + Proto: auth.ProtocolRTSP, + ID: &c.uuid, + Credentials: rtsp.Credentials(ctx.Request), + IP: c.ip(), + CustomVerifyFunc: customVerifyFunc, + }, + }) + if err != nil { + if terr, ok := errors.AsType[*auth.Error](err); ok { + res, err2 := c.handleAuthError(terr) + return res, nil, err2 + } + + if _, ok := errors.AsType[*defs.PathNoStreamAvailableError](err); ok { + return &base.Response{ + StatusCode: base.StatusNotFound, + }, nil, err + } + + return &base.Response{ + StatusCode: base.StatusBadRequest, + }, nil, err + } + + var rtspStream *gortsplib.ServerStream + if !s.encryption { + rtspStream, err = res.Stream.RTSPStream(s.rserver) + } else { + rtspStream, err = res.Stream.RTSPSStream(s.rserver) + } + + if err != nil { + res.Path.RemoveReader(defs.PathRemoveReaderReq{Author: s}) + return &base.Response{ + StatusCode: base.StatusBadRequest, + }, nil, err + } + + s.stream = res.Stream + s.rtspStream = rtspStream + s.path = res.Path + + s.mutex.Lock() + s.user = res.User + s.userAgent = userAgent + s.mutex.Unlock() + + return &base.Response{ + StatusCode: base.StatusOK, + }, s.rtspStream, nil + + case gortsplib.ServerSessionStatePrePlay: // play, subsequent calls + return &base.Response{ + StatusCode: base.StatusOK, + }, s.rtspStream, nil + + default: // record + return &base.Response{ + StatusCode: base.StatusOK, + }, nil, nil + } +} + +// onPlay is called by rtspServer. +func (s *session) onPlay(_ *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) { + h := make(base.Header) + + if s.rsession.State() == gortsplib.ServerSessionStatePrePlay { + s.Log(logger.Info, "is reading from path '%s', with %s, %s", + s.path.Name(), + s.rsession.Transport().Protocol, + defs.MediasInfo(s.rsession.Medias())) + + s.onUnreadHook = hooks.OnRead(hooks.OnReadParams{ + Logger: s, + ExternalCmdPool: s.externalCmdPool, + Conf: s.path.SafeConf(), + ExternalCmdEnv: s.path.ExternalCmdEnv(), + Reader: *s.APIReaderDescribe(), + Query: s.rsession.Query(), + }) + } + + return &base.Response{ + StatusCode: base.StatusOK, + Header: h, + }, nil +} + +// onRecord is called by rtspServer. +func (s *session) onRecord(_ *gortsplib.ServerHandlerOnRecordCtx) (*base.Response, error) { + if s.pathConf.RTSPDemuxMpegts { + mpegtsMedia, mpegtsFormat := findSingleMPEGTSFormat(s.rsession.AnnouncedDescription()) + if mpegtsFormat != nil { + s.Log(logger.Info, "MPEG-TS demux mode enabled, starting demuxer...") + + s.mpegtsDemuxer = &mpegtsDemuxer{ + session: s, + pathManager: s.pathManager, + pathConf: s.pathConf, + mpegtsMedia: mpegtsMedia, + mpegtsFormat: mpegtsFormat, + decodeErrors: s.inboundRTPPacketsInError, + pathName: s.rsession.Path()[1:], + query: s.rsession.Query(), + } + err := s.mpegtsDemuxer.initialize() + if err != nil { + return &base.Response{ + StatusCode: base.StatusInternalServerError, + }, err + } + + return &base.Response{ + StatusCode: base.StatusOK, + }, nil + } + } + + res, err := s.pathManager.AddPublisher(defs.PathAddPublisherReq{ + Author: s, + Desc: s.rsession.AnnouncedDescription(), + UseRTPPackets: true, + ReplaceNTP: !s.pathConf.UseAbsoluteTimestamp, + ConfToCompare: s.pathConf, + AccessRequest: defs.PathAccessRequest{ + Name: s.rsession.Path()[1:], + Query: s.rsession.Query(), + Publish: true, + SkipAuth: true, + UserAgent: s.userAgent, + }, + }) + if err != nil { + return &base.Response{ + StatusCode: base.StatusBadRequest, + }, err + } + + rtsp.ToStream( + s.rsession, + s.rsession.AnnouncedDescription().Medias, + res.Path.SafeConf(), + &s.subStream, + s) + + s.path = res.Path + s.subStream = res.SubStream + + return &base.Response{ + StatusCode: base.StatusOK, + }, nil +} + +// onPause is called by rtspServer. +func (s *session) onPause(_ *gortsplib.ServerHandlerOnPauseCtx) (*base.Response, error) { + // we can't close mpegtsDemuxer during pause because OnPacketRTP() is paused after onPause(), + // therefore a call to pipeWriter.CloseWithError() would cause a race condition. + if s.mpegtsDemuxer != nil { + return &base.Response{ + StatusCode: base.StatusBadRequest, + }, fmt.Errorf("cannot pause in MPEG-TS demux mode") + } + + switch s.rsession.State() { + case gortsplib.ServerSessionStatePlay: + s.onUnreadHook() + + case gortsplib.ServerSessionStateRecord: + s.path.RemovePublisher(defs.PathRemovePublisherReq{Author: s}) + } + + return &base.Response{ + StatusCode: base.StatusOK, + }, nil +} + +// APIReaderDescribe implements reader. +func (s *session) APIReaderDescribe() *defs.APIPathReader { + return &defs.APIPathReader{ + Type: func() defs.APIPathReaderType { + if s.encryption { + return defs.APIPathReaderTypeRTSPSSession + } + return defs.APIPathReaderTypeRTSPSession + }(), + ID: s.uuid.String(), + } +} + +// APISourceDescribe implements source. +func (s *session) APISourceDescribe() *defs.APIPathSource { + return &defs.APIPathSource{ + Type: func() defs.APIPathSourceType { + if s.encryption { + return defs.APIPathSourceTypeRTSPSSession + } + return defs.APIPathSourceTypeRTSPSession + }(), + ID: s.uuid.String(), + } +} + +// onPacketLost is called by rtspServer. +func (s *session) onPacketsLost(ctx *gortsplib.ServerHandlerOnPacketsLostCtx) { + s.inboundRTPPacketsLost.Add(ctx.Lost) +} + +// onDecodeError is called by rtspServer. +func (s *session) onDecodeError(ctx *gortsplib.ServerHandlerOnDecodeErrorCtx) { + s.inboundRTPPacketsInError.Add(ctx.Error) +} + +// onStreamWriteError is called by rtspServer. +func (s *session) onStreamWriteError(_ *gortsplib.ServerHandlerOnStreamWriteErrorCtx) { + // currently the only error returned by OnStreamWriteError is ErrServerWriteQueueFull + s.outboundRTPPacketsDiscarded.Increase() +} + +func (s *session) apiItem() *defs.APIRTSPSession { + stats := s.rsession.Stats() + + s.mutex.RLock() + defer s.mutex.RUnlock() + + return &defs.APIRTSPSession{ + ID: s.uuid, + Created: s.created, + RemoteAddr: s.remoteAddr().String(), + State: func() defs.APIRTSPSessionState { + state := s.rsession.State() + switch state { + case gortsplib.ServerSessionStatePlay: + return defs.APIRTSPSessionStateRead + + case gortsplib.ServerSessionStateRecord: + return defs.APIRTSPSessionStatePublish + + default: + return defs.APIRTSPSessionStateIdle + } + }(), + Path: func() string { + pa := s.rsession.Path() + if len(pa) >= 1 { + return pa[1:] + } + return "" + }(), + Query: s.rsession.Query(), + User: s.user, + UserAgent: s.userAgent, + Transport: func() *string { + transport := s.rsession.Transport() + if transport == nil { + return nil + } + v := transport.Protocol.String() + return &v + }(), + Profile: func() *string { + transport := s.rsession.Transport() + if transport == nil { + return nil + } + v := profileLabel(transport.Profile) + return &v + }(), + Conns: func() []uuid.UUID { + ret := []uuid.UUID{} + + for _, rconn := range s.rsession.Conns() { + conn := s.parent.getConnByRConnUnsafe(rconn) + if conn != nil { + ret = append(ret, conn.uuid) + } + } + + return ret + }(), + InboundBytes: stats.InboundBytes, + InboundRTPPackets: stats.InboundRTPPackets, + InboundRTPPacketsLost: stats.InboundRTPPacketsLost, + InboundRTPPacketsInError: stats.InboundRTPPacketsInError, + InboundRTPPacketsJitter: stats.InboundRTPPacketsJitter, + InboundRTCPPackets: stats.InboundRTCPPackets, + InboundRTCPPacketsInError: stats.InboundRTCPPacketsInError, + OutboundBytes: stats.OutboundBytes, + OutboundRTPPackets: stats.OutboundRTPPackets, + OutboundRTPPacketsReportedLost: stats.OutboundRTPPacketsReportedLost, + OutboundRTPPacketsDiscarded: s.outboundRTPPacketsDiscarded.Get(), + OutboundRTCPPackets: stats.OutboundRTCPPackets, + BytesReceived: stats.InboundBytes, + BytesSent: stats.OutboundBytes, + RTPPacketsReceived: stats.InboundRTPPackets, + RTPPacketsSent: stats.OutboundRTPPackets, + RTPPacketsLost: stats.InboundRTPPacketsLost, + RTPPacketsInError: stats.InboundRTPPacketsInError, + RTPPacketsJitter: stats.InboundRTPPacketsJitter, + RTCPPacketsReceived: stats.InboundRTCPPackets, + RTCPPacketsSent: stats.OutboundRTCPPackets, + RTCPPacketsInError: stats.InboundRTCPPacketsInError, + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/conn.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/conn.go new file mode 100644 index 0000000000000000000000000000000000000000..a1174ac07766391e97cb95c76e866836e100c1d7 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/conn.go @@ -0,0 +1,440 @@ +package srt + +import ( + "bufio" + "context" + "errors" + "fmt" + "net" + "sync" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + srt "github.com/datarhei/gosrt" + "github.com/google/uuid" + + "github.com/bluenviron/mediamtx/internal/auth" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/errordumper" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/hooks" + "github.com/bluenviron/mediamtx/internal/logger" + "github.com/bluenviron/mediamtx/internal/protocols/mpegts" + "github.com/bluenviron/mediamtx/internal/stream" +) + +func srtCheckPassphrase(connReq srt.ConnRequest, passphrase string) error { + if passphrase == "" { + return nil + } + + if !connReq.IsEncrypted() { + return fmt.Errorf("connection is encrypted, but not passphrase is defined in configuration") + } + + err := connReq.SetPassphrase(passphrase) + if err != nil { + return fmt.Errorf("invalid passphrase") + } + + return nil +} + +type conn struct { + parentCtx context.Context + rtspAddress string + readTimeout conf.Duration + writeTimeout conf.Duration + udpMaxPayloadSize int + connReq srt.ConnRequest + runOnConnect string + runOnConnectRestart bool + runOnDisconnect string + wg *sync.WaitGroup + externalCmdPool *externalcmd.Pool + pathManager serverPathManager + parent *Server + + ctx context.Context + ctxCancel func() + created time.Time + uuid uuid.UUID + mutex sync.RWMutex + state defs.APISRTConnState + pathName string + query string + user string + sconn srt.Conn + reader *stream.Reader +} + +func (c *conn) initialize() { + c.ctx, c.ctxCancel = context.WithCancel(c.parentCtx) + + c.created = time.Now() + c.uuid = uuid.New() + c.state = defs.APISRTConnStateIdle + + c.Log(logger.Info, "opened") + + c.wg.Add(1) + go c.run() +} + +func (c *conn) Close() { + c.ctxCancel() +} + +// Log implements logger.Writer. +func (c *conn) Log(level logger.Level, format string, args ...any) { + c.parent.Log(level, "[conn %v] "+format, append([]any{c.connReq.RemoteAddr()}, args...)...) +} + +func (c *conn) ip() net.IP { + return c.connReq.RemoteAddr().(*net.UDPAddr).IP +} + +func (c *conn) run() { //nolint:dupl + defer c.wg.Done() + + onDisconnectHook := hooks.OnConnect(hooks.OnConnectParams{ + Logger: c, + ExternalCmdPool: c.externalCmdPool, + RunOnConnect: c.runOnConnect, + RunOnConnectRestart: c.runOnConnectRestart, + RunOnDisconnect: c.runOnDisconnect, + RTSPAddress: c.rtspAddress, + Desc: *c.APIReaderDescribe(), + }) + defer onDisconnectHook() + + err := c.runInner() + + c.ctxCancel() + + c.parent.closeConn(c) + + c.Log(logger.Info, "closed: %v", err) +} + +func (c *conn) runInner() error { + var streamID streamID + err := streamID.unmarshal(c.connReq.StreamId()) + if err != nil { + c.connReq.Reject(srt.REJ_PEER) + return fmt.Errorf("invalid stream ID '%s': %w", c.connReq.StreamId(), err) + } + + if streamID.mode == streamIDModePublish { + return c.runPublish(&streamID) + } + return c.runRead(&streamID) +} + +func (c *conn) runPublish(streamID *streamID) error { + res, err := c.pathManager.FindPathConf(defs.PathFindPathConfReq{ + AccessRequest: defs.PathAccessRequest{ + Name: streamID.path, + Query: streamID.query, + Publish: true, + Proto: auth.ProtocolSRT, + ID: &c.uuid, + Credentials: &auth.Credentials{ + User: streamID.user, + Pass: streamID.pass, + }, + IP: c.ip(), + }, + }) + if err != nil { + if terr, ok := errors.AsType[*auth.Error](err); ok { + c.connReq.Reject(srt.REJ_PEER) + return terr + } + c.connReq.Reject(srt.REJ_PEER) + return err + } + + c.mutex.Lock() + c.user = res.User + c.mutex.Unlock() + + err = srtCheckPassphrase(c.connReq, res.Conf.SRTPublishPassphrase) + if err != nil { + c.connReq.Reject(srt.REJ_PEER) + return err + } + + sconn, err := c.connReq.Accept() + if err != nil { + return err + } + + readerErr := make(chan error) + go func() { + readerErr <- c.runPublishReader(sconn, streamID, res.Conf) + }() + + select { + case err = <-readerErr: + sconn.Close() + return err + + case <-c.ctx.Done(): + sconn.Close() + <-readerErr + return errors.New("terminated") + } +} + +func (c *conn) runPublishReader(sconn srt.Conn, streamID *streamID, pathConf *conf.Path) error { + sconn.SetReadDeadline(time.Now().Add(time.Duration(c.readTimeout))) + r := &mpegts.EnhancedReader{R: sconn} + err := r.Initialize() + if err != nil { + return err + } + + decodeErrors := &errordumper.Dumper{ + OnReport: func(val uint64, last error) { + if val == 1 { + c.Log(logger.Warn, "decode error: %v", last) + } else { + c.Log(logger.Warn, "%d decode errors, last was: %v", val, last) + } + }, + } + + decodeErrors.Start() + defer decodeErrors.Stop() + + r.OnDecodeError(func(err error) { + decodeErrors.Add(err) + }) + + var subStream *stream.SubStream + + medias, err := mpegts.ToStream(r, &subStream, c) + if err != nil { + return err + } + + res, err := c.pathManager.AddPublisher(defs.PathAddPublisherReq{ + Author: c, + Desc: &description.Session{Medias: medias}, + UseRTPPackets: false, + ReplaceNTP: true, + ConfToCompare: pathConf, + AccessRequest: defs.PathAccessRequest{ + Name: streamID.path, + Query: streamID.query, + Publish: true, + SkipAuth: true, + }, + }) + if err != nil { + return err + } + + defer res.Path.RemovePublisher(defs.PathRemovePublisherReq{Author: c}) + + subStream = res.SubStream + + c.mutex.Lock() + c.state = defs.APISRTConnStatePublish + c.pathName = streamID.path + c.query = streamID.query + c.sconn = sconn + c.mutex.Unlock() + + for { + err = r.Read() + if err != nil { + return err + } + } +} + +func (c *conn) runRead(streamID *streamID) error { + res, err := c.pathManager.AddReader(defs.PathAddReaderReq{ + Author: c, + AccessRequest: defs.PathAccessRequest{ + Name: streamID.path, + Query: streamID.query, + Proto: auth.ProtocolSRT, + ID: &c.uuid, + Credentials: &auth.Credentials{ + User: streamID.user, + Pass: streamID.pass, + }, + IP: c.ip(), + }, + }) + if err != nil { + if terr, ok := errors.AsType[*auth.Error](err); ok { + c.connReq.Reject(srt.REJ_PEER) + return terr + } + c.connReq.Reject(srt.REJ_PEER) + return err + } + + defer res.Path.RemoveReader(defs.PathRemoveReaderReq{Author: c}) + + err = srtCheckPassphrase(c.connReq, res.Path.SafeConf().SRTReadPassphrase) + if err != nil { + c.connReq.Reject(srt.REJ_PEER) + return err + } + + sconn, err := c.connReq.Accept() + if err != nil { + return err + } + defer sconn.Close() + + bw := bufio.NewWriterSize(sconn, srtMaxPayloadSize(c.udpMaxPayloadSize)) + + r := &stream.Reader{Parent: c} + + err = mpegts.FromStream(res.Stream.OrigDesc, r, bw, sconn, time.Duration(c.writeTimeout)) + if err != nil { + return err + } + + c.mutex.Lock() + c.state = defs.APISRTConnStateRead + c.pathName = streamID.path + c.query = streamID.query + c.user = res.User + c.sconn = sconn + c.mutex.Unlock() + + c.Log(logger.Info, "is reading from path '%s', %s", + res.Path.Name(), defs.FormatsInfo(r.Formats())) + + onUnreadHook := hooks.OnRead(hooks.OnReadParams{ + Logger: c, + ExternalCmdPool: c.externalCmdPool, + Conf: res.Path.SafeConf(), + ExternalCmdEnv: res.Path.ExternalCmdEnv(), + Reader: *c.APIReaderDescribe(), + Query: streamID.query, + }) + defer onUnreadHook() + + // disable read deadline + sconn.SetReadDeadline(time.Time{}) + + res.Stream.AddReader(r) + defer res.Stream.RemoveReader(r) + + c.mutex.Lock() + c.reader = r + c.mutex.Unlock() + + select { + case <-c.ctx.Done(): + return fmt.Errorf("terminated") + + case err = <-r.Error(): + return err + } +} + +// APIReaderDescribe implements reader. +func (c *conn) APIReaderDescribe() *defs.APIPathReader { + return &defs.APIPathReader{ + Type: defs.APIPathReaderTypeSRTConn, + ID: c.uuid.String(), + } +} + +// APISourceDescribe implements source. +func (c *conn) APISourceDescribe() *defs.APIPathSource { + return &defs.APIPathSource{ + Type: defs.APIPathSourceTypeSRTConn, + ID: c.uuid.String(), + } +} + +func (c *conn) apiItem() *defs.APISRTConn { + c.mutex.RLock() + defer c.mutex.RUnlock() + + item := &defs.APISRTConn{ + ID: c.uuid, + Created: c.created, + RemoteAddr: c.connReq.RemoteAddr().String(), + State: c.state, + Path: c.pathName, + Query: c.query, + User: c.user, + } + + if c.sconn != nil { + var s srt.Statistics + c.sconn.Stats(&s) + + item.PacketsSent = s.Accumulated.PktSent + item.PacketsReceived = s.Accumulated.PktRecv + item.PacketsSentUnique = s.Accumulated.PktSentUnique + item.PacketsReceivedUnique = s.Accumulated.PktRecvUnique + item.PacketsSendLoss = s.Accumulated.PktSendLoss + item.PacketsReceivedLoss = s.Accumulated.PktRecvLoss + item.PacketsRetrans = s.Accumulated.PktRetrans + item.PacketsReceivedRetrans = s.Accumulated.PktRecvRetrans + item.PacketsSentACK = s.Accumulated.PktSentACK + item.PacketsReceivedACK = s.Accumulated.PktRecvACK + item.PacketsSentNAK = s.Accumulated.PktSentNAK + item.PacketsReceivedNAK = s.Accumulated.PktRecvNAK + item.PacketsSentKM = s.Accumulated.PktSentKM + item.PacketsReceivedKM = s.Accumulated.PktRecvKM + item.UsSndDuration = s.Accumulated.UsSndDuration + item.PacketsReceivedBelated = s.Accumulated.PktRecvBelated + item.PacketsSendDrop = s.Accumulated.PktSendDrop + item.PacketsReceivedDrop = s.Accumulated.PktRecvDrop + item.PacketsReceivedUndecrypt = s.Accumulated.PktRecvUndecrypt + item.BytesSent = s.Accumulated.ByteSent + item.BytesReceived = s.Accumulated.ByteRecv + item.BytesSentUnique = s.Accumulated.ByteSentUnique + item.BytesReceivedUnique = s.Accumulated.ByteRecvUnique + item.BytesReceivedLoss = s.Accumulated.ByteRecvLoss + item.BytesRetrans = s.Accumulated.ByteRetrans + item.BytesReceivedRetrans = s.Accumulated.ByteRecvRetrans + item.BytesReceivedBelated = s.Accumulated.ByteRecvBelated + item.BytesSendDrop = s.Accumulated.ByteSendDrop + item.BytesReceivedDrop = s.Accumulated.ByteRecvDrop + item.BytesReceivedUndecrypt = s.Accumulated.ByteRecvUndecrypt + item.UsPacketsSendPeriod = s.Instantaneous.UsPktSendPeriod + item.PacketsFlowWindow = s.Instantaneous.PktFlowWindow + item.PacketsFlightSize = s.Instantaneous.PktFlightSize + item.MsRTT = s.Instantaneous.MsRTT + item.MbpsSendRate = s.Instantaneous.MbpsSentRate + item.MbpsReceiveRate = s.Instantaneous.MbpsRecvRate + item.MbpsLinkCapacity = s.Instantaneous.MbpsLinkCapacity + item.BytesAvailSendBuf = s.Instantaneous.ByteAvailSendBuf + item.BytesAvailReceiveBuf = s.Instantaneous.ByteAvailRecvBuf + item.MbpsMaxBW = s.Instantaneous.MbpsMaxBW + item.ByteMSS = s.Instantaneous.ByteMSS + item.PacketsSendBuf = s.Instantaneous.PktSendBuf + item.BytesSendBuf = s.Instantaneous.ByteSendBuf + item.MsSendBuf = s.Instantaneous.MsSendBuf + item.MsSendTsbPdDelay = s.Instantaneous.MsSendTsbPdDelay + item.PacketsReceiveBuf = s.Instantaneous.PktRecvBuf + item.BytesReceiveBuf = s.Instantaneous.ByteRecvBuf + item.MsReceiveBuf = s.Instantaneous.MsRecvBuf + item.MsReceiveTsbPdDelay = s.Instantaneous.MsRecvTsbPdDelay + item.PacketsReorderTolerance = s.Instantaneous.PktReorderTolerance + item.PacketsReceivedAvgBelatedTime = s.Instantaneous.PktRecvAvgBelatedTime + item.PacketsSendLossRate = s.Instantaneous.PktSendLossRate + item.PacketsReceivedLossRate = s.Instantaneous.PktRecvLossRate + } + + if c.reader != nil { + item.OutboundFramesDiscarded = c.reader.OutboundFramesDiscarded() + } + + return item +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/listener.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/listener.go new file mode 100644 index 0000000000000000000000000000000000000000..0e8fff18387e2260b423fcf4f61e339c77cc0a7a --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/listener.go @@ -0,0 +1,37 @@ +package srt + +import ( + "sync" + + srt "github.com/datarhei/gosrt" +) + +type listener struct { + ln srt.Listener + wg *sync.WaitGroup + parent *Server +} + +func (l *listener) initialize() { + l.wg.Add(1) + go l.run() +} + +func (l *listener) run() { + defer l.wg.Done() + + err := l.runInner() + + l.parent.acceptError(err) +} + +func (l *listener) runInner() error { + for { + req, err := l.ln.Accept2() + if err != nil { + return err + } + + l.parent.newConnRequest(req) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/server.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/server.go new file mode 100644 index 0000000000000000000000000000000000000000..e14f239d7e7a32263cdcfd140b0b1f37d9217581 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/server.go @@ -0,0 +1,323 @@ +// Package srt contains a SRT server. +package srt + +import ( + "context" + "errors" + "fmt" + "reflect" + "sort" + "sync" + "time" + + srt "github.com/datarhei/gosrt" + "github.com/google/uuid" + + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/logger" +) + +// ErrConnNotFound is returned when a connection is not found. +var ErrConnNotFound = errors.New("connection not found") + +func interfaceIsEmpty(i any) bool { + return reflect.ValueOf(i).Kind() != reflect.Pointer || reflect.ValueOf(i).IsNil() +} + +func srtMaxPayloadSize(u int) int { + return ((u - 16) / 188) * 188 // 16 = SRT header, 188 = MPEG-TS packet +} + +type serverAPIConnsListRes struct { + data *defs.APISRTConnList + err error +} + +type serverAPIConnsListReq struct { + res chan serverAPIConnsListRes +} + +type serverAPIConnsGetRes struct { + data *defs.APISRTConn + err error +} + +type serverAPIConnsGetReq struct { + uuid uuid.UUID + res chan serverAPIConnsGetRes +} + +type serverAPIConnsKickRes struct { + err error +} + +type serverAPIConnsKickReq struct { + uuid uuid.UUID + res chan serverAPIConnsKickRes +} + +type serverMetrics interface { + SetSRTServer(defs.APISRTServer) +} + +type serverPathManager interface { + FindPathConf(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) + AddPublisher(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) + AddReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) +} + +type serverParent interface { + logger.Writer +} + +// Server is a SRT server. +type Server struct { + Address string + RTSPAddress string + ReadTimeout conf.Duration + WriteTimeout conf.Duration + UDPMaxPayloadSize int + RunOnConnect string + RunOnConnectRestart bool + RunOnDisconnect string + ExternalCmdPool *externalcmd.Pool + Metrics serverMetrics + PathManager serverPathManager + Parent serverParent + + ctx context.Context + ctxCancel func() + wg sync.WaitGroup + ln srt.Listener + conns map[*conn]struct{} + + // in + chNewConnRequest chan srt.ConnRequest + chAcceptErr chan error + chCloseConn chan *conn + chAPIConnsList chan serverAPIConnsListReq + chAPIConnsGet chan serverAPIConnsGetReq + chAPIConnsKick chan serverAPIConnsKickReq +} + +// Initialize initializes the server. +func (s *Server) Initialize() error { + conf := srt.DefaultConfig() + conf.ConnectionTimeout = time.Duration(s.ReadTimeout) + conf.PeerIdleTimeout = time.Duration(s.ReadTimeout) + conf.PayloadSize = uint32(srtMaxPayloadSize(s.UDPMaxPayloadSize)) + + var err error + s.ln, err = srt.Listen("srt", s.Address, conf) + if err != nil { + return err + } + + s.ctx, s.ctxCancel = context.WithCancel(context.Background()) + + s.conns = make(map[*conn]struct{}) + s.chNewConnRequest = make(chan srt.ConnRequest) + s.chAcceptErr = make(chan error) + s.chCloseConn = make(chan *conn) + s.chAPIConnsList = make(chan serverAPIConnsListReq) + s.chAPIConnsGet = make(chan serverAPIConnsGetReq) + s.chAPIConnsKick = make(chan serverAPIConnsKickReq) + + s.Log(logger.Info, "started with listener on "+s.Address+" (UDP/SRT)") + + l := &listener{ + ln: s.ln, + wg: &s.wg, + parent: s, + } + l.initialize() + + s.wg.Add(1) + go s.run() + + if !interfaceIsEmpty(s.Metrics) { + s.Metrics.SetSRTServer(s) + } + + return nil +} + +// Log implements logger.Writer. +func (s *Server) Log(level logger.Level, format string, args ...any) { + s.Parent.Log(level, "[SRT] "+format, args...) +} + +// Close closes the server. +func (s *Server) Close() { + s.Log(logger.Info, "closing") + + if !interfaceIsEmpty(s.Metrics) { + s.Metrics.SetSRTServer(nil) + } + + s.ctxCancel() + s.wg.Wait() +} + +func (s *Server) run() { + defer s.wg.Done() + +outer: + for { + select { + case err := <-s.chAcceptErr: + s.Log(logger.Error, "%s", err) + break outer + + case req := <-s.chNewConnRequest: + c := &conn{ + parentCtx: s.ctx, + rtspAddress: s.RTSPAddress, + readTimeout: s.ReadTimeout, + writeTimeout: s.WriteTimeout, + udpMaxPayloadSize: s.UDPMaxPayloadSize, + connReq: req, + runOnConnect: s.RunOnConnect, + runOnConnectRestart: s.RunOnConnectRestart, + runOnDisconnect: s.RunOnDisconnect, + wg: &s.wg, + externalCmdPool: s.ExternalCmdPool, + pathManager: s.PathManager, + parent: s, + } + c.initialize() + s.conns[c] = struct{}{} + + case c := <-s.chCloseConn: + delete(s.conns, c) + + case req := <-s.chAPIConnsList: + data := &defs.APISRTConnList{ + Items: []defs.APISRTConn{}, + } + + for c := range s.conns { + data.Items = append(data.Items, *c.apiItem()) + } + + sort.Slice(data.Items, func(i, j int) bool { + return data.Items[i].Created.Before(data.Items[j].Created) + }) + + req.res <- serverAPIConnsListRes{data: data} + + case req := <-s.chAPIConnsGet: + c := s.findConnByUUID(req.uuid) + if c == nil { + req.res <- serverAPIConnsGetRes{err: ErrConnNotFound} + continue + } + + req.res <- serverAPIConnsGetRes{data: c.apiItem()} + + case req := <-s.chAPIConnsKick: + c := s.findConnByUUID(req.uuid) + if c == nil { + req.res <- serverAPIConnsKickRes{err: ErrConnNotFound} + continue + } + + delete(s.conns, c) + c.Close() + req.res <- serverAPIConnsKickRes{} + + case <-s.ctx.Done(): + break outer + } + } + + s.ctxCancel() + + s.ln.Close() +} + +func (s *Server) findConnByUUID(uuid uuid.UUID) *conn { + for sx := range s.conns { + if sx.uuid == uuid { + return sx + } + } + return nil +} + +// newConnRequest is called by srtListener. +func (s *Server) newConnRequest(connReq srt.ConnRequest) { + select { + case s.chNewConnRequest <- connReq: + case <-s.ctx.Done(): + connReq.Reject(srt.REJ_CLOSE) + } +} + +// acceptError is called by srtListener. +func (s *Server) acceptError(err error) { + select { + case s.chAcceptErr <- err: + case <-s.ctx.Done(): + } +} + +// closeConn is called by conn. +func (s *Server) closeConn(c *conn) { + select { + case s.chCloseConn <- c: + case <-s.ctx.Done(): + } +} + +// APIConnsList implements defs.APISRTServer. +func (s *Server) APIConnsList() (*defs.APISRTConnList, error) { + req := serverAPIConnsListReq{ + res: make(chan serverAPIConnsListRes), + } + + select { + case s.chAPIConnsList <- req: + res := <-req.res + return res.data, res.err + + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// APIConnsGet implements defs.APISRTServer. +func (s *Server) APIConnsGet(uuid uuid.UUID) (*defs.APISRTConn, error) { + req := serverAPIConnsGetReq{ + uuid: uuid, + res: make(chan serverAPIConnsGetRes), + } + + select { + case s.chAPIConnsGet <- req: + res := <-req.res + return res.data, res.err + + case <-s.ctx.Done(): + return nil, fmt.Errorf("terminated") + } +} + +// APIConnsKick implements defs.APISRTServer. +func (s *Server) APIConnsKick(uuid uuid.UUID) error { + req := serverAPIConnsKickReq{ + uuid: uuid, + res: make(chan serverAPIConnsKickRes), + } + + select { + case s.chAPIConnsKick <- req: + res := <-req.res + return res.err + + case <-s.ctx.Done(): + return fmt.Errorf("terminated") + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/server_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c326b02fce5ac5a8a696a4a3d34bac65836d6b5a --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/server_test.go @@ -0,0 +1,430 @@ +package srt + +import ( + "bufio" + "testing" + "time" + + "github.com/bluenviron/gortsplib/v5/pkg/description" + "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts" + tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs" + "github.com/bluenviron/mediamtx/internal/conf" + "github.com/bluenviron/mediamtx/internal/defs" + "github.com/bluenviron/mediamtx/internal/externalcmd" + "github.com/bluenviron/mediamtx/internal/stream" + "github.com/bluenviron/mediamtx/internal/test" + "github.com/bluenviron/mediamtx/internal/unit" + srt "github.com/datarhei/gosrt" + "github.com/stretchr/testify/require" +) + +type dummyPath struct{} + +func (p *dummyPath) Name() string { + return "teststream" +} + +func (p *dummyPath) SafeConf() *conf.Path { + return &conf.Path{} +} + +func (p *dummyPath) ExternalCmdEnv() externalcmd.Environment { + return externalcmd.Environment{} +} + +func (p *dummyPath) RemovePublisher(_ defs.PathRemovePublisherReq) { +} + +func (p *dummyPath) RemoveReader(_ defs.PathRemoveReaderReq) { +} + +func TestServerPublish(t *testing.T) { + externalCmdPool := &externalcmd.Pool{} + externalCmdPool.Initialize() + defer externalCmdPool.Close() + + var strm *stream.Stream + var reader *stream.Reader + defer func() { + strm.RemoveReader(reader) + }() + dataReceived := make(chan struct{}) + dataReceived2 := make(chan struct{}) + n := 0 + + pathManager := &test.PathManager{ + FindPathConfImpl: func(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + require.Equal(t, "param=value", req.AccessRequest.Query) + require.Equal(t, "myuser", req.AccessRequest.Credentials.User) + require.Equal(t, "mypass", req.AccessRequest.Credentials.Pass) + return &defs.PathFindPathConfRes{Conf: &conf.Path{}, User: req.AccessRequest.Credentials.User}, nil + }, + AddPublisherImpl: func(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + require.Equal(t, "param=value", req.AccessRequest.Query) + require.True(t, req.AccessRequest.SkipAuth) + + strm = &stream.Stream{ + OrigDesc: req.Desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + reader = &stream.Reader{Parent: test.NilLogger} + + reader.OnData( + strm.OrigDesc.Medias[0], + strm.OrigDesc.Medias[0].Formats[0], + func(u *unit.Unit) error { + switch n { + case 0: + require.Equal(t, unit.PayloadH264{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5, 1}, + }, u.Payload) + close(dataReceived) + + case 1: + require.Equal(t, unit.PayloadH264{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5, 2}, + }, u.Payload) + close(dataReceived2) + + default: + t.Errorf("should not happen") + } + n++ + return nil + }) + + strm.AddReader(reader) + + return &defs.PathAddPublisherRes{Path: &dummyPath{}, SubStream: subStream}, nil + }, + } + + s := &Server{ + Address: "127.0.0.1:8890", + RTSPAddress: "", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + UDPMaxPayloadSize: 1472, + RunOnConnect: "", + RunOnConnectRestart: false, + RunOnDisconnect: "string", + ExternalCmdPool: externalCmdPool, + PathManager: pathManager, + Parent: test.NilLogger, + } + err := s.Initialize() + require.NoError(t, err) + defer s.Close() + + u := "srt://127.0.0.1:8890?streamid=publish:teststream:myuser:mypass:param=value" + + 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) + + track := &mpegts.Track{ + Codec: &tscodecs.H264{}, + } + + bw := bufio.NewWriter(publisher) + w := &mpegts.Writer{W: bw, Tracks: []*mpegts.Track{track}} + err = w.Initialize() + require.NoError(t, err) + + // the MPEG-TS muxer needs two PES packets in order to write the first one + + err = w.WriteH264(track, 0, 0, [][]byte{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {5, 1}, // IDR + }) + require.NoError(t, err) + + err = w.WriteH264(track, 0, 0, [][]byte{ + {5, 2}, // IDR + }) + require.NoError(t, err) + + err = bw.Flush() + require.NoError(t, err) + + <-dataReceived + + list, err := s.APIConnsList() + require.NoError(t, err) + require.Equal(t, &defs.APISRTConnList{ //nolint:dupl + Items: []defs.APISRTConn{ + { + ID: list.Items[0].ID, + Created: list.Items[0].Created, + RemoteAddr: list.Items[0].RemoteAddr, + State: "publish", + Path: "teststream", + Query: "param=value", + User: "myuser", + PacketsSent: list.Items[0].PacketsSent, + PacketsReceived: list.Items[0].PacketsReceived, + PacketsSentUnique: list.Items[0].PacketsSentUnique, + PacketsReceivedUnique: list.Items[0].PacketsReceivedUnique, + PacketsSendLoss: list.Items[0].PacketsSendLoss, + PacketsReceivedLoss: list.Items[0].PacketsReceivedLoss, + PacketsRetrans: list.Items[0].PacketsRetrans, + PacketsReceivedRetrans: list.Items[0].PacketsReceivedRetrans, + PacketsSentACK: list.Items[0].PacketsSentACK, + PacketsReceivedACK: list.Items[0].PacketsReceivedACK, + PacketsSentNAK: list.Items[0].PacketsSentNAK, + PacketsReceivedNAK: list.Items[0].PacketsReceivedNAK, + PacketsSentKM: list.Items[0].PacketsSentKM, + PacketsReceivedKM: list.Items[0].PacketsReceivedKM, + UsSndDuration: list.Items[0].UsSndDuration, + PacketsReceivedBelated: list.Items[0].PacketsReceivedBelated, + PacketsSendDrop: list.Items[0].PacketsSendDrop, + PacketsReceivedDrop: list.Items[0].PacketsReceivedDrop, + PacketsReceivedUndecrypt: list.Items[0].PacketsReceivedUndecrypt, + BytesReceived: list.Items[0].BytesReceived, + BytesSent: list.Items[0].BytesSent, + BytesSentUnique: list.Items[0].BytesSentUnique, + BytesReceivedUnique: list.Items[0].BytesReceivedUnique, + BytesReceivedLoss: list.Items[0].BytesReceivedLoss, + BytesRetrans: list.Items[0].BytesRetrans, + BytesReceivedRetrans: list.Items[0].BytesReceivedRetrans, + BytesReceivedBelated: list.Items[0].BytesReceivedBelated, + BytesSendDrop: list.Items[0].BytesSendDrop, + BytesReceivedDrop: list.Items[0].BytesReceivedDrop, + BytesReceivedUndecrypt: list.Items[0].BytesReceivedUndecrypt, + OutboundFramesDiscarded: list.Items[0].OutboundFramesDiscarded, + UsPacketsSendPeriod: list.Items[0].UsPacketsSendPeriod, + PacketsFlowWindow: list.Items[0].PacketsFlowWindow, + PacketsFlightSize: list.Items[0].PacketsFlightSize, + MsRTT: list.Items[0].MsRTT, + MbpsSendRate: list.Items[0].MbpsSendRate, + MbpsReceiveRate: list.Items[0].MbpsReceiveRate, + MbpsLinkCapacity: list.Items[0].MbpsLinkCapacity, + BytesAvailSendBuf: list.Items[0].BytesAvailSendBuf, + BytesAvailReceiveBuf: list.Items[0].BytesAvailReceiveBuf, + MbpsMaxBW: list.Items[0].MbpsMaxBW, + ByteMSS: list.Items[0].ByteMSS, + PacketsSendBuf: list.Items[0].PacketsSendBuf, + BytesSendBuf: list.Items[0].BytesSendBuf, + MsSendBuf: list.Items[0].MsSendBuf, + MsSendTsbPdDelay: list.Items[0].MsSendTsbPdDelay, + PacketsReceiveBuf: list.Items[0].PacketsReceiveBuf, + BytesReceiveBuf: list.Items[0].BytesReceiveBuf, + MsReceiveBuf: list.Items[0].MsReceiveBuf, + MsReceiveTsbPdDelay: list.Items[0].MsReceiveTsbPdDelay, + PacketsReorderTolerance: list.Items[0].PacketsReorderTolerance, + PacketsReceivedAvgBelatedTime: list.Items[0].PacketsReceivedAvgBelatedTime, + PacketsSendLossRate: list.Items[0].PacketsSendLossRate, + PacketsReceivedLossRate: list.Items[0].PacketsReceivedLossRate, + }, + }, + }, list) + + // the second PES is written after writer is closed + publisher.Close() + <-dataReceived2 +} + +func TestServerRead(t *testing.T) { + externalCmdPool := &externalcmd.Pool{} + externalCmdPool.Initialize() + defer externalCmdPool.Close() + + desc := &description.Session{Medias: []*description.Media{test.MediaH264}} + + strm := &stream.Stream{ + OrigDesc: desc, + WriteQueueSize: 512, + RTPMaxPayloadSize: 1450, + Parent: test.NilLogger, + } + err := strm.Initialize() + require.NoError(t, err) + + subStream := &stream.SubStream{ + Stream: strm, + UseRTPPackets: false, + } + err = subStream.Initialize() + require.NoError(t, err) + + pathManager := &test.PathManager{ + AddReaderImpl: func(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) { + require.Equal(t, "teststream", req.AccessRequest.Name) + require.Equal(t, "param=value", req.AccessRequest.Query) + require.Equal(t, "myuser", req.AccessRequest.Credentials.User) + require.Equal(t, "mypass", req.AccessRequest.Credentials.Pass) + return &defs.PathAddReaderRes{Path: &dummyPath{}, User: req.AccessRequest.Credentials.User, Stream: strm}, nil + }, + } + + s := &Server{ + Address: "127.0.0.1:8890", + RTSPAddress: "", + ReadTimeout: conf.Duration(10 * time.Second), + WriteTimeout: conf.Duration(10 * time.Second), + UDPMaxPayloadSize: 1472, + RunOnConnect: "", + RunOnConnectRestart: false, + RunOnDisconnect: "string", + ExternalCmdPool: externalCmdPool, + PathManager: pathManager, + Parent: test.NilLogger, + } + err = s.Initialize() + require.NoError(t, err) + defer s.Close() + + u := "srt://127.0.0.1:8890?streamid=read:teststream:myuser:mypass:param=value" + + 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() + + strm.WaitForReaders() + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + NTP: time.Time{}, + Payload: unit.PayloadH264{ + {5, 1}, // IDR + }, + }) + + r := &mpegts.Reader{R: reader} + err = r.Initialize() + require.NoError(t, err) + + require.Equal(t, []*mpegts.Track{{ + PID: 256, + Codec: &tscodecs.H264{}, + }}, r.Tracks()) + + received := false + + r.OnDataH264(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{ + test.FormatH264.SPS, + test.FormatH264.PPS, + {0x05, 1}, + }, au) + received = true + return nil + }) + + subStream.WriteUnit(desc.Medias[0], desc.Medias[0].Formats[0], &unit.Unit{ + NTP: time.Time{}, + Payload: unit.PayloadH264{ + {5, 2}, + }, + }) + + for { + err = r.Read() + require.NoError(t, err) + if received { + break + } + } + + list, err := s.APIConnsList() + require.NoError(t, err) + require.Equal(t, &defs.APISRTConnList{ //nolint:dupl + Items: []defs.APISRTConn{ + { + ID: list.Items[0].ID, + Created: list.Items[0].Created, + RemoteAddr: list.Items[0].RemoteAddr, + State: "read", + Path: "teststream", + Query: "param=value", + User: "myuser", + PacketsSent: list.Items[0].PacketsSent, + PacketsReceived: list.Items[0].PacketsReceived, + PacketsSentUnique: list.Items[0].PacketsSentUnique, + PacketsReceivedUnique: list.Items[0].PacketsReceivedUnique, + PacketsSendLoss: list.Items[0].PacketsSendLoss, + PacketsReceivedLoss: list.Items[0].PacketsReceivedLoss, + PacketsRetrans: list.Items[0].PacketsRetrans, + PacketsReceivedRetrans: list.Items[0].PacketsReceivedRetrans, + PacketsSentACK: list.Items[0].PacketsSentACK, + PacketsReceivedACK: list.Items[0].PacketsReceivedACK, + PacketsSentNAK: list.Items[0].PacketsSentNAK, + PacketsReceivedNAK: list.Items[0].PacketsReceivedNAK, + PacketsSentKM: list.Items[0].PacketsSentKM, + PacketsReceivedKM: list.Items[0].PacketsReceivedKM, + UsSndDuration: list.Items[0].UsSndDuration, + PacketsReceivedBelated: list.Items[0].PacketsReceivedBelated, + PacketsSendDrop: list.Items[0].PacketsSendDrop, + PacketsReceivedDrop: list.Items[0].PacketsReceivedDrop, + PacketsReceivedUndecrypt: list.Items[0].PacketsReceivedUndecrypt, + BytesReceived: list.Items[0].BytesReceived, + BytesSent: list.Items[0].BytesSent, + BytesSentUnique: list.Items[0].BytesSentUnique, + BytesReceivedUnique: list.Items[0].BytesReceivedUnique, + BytesReceivedLoss: list.Items[0].BytesReceivedLoss, + BytesRetrans: list.Items[0].BytesRetrans, + BytesReceivedRetrans: list.Items[0].BytesReceivedRetrans, + BytesReceivedBelated: list.Items[0].BytesReceivedBelated, + BytesSendDrop: list.Items[0].BytesSendDrop, + BytesReceivedDrop: list.Items[0].BytesReceivedDrop, + BytesReceivedUndecrypt: list.Items[0].BytesReceivedUndecrypt, + UsPacketsSendPeriod: list.Items[0].UsPacketsSendPeriod, + PacketsFlowWindow: list.Items[0].PacketsFlowWindow, + PacketsFlightSize: list.Items[0].PacketsFlightSize, + MsRTT: list.Items[0].MsRTT, + MbpsSendRate: list.Items[0].MbpsSendRate, + MbpsReceiveRate: list.Items[0].MbpsReceiveRate, + MbpsLinkCapacity: list.Items[0].MbpsLinkCapacity, + BytesAvailSendBuf: list.Items[0].BytesAvailSendBuf, + BytesAvailReceiveBuf: list.Items[0].BytesAvailReceiveBuf, + MbpsMaxBW: list.Items[0].MbpsMaxBW, + ByteMSS: list.Items[0].ByteMSS, + PacketsSendBuf: list.Items[0].PacketsSendBuf, + BytesSendBuf: list.Items[0].BytesSendBuf, + MsSendBuf: list.Items[0].MsSendBuf, + MsSendTsbPdDelay: list.Items[0].MsSendTsbPdDelay, + PacketsReceiveBuf: list.Items[0].PacketsReceiveBuf, + BytesReceiveBuf: list.Items[0].BytesReceiveBuf, + MsReceiveBuf: list.Items[0].MsReceiveBuf, + MsReceiveTsbPdDelay: list.Items[0].MsReceiveTsbPdDelay, + PacketsReorderTolerance: list.Items[0].PacketsReorderTolerance, + PacketsReceivedAvgBelatedTime: list.Items[0].PacketsReceivedAvgBelatedTime, + PacketsSendLossRate: list.Items[0].PacketsSendLossRate, + PacketsReceivedLossRate: list.Items[0].PacketsReceivedLossRate, + }, + }, + }, list) +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/streamid.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/streamid.go new file mode 100644 index 0000000000000000000000000000000000000000..4876d09ae31320431027778586b96e8d9fc10518 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/streamid.go @@ -0,0 +1,97 @@ +package srt + +import ( + "fmt" + "strings" +) + +type streamIDMode int + +const ( + streamIDModeRead streamIDMode = iota + streamIDModePublish +) + +type streamID struct { + mode streamIDMode + path string + query string + user string + pass string +} + +func (s *streamID) unmarshal(raw string) error { + // standard syntax + // https://github.com/Haivision/srt/blob/master/docs/features/access-control.md + if strings.HasPrefix(raw, "#!::") { + for kv := range strings.SplitSeq(raw[len("#!::"):], ",") { + kv2 := strings.SplitN(kv, "=", 2) + if len(kv2) != 2 { + return fmt.Errorf("invalid value") + } + + key, value := kv2[0], kv2[1] + + switch key { + case "u": + s.user = value + + case "r": + s.path = value + + case "h": + + case "s": + s.pass = value + + case "t": + + case "m": + switch value { + case "request": + s.mode = streamIDModeRead + + case "publish": + s.mode = streamIDModePublish + + default: + return fmt.Errorf("unsupported mode '%s'", value) + } + } + } + } else { + parts := strings.Split(raw, ":") + if len(parts) < 2 || len(parts) > 5 { + return fmt.Errorf("stream ID must be 'action:pathname[:query]' or 'action:pathname:user:pass[:query]', " + + "where action is either read or publish, pathname is the path name, user and pass are the credentials, " + + "query is an optional token containing additional information") + } + + switch parts[0] { + case "read": + s.mode = streamIDModeRead + + case "publish": + s.mode = streamIDModePublish + + default: + return fmt.Errorf("stream ID must be 'action:pathname[:query]' or 'action:pathname:user:pass[:query]', " + + "where action is either read or publish, pathname is the path name, user and pass are the credentials, " + + "query is an optional token containing additional information") + } + + s.path = parts[1] + + if len(parts) == 4 || len(parts) == 5 { + s.user, s.pass = parts[2], parts[3] + } + + if len(parts) == 3 { + s.query = parts[2] + } else if len(parts) == 5 { + s.query = parts[4] + } + } + + return nil +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/streamid_test.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/streamid_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a4e6629b3374b66560b3b529bcc4e08870309e53 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/srt/streamid_test.go @@ -0,0 +1,69 @@ +package srt + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestStreamIDUnmarshal(t *testing.T) { + for _, ca := range []struct { + name string + raw string + dec streamID + }{ + { + "mediamtx syntax 1", + "read:mypath", + streamID{ + mode: streamIDModeRead, + path: "mypath", + }, + }, + { + "mediamtx syntax 2", + "publish:mypath:myquery", + streamID{ + mode: streamIDModePublish, + path: "mypath", + query: "myquery", + }, + }, + { + "mediamtx syntax 3", + "read:mypath:myuser:mypass:myquery", + streamID{ + mode: streamIDModeRead, + path: "mypath", + user: "myuser", + pass: "mypass", + query: "myquery", + }, + }, + { + "standard syntax", + "#!::u=johnny,t=file,m=publish,r=results.csv,s=mypass,h=myhost.com", + streamID{ + mode: streamIDModePublish, + path: "results.csv", + user: "johnny", + pass: "mypass", + }, + }, + { + "issue 3701", + "#!::bmd_uuid=0e1df79f-77e6-465c-b099-29a616e964f7,bmd_name=rdt-wp-003,r=test3,m=publish", + streamID{ + mode: streamIDModePublish, + path: "test3", + }, + }, + } { + t.Run(ca.name, func(t *testing.T) { + var sid streamID + err := sid.unmarshal(ca.raw) + require.NoError(t, err) + require.Equal(t, ca.dec, sid) + }) + } +} diff --git a/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/webrtc/custom_limit_reader.go b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/webrtc/custom_limit_reader.go new file mode 100644 index 0000000000000000000000000000000000000000..29cb9c9897a9cfc531e102cda04eda0b8b8dd4d1 --- /dev/null +++ b/fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/servers/webrtc/custom_limit_reader.go @@ -0,0 +1,26 @@ +package webrtc + +import ( + "fmt" + "io" +) + +var errSizeExceeded = fmt.Errorf("size exceeds maximum allowed") + +// like io.LimitReader, but returns a dedicated error if the limit is exceeded. +type customLimitReader struct { + r io.Reader + n int64 +} + +func (l *customLimitReader) Read(p []byte) (n int, err error) { + if l.n <= 0 { + return 0, errSizeExceeded + } + if int64(len(p)) > l.n { + p = p[0:l.n] + } + n, err = l.r.Read(p) + l.n -= int64(n) + return +}