tunahangkrr commited on
Commit
db97321
·
verified ·
1 Parent(s): d6deb27

Buyuk dosyalar ve gorseller (git deposundan haric tutulanlar) (part 2)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/webrtc_ice_server.go +9 -0
  2. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/90b5d1b18dd9f8ac +2 -0
  3. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/dc806ec658c460fc +2 -0
  4. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal.go +106 -0
  5. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal_test.go +80 -0
  6. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher.go +122 -0
  7. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher_test.go +145 -0
  8. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/api_test.go +1412 -0
  9. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core.go +1171 -0
  10. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core_test.go +148 -0
  11. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/metrics_test.go +513 -0
  12. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path.go +1116 -0
  13. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager.go +690 -0
  14. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager_test.go +217 -0
  15. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_test.go +1035 -0
  16. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/source_redirect.go +20 -0
  17. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/test_on_demand/main.go +54 -0
  18. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/versiongetter/main.go +143 -0
  19. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper.go +84 -0
  20. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper_test.go +42 -0
  21. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api.go +47 -0
  22. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_hls.go +54 -0
  23. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_moq.go +44 -0
  24. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path.go +93 -0
  25. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track.go +55 -0
  26. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec.go +6 -0
  27. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec_props.go +257 -0
  28. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_recording.go +21 -0
  29. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtmp.go +49 -0
  30. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtsp.go +91 -0
  31. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_srt.go +165 -0
  32. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_webrtc.go +63 -0
  33. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/defs.go +2 -0
  34. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path.go +122 -0
  35. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path_access_request.go +45 -0
  36. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/publisher.go +7 -0
  37. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/reader.go +7 -0
  38. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/source.go +46 -0
  39. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/static_source.go +15 -0
  40. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper.go +79 -0
  41. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper_test.go +43 -0
  42. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd.go +95 -0
  43. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os.go +66 -0
  44. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os_windows.go +141 -0
  45. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_test.go +44 -0
  46. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/pool.go +19 -0
  47. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label.go +133 -0
  48. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label_test.go +90 -0
  49. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/hooks.go +2 -0
  50. fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_connect.go +68 -0
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/webrtc_ice_server.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ package conf
2
+
3
+ // WebRTCICEServer is a WebRTC ICE Server.
4
+ type WebRTCICEServer struct {
5
+ URL string `json:"url"`
6
+ Username string `json:"username"`
7
+ Password string `json:"password"`
8
+ ClientOnly bool `json:"clientOnly"`
9
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/90b5d1b18dd9f8ac ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ go test fuzz v1
2
+ []byte("*0")
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/dc806ec658c460fc ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ go test fuzz v1
2
+ []byte("...")
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal.go ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package yamlwrapper contains a YAML unmarshaler.
2
+ package yamlwrapper
3
+
4
+ import (
5
+ "encoding/json"
6
+ "fmt"
7
+
8
+ "github.com/bluenviron/mediamtx/internal/conf/jsonwrapper"
9
+ "github.com/goccy/go-yaml"
10
+ "github.com/goccy/go-yaml/ast"
11
+ "github.com/goccy/go-yaml/parser"
12
+ "github.com/goccy/go-yaml/token"
13
+ )
14
+
15
+ // differences with respect to the standard package:
16
+ // - some legacy YAML 1.1 boolean values (yes, no) are supported
17
+ // - all differences of jsonwrapper are inherited
18
+
19
+ func convertLegacyBools(node ast.Node) ast.Node {
20
+ if node != nil {
21
+ switch n := node.(type) {
22
+ case *ast.MappingNode:
23
+ for _, value := range n.Values {
24
+ convertLegacyBools(value)
25
+ }
26
+
27
+ case *ast.MappingValueNode:
28
+ n.Key = convertLegacyBools(n.Key).(ast.MapKeyNode)
29
+ n.Value = convertLegacyBools(n.Value)
30
+
31
+ case *ast.SequenceNode:
32
+ for i, value := range n.Values {
33
+ n.Values[i] = convertLegacyBools(value)
34
+ }
35
+
36
+ case *ast.DocumentNode:
37
+ n.Body = convertLegacyBools(n.Body)
38
+
39
+ case *ast.StringNode:
40
+ if n.Token.Type == token.StringType {
41
+ var boolVal bool
42
+ shouldConvert := false
43
+
44
+ switch n.Token.Value {
45
+ case "yes", "Yes", "YES", "on", "On", "ON":
46
+ boolVal = true
47
+ shouldConvert = true
48
+
49
+ case "no", "No", "NO", "off", "Off", "OFF":
50
+ boolVal = false
51
+ shouldConvert = true
52
+ }
53
+
54
+ if shouldConvert {
55
+ newToken := &token.Token{
56
+ Type: token.BoolType,
57
+ Value: n.Token.Value,
58
+ }
59
+
60
+ if boolVal {
61
+ newToken.Value = "true"
62
+ } else {
63
+ newToken.Value = "false"
64
+ }
65
+
66
+ boolNode := ast.Bool(newToken)
67
+ boolNode.Value = boolVal
68
+ return boolNode
69
+ }
70
+ }
71
+ }
72
+ }
73
+
74
+ return node
75
+ }
76
+
77
+ // Unmarshal loads the configuration from YAML.
78
+ func Unmarshal(buf []byte, dest any) error {
79
+ file, err := parser.ParseBytes(buf, parser.ParseComments)
80
+ if err != nil {
81
+ return err
82
+ }
83
+
84
+ if len(file.Docs) != 1 {
85
+ return fmt.Errorf("invalid YAML")
86
+ }
87
+
88
+ file.Docs[0] = convertLegacyBools(file.Docs[0]).(*ast.DocumentNode)
89
+
90
+ var temp any
91
+ if file.Docs[0].Body != nil {
92
+ err = yaml.NodeToValue(file.Docs[0].Body, &temp)
93
+ if err != nil {
94
+ return err
95
+ }
96
+ }
97
+
98
+ // convert the generic map into JSON
99
+ buf, err = json.Marshal(temp)
100
+ if err != nil {
101
+ return err
102
+ }
103
+
104
+ // load JSON into destination
105
+ return jsonwrapper.Unmarshal(buf, dest)
106
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal_test.go ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package yamlwrapper
2
+
3
+ import (
4
+ "testing"
5
+
6
+ "github.com/stretchr/testify/require"
7
+ )
8
+
9
+ func TestUnmarshalIntegerMapKey(t *testing.T) {
10
+ buf := []byte(`
11
+ 1: value
12
+ test: value2
13
+ `)
14
+
15
+ var dest any
16
+ err := Unmarshal(buf, &dest)
17
+ require.NoError(t, err)
18
+
19
+ require.Equal(t, map[string]any{
20
+ "1": "value",
21
+ "test": "value2",
22
+ }, dest)
23
+ }
24
+
25
+ func TestUnmarshalDuplicateKey(t *testing.T) {
26
+ buf := []byte(`
27
+ key: value1
28
+ key: value2
29
+ `)
30
+
31
+ err := Unmarshal(buf, &map[string]string{})
32
+ require.EqualError(t, err, "[3:1] mapping key \"key\" already defined at [2:1]"+
33
+ "\n 2 | key: value1\n> 3 | key: value2\n ^\n")
34
+ }
35
+
36
+ func TestUnmarshalUnknownFields(t *testing.T) {
37
+ type testStruct struct {
38
+ Field1 string `json:"field1"`
39
+ Field2 int `json:"field2"`
40
+ }
41
+
42
+ input := []byte(`field1: test
43
+ unknownField: value
44
+ field2: 456`)
45
+
46
+ var result testStruct
47
+ err := Unmarshal(input, &result)
48
+ require.Error(t, err)
49
+ require.EqualError(t, err, "json: unknown field \"unknownField\"")
50
+ }
51
+
52
+ func TestUnmarshalLegacyBools(t *testing.T) {
53
+ type testStruct struct {
54
+ Field1 bool `json:"field1"`
55
+ Field2 string `json:"field2"`
56
+ }
57
+
58
+ input := []byte("field1: yes\n" +
59
+ "field2: \"yes\"\n")
60
+
61
+ var result testStruct
62
+ err := Unmarshal(input, &result)
63
+ require.NoError(t, err)
64
+ require.Equal(t, true, result.Field1)
65
+ }
66
+
67
+ func TestUnmarshalEmpty(t *testing.T) {
68
+ input := []byte(``)
69
+
70
+ var result any
71
+ err := Unmarshal(input, &result)
72
+ require.NoError(t, err)
73
+ }
74
+
75
+ func FuzzUnmarshal(f *testing.F) {
76
+ f.Fuzz(func(_ *testing.T, buf []byte) {
77
+ var dest any
78
+ Unmarshal(buf, &dest) //nolint:errcheck
79
+ })
80
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher.go ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package confwatcher contains a configuration watcher.
2
+ package confwatcher
3
+
4
+ import (
5
+ "os"
6
+ "path/filepath"
7
+ "time"
8
+
9
+ "github.com/fsnotify/fsnotify"
10
+ )
11
+
12
+ const (
13
+ minInterval = 1 * time.Second
14
+ additionalWait = 10 * time.Millisecond
15
+ )
16
+
17
+ // ConfWatcher is a configuration file watcher.
18
+ type ConfWatcher struct {
19
+ FilePath string
20
+
21
+ inner *fsnotify.Watcher
22
+ absolutePath string
23
+
24
+ // in
25
+ terminate chan struct{}
26
+
27
+ // out
28
+ signal chan struct{}
29
+ done chan struct{}
30
+ }
31
+
32
+ // Initialize initializes a ConfWatcher.
33
+ func (w *ConfWatcher) Initialize() error {
34
+ if _, err := os.Stat(w.FilePath); err != nil {
35
+ return err
36
+ }
37
+
38
+ var err error
39
+ w.inner, err = fsnotify.NewWatcher()
40
+ if err != nil {
41
+ return err
42
+ }
43
+
44
+ // use absolute paths to support Darwin
45
+ w.absolutePath, _ = filepath.Abs(w.FilePath)
46
+ parentPath := filepath.Dir(w.absolutePath)
47
+
48
+ err = w.inner.Add(parentPath)
49
+ if err != nil {
50
+ w.inner.Close() //nolint:errcheck
51
+ return err
52
+ }
53
+
54
+ w.terminate = make(chan struct{})
55
+ w.signal = make(chan struct{})
56
+ w.done = make(chan struct{})
57
+
58
+ go w.run()
59
+
60
+ return nil
61
+ }
62
+
63
+ // Close closes a ConfWatcher.
64
+ func (w *ConfWatcher) Close() {
65
+ close(w.terminate)
66
+ <-w.done
67
+ }
68
+
69
+ func (w *ConfWatcher) run() {
70
+ defer close(w.done)
71
+
72
+ var lastCalled time.Time
73
+ previousWatchedPath, _ := filepath.EvalSymlinks(w.absolutePath)
74
+
75
+ outer:
76
+ for {
77
+ select {
78
+ case event := <-w.inner.Events:
79
+ if time.Since(lastCalled) < minInterval {
80
+ continue
81
+ }
82
+
83
+ currentWatchedPath, _ := filepath.EvalSymlinks(w.absolutePath)
84
+ eventPath, _ := filepath.Abs(event.Name)
85
+ eventPath, _ = filepath.EvalSymlinks(eventPath)
86
+
87
+ if currentWatchedPath == "" {
88
+ // watched file was removed; wait for write event to trigger reload
89
+ previousWatchedPath = ""
90
+ } else if currentWatchedPath != previousWatchedPath ||
91
+ (eventPath == currentWatchedPath &&
92
+ ((event.Op&fsnotify.Write) == fsnotify.Write ||
93
+ (event.Op&fsnotify.Create) == fsnotify.Create)) {
94
+ // wait some additional time to allow the writer to complete its job
95
+ time.Sleep(additionalWait)
96
+ previousWatchedPath = currentWatchedPath
97
+
98
+ lastCalled = time.Now()
99
+
100
+ select {
101
+ case w.signal <- struct{}{}:
102
+ case <-w.terminate:
103
+ break outer
104
+ }
105
+ }
106
+
107
+ case <-w.inner.Errors:
108
+ break outer
109
+
110
+ case <-w.terminate:
111
+ break outer
112
+ }
113
+ }
114
+
115
+ close(w.signal)
116
+ w.inner.Close() //nolint:errcheck
117
+ }
118
+
119
+ // Watch returns a channel that is called after the configuration file has changed.
120
+ func (w *ConfWatcher) Watch() chan struct{} {
121
+ return w.signal
122
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher_test.go ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package confwatcher
2
+
3
+ import (
4
+ "os"
5
+ "testing"
6
+ "time"
7
+
8
+ "github.com/bluenviron/mediamtx/internal/test"
9
+ "github.com/stretchr/testify/require"
10
+ )
11
+
12
+ func TestNoFile(t *testing.T) {
13
+ w := &ConfWatcher{FilePath: "/nonexistent"}
14
+ err := w.Initialize()
15
+ require.Error(t, err)
16
+ }
17
+
18
+ func TestWrite(t *testing.T) {
19
+ fpath := test.CreateTempFile(t, []byte("{}"))
20
+
21
+ w := &ConfWatcher{FilePath: fpath}
22
+ err := w.Initialize()
23
+ require.NoError(t, err)
24
+ defer w.Close()
25
+
26
+ func() {
27
+ var f *os.File
28
+ f, err = os.Create(fpath)
29
+ require.NoError(t, err)
30
+ defer f.Close()
31
+
32
+ _, err = f.Write([]byte("{}"))
33
+ require.NoError(t, err)
34
+ }()
35
+
36
+ select {
37
+ case <-w.Watch():
38
+ case <-time.After(500 * time.Millisecond):
39
+ t.Errorf("timed out")
40
+ return
41
+ }
42
+ }
43
+
44
+ func TestWriteMultipleTimes(t *testing.T) {
45
+ fpath := test.CreateTempFile(t, []byte("{}"))
46
+
47
+ w := &ConfWatcher{FilePath: fpath}
48
+ err := w.Initialize()
49
+ require.NoError(t, err)
50
+ defer w.Close()
51
+
52
+ func() {
53
+ f, err2 := os.Create(fpath)
54
+ require.NoError(t, err2)
55
+ defer f.Close()
56
+
57
+ _, err2 = f.Write([]byte("{}"))
58
+ require.NoError(t, err2)
59
+ }()
60
+
61
+ time.Sleep(10 * time.Millisecond)
62
+
63
+ func() {
64
+ f, err2 := os.Create(fpath)
65
+ require.NoError(t, err2)
66
+ defer f.Close()
67
+
68
+ _, err2 = f.Write([]byte("{}"))
69
+ require.NoError(t, err2)
70
+ }()
71
+
72
+ select {
73
+ case <-w.Watch():
74
+ case <-time.After(500 * time.Millisecond):
75
+ t.Errorf("timed out")
76
+ return
77
+ }
78
+
79
+ select {
80
+ case <-time.After(500 * time.Millisecond):
81
+ case <-w.Watch():
82
+ t.Errorf("should not happen")
83
+ return
84
+ }
85
+ }
86
+
87
+ func TestDeleteCreate(t *testing.T) {
88
+ fpath := test.CreateTempFile(t, []byte("{}"))
89
+
90
+ w := &ConfWatcher{FilePath: fpath}
91
+ err := w.Initialize()
92
+ require.NoError(t, err)
93
+ defer w.Close()
94
+
95
+ os.Remove(fpath)
96
+
97
+ time.Sleep(10 * time.Millisecond)
98
+
99
+ func() {
100
+ var f *os.File
101
+ f, err = os.Create(fpath)
102
+ require.NoError(t, err)
103
+ defer f.Close()
104
+
105
+ _, err = f.Write([]byte("{}"))
106
+ require.NoError(t, err)
107
+ }()
108
+
109
+ select {
110
+ case <-w.Watch():
111
+ case <-time.After(500 * time.Millisecond):
112
+ t.Errorf("timed out")
113
+ return
114
+ }
115
+ }
116
+
117
+ func TestSymlinkDeleteCreate(t *testing.T) {
118
+ fpath := test.CreateTempFile(t, []byte("{}"))
119
+
120
+ err := os.Symlink(fpath, fpath+"-sym")
121
+ require.NoError(t, err)
122
+
123
+ w := &ConfWatcher{FilePath: fpath + "-sym"}
124
+ err = w.Initialize()
125
+ require.NoError(t, err)
126
+ defer w.Close()
127
+
128
+ os.Remove(fpath)
129
+
130
+ func() {
131
+ f, err2 := os.Create(fpath)
132
+ require.NoError(t, err2)
133
+ defer f.Close()
134
+
135
+ _, err2 = f.Write([]byte("{}"))
136
+ require.NoError(t, err2)
137
+ }()
138
+
139
+ select {
140
+ case <-w.Watch():
141
+ case <-time.After(500 * time.Millisecond):
142
+ t.Errorf("timed out")
143
+ return
144
+ }
145
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/api_test.go ADDED
@@ -0,0 +1,1412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //nolint:dupl,lll
2
+ package core
3
+
4
+ import (
5
+ "bufio"
6
+ "bytes"
7
+ "context"
8
+ "crypto/tls"
9
+ "encoding/json"
10
+ "io"
11
+ "net/http"
12
+ "net/url"
13
+ "testing"
14
+ "time"
15
+
16
+ "github.com/bluenviron/gohlslib/v2"
17
+ "github.com/bluenviron/gortmplib"
18
+ rtmpcodecs "github.com/bluenviron/gortmplib/pkg/codecs"
19
+ "github.com/bluenviron/gortsplib/v5"
20
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
21
+ "github.com/bluenviron/gortsplib/v5/pkg/format"
22
+ "github.com/bluenviron/gortsplib/v5/pkg/format/rtph264"
23
+ "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts"
24
+ tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs"
25
+ srt "github.com/datarhei/gosrt"
26
+ "github.com/google/uuid"
27
+ "github.com/pion/rtp"
28
+ pwebrtc "github.com/pion/webrtc/v4"
29
+ "github.com/stretchr/testify/require"
30
+
31
+ "github.com/bluenviron/mediamtx/internal/defs"
32
+ "github.com/bluenviron/mediamtx/internal/formatlabel"
33
+ "github.com/bluenviron/mediamtx/internal/protocols/webrtc"
34
+ "github.com/bluenviron/mediamtx/internal/protocols/whip"
35
+ "github.com/bluenviron/mediamtx/internal/test"
36
+ )
37
+
38
+ func checkClose(t *testing.T, closeFunc func() error) {
39
+ require.NoError(t, closeFunc())
40
+ }
41
+
42
+ func httpRequest(t *testing.T, hc *http.Client, method string, ur string, in any, out any) {
43
+ buf := func() io.Reader {
44
+ if in == nil {
45
+ return nil
46
+ }
47
+
48
+ byts, err := json.Marshal(in)
49
+ require.NoError(t, err)
50
+
51
+ return bytes.NewBuffer(byts)
52
+ }()
53
+
54
+ req, err := http.NewRequest(method, ur, buf)
55
+ require.NoError(t, err)
56
+
57
+ res, err := hc.Do(req)
58
+ require.NoError(t, err)
59
+ defer res.Body.Close()
60
+
61
+ if res.StatusCode != http.StatusOK {
62
+ t.Errorf("bad status code: %d", res.StatusCode)
63
+ }
64
+
65
+ if out == nil {
66
+ return
67
+ }
68
+
69
+ err = json.NewDecoder(res.Body).Decode(out)
70
+ require.NoError(t, err)
71
+ }
72
+
73
+ func checkError(t *testing.T, msg string, body io.Reader) {
74
+ var resErr map[string]any
75
+ err := json.NewDecoder(body).Decode(&resErr)
76
+ require.NoError(t, err)
77
+ require.Equal(t, map[string]any{"status": "error", "error": msg}, resErr)
78
+ }
79
+
80
+ func TestAPIPathsList(t *testing.T) {
81
+ type pathSource struct {
82
+ Type string `json:"type"`
83
+ }
84
+
85
+ type path struct {
86
+ Name string `json:"name"`
87
+ Source pathSource `json:"source"`
88
+ Ready bool `json:"ready"`
89
+ Tracks []defs.APIPathTrackCodec `json:"tracks"`
90
+ InboundBytes uint64 `json:"inboundBytes"`
91
+ OutboundBytes uint64 `json:"outboundBytes"`
92
+ InboundFramesInError uint64 `json:"inboundFramesInError"`
93
+ BytesReceived uint64 `json:"bytesReceived"`
94
+ BytesSent uint64 `json:"bytesSent"`
95
+ }
96
+
97
+ type pathList struct {
98
+ ItemCount int `json:"itemCount"`
99
+ PageCount int `json:"pageCount"`
100
+ Items []path `json:"items"`
101
+ }
102
+
103
+ t.Run("rtsp session", func(t *testing.T) {
104
+ p, ok := newInstance(t, "api: yes\n"+
105
+ "paths:\n"+
106
+ " mypath:\n")
107
+ require.Equal(t, true, ok)
108
+ defer p.Close()
109
+
110
+ tr := &http.Transport{}
111
+ defer tr.CloseIdleConnections()
112
+ hc := &http.Client{Transport: tr}
113
+
114
+ media0 := test.UniqueMediaH264()
115
+
116
+ source := gortsplib.Client{}
117
+ err := source.StartRecording(
118
+ "rtsp://localhost:8554/mypath",
119
+ &description.Session{Medias: []*description.Media{
120
+ media0,
121
+ test.MediaMPEG4Audio,
122
+ }})
123
+ require.NoError(t, err)
124
+ defer source.Close()
125
+
126
+ err = source.WritePacketRTP(media0, &rtp.Packet{
127
+ Header: rtp.Header{
128
+ Version: 2,
129
+ PayloadType: 96,
130
+ },
131
+ Payload: []byte{5, 1, 2, 3, 4},
132
+ })
133
+ require.NoError(t, err)
134
+
135
+ var out pathList
136
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out)
137
+ require.Equal(t, pathList{
138
+ ItemCount: 1,
139
+ PageCount: 1,
140
+ Items: []path{{
141
+ Name: "mypath",
142
+ Source: pathSource{
143
+ Type: "rtspSession",
144
+ },
145
+ Ready: true,
146
+ Tracks: []defs.APIPathTrackCodec{formatlabel.H264, formatlabel.MPEG4Audio},
147
+ InboundBytes: 17,
148
+ InboundFramesInError: 0,
149
+ BytesReceived: 17,
150
+ }},
151
+ }, out)
152
+ })
153
+
154
+ t.Run("rtsps session", func(t *testing.T) {
155
+ serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
156
+ serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
157
+
158
+ p, ok := newInstance(t, "api: yes\n"+
159
+ "rtspEncryption: optional\n"+
160
+ "rtspServerCert: "+serverCertFpath+"\n"+
161
+ "rtspServerKey: "+serverKeyFpath+"\n"+
162
+ "paths:\n"+
163
+ " mypath:\n")
164
+ require.Equal(t, true, ok)
165
+ defer p.Close()
166
+
167
+ tr := &http.Transport{}
168
+ defer tr.CloseIdleConnections()
169
+ hc := &http.Client{Transport: tr}
170
+
171
+ source := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}}
172
+ err := source.StartRecording("rtsps://localhost:8322/mypath",
173
+ &description.Session{Medias: []*description.Media{
174
+ test.UniqueMediaH264(),
175
+ test.UniqueMediaMPEG4Audio(),
176
+ }})
177
+ require.NoError(t, err)
178
+ defer source.Close()
179
+
180
+ var out pathList
181
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out)
182
+ require.Equal(t, pathList{
183
+ ItemCount: 1,
184
+ PageCount: 1,
185
+ Items: []path{{
186
+ Name: "mypath",
187
+ Source: pathSource{
188
+ Type: "rtspsSession",
189
+ },
190
+ Ready: true,
191
+ Tracks: []defs.APIPathTrackCodec{formatlabel.H264, formatlabel.MPEG4Audio},
192
+ }},
193
+ }, out)
194
+ })
195
+
196
+ t.Run("rtsp source", func(t *testing.T) {
197
+ p, ok := newInstance(t, "api: yes\n"+
198
+ "paths:\n"+
199
+ " mypath:\n"+
200
+ " source: rtsp://127.0.0.1:1234/mypath\n"+
201
+ " sourceOnDemand: yes\n")
202
+ require.Equal(t, true, ok)
203
+ defer p.Close()
204
+
205
+ tr := &http.Transport{}
206
+ defer tr.CloseIdleConnections()
207
+ hc := &http.Client{Transport: tr}
208
+
209
+ var out pathList
210
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out)
211
+ require.Equal(t, pathList{
212
+ ItemCount: 1,
213
+ PageCount: 1,
214
+ Items: []path{{
215
+ Name: "mypath",
216
+ Source: pathSource{
217
+ Type: "rtspSource",
218
+ },
219
+ Ready: false,
220
+ Tracks: []defs.APIPathTrackCodec{},
221
+ }},
222
+ }, out)
223
+ })
224
+
225
+ t.Run("rtmp source", func(t *testing.T) {
226
+ p, ok := newInstance(t, "api: yes\n"+
227
+ "paths:\n"+
228
+ " mypath:\n"+
229
+ " source: rtmp://127.0.0.1:1234/mypath\n"+
230
+ " sourceOnDemand: yes\n")
231
+ require.Equal(t, true, ok)
232
+ defer p.Close()
233
+
234
+ tr := &http.Transport{}
235
+ defer tr.CloseIdleConnections()
236
+ hc := &http.Client{Transport: tr}
237
+
238
+ var out pathList
239
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out)
240
+ require.Equal(t, pathList{
241
+ ItemCount: 1,
242
+ PageCount: 1,
243
+ Items: []path{{
244
+ Name: "mypath",
245
+ Source: pathSource{
246
+ Type: "rtmpSource",
247
+ },
248
+ Ready: false,
249
+ Tracks: []defs.APIPathTrackCodec{},
250
+ }},
251
+ }, out)
252
+ })
253
+
254
+ t.Run("hls source", func(t *testing.T) {
255
+ p, ok := newInstance(t, "api: yes\n"+
256
+ "paths:\n"+
257
+ " mypath:\n"+
258
+ " source: http://127.0.0.1:1234/mypath\n"+
259
+ " sourceOnDemand: yes\n")
260
+ require.Equal(t, true, ok)
261
+ defer p.Close()
262
+
263
+ tr := &http.Transport{}
264
+ defer tr.CloseIdleConnections()
265
+ hc := &http.Client{Transport: tr}
266
+
267
+ var out pathList
268
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out)
269
+ require.Equal(t, pathList{
270
+ ItemCount: 1,
271
+ PageCount: 1,
272
+ Items: []path{{
273
+ Name: "mypath",
274
+ Source: pathSource{
275
+ Type: "hlsSource",
276
+ },
277
+ Ready: false,
278
+ Tracks: []defs.APIPathTrackCodec{},
279
+ }},
280
+ }, out)
281
+ })
282
+ }
283
+
284
+ func TestAPIPathsGet(t *testing.T) {
285
+ p, ok := newInstance(t, "api: yes\n"+
286
+ "paths:\n"+
287
+ " all_others:\n")
288
+ require.Equal(t, true, ok)
289
+ defer p.Close()
290
+
291
+ tr := &http.Transport{}
292
+ defer tr.CloseIdleConnections()
293
+ hc := &http.Client{Transport: tr}
294
+
295
+ for _, ca := range []string{"ok", "ok-nested", "not found"} {
296
+ t.Run(ca, func(t *testing.T) {
297
+ type pathSource struct {
298
+ Type string `json:"type"`
299
+ }
300
+
301
+ type path struct {
302
+ Name string `json:"name"`
303
+ Source pathSource `json:"source"`
304
+ Ready bool `json:"Ready"`
305
+ Tracks []defs.APIPathTrackCodec `json:"tracks"`
306
+ InboundBytes uint64 `json:"inboundBytes"`
307
+ OutboundBytes uint64 `json:"outboundBytes"`
308
+ InboundFramesInError uint64 `json:"inboundFramesInError"`
309
+ BytesReceived uint64 `json:"bytesReceived"`
310
+ BytesSent uint64 `json:"bytesSent"`
311
+ }
312
+
313
+ var pathName string
314
+
315
+ switch ca {
316
+ case "ok":
317
+ pathName = "mypath"
318
+ case "ok-nested":
319
+ pathName = "my/nested/path"
320
+ case "not found":
321
+ pathName = "nonexisting"
322
+ }
323
+
324
+ if ca == "ok" || ca == "ok-nested" {
325
+ source := gortsplib.Client{}
326
+ err := source.StartRecording("rtsp://localhost:8554/"+pathName,
327
+ &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
328
+ require.NoError(t, err)
329
+ defer source.Close()
330
+
331
+ var out path
332
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/get/"+pathName, nil, &out)
333
+ require.Equal(t, path{
334
+ Name: pathName,
335
+ Source: pathSource{
336
+ Type: "rtspSession",
337
+ },
338
+ Ready: true,
339
+ Tracks: []defs.APIPathTrackCodec{formatlabel.H264},
340
+ }, out)
341
+ } else {
342
+ res, err := hc.Get("http://localhost:9997/v3/paths/get/" + pathName)
343
+ require.NoError(t, err)
344
+ defer res.Body.Close()
345
+
346
+ require.Equal(t, http.StatusNotFound, res.StatusCode)
347
+ checkError(t, "path not found", res.Body)
348
+ }
349
+ })
350
+ }
351
+ }
352
+
353
+ func TestAPIProtocolListGet(t *testing.T) {
354
+ serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
355
+ serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
356
+
357
+ for _, ca := range []string{
358
+ "rtsp conns",
359
+ "rtsp sessions",
360
+ "rtsps conns",
361
+ "rtsps sessions",
362
+ "rtmp",
363
+ "rtmps",
364
+ "hls sessions",
365
+ "hls muxers",
366
+ "webrtc",
367
+ "srt",
368
+ } {
369
+ t.Run(ca, func(t *testing.T) {
370
+ cnf := "api: yes\n"
371
+
372
+ switch ca {
373
+ case "rtsps conns", "rtsps sessions":
374
+ cnf += "rtspEncryption: strict\n" +
375
+ "rtspServerCert: " + serverCertFpath + "\n" +
376
+ "rtspServerKey: " + serverKeyFpath + "\n"
377
+
378
+ case "rtmps":
379
+ cnf += "rtmpEncryption: strict\n" +
380
+ "rtmpServerCert: " + serverCertFpath + "\n" +
381
+ "rtmpServerKey: " + serverKeyFpath + "\n"
382
+ }
383
+
384
+ cnf += "paths:\n" +
385
+ " all_others:\n"
386
+
387
+ p, ok := newInstance(t, cnf)
388
+ require.Equal(t, true, ok)
389
+ defer p.Close()
390
+
391
+ tr := &http.Transport{}
392
+ defer tr.CloseIdleConnections()
393
+ hc := &http.Client{Transport: tr}
394
+
395
+ medi := test.UniqueMediaH264()
396
+
397
+ switch ca { //nolint:dupl
398
+ case "rtsp conns", "rtsp sessions":
399
+ source := gortsplib.Client{}
400
+
401
+ err := source.StartRecording("rtsp://localhost:8554/mypath?key=val",
402
+ &description.Session{Medias: []*description.Media{medi}})
403
+ require.NoError(t, err)
404
+ defer source.Close()
405
+
406
+ case "rtsps conns", "rtsps sessions":
407
+ source := gortsplib.Client{
408
+ TLSConfig: &tls.Config{InsecureSkipVerify: true},
409
+ }
410
+
411
+ err := source.StartRecording("rtsps://localhost:8322/mypath?key=val",
412
+ &description.Session{Medias: []*description.Media{medi}})
413
+ require.NoError(t, err)
414
+ defer source.Close()
415
+
416
+ case "rtmp", "rtmps":
417
+ var port string
418
+ if ca == "rtmp" {
419
+ port = "1935"
420
+ } else {
421
+ port = "1936"
422
+ }
423
+
424
+ var rawURL string
425
+
426
+ if ca == "rtmps" {
427
+ rawURL = "rtmps://"
428
+ } else {
429
+ rawURL = "rtmp://"
430
+ }
431
+
432
+ rawURL += "127.0.0.1:" + port + "/mypath?key=val"
433
+
434
+ var u *url.URL
435
+ u, err := url.Parse(rawURL)
436
+ require.NoError(t, err)
437
+
438
+ conn := &gortmplib.Client{
439
+ URL: u,
440
+ TLSConfig: &tls.Config{InsecureSkipVerify: true},
441
+ Publish: true,
442
+ }
443
+ err = conn.Initialize(context.Background())
444
+ require.NoError(t, err)
445
+ defer conn.Close()
446
+
447
+ track := &gortmplib.Track{
448
+ Codec: &rtmpcodecs.H264{
449
+ SPS: test.FormatH264.SPS,
450
+ PPS: test.FormatH264.PPS,
451
+ },
452
+ }
453
+
454
+ w := &gortmplib.Writer{
455
+ Conn: conn,
456
+ Tracks: []*gortmplib.Track{track},
457
+ }
458
+ err = w.Initialize()
459
+ require.NoError(t, err)
460
+
461
+ err = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}})
462
+ require.NoError(t, err)
463
+
464
+ time.Sleep(500 * time.Millisecond)
465
+
466
+ case "hls sessions", "hls muxers":
467
+ source := gortsplib.Client{}
468
+ err := source.StartRecording("rtsp://localhost:8554/mypath",
469
+ &description.Session{Medias: []*description.Media{medi}})
470
+ require.NoError(t, err)
471
+ defer source.Close()
472
+
473
+ go func() {
474
+ time.Sleep(500 * time.Millisecond)
475
+
476
+ for i := range 3 {
477
+ /*source.WritePacketRTP(medi, &rtp.Packet{
478
+ Header: rtp.Header{
479
+ Version: 2,
480
+ Marker: true,
481
+ PayloadType: 96,
482
+ SequenceNumber: 123 + uint16(i),
483
+ Timestamp: 45343 + uint32(i)*90000,
484
+ SSRC: 563423,
485
+ },
486
+ Payload: []byte{
487
+ testSPS,
488
+ 0x05,
489
+ },
490
+ })
491
+
492
+ []byte{ // 1920x1080 baseline
493
+ 0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02,
494
+ 0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
495
+ 0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, 0x20,
496
+ },*/
497
+
498
+ err2 := source.WritePacketRTP(medi, &rtp.Packet{
499
+ Header: rtp.Header{
500
+ Version: 2,
501
+ Marker: true,
502
+ PayloadType: 96,
503
+ SequenceNumber: 123 + uint16(i),
504
+ Timestamp: 45343 + uint32(i)*90000,
505
+ SSRC: 563423,
506
+ },
507
+ Payload: []byte{
508
+ // testSPS,
509
+ 0x05,
510
+ },
511
+ })
512
+ require.NoError(t, err2)
513
+ }
514
+ }()
515
+
516
+ func() {
517
+ res, err2 := hc.Get("http://localhost:8888/mypath/index.m3u8")
518
+ require.NoError(t, err2)
519
+ defer res.Body.Close()
520
+ require.Equal(t, 200, res.StatusCode)
521
+ }()
522
+
523
+ case "webrtc":
524
+ source := gortsplib.Client{}
525
+ err := source.StartRecording("rtsp://localhost:8554/mypath",
526
+ &description.Session{Medias: []*description.Media{medi}})
527
+ require.NoError(t, err)
528
+ defer source.Close()
529
+
530
+ var u *url.URL
531
+ u, err = url.Parse("http://localhost:8889/mypath/whep?key=val")
532
+ require.NoError(t, err)
533
+
534
+ go func() {
535
+ time.Sleep(500 * time.Millisecond)
536
+
537
+ err2 := source.WritePacketRTP(medi, &rtp.Packet{
538
+ Header: rtp.Header{
539
+ Version: 2,
540
+ Marker: true,
541
+ PayloadType: 96,
542
+ SequenceNumber: 123,
543
+ Timestamp: 45343,
544
+ SSRC: 563423,
545
+ },
546
+ Payload: []byte{5, 1, 2, 3, 4},
547
+ })
548
+ require.NoError(t, err2)
549
+ }()
550
+
551
+ c := &whip.Client{
552
+ HTTPClient: hc,
553
+ URL: u,
554
+ Log: test.NilLogger,
555
+ }
556
+
557
+ err = c.Initialize(context.Background())
558
+ require.NoError(t, err)
559
+ defer checkClose(t, c.Close)
560
+
561
+ case "srt":
562
+ conf := srt.DefaultConfig()
563
+ conf.StreamId = "publish:mypath:::key=val"
564
+
565
+ var conn srt.Conn
566
+ conn, err := srt.Dial("srt", "localhost:8890", conf)
567
+ require.NoError(t, err)
568
+ defer conn.Close()
569
+
570
+ track := &mpegts.Track{
571
+ Codec: &tscodecs.H264{},
572
+ }
573
+
574
+ bw := bufio.NewWriter(conn)
575
+ w := &mpegts.Writer{W: bw, Tracks: []*mpegts.Track{track}}
576
+ err = w.Initialize()
577
+ require.NoError(t, err)
578
+
579
+ err = w.WriteH264(track, 0, 0, [][]byte{{1}})
580
+ require.NoError(t, err)
581
+
582
+ err = bw.Flush()
583
+ require.NoError(t, err)
584
+
585
+ time.Sleep(500 * time.Millisecond)
586
+ }
587
+
588
+ var pa string
589
+ switch ca {
590
+ case "rtsp conns":
591
+ pa = "rtspconns"
592
+
593
+ case "rtsp sessions":
594
+ pa = "rtspsessions"
595
+
596
+ case "rtsps conns":
597
+ pa = "rtspsconns"
598
+
599
+ case "rtsps sessions":
600
+ pa = "rtspssessions"
601
+
602
+ case "rtmp":
603
+ pa = "rtmpconns"
604
+
605
+ case "rtmps":
606
+ pa = "rtmpsconns"
607
+
608
+ case "hls sessions":
609
+ pa = "hlssessions"
610
+
611
+ case "hls muxers":
612
+ pa = "hlsmuxers"
613
+
614
+ case "webrtc":
615
+ pa = "webrtcsessions"
616
+
617
+ case "srt":
618
+ pa = "srtconns"
619
+ }
620
+
621
+ var out1 any
622
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/list", nil, &out1)
623
+
624
+ switch ca {
625
+ case "rtsp conns":
626
+ require.Equal(t, map[string]any{
627
+ "pageCount": float64(1),
628
+ "itemCount": float64(1),
629
+ "items": []any{
630
+ map[string]any{
631
+ "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
632
+ "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
633
+ "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
634
+ "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
635
+ "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
636
+ "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
637
+ "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
638
+ "session": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["session"],
639
+ "tunnel": "none",
640
+ },
641
+ },
642
+ }, out1)
643
+
644
+ case "rtsp sessions":
645
+ require.Equal(t, map[string]any{
646
+ "pageCount": float64(1),
647
+ "itemCount": float64(1),
648
+ "items": []any{
649
+ map[string]any{
650
+ "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
651
+ "inboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"],
652
+ "inboundRTPPacketsLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"],
653
+ "inboundRTPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsInError"],
654
+ "inboundRTPPacketsJitter": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"],
655
+ "inboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"],
656
+ "inboundRTCPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPacketsInError"],
657
+ "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
658
+ "outboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"],
659
+ "outboundRTPPacketsReportedLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsReportedLost"],
660
+ "outboundRTPPacketsDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsDiscarded"],
661
+ "outboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"],
662
+ "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
663
+ "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
664
+ "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
665
+ "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
666
+ "path": "mypath",
667
+ "query": "key=val",
668
+ "user": "",
669
+ "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
670
+ "state": "publish",
671
+ "transport": "UDP",
672
+ "profile": "AVP",
673
+ "rtpPacketsReceived": float64(0),
674
+ "rtpPacketsSent": float64(0),
675
+ "rtpPacketsLost": float64(0),
676
+ "rtpPacketsInError": float64(0),
677
+ "rtpPacketsJitter": float64(0),
678
+ "rtcpPacketsReceived": float64(0),
679
+ "rtcpPacketsSent": float64(0),
680
+ "rtcpPacketsInError": float64(0),
681
+ "conns": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["conns"],
682
+ "userAgent": "gortsplib",
683
+ },
684
+ },
685
+ }, out1)
686
+
687
+ case "rtsps conns":
688
+ require.Equal(t, map[string]any{
689
+ "pageCount": float64(1),
690
+ "itemCount": float64(1),
691
+ "items": []any{
692
+ map[string]any{
693
+ "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
694
+ "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
695
+ "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
696
+ "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
697
+ "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
698
+ "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
699
+ "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
700
+ "session": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["session"],
701
+ "tunnel": "none",
702
+ },
703
+ },
704
+ }, out1)
705
+
706
+ case "rtsps sessions":
707
+ require.Equal(t, map[string]any{
708
+ "pageCount": float64(1),
709
+ "itemCount": float64(1),
710
+ "items": []any{
711
+ map[string]any{
712
+ "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
713
+ "inboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"],
714
+ "inboundRTPPacketsLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"],
715
+ "inboundRTPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsInError"],
716
+ "inboundRTPPacketsJitter": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"],
717
+ "inboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"],
718
+ "inboundRTCPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPacketsInError"],
719
+ "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
720
+ "outboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"],
721
+ "outboundRTPPacketsReportedLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsReportedLost"],
722
+ "outboundRTPPacketsDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsDiscarded"],
723
+ "outboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"],
724
+ "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
725
+ "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
726
+ "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
727
+ "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
728
+ "path": "mypath",
729
+ "query": "key=val",
730
+ "user": "",
731
+ "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
732
+ "state": "publish",
733
+ "transport": "UDP",
734
+ "profile": "SAVP",
735
+ "rtpPacketsReceived": float64(0),
736
+ "rtpPacketsSent": float64(0),
737
+ "rtpPacketsLost": float64(0),
738
+ "rtpPacketsInError": float64(0),
739
+ "rtpPacketsJitter": float64(0),
740
+ "rtcpPacketsReceived": float64(0),
741
+ "rtcpPacketsSent": float64(0),
742
+ "rtcpPacketsInError": float64(0),
743
+ "conns": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["conns"],
744
+ "userAgent": "gortsplib",
745
+ },
746
+ },
747
+ }, out1)
748
+
749
+ case "rtmp":
750
+ require.Equal(t, map[string]any{
751
+ "pageCount": float64(1),
752
+ "itemCount": float64(1),
753
+ "items": []any{
754
+ map[string]any{
755
+ "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
756
+ "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
757
+ "outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"],
758
+ "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
759
+ "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
760
+ "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
761
+ "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
762
+ "path": "mypath",
763
+ "query": "key=val",
764
+ "user": "",
765
+ "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
766
+ "state": "publish",
767
+ "userAgent": "LNX 9,0,124,2",
768
+ },
769
+ },
770
+ }, out1)
771
+
772
+ case "rtmps":
773
+ require.Equal(t, map[string]any{
774
+ "pageCount": float64(1),
775
+ "itemCount": float64(1),
776
+ "items": []any{
777
+ map[string]any{
778
+ "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
779
+ "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
780
+ "outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"],
781
+ "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
782
+ "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
783
+ "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
784
+ "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
785
+ "path": "mypath",
786
+ "query": "key=val",
787
+ "user": "",
788
+ "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
789
+ "state": "publish",
790
+ "userAgent": "LNX 9,0,124,2",
791
+ },
792
+ },
793
+ }, out1)
794
+
795
+ case "hls sessions":
796
+ require.Equal(t, map[string]any{
797
+ "itemCount": float64(1),
798
+ "pageCount": float64(1),
799
+ "items": []any{
800
+ map[string]any{
801
+ "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
802
+ "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
803
+ "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
804
+ "path": "mypath",
805
+ "query": "",
806
+ "user": "",
807
+ "isCDN": false,
808
+ "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
809
+ "userAgent": "Go-http-client/1.1",
810
+ },
811
+ },
812
+ }, out1)
813
+
814
+ case "hls muxers":
815
+ require.Equal(t, map[string]any{
816
+ "itemCount": float64(1),
817
+ "pageCount": float64(1),
818
+ "items": []any{
819
+ map[string]any{
820
+ "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
821
+ "outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"],
822
+ "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
823
+ "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
824
+ "lastRequest": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["lastRequest"],
825
+ "path": "mypath",
826
+ },
827
+ },
828
+ }, out1)
829
+
830
+ case "webrtc":
831
+ require.Equal(t, map[string]any{
832
+ "itemCount": float64(1),
833
+ "pageCount": float64(1),
834
+ "items": []any{
835
+ map[string]any{
836
+ "inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
837
+ "inboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"],
838
+ "inboundRTPPacketsLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"],
839
+ "inboundRTPPacketsJitter": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"],
840
+ "inboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"],
841
+ "outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
842
+ "outboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"],
843
+ "outboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"],
844
+ "outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"],
845
+ "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
846
+ "bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
847
+ "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
848
+ "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
849
+ "localCandidate": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["localCandidate"],
850
+ "path": "mypath",
851
+ "peerConnectionEstablished": true,
852
+ "query": "key=val",
853
+ "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
854
+ "remoteCandidate": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteCandidate"],
855
+ "state": "read",
856
+ "user": "",
857
+ "rtcpPacketsReceived": float64(0),
858
+ "rtcpPacketsSent": float64(2),
859
+ "rtpPacketsJitter": float64(0),
860
+ "rtpPacketsLost": float64(0),
861
+ "rtpPacketsReceived": float64(0),
862
+ "rtpPacketsSent": float64(1),
863
+ "userAgent": "Go-http-client/1.1",
864
+ },
865
+ },
866
+ }, out1)
867
+
868
+ case "srt":
869
+ require.Equal(t, map[string]any{
870
+ "itemCount": float64(1),
871
+ "pageCount": float64(1),
872
+ "items": []any{
873
+ map[string]any{
874
+ "byteMSS": float64(1500),
875
+ "bytesAvailReceiveBuf": float64(0),
876
+ "bytesAvailSendBuf": float64(0),
877
+ "bytesReceiveBuf": float64(0),
878
+ "bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
879
+ "bytesReceivedBelated": float64(0),
880
+ "bytesReceivedDrop": float64(0),
881
+ "bytesReceivedLoss": float64(0),
882
+ "bytesReceivedRetrans": float64(0),
883
+ "bytesReceivedUndecrypt": float64(0),
884
+ "outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"],
885
+ "bytesReceivedUnique": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceivedUnique"],
886
+ "bytesRetrans": float64(0),
887
+ "bytesSendBuf": float64(0),
888
+ "bytesSendDrop": float64(0),
889
+ "bytesSent": float64(0),
890
+ "bytesSentUnique": float64(0),
891
+ "created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
892
+ "id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
893
+ "mbpsLinkCapacity": float64(0),
894
+ "mbpsMaxBW": float64(-1),
895
+ "mbpsReceiveRate": float64(0),
896
+ "mbpsSendRate": float64(0),
897
+ "msRTT": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["msRTT"],
898
+ "msReceiveBuf": float64(0),
899
+ "msReceiveTsbPdDelay": float64(120),
900
+ "msSendBuf": float64(0),
901
+ "msSendTsbPdDelay": float64(120),
902
+ "packetsFlightSize": float64(0),
903
+ "packetsFlowWindow": float64(25600),
904
+ "packetsReceiveBuf": float64(0),
905
+ "packetsReceived": float64(1),
906
+ "packetsReceivedACK": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsReceivedACK"],
907
+ "packetsReceivedAvgBelatedTime": float64(0),
908
+ "packetsReceivedBelated": float64(0),
909
+ "packetsReceivedDrop": float64(0),
910
+ "packetsReceivedKM": float64(0),
911
+ "packetsReceivedLoss": float64(0),
912
+ "packetsReceivedLossRate": float64(0),
913
+ "packetsReceivedNAK": float64(0),
914
+ "packetsReceivedRetrans": float64(0),
915
+ "packetsReceivedUndecrypt": float64(0),
916
+ "packetsReceivedUnique": float64(1),
917
+ "packetsReorderTolerance": float64(0),
918
+ "packetsRetrans": float64(0),
919
+ "packetsSendBuf": float64(0),
920
+ "packetsSendDrop": float64(0),
921
+ "packetsSendLoss": float64(0),
922
+ "packetsSendLossRate": float64(0),
923
+ "packetsSent": float64(0),
924
+ "packetsSentACK": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsSentACK"],
925
+ "packetsSentKM": float64(0),
926
+ "packetsSentNAK": float64(0),
927
+ "packetsSentUnique": float64(0),
928
+ "path": "mypath",
929
+ "query": "key=val",
930
+ "remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
931
+ "state": "publish",
932
+ "user": "",
933
+ "usPacketsSendPeriod": float64(10.967254638671875),
934
+ "usSndDuration": float64(0),
935
+ },
936
+ },
937
+ }, out1)
938
+ }
939
+
940
+ var out2 any
941
+
942
+ if ca == "hls muxers" {
943
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/get/"+
944
+ out1.(map[string]any)["items"].([]any)[0].(map[string]any)["path"].(string),
945
+ nil, &out2)
946
+ } else {
947
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/get/"+
948
+ out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"].(string),
949
+ nil, &out2)
950
+ }
951
+
952
+ switch ca {
953
+ case "rtsp conns", "rtsps conns":
954
+ out2.(map[string]any)["inboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"]
955
+ out2.(map[string]any)["outboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"]
956
+ out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"]
957
+ out2.(map[string]any)["bytesSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"]
958
+
959
+ case "rtsp sessions", "rtsps sessions":
960
+ out2.(map[string]any)["inboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"]
961
+ out2.(map[string]any)["inboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"]
962
+ out2.(map[string]any)["inboundRTPPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"]
963
+ out2.(map[string]any)["inboundRTPPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsInError"]
964
+ out2.(map[string]any)["inboundRTPPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"]
965
+ out2.(map[string]any)["inboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"]
966
+ out2.(map[string]any)["inboundRTCPPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPacketsInError"]
967
+ out2.(map[string]any)["outboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"]
968
+ out2.(map[string]any)["outboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"]
969
+ out2.(map[string]any)["outboundRTPPacketsReportedLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsReportedLost"]
970
+ out2.(map[string]any)["outboundRTPPacketsDiscarded"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsDiscarded"]
971
+ out2.(map[string]any)["outboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"]
972
+ out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"]
973
+ out2.(map[string]any)["bytesSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"]
974
+ out2.(map[string]any)["rtpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsReceived"]
975
+ out2.(map[string]any)["rtpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsSent"]
976
+ out2.(map[string]any)["rtpPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsLost"]
977
+ out2.(map[string]any)["rtpPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsInError"]
978
+ out2.(map[string]any)["rtpPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsJitter"]
979
+ out2.(map[string]any)["rtcpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsReceived"]
980
+ out2.(map[string]any)["rtcpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsSent"]
981
+ out2.(map[string]any)["rtcpPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsInError"]
982
+
983
+ case "webrtc":
984
+ out2.(map[string]any)["inboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"]
985
+ out2.(map[string]any)["inboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"]
986
+ out2.(map[string]any)["inboundRTPPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"]
987
+ out2.(map[string]any)["inboundRTPPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"]
988
+ out2.(map[string]any)["inboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"]
989
+ out2.(map[string]any)["outboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"]
990
+ out2.(map[string]any)["outboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"]
991
+ out2.(map[string]any)["outboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"]
992
+ out2.(map[string]any)["outboundFramesDiscarded"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"]
993
+ out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"]
994
+ out2.(map[string]any)["bytesSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"]
995
+ out2.(map[string]any)["rtpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsReceived"]
996
+ out2.(map[string]any)["rtpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsSent"]
997
+ out2.(map[string]any)["rtpPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsLost"]
998
+ out2.(map[string]any)["rtpPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsJitter"]
999
+ out2.(map[string]any)["rtcpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsReceived"]
1000
+ out2.(map[string]any)["rtcpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsSent"]
1001
+
1002
+ case "hls muxers":
1003
+ out2.(map[string]any)["lastRequest"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["lastRequest"]
1004
+
1005
+ case "srt":
1006
+ out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"]
1007
+ out2.(map[string]any)["bytesReceivedUnique"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceivedUnique"]
1008
+ out2.(map[string]any)["packetsReceivedACK"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsReceivedACK"]
1009
+ out2.(map[string]any)["packetsSentACK"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsSentACK"]
1010
+ out2.(map[string]any)["msRTT"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["msRTT"]
1011
+ }
1012
+
1013
+ require.Equal(t, out1.(map[string]any)["items"].([]any)[0], out2)
1014
+ })
1015
+ }
1016
+ }
1017
+
1018
+ func TestAPIProtocolGetNotFound(t *testing.T) {
1019
+ serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
1020
+ serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
1021
+
1022
+ for _, ca := range []string{
1023
+ "rtsp conns",
1024
+ "rtsp sessions",
1025
+ "rtsps conns",
1026
+ "rtsps sessions",
1027
+ "rtmp",
1028
+ "rtmps",
1029
+ "hls sessions",
1030
+ "hls muxers",
1031
+ "webrtc",
1032
+ "srt",
1033
+ } {
1034
+ t.Run(ca, func(t *testing.T) {
1035
+ cnf := "api: yes\n"
1036
+
1037
+ switch ca {
1038
+ case "rtsps conns", "rtsps sessions":
1039
+ cnf += "rtspTransports: [tcp]\n" +
1040
+ "rtspEncryption: strict\n" +
1041
+ "rtspServerCert: " + serverCertFpath + "\n" +
1042
+ "rtspServerKey: " + serverKeyFpath + "\n"
1043
+
1044
+ case "rtmps":
1045
+ cnf += "rtmpEncryption: strict\n" +
1046
+ "rtmpServerCert: " + serverCertFpath + "\n" +
1047
+ "rtmpServerKey: " + serverKeyFpath + "\n"
1048
+ }
1049
+
1050
+ cnf += "paths:\n" +
1051
+ " all_others:\n"
1052
+
1053
+ p, ok := newInstance(t, cnf)
1054
+ require.Equal(t, true, ok)
1055
+ defer p.Close()
1056
+
1057
+ tr := &http.Transport{}
1058
+ defer tr.CloseIdleConnections()
1059
+ hc := &http.Client{Transport: tr}
1060
+
1061
+ var pa string
1062
+ switch ca {
1063
+ case "rtsp conns":
1064
+ pa = "rtspconns"
1065
+
1066
+ case "rtsp sessions":
1067
+ pa = "rtspsessions"
1068
+
1069
+ case "rtsps conns":
1070
+ pa = "rtspsconns"
1071
+
1072
+ case "rtsps sessions":
1073
+ pa = "rtspssessions"
1074
+
1075
+ case "rtmp":
1076
+ pa = "rtmpconns"
1077
+
1078
+ case "rtmps":
1079
+ pa = "rtmpsconns"
1080
+
1081
+ case "hls sessions":
1082
+ pa = "hlssessions"
1083
+
1084
+ case "hls muxers":
1085
+ pa = "hlsmuxers"
1086
+
1087
+ case "webrtc":
1088
+ pa = "webrtcsessions"
1089
+
1090
+ case "srt":
1091
+ pa = "srtconns"
1092
+ }
1093
+
1094
+ func() {
1095
+ var req *http.Request
1096
+ req, err := http.NewRequest(http.MethodGet, "http://localhost:9997/v3/"+pa+"/get/"+uuid.New().String(), nil)
1097
+ require.NoError(t, err)
1098
+
1099
+ var res *http.Response
1100
+ res, err = hc.Do(req)
1101
+ require.NoError(t, err)
1102
+ defer res.Body.Close()
1103
+
1104
+ require.Equal(t, http.StatusNotFound, res.StatusCode)
1105
+
1106
+ switch ca {
1107
+ case "rtsp conns", "rtsps conns", "rtmp", "rtmps", "srt":
1108
+ checkError(t, "connection not found", res.Body)
1109
+
1110
+ case "rtsp sessions", "rtsps sessions", "hls sessions", "webrtc":
1111
+ checkError(t, "session not found", res.Body)
1112
+
1113
+ case "hls muxers":
1114
+ checkError(t, "muxer not found", res.Body)
1115
+ }
1116
+ }()
1117
+ })
1118
+ }
1119
+ }
1120
+
1121
+ func TestAPIProtocolKick(t *testing.T) {
1122
+ serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
1123
+ serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
1124
+
1125
+ for _, ca := range []string{
1126
+ "rtsp",
1127
+ "rtsps",
1128
+ "rtmp",
1129
+ "hls",
1130
+ "webrtc",
1131
+ "srt",
1132
+ } {
1133
+ t.Run(ca, func(t *testing.T) {
1134
+ cnf := "api: yes\n"
1135
+
1136
+ if ca == "rtsps" {
1137
+ cnf += "rtspTransports: [tcp]\n" +
1138
+ "rtspEncryption: strict\n" +
1139
+ "rtspServerCert: " + serverCertFpath + "\n" +
1140
+ "rtspServerKey: " + serverKeyFpath + "\n"
1141
+ }
1142
+
1143
+ cnf += "paths:\n" +
1144
+ " all_others:\n"
1145
+
1146
+ p, ok := newInstance(t, cnf)
1147
+ require.Equal(t, true, ok)
1148
+ defer p.Close()
1149
+
1150
+ tr := &http.Transport{}
1151
+ defer tr.CloseIdleConnections()
1152
+ hc := &http.Client{Transport: tr}
1153
+
1154
+ medi := test.MediaH264
1155
+
1156
+ switch ca {
1157
+ case "rtsp":
1158
+ source := gortsplib.Client{}
1159
+ err := source.StartRecording("rtsp://localhost:8554/mypath",
1160
+ &description.Session{Medias: []*description.Media{medi}})
1161
+ require.NoError(t, err)
1162
+ defer source.Close()
1163
+
1164
+ case "rtsps":
1165
+ source := gortsplib.Client{
1166
+ TLSConfig: &tls.Config{InsecureSkipVerify: true},
1167
+ }
1168
+ err := source.StartRecording("rtsps://localhost:8322/mypath",
1169
+ &description.Session{Medias: []*description.Media{medi}})
1170
+ require.NoError(t, err)
1171
+ defer source.Close()
1172
+
1173
+ case "rtmp":
1174
+ var u *url.URL
1175
+ u, err := url.Parse("rtmp://localhost:1935/mypath")
1176
+ require.NoError(t, err)
1177
+
1178
+ conn := &gortmplib.Client{
1179
+ URL: u,
1180
+ Publish: true,
1181
+ }
1182
+ err = conn.Initialize(context.Background())
1183
+ require.NoError(t, err)
1184
+ defer conn.Close()
1185
+
1186
+ track := &gortmplib.Track{
1187
+ Codec: &rtmpcodecs.H264{
1188
+ SPS: test.FormatH264.SPS,
1189
+ PPS: test.FormatH264.PPS,
1190
+ },
1191
+ }
1192
+
1193
+ w := &gortmplib.Writer{
1194
+ Conn: conn,
1195
+ Tracks: []*gortmplib.Track{track},
1196
+ }
1197
+ err = w.Initialize()
1198
+ require.NoError(t, err)
1199
+
1200
+ err = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}})
1201
+ require.NoError(t, err)
1202
+
1203
+ case "hls":
1204
+ source := gortsplib.Client{}
1205
+ err := source.StartRecording("rtsp://localhost:8554/mypath",
1206
+ &description.Session{Medias: []*description.Media{medi}})
1207
+ require.NoError(t, err)
1208
+ defer source.Close()
1209
+
1210
+ var enc *rtph264.Encoder
1211
+ enc, err = medi.Formats[0].(*format.H264).CreateEncoder()
1212
+ require.NoError(t, err)
1213
+
1214
+ tracksReceived := make(chan struct{})
1215
+
1216
+ client := &gohlslib.Client{
1217
+ URI: "http://localhost:8888/mypath/index.m3u8",
1218
+ OnTracks: func(_ []*gohlslib.Track) error {
1219
+ close(tracksReceived)
1220
+ return nil
1221
+ },
1222
+ }
1223
+ err = client.Start()
1224
+ require.NoError(t, err)
1225
+ defer client.Close()
1226
+
1227
+ time.Sleep(500 * time.Millisecond)
1228
+
1229
+ for i := range 2 {
1230
+ var pkts []*rtp.Packet
1231
+ pkts, err = enc.Encode([][]byte{{5, 2, 3, 4}})
1232
+ require.NoError(t, err)
1233
+
1234
+ pkts[0].Timestamp = uint32(i * 90000)
1235
+
1236
+ err = source.WritePacketRTP(medi, pkts[0])
1237
+ require.NoError(t, err)
1238
+ }
1239
+
1240
+ <-tracksReceived
1241
+
1242
+ case "webrtc":
1243
+ var u *url.URL
1244
+ u, err := url.Parse("http://localhost:8889/mypath/whip")
1245
+ require.NoError(t, err)
1246
+
1247
+ track := &webrtc.OutboundTrack{
1248
+ Caps: pwebrtc.RTPCodecCapability{
1249
+ MimeType: pwebrtc.MimeTypeH264,
1250
+ ClockRate: 90000,
1251
+ SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
1252
+ },
1253
+ }
1254
+
1255
+ c := &whip.Client{
1256
+ HTTPClient: hc,
1257
+ URL: u,
1258
+ Log: test.NilLogger,
1259
+ Publish: true,
1260
+ OutboundTracks: []*webrtc.OutboundTrack{track},
1261
+ }
1262
+
1263
+ err = c.Initialize(context.Background())
1264
+ require.NoError(t, err)
1265
+ defer func() {
1266
+ require.Error(t, c.Close())
1267
+ }()
1268
+
1269
+ case "srt":
1270
+ conf := srt.DefaultConfig()
1271
+ conf.StreamId = "publish:mypath"
1272
+
1273
+ var conn srt.Conn
1274
+ conn, err := srt.Dial("srt", "localhost:8890", conf)
1275
+ require.NoError(t, err)
1276
+ defer conn.Close()
1277
+
1278
+ track := &mpegts.Track{
1279
+ Codec: &tscodecs.H264{},
1280
+ }
1281
+
1282
+ bw := bufio.NewWriter(conn)
1283
+ w := &mpegts.Writer{W: bw, Tracks: []*mpegts.Track{track}}
1284
+ err = w.Initialize()
1285
+ require.NoError(t, err)
1286
+
1287
+ err = w.WriteH264(track, 0, 0, [][]byte{{1}})
1288
+ require.NoError(t, err)
1289
+
1290
+ err = bw.Flush()
1291
+ require.NoError(t, err)
1292
+ }
1293
+
1294
+ var pa string
1295
+ switch ca {
1296
+ case "rtsp":
1297
+ pa = "rtspsessions"
1298
+
1299
+ case "rtsps":
1300
+ pa = "rtspssessions"
1301
+
1302
+ case "rtmp":
1303
+ pa = "rtmpconns"
1304
+
1305
+ case "hls":
1306
+ pa = "hlssessions"
1307
+
1308
+ case "webrtc":
1309
+ pa = "webrtcsessions"
1310
+
1311
+ case "srt":
1312
+ pa = "srtconns"
1313
+ }
1314
+
1315
+ var out1 struct {
1316
+ Items []struct {
1317
+ ID string `json:"id"`
1318
+ } `json:"items"`
1319
+ }
1320
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/list", nil, &out1)
1321
+ require.NotEmpty(t, out1.Items)
1322
+
1323
+ httpRequest(t, hc, http.MethodPost, "http://localhost:9997/v3/"+pa+"/kick/"+out1.Items[0].ID, nil, nil)
1324
+
1325
+ var out2 struct {
1326
+ Items []struct {
1327
+ ID string `json:"id"`
1328
+ } `json:"items"`
1329
+ }
1330
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/list", nil, &out2)
1331
+ require.Empty(t, out2.Items)
1332
+ })
1333
+ }
1334
+ }
1335
+
1336
+ func TestAPIProtocolKickNotFound(t *testing.T) {
1337
+ serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
1338
+ serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
1339
+
1340
+ for _, ca := range []string{
1341
+ "rtsp",
1342
+ "rtsps",
1343
+ "rtmp",
1344
+ "hls",
1345
+ "webrtc",
1346
+ "srt",
1347
+ } {
1348
+ t.Run(ca, func(t *testing.T) {
1349
+ cnf := "api: yes\n"
1350
+
1351
+ if ca == "rtsps" {
1352
+ cnf += "rtspTransports: [tcp]\n" +
1353
+ "rtspEncryption: strict\n" +
1354
+ "rtspServerCert: " + serverCertFpath + "\n" +
1355
+ "rtspServerKey: " + serverKeyFpath + "\n"
1356
+ }
1357
+
1358
+ cnf += "paths:\n" +
1359
+ " all_others:\n"
1360
+
1361
+ p, ok := newInstance(t, cnf)
1362
+ require.Equal(t, true, ok)
1363
+ defer p.Close()
1364
+
1365
+ tr := &http.Transport{}
1366
+ defer tr.CloseIdleConnections()
1367
+ hc := &http.Client{Transport: tr}
1368
+
1369
+ var pa string
1370
+ switch ca {
1371
+ case "rtsp":
1372
+ pa = "rtspsessions"
1373
+
1374
+ case "rtsps":
1375
+ pa = "rtspssessions"
1376
+
1377
+ case "rtmp":
1378
+ pa = "rtmpconns"
1379
+
1380
+ case "hls":
1381
+ pa = "hlssessions"
1382
+
1383
+ case "webrtc":
1384
+ pa = "webrtcsessions"
1385
+
1386
+ case "srt":
1387
+ pa = "srtconns"
1388
+ }
1389
+
1390
+ func() {
1391
+ var req *http.Request
1392
+ req, err := http.NewRequest(http.MethodPost, "http://localhost:9997/v3/"+pa+"/kick/"+uuid.New().String(), nil)
1393
+ require.NoError(t, err)
1394
+
1395
+ var res *http.Response
1396
+ res, err = hc.Do(req)
1397
+ require.NoError(t, err)
1398
+ defer res.Body.Close()
1399
+
1400
+ require.Equal(t, http.StatusNotFound, res.StatusCode)
1401
+
1402
+ switch ca {
1403
+ case "rtsp conns", "rtsps conns", "rtmp", "rtmps", "srt":
1404
+ checkError(t, "connection not found", res.Body)
1405
+
1406
+ case "rtsp sessions", "rtsps sessions", "hls", "webrtc":
1407
+ checkError(t, "session not found", res.Body)
1408
+ }
1409
+ }()
1410
+ })
1411
+ }
1412
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core.go ADDED
@@ -0,0 +1,1171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package core contains the main struct of the software.
2
+ package core
3
+
4
+ import (
5
+ "context"
6
+ _ "embed"
7
+ "fmt"
8
+ "os"
9
+ "os/signal"
10
+ "path/filepath"
11
+ "reflect"
12
+ "runtime"
13
+ "runtime/debug"
14
+ "slices"
15
+ "strings"
16
+ "syscall"
17
+ "time"
18
+
19
+ "github.com/alecthomas/kong"
20
+ "github.com/gin-gonic/gin"
21
+
22
+ "github.com/bluenviron/mediamtx/internal/api"
23
+ "github.com/bluenviron/mediamtx/internal/auth"
24
+ "github.com/bluenviron/mediamtx/internal/conf"
25
+ "github.com/bluenviron/mediamtx/internal/confwatcher"
26
+ "github.com/bluenviron/mediamtx/internal/externalcmd"
27
+ "github.com/bluenviron/mediamtx/internal/logger"
28
+ "github.com/bluenviron/mediamtx/internal/metrics"
29
+ "github.com/bluenviron/mediamtx/internal/playback"
30
+ "github.com/bluenviron/mediamtx/internal/pprof"
31
+ "github.com/bluenviron/mediamtx/internal/recordcleaner"
32
+ "github.com/bluenviron/mediamtx/internal/rlimit"
33
+ "github.com/bluenviron/mediamtx/internal/servers/hls"
34
+ "github.com/bluenviron/mediamtx/internal/servers/moq"
35
+ "github.com/bluenviron/mediamtx/internal/servers/rtmp"
36
+ "github.com/bluenviron/mediamtx/internal/servers/rtsp"
37
+ "github.com/bluenviron/mediamtx/internal/servers/srt"
38
+ "github.com/bluenviron/mediamtx/internal/servers/webrtc"
39
+ "github.com/bluenviron/mediamtx/internal/upgrade"
40
+ )
41
+
42
+ //go:generate go run ./versiongetter
43
+
44
+ //go:embed VERSION
45
+ var version []byte
46
+
47
+ var started = time.Now()
48
+
49
+ var defaultConfPaths = []string{
50
+ "rtsp-simple-server.yml",
51
+ "mediamtx.yml",
52
+ }
53
+
54
+ var defaultConfPathsNotWin = []string{
55
+ "/usr/local/etc/mediamtx.yml",
56
+ "/usr/etc/mediamtx.yml",
57
+ "/etc/mediamtx/mediamtx.yml",
58
+ }
59
+
60
+ func goArm() string {
61
+ bi, _ := debug.ReadBuildInfo()
62
+ for _, bs := range bi.Settings {
63
+ if bs.Key == "GOARM" {
64
+ return bs.Value
65
+ }
66
+ }
67
+ return ""
68
+ }
69
+
70
+ func getArch() string {
71
+ var arch string
72
+ if runtime.GOARCH == "arm" {
73
+ arch = "armv" + goArm()
74
+ } else {
75
+ arch = runtime.GOARCH
76
+ }
77
+ return arch
78
+ }
79
+
80
+ func atLeastOneRecordDeleteAfter(pathConfs map[string]*conf.Path) bool {
81
+ for _, e := range pathConfs {
82
+ if e.RecordDeleteAfter != 0 {
83
+ return true
84
+ }
85
+ }
86
+ return false
87
+ }
88
+
89
+ func getRTPMaxPayloadSize(udpMaxPayloadSize int, rtspEncryption conf.Encryption) int {
90
+ // UDP max payload size - 12 (RTP header)
91
+ v := udpMaxPayloadSize - 12
92
+
93
+ // 10 (SRTP HMAC SHA1 authentication tag)
94
+ if rtspEncryption == conf.EncryptionOptional || rtspEncryption == conf.EncryptionStrict {
95
+ v -= 10
96
+ }
97
+
98
+ return v
99
+ }
100
+
101
+ var cli struct {
102
+ Confpath string `arg:"" default:""`
103
+ Version bool `help:"print version"`
104
+ CheckVersion bool `help:"check whether a new version is available"`
105
+ Upgrade bool `help:"upgrade executable to the latest version"`
106
+ }
107
+
108
+ // Core is an instance of MediaMTX.
109
+ type Core struct {
110
+ ctx context.Context
111
+ ctxCancel func()
112
+ confPath string
113
+ conf *conf.Conf
114
+ logger *logger.Logger
115
+ externalCmdPool *externalcmd.Pool
116
+ authManager *auth.Manager
117
+ metrics *metrics.Metrics
118
+ pprof *pprof.PPROF
119
+ recordCleaner *recordcleaner.Cleaner
120
+ playbackServer *playback.Server
121
+ pathManager *pathManager
122
+ rtspServer *rtsp.Server
123
+ rtspsServer *rtsp.Server
124
+ rtmpServer *rtmp.Server
125
+ rtmpsServer *rtmp.Server
126
+ hlsServer *hls.Server
127
+ webRTCServer *webrtc.Server
128
+ srtServer *srt.Server
129
+ moqServer *moq.Server
130
+ api *api.API
131
+ confWatcher *confwatcher.ConfWatcher
132
+
133
+ // in
134
+ chAPIConfigSet chan *conf.Conf
135
+
136
+ // out
137
+ done chan struct{}
138
+ }
139
+
140
+ // New allocates a Core.
141
+ func New(args []string) (*Core, bool) {
142
+ parser, err := kong.New(&cli,
143
+ kong.Description("MediaMTX "+string(version)+", "+runtime.GOOS+", "+getArch()),
144
+ kong.UsageOnError(),
145
+ kong.ValueFormatter(func(value *kong.Value) string {
146
+ switch value.Name {
147
+ case "confpath":
148
+ return "path to a config file. The default is mediamtx.yml."
149
+
150
+ default:
151
+ return kong.DefaultHelpValueFormatter(value)
152
+ }
153
+ }))
154
+ if err != nil {
155
+ panic(err)
156
+ }
157
+
158
+ _, err = parser.Parse(args)
159
+ parser.FatalIfErrorf(err)
160
+
161
+ if cli.Version {
162
+ fmt.Println(string(version))
163
+ os.Exit(0)
164
+ }
165
+
166
+ if cli.CheckVersion {
167
+ var newVersionAvailable bool
168
+ newVersionAvailable, err = upgrade.CheckVersion(string(version), getArch())
169
+ if err != nil {
170
+ fmt.Printf("ERR: %v\n", err)
171
+ os.Exit(1)
172
+ }
173
+ if newVersionAvailable {
174
+ os.Exit(2)
175
+ }
176
+ os.Exit(0)
177
+ }
178
+
179
+ if cli.Upgrade {
180
+ err = upgrade.Upgrade(string(version), getArch())
181
+ if err != nil {
182
+ fmt.Printf("ERR: %v\n", err)
183
+ os.Exit(1)
184
+ }
185
+ os.Exit(0)
186
+ }
187
+
188
+ ctx, ctxCancel := context.WithCancel(context.Background())
189
+
190
+ p := &Core{
191
+ ctx: ctx,
192
+ ctxCancel: ctxCancel,
193
+ chAPIConfigSet: make(chan *conf.Conf),
194
+ done: make(chan struct{}),
195
+ }
196
+
197
+ tempLogger := &logger.Logger{
198
+ Level: logger.Warn,
199
+ Destinations: []logger.Destination{logger.DestinationStdout},
200
+ Structured: false,
201
+ File: "",
202
+ SysLogPrefix: "",
203
+ }
204
+ tempLogger.Initialize() //nolint:errcheck
205
+
206
+ confPaths := append([]string(nil), defaultConfPaths...)
207
+ if runtime.GOOS != "windows" {
208
+ confPaths = append(confPaths, defaultConfPathsNotWin...)
209
+ }
210
+
211
+ p.conf, p.confPath, err = conf.Load(cli.Confpath, confPaths, tempLogger)
212
+ if err != nil {
213
+ fmt.Printf("ERR: %s\n", err)
214
+ return nil, false
215
+ }
216
+
217
+ err = p.createResources(true)
218
+ if err != nil {
219
+ if p.logger != nil {
220
+ p.Log(logger.Error, "%s", err)
221
+ } else {
222
+ fmt.Printf("ERR: %s\n", err)
223
+ }
224
+ p.closeResources(nil, false)
225
+ return nil, false
226
+ }
227
+
228
+ go p.run()
229
+
230
+ return p, true
231
+ }
232
+
233
+ // Close closes Core and waits for all goroutines to return.
234
+ func (p *Core) Close() {
235
+ p.ctxCancel()
236
+ <-p.done
237
+ }
238
+
239
+ // Wait waits for the Core to exit.
240
+ func (p *Core) Wait() {
241
+ <-p.done
242
+ }
243
+
244
+ // Log implements logger.Writer.
245
+ func (p *Core) Log(level logger.Level, format string, args ...any) {
246
+ p.logger.Log(level, format, args...)
247
+ }
248
+
249
+ func (p *Core) run() {
250
+ defer close(p.done)
251
+
252
+ confChanged := func() chan struct{} {
253
+ if p.confWatcher != nil {
254
+ return p.confWatcher.Watch()
255
+ }
256
+ return make(chan struct{})
257
+ }()
258
+
259
+ interrupt := make(chan os.Signal, 1)
260
+ signal.Notify(interrupt, os.Interrupt)
261
+ if runtime.GOOS == "linux" {
262
+ signal.Notify(interrupt, syscall.SIGTERM)
263
+ }
264
+
265
+ outer:
266
+ for {
267
+ select {
268
+ case <-confChanged:
269
+ p.Log(logger.Info, "reloading configuration (file changed)")
270
+
271
+ newConf, _, err := conf.Load(p.confPath, nil, p.logger)
272
+ if err != nil {
273
+ p.Log(logger.Error, "%s", err)
274
+ break outer
275
+ }
276
+
277
+ err = p.reloadConf(newConf, false)
278
+ if err != nil {
279
+ p.Log(logger.Error, "%s", err)
280
+ break outer
281
+ }
282
+
283
+ case newConf := <-p.chAPIConfigSet:
284
+ p.Log(logger.Info, "reloading configuration (API request)")
285
+
286
+ err := p.reloadConf(newConf, true)
287
+ if err != nil {
288
+ p.Log(logger.Error, "%s", err)
289
+ break outer
290
+ }
291
+
292
+ case <-interrupt:
293
+ p.Log(logger.Info, "shutting down gracefully")
294
+ break outer
295
+
296
+ case <-p.ctx.Done():
297
+ break outer
298
+ }
299
+ }
300
+
301
+ p.ctxCancel()
302
+
303
+ p.closeResources(nil, false)
304
+ }
305
+
306
+ func (p *Core) createResources(initial bool) error {
307
+ var err error
308
+
309
+ if p.logger == nil {
310
+ i := &logger.Logger{
311
+ Level: logger.Level(p.conf.LogLevel),
312
+ Destinations: p.conf.LogDestinations.ToDestinations(),
313
+ Structured: p.conf.LogStructured,
314
+ File: p.conf.LogFile,
315
+ SysLogPrefix: p.conf.SysLogPrefix,
316
+ }
317
+ err = i.Initialize()
318
+ if err != nil {
319
+ return err
320
+ }
321
+ p.logger = i
322
+ }
323
+
324
+ if initial {
325
+ p.Log(logger.Info, "MediaMTX %s, %s, %s", string(version), runtime.GOOS, getArch())
326
+
327
+ if p.confPath != "" {
328
+ a, _ := filepath.Abs(p.confPath)
329
+ p.Log(logger.Info, "configuration loaded from %s", a)
330
+ } else {
331
+ list := make([]string, len(defaultConfPaths))
332
+ for i, pa := range defaultConfPaths {
333
+ a, _ := filepath.Abs(pa)
334
+ list[i] = a
335
+ }
336
+
337
+ p.Log(logger.Warn,
338
+ "configuration file not found (looked in %s), using an empty configuration",
339
+ strings.Join(list, ", "))
340
+ }
341
+
342
+ // on Linux, try to raise the number of file descriptors that can be opened
343
+ // to allow the maximum possible number of clients.
344
+ rlimit.Raise() //nolint:errcheck
345
+
346
+ gin.SetMode(gin.ReleaseMode)
347
+
348
+ p.externalCmdPool = &externalcmd.Pool{}
349
+ p.externalCmdPool.Initialize()
350
+ }
351
+
352
+ if p.authManager == nil {
353
+ p.authManager = &auth.Manager{
354
+ Method: p.conf.AuthMethod,
355
+ InternalUsers: p.conf.AuthInternalUsers,
356
+ HTTPAddress: p.conf.AuthHTTPAddress,
357
+ HTTPFingerprint: p.conf.AuthHTTPFingerprint,
358
+ HTTPExclude: p.conf.AuthHTTPExclude,
359
+ JWTJWKS: p.conf.AuthJWTJWKS,
360
+ JWTJWKSFingerprint: p.conf.AuthJWTJWKSFingerprint,
361
+ JWTClaimKey: p.conf.AuthJWTClaimKey,
362
+ JWTExclude: p.conf.AuthJWTExclude,
363
+ JWTInHTTPQuery: p.conf.AuthJWTInHTTPQuery,
364
+ JWTIssuer: p.conf.AuthJWTIssuer,
365
+ JWTAudience: p.conf.AuthJWTAudience,
366
+ ReadTimeout: time.Duration(p.conf.ReadTimeout),
367
+ }
368
+ }
369
+
370
+ if p.conf.Metrics &&
371
+ p.metrics == nil {
372
+ i := &metrics.Metrics{
373
+ Address: p.conf.MetricsAddress,
374
+ DumpPackets: p.conf.DumpPackets,
375
+ Encryption: p.conf.MetricsEncryption,
376
+ ServerKey: p.conf.MetricsServerKey,
377
+ ServerCert: p.conf.MetricsServerCert,
378
+ AllowOrigins: p.conf.MetricsAllowOrigins,
379
+ TrustedProxies: p.conf.MetricsTrustedProxies,
380
+ ReadTimeout: p.conf.ReadTimeout,
381
+ WriteTimeout: p.conf.WriteTimeout,
382
+ AuthManager: p.authManager,
383
+ Parent: p,
384
+ }
385
+ err = i.Initialize()
386
+ if err != nil {
387
+ return err
388
+ }
389
+ p.metrics = i
390
+ }
391
+
392
+ if p.conf.PPROF &&
393
+ p.pprof == nil {
394
+ i := &pprof.PPROF{
395
+ Address: p.conf.PPROFAddress,
396
+ DumpPackets: p.conf.DumpPackets,
397
+ Encryption: p.conf.PPROFEncryption,
398
+ ServerKey: p.conf.PPROFServerKey,
399
+ ServerCert: p.conf.PPROFServerCert,
400
+ AllowOrigins: p.conf.PPROFAllowOrigins,
401
+ TrustedProxies: p.conf.PPROFTrustedProxies,
402
+ ReadTimeout: p.conf.ReadTimeout,
403
+ WriteTimeout: p.conf.WriteTimeout,
404
+ AuthManager: p.authManager,
405
+ Parent: p,
406
+ }
407
+ err = i.Initialize()
408
+ if err != nil {
409
+ return err
410
+ }
411
+ p.pprof = i
412
+ }
413
+
414
+ if p.recordCleaner == nil &&
415
+ atLeastOneRecordDeleteAfter(p.conf.Paths) {
416
+ p.recordCleaner = &recordcleaner.Cleaner{
417
+ PathConfs: p.conf.Paths,
418
+ Parent: p,
419
+ }
420
+ p.recordCleaner.Initialize()
421
+ }
422
+
423
+ if p.conf.Playback &&
424
+ p.playbackServer == nil {
425
+ i := &playback.Server{
426
+ Address: p.conf.PlaybackAddress,
427
+ DumpPackets: p.conf.DumpPackets,
428
+ Encryption: p.conf.PlaybackEncryption,
429
+ ServerKey: p.conf.PlaybackServerKey,
430
+ ServerCert: p.conf.PlaybackServerCert,
431
+ AllowOrigins: p.conf.PlaybackAllowOrigins,
432
+ TrustedProxies: p.conf.PlaybackTrustedProxies,
433
+ ReadTimeout: p.conf.ReadTimeout,
434
+ WriteTimeout: p.conf.WriteTimeout,
435
+ PathConfs: p.conf.Paths,
436
+ AuthManager: p.authManager,
437
+ Parent: p,
438
+ }
439
+ err = i.Initialize()
440
+ if err != nil {
441
+ return err
442
+ }
443
+ p.playbackServer = i
444
+ }
445
+
446
+ if p.pathManager == nil {
447
+ rtpMaxPayloadSize := getRTPMaxPayloadSize(p.conf.UDPMaxPayloadSize, p.conf.RTSPEncryption)
448
+
449
+ p.pathManager = &pathManager{
450
+ logLevel: p.conf.LogLevel,
451
+ dumpPackets: p.conf.DumpPackets,
452
+ rtspAddress: p.conf.RTSPAddress,
453
+ readTimeout: p.conf.ReadTimeout,
454
+ writeTimeout: p.conf.WriteTimeout,
455
+ writeQueueSize: p.conf.WriteQueueSize,
456
+ udpReadBufferSize: p.conf.UDPReadBufferSize,
457
+ rtpMaxPayloadSize: rtpMaxPayloadSize,
458
+ pathConfs: p.conf.Paths,
459
+ authManager: p.authManager,
460
+ externalCmdPool: p.externalCmdPool,
461
+ metrics: p.metrics,
462
+ parent: p,
463
+ }
464
+ p.pathManager.initialize()
465
+ }
466
+
467
+ if p.conf.RTSP &&
468
+ (p.conf.RTSPEncryption == conf.EncryptionNo ||
469
+ p.conf.RTSPEncryption == conf.EncryptionOptional) &&
470
+ p.rtspServer == nil {
471
+ udpReadBufferSize := p.conf.UDPReadBufferSize
472
+ if p.conf.RTSPUDPReadBufferSize != nil {
473
+ udpReadBufferSize = *p.conf.RTSPUDPReadBufferSize
474
+ }
475
+
476
+ i := &rtsp.Server{
477
+ Address: p.conf.RTSPAddress,
478
+ AuthMethods: p.conf.RTSPAuthMethods.ToAuthMethods(),
479
+ DumpPackets: p.conf.DumpPackets,
480
+ UDPReadBufferSize: udpReadBufferSize,
481
+ ReadTimeout: p.conf.ReadTimeout,
482
+ WriteTimeout: p.conf.WriteTimeout,
483
+ WriteQueueSize: p.conf.WriteQueueSize,
484
+ RTSPTransports: p.conf.RTSPTransports,
485
+ RTPAddress: p.conf.RTPAddress,
486
+ RTCPAddress: p.conf.RTCPAddress,
487
+ MulticastIPRange: p.conf.MulticastIPRange,
488
+ MulticastRTPPort: p.conf.MulticastRTPPort,
489
+ MulticastRTCPPort: p.conf.MulticastRTCPPort,
490
+ Encryption: false,
491
+ ServerCert: "",
492
+ ServerKey: "",
493
+ RTSPAddress: p.conf.RTSPAddress,
494
+ TrustedProxies: p.conf.RTSPTrustedProxies,
495
+ Transports: p.conf.RTSPTransports,
496
+ RunOnConnect: p.conf.RunOnConnect,
497
+ RunOnConnectRestart: p.conf.RunOnConnectRestart,
498
+ RunOnDisconnect: p.conf.RunOnDisconnect,
499
+ ExternalCmdPool: p.externalCmdPool,
500
+ Metrics: p.metrics,
501
+ PathManager: p.pathManager,
502
+ Parent: p,
503
+ }
504
+ err = i.Initialize()
505
+ if err != nil {
506
+ return err
507
+ }
508
+ p.rtspServer = i
509
+ }
510
+
511
+ if p.conf.RTSP &&
512
+ (p.conf.RTSPEncryption == conf.EncryptionStrict ||
513
+ p.conf.RTSPEncryption == conf.EncryptionOptional) &&
514
+ p.rtspsServer == nil {
515
+ udpReadBufferSize := p.conf.UDPReadBufferSize
516
+ if p.conf.RTSPUDPReadBufferSize != nil {
517
+ udpReadBufferSize = *p.conf.RTSPUDPReadBufferSize
518
+ }
519
+
520
+ i := &rtsp.Server{
521
+ Address: p.conf.RTSPSAddress,
522
+ AuthMethods: p.conf.RTSPAuthMethods.ToAuthMethods(),
523
+ DumpPackets: p.conf.DumpPackets,
524
+ UDPReadBufferSize: udpReadBufferSize,
525
+ ReadTimeout: p.conf.ReadTimeout,
526
+ WriteTimeout: p.conf.WriteTimeout,
527
+ WriteQueueSize: p.conf.WriteQueueSize,
528
+ RTSPTransports: p.conf.RTSPTransports,
529
+ RTPAddress: p.conf.SRTPAddress,
530
+ RTCPAddress: p.conf.SRTCPAddress,
531
+ MulticastIPRange: p.conf.MulticastIPRange,
532
+ MulticastRTPPort: p.conf.MulticastSRTPPort,
533
+ MulticastRTCPPort: p.conf.MulticastSRTCPPort,
534
+ Encryption: true,
535
+ ServerCert: p.conf.RTSPServerCert,
536
+ ServerKey: p.conf.RTSPServerKey,
537
+ RTSPAddress: p.conf.RTSPAddress,
538
+ TrustedProxies: p.conf.RTSPTrustedProxies,
539
+ Transports: p.conf.RTSPTransports,
540
+ RunOnConnect: p.conf.RunOnConnect,
541
+ RunOnConnectRestart: p.conf.RunOnConnectRestart,
542
+ RunOnDisconnect: p.conf.RunOnDisconnect,
543
+ ExternalCmdPool: p.externalCmdPool,
544
+ Metrics: p.metrics,
545
+ PathManager: p.pathManager,
546
+ Parent: p,
547
+ }
548
+ err = i.Initialize()
549
+ if err != nil {
550
+ return err
551
+ }
552
+ p.rtspsServer = i
553
+ }
554
+
555
+ if p.conf.RTMP &&
556
+ (p.conf.RTMPEncryption == conf.EncryptionNo ||
557
+ p.conf.RTMPEncryption == conf.EncryptionOptional) &&
558
+ p.rtmpServer == nil {
559
+ i := &rtmp.Server{
560
+ Address: p.conf.RTMPAddress,
561
+ DumpPackets: p.conf.DumpPackets,
562
+ ReadTimeout: p.conf.ReadTimeout,
563
+ WriteTimeout: p.conf.WriteTimeout,
564
+ Encryption: false,
565
+ ServerCert: "",
566
+ ServerKey: "",
567
+ RTSPAddress: p.conf.RTSPAddress,
568
+ TrustedProxies: p.conf.RTMPTrustedProxies,
569
+ RunOnConnect: p.conf.RunOnConnect,
570
+ RunOnConnectRestart: p.conf.RunOnConnectRestart,
571
+ RunOnDisconnect: p.conf.RunOnDisconnect,
572
+ ExternalCmdPool: p.externalCmdPool,
573
+ Metrics: p.metrics,
574
+ PathManager: p.pathManager,
575
+ Parent: p,
576
+ }
577
+ err = i.Initialize()
578
+ if err != nil {
579
+ return err
580
+ }
581
+ p.rtmpServer = i
582
+ }
583
+
584
+ if p.conf.RTMP &&
585
+ (p.conf.RTMPEncryption == conf.EncryptionStrict ||
586
+ p.conf.RTMPEncryption == conf.EncryptionOptional) &&
587
+ p.rtmpsServer == nil {
588
+ i := &rtmp.Server{
589
+ Address: p.conf.RTMPSAddress,
590
+ ReadTimeout: p.conf.ReadTimeout,
591
+ WriteTimeout: p.conf.WriteTimeout,
592
+ Encryption: true,
593
+ ServerCert: p.conf.RTMPServerCert,
594
+ ServerKey: p.conf.RTMPServerKey,
595
+ DumpPackets: p.conf.DumpPackets,
596
+ RTSPAddress: p.conf.RTSPAddress,
597
+ TrustedProxies: p.conf.RTMPTrustedProxies,
598
+ RunOnConnect: p.conf.RunOnConnect,
599
+ RunOnConnectRestart: p.conf.RunOnConnectRestart,
600
+ RunOnDisconnect: p.conf.RunOnDisconnect,
601
+ ExternalCmdPool: p.externalCmdPool,
602
+ Metrics: p.metrics,
603
+ PathManager: p.pathManager,
604
+ Parent: p,
605
+ }
606
+ err = i.Initialize()
607
+ if err != nil {
608
+ return err
609
+ }
610
+ p.rtmpsServer = i
611
+ }
612
+
613
+ if p.conf.HLS &&
614
+ p.hlsServer == nil {
615
+ i := &hls.Server{
616
+ Address: p.conf.HLSAddress,
617
+ DumpPackets: p.conf.DumpPackets,
618
+ Encryption: p.conf.HLSEncryption,
619
+ ServerKey: p.conf.HLSServerKey,
620
+ ServerCert: p.conf.HLSServerCert,
621
+ AllowOrigins: p.conf.HLSAllowOrigins,
622
+ TrustedProxies: p.conf.HLSTrustedProxies,
623
+ AlwaysRemux: p.conf.HLSAlwaysRemux,
624
+ Variant: p.conf.HLSVariant,
625
+ SegmentCount: p.conf.HLSSegmentCount,
626
+ SegmentDuration: p.conf.HLSSegmentDuration,
627
+ PartDuration: p.conf.HLSPartDuration,
628
+ SegmentMaxSize: p.conf.HLSSegmentMaxSize,
629
+ Directory: p.conf.HLSDirectory,
630
+ CDNSecret: p.conf.HLSCDNSecret,
631
+ ReadTimeout: p.conf.ReadTimeout,
632
+ WriteTimeout: p.conf.WriteTimeout,
633
+ MuxerCloseAfter: p.conf.HLSMuxerCloseAfter,
634
+ ExternalCmdPool: p.externalCmdPool,
635
+ Metrics: p.metrics,
636
+ PathManager: p.pathManager,
637
+ Parent: p,
638
+ }
639
+ err = i.Initialize()
640
+ if err != nil {
641
+ return err
642
+ }
643
+ p.hlsServer = i
644
+ }
645
+
646
+ if p.conf.WebRTC &&
647
+ p.webRTCServer == nil {
648
+ i := &webrtc.Server{
649
+ Address: p.conf.WebRTCAddress,
650
+ DumpPackets: p.conf.DumpPackets,
651
+ Encryption: p.conf.WebRTCEncryption,
652
+ ServerKey: p.conf.WebRTCServerKey,
653
+ ServerCert: p.conf.WebRTCServerCert,
654
+ AllowOrigins: p.conf.WebRTCAllowOrigins,
655
+ TrustedProxies: p.conf.WebRTCTrustedProxies,
656
+ ReadTimeout: p.conf.ReadTimeout,
657
+ WriteTimeout: p.conf.WriteTimeout,
658
+ UDPReadBufferSize: p.conf.UDPReadBufferSize,
659
+ LocalUDPAddress: p.conf.WebRTCLocalUDPAddress,
660
+ LocalTCPAddress: p.conf.WebRTCLocalTCPAddress,
661
+ IPsFromInterfaces: p.conf.WebRTCIPsFromInterfaces,
662
+ IPsFromInterfacesList: p.conf.WebRTCIPsFromInterfacesList,
663
+ AdditionalHosts: p.conf.WebRTCAdditionalHosts,
664
+ ICEServers: p.conf.WebRTCICEServers2,
665
+ STUNGatherTimeout: p.conf.WebRTCSTUNGatherTimeout,
666
+ HandshakeTimeout: p.conf.WebRTCHandshakeTimeout,
667
+ TrackGatherTimeout: p.conf.WebRTCTrackGatherTimeout,
668
+ ExternalCmdPool: p.externalCmdPool,
669
+ Metrics: p.metrics,
670
+ PathManager: p.pathManager,
671
+ Parent: p,
672
+ }
673
+ err = i.Initialize()
674
+ if err != nil {
675
+ return err
676
+ }
677
+ p.webRTCServer = i
678
+ }
679
+
680
+ if p.conf.SRT &&
681
+ p.srtServer == nil {
682
+ i := &srt.Server{
683
+ Address: p.conf.SRTAddress,
684
+ RTSPAddress: p.conf.RTSPAddress,
685
+ ReadTimeout: p.conf.ReadTimeout,
686
+ WriteTimeout: p.conf.WriteTimeout,
687
+ UDPMaxPayloadSize: p.conf.UDPMaxPayloadSize,
688
+ RunOnConnect: p.conf.RunOnConnect,
689
+ RunOnConnectRestart: p.conf.RunOnConnectRestart,
690
+ RunOnDisconnect: p.conf.RunOnDisconnect,
691
+ ExternalCmdPool: p.externalCmdPool,
692
+ Metrics: p.metrics,
693
+ PathManager: p.pathManager,
694
+ Parent: p,
695
+ }
696
+ err = i.Initialize()
697
+ if err != nil {
698
+ return err
699
+ }
700
+ p.srtServer = i
701
+ }
702
+
703
+ if p.conf.MoQ &&
704
+ p.moqServer == nil {
705
+ i := &moq.Server{
706
+ HTTP2Address: p.conf.MoQHTTP2Address,
707
+ HTTP3Address: p.conf.MoQHTTP3Address,
708
+ ServerKey: p.conf.MoQServerKey,
709
+ ServerCert: p.conf.MoQServerCert,
710
+ AllowOrigins: p.conf.MoQAllowOrigins,
711
+ TrustedProxies: p.conf.MoQTrustedProxies,
712
+ UDPReadBufferSize: p.conf.UDPReadBufferSize,
713
+ ReadTimeout: p.conf.ReadTimeout,
714
+ WriteTimeout: p.conf.WriteTimeout,
715
+ PathManager: p.pathManager,
716
+ Metrics: p.metrics,
717
+ Parent: p,
718
+ }
719
+ err = i.Initialize()
720
+ if err != nil {
721
+ return err
722
+ }
723
+ p.moqServer = i
724
+ }
725
+
726
+ if p.conf.API &&
727
+ p.api == nil {
728
+ i := &api.API{
729
+ Version: string(version),
730
+ Started: started,
731
+ Address: p.conf.APIAddress,
732
+ DumpPackets: p.conf.DumpPackets,
733
+ Encryption: p.conf.APIEncryption,
734
+ ServerKey: p.conf.APIServerKey,
735
+ ServerCert: p.conf.APIServerCert,
736
+ AllowOrigins: p.conf.APIAllowOrigins,
737
+ TrustedProxies: p.conf.APITrustedProxies,
738
+ ReadTimeout: p.conf.ReadTimeout,
739
+ WriteTimeout: p.conf.WriteTimeout,
740
+ Conf: p.conf,
741
+ AuthManager: p.authManager,
742
+ PathManager: p.pathManager,
743
+ RTSPServer: p.rtspServer,
744
+ RTSPSServer: p.rtspsServer,
745
+ RTMPServer: p.rtmpServer,
746
+ RTMPSServer: p.rtmpsServer,
747
+ HLSServer: p.hlsServer,
748
+ WebRTCServer: p.webRTCServer,
749
+ SRTServer: p.srtServer,
750
+ MoQServer: p.moqServer,
751
+ Parent: p,
752
+ }
753
+ err = i.Initialize()
754
+ if err != nil {
755
+ return err
756
+ }
757
+ p.api = i
758
+ }
759
+
760
+ if initial && p.confPath != "" {
761
+ cf := &confwatcher.ConfWatcher{FilePath: p.confPath}
762
+ err = cf.Initialize()
763
+ if err != nil {
764
+ return err
765
+ }
766
+ p.confWatcher = cf
767
+ }
768
+
769
+ return nil
770
+ }
771
+
772
+ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) {
773
+ closeLogger := newConf == nil ||
774
+ newConf.LogLevel != p.conf.LogLevel ||
775
+ !reflect.DeepEqual(newConf.LogDestinations, p.conf.LogDestinations) ||
776
+ newConf.LogFile != p.conf.LogFile ||
777
+ newConf.SysLogPrefix != p.conf.SysLogPrefix ||
778
+ newConf.LogStructured != p.conf.LogStructured
779
+
780
+ closeAuthManager := newConf == nil ||
781
+ newConf.AuthMethod != p.conf.AuthMethod ||
782
+ newConf.AuthHTTPAddress != p.conf.AuthHTTPAddress ||
783
+ newConf.AuthHTTPFingerprint != p.conf.AuthHTTPFingerprint ||
784
+ !reflect.DeepEqual(newConf.AuthHTTPExclude, p.conf.AuthHTTPExclude) ||
785
+ newConf.AuthJWTJWKS != p.conf.AuthJWTJWKS ||
786
+ newConf.AuthJWTJWKSFingerprint != p.conf.AuthJWTJWKSFingerprint ||
787
+ newConf.AuthJWTClaimKey != p.conf.AuthJWTClaimKey ||
788
+ !reflect.DeepEqual(newConf.AuthJWTExclude, p.conf.AuthJWTExclude) ||
789
+ !reflect.DeepEqual(newConf.AuthJWTInHTTPQuery, p.conf.AuthJWTInHTTPQuery) ||
790
+ newConf.AuthJWTIssuer != p.conf.AuthJWTIssuer ||
791
+ newConf.AuthJWTAudience != p.conf.AuthJWTAudience ||
792
+ newConf.ReadTimeout != p.conf.ReadTimeout
793
+ if !closeAuthManager && !reflect.DeepEqual(newConf.AuthInternalUsers, p.conf.AuthInternalUsers) {
794
+ p.authManager.ReloadInternalUsers(newConf.AuthInternalUsers)
795
+ }
796
+
797
+ closeMetrics := newConf == nil ||
798
+ newConf.Metrics != p.conf.Metrics ||
799
+ newConf.MetricsAddress != p.conf.MetricsAddress ||
800
+ newConf.MetricsEncryption != p.conf.MetricsEncryption ||
801
+ newConf.MetricsServerKey != p.conf.MetricsServerKey ||
802
+ newConf.MetricsServerCert != p.conf.MetricsServerCert ||
803
+ !slices.Equal(newConf.MetricsAllowOrigins, p.conf.MetricsAllowOrigins) ||
804
+ !reflect.DeepEqual(newConf.MetricsTrustedProxies, p.conf.MetricsTrustedProxies) ||
805
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
806
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
807
+ newConf.DumpPackets != p.conf.DumpPackets ||
808
+ closeAuthManager ||
809
+ closeLogger
810
+
811
+ closePPROF := newConf == nil ||
812
+ newConf.PPROF != p.conf.PPROF ||
813
+ newConf.PPROFAddress != p.conf.PPROFAddress ||
814
+ newConf.PPROFEncryption != p.conf.PPROFEncryption ||
815
+ newConf.PPROFServerKey != p.conf.PPROFServerKey ||
816
+ newConf.PPROFServerCert != p.conf.PPROFServerCert ||
817
+ !slices.Equal(newConf.PPROFAllowOrigins, p.conf.PPROFAllowOrigins) ||
818
+ !reflect.DeepEqual(newConf.PPROFTrustedProxies, p.conf.PPROFTrustedProxies) ||
819
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
820
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
821
+ newConf.DumpPackets != p.conf.DumpPackets ||
822
+ closeAuthManager ||
823
+ closeLogger
824
+
825
+ closeRecorderCleaner := newConf == nil ||
826
+ atLeastOneRecordDeleteAfter(newConf.Paths) != atLeastOneRecordDeleteAfter(p.conf.Paths) ||
827
+ closeLogger
828
+ if !closeRecorderCleaner && p.recordCleaner != nil && !reflect.DeepEqual(newConf.Paths, p.conf.Paths) {
829
+ p.recordCleaner.ReloadPathConfs(newConf.Paths)
830
+ }
831
+
832
+ closePlaybackServer := newConf == nil ||
833
+ newConf.Playback != p.conf.Playback ||
834
+ newConf.PlaybackAddress != p.conf.PlaybackAddress ||
835
+ newConf.PlaybackEncryption != p.conf.PlaybackEncryption ||
836
+ newConf.PlaybackServerKey != p.conf.PlaybackServerKey ||
837
+ newConf.PlaybackServerCert != p.conf.PlaybackServerCert ||
838
+ !slices.Equal(newConf.PlaybackAllowOrigins, p.conf.PlaybackAllowOrigins) ||
839
+ !reflect.DeepEqual(newConf.PlaybackTrustedProxies, p.conf.PlaybackTrustedProxies) ||
840
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
841
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
842
+ newConf.DumpPackets != p.conf.DumpPackets ||
843
+ closeAuthManager ||
844
+ closeLogger
845
+ if !closePlaybackServer && p.playbackServer != nil && !reflect.DeepEqual(newConf.Paths, p.conf.Paths) {
846
+ p.playbackServer.ReloadPathConfs(newConf.Paths)
847
+ }
848
+
849
+ closePathManager := newConf == nil ||
850
+ newConf.LogLevel != p.conf.LogLevel ||
851
+ newConf.DumpPackets != p.conf.DumpPackets ||
852
+ newConf.RTSPAddress != p.conf.RTSPAddress ||
853
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
854
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
855
+ newConf.WriteQueueSize != p.conf.WriteQueueSize ||
856
+ newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize ||
857
+ newConf.UDPMaxPayloadSize != p.conf.UDPMaxPayloadSize ||
858
+ newConf.RTSPEncryption != p.conf.RTSPEncryption ||
859
+ closeMetrics ||
860
+ closeAuthManager ||
861
+ closeLogger
862
+ if !closePathManager && !reflect.DeepEqual(newConf.Paths, p.conf.Paths) {
863
+ p.pathManager.ReloadPathConfs(newConf.Paths)
864
+ }
865
+
866
+ closeRTSPServer := newConf == nil ||
867
+ newConf.RTSP != p.conf.RTSP ||
868
+ newConf.RTSPEncryption != p.conf.RTSPEncryption ||
869
+ newConf.RTSPAddress != p.conf.RTSPAddress ||
870
+ !reflect.DeepEqual(newConf.RTSPAuthMethods, p.conf.RTSPAuthMethods) ||
871
+ newConf.RTSPUDPReadBufferSize != p.conf.RTSPUDPReadBufferSize ||
872
+ newConf.DumpPackets != p.conf.DumpPackets ||
873
+ newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize ||
874
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
875
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
876
+ newConf.WriteQueueSize != p.conf.WriteQueueSize ||
877
+ newConf.RTPAddress != p.conf.RTPAddress ||
878
+ newConf.RTCPAddress != p.conf.RTCPAddress ||
879
+ newConf.MulticastIPRange != p.conf.MulticastIPRange ||
880
+ newConf.MulticastRTPPort != p.conf.MulticastRTPPort ||
881
+ newConf.MulticastRTCPPort != p.conf.MulticastRTCPPort ||
882
+ !reflect.DeepEqual(newConf.RTSPTransports, p.conf.RTSPTransports) ||
883
+ !reflect.DeepEqual(newConf.RTSPTrustedProxies, p.conf.RTSPTrustedProxies) ||
884
+ newConf.RunOnConnect != p.conf.RunOnConnect ||
885
+ newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart ||
886
+ newConf.RunOnDisconnect != p.conf.RunOnDisconnect ||
887
+ closeMetrics ||
888
+ closePathManager ||
889
+ closeLogger
890
+
891
+ closeRTSPSServer := newConf == nil ||
892
+ newConf.RTSP != p.conf.RTSP ||
893
+ newConf.RTSPEncryption != p.conf.RTSPEncryption ||
894
+ newConf.RTSPSAddress != p.conf.RTSPSAddress ||
895
+ !reflect.DeepEqual(newConf.RTSPAuthMethods, p.conf.RTSPAuthMethods) ||
896
+ newConf.RTSPUDPReadBufferSize != p.conf.RTSPUDPReadBufferSize ||
897
+ newConf.DumpPackets != p.conf.DumpPackets ||
898
+ newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize ||
899
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
900
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
901
+ newConf.WriteQueueSize != p.conf.WriteQueueSize ||
902
+ newConf.RTSPServerCert != p.conf.RTSPServerCert ||
903
+ newConf.RTSPServerKey != p.conf.RTSPServerKey ||
904
+ newConf.RTSPAddress != p.conf.RTSPAddress ||
905
+ !reflect.DeepEqual(newConf.RTSPTransports, p.conf.RTSPTransports) ||
906
+ !reflect.DeepEqual(newConf.RTSPTrustedProxies, p.conf.RTSPTrustedProxies) ||
907
+ newConf.RunOnConnect != p.conf.RunOnConnect ||
908
+ newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart ||
909
+ newConf.RunOnDisconnect != p.conf.RunOnDisconnect ||
910
+ closeMetrics ||
911
+ closePathManager ||
912
+ closeLogger
913
+
914
+ closeRTMPServer := newConf == nil ||
915
+ newConf.RTMP != p.conf.RTMP ||
916
+ newConf.RTMPEncryption != p.conf.RTMPEncryption ||
917
+ newConf.RTMPAddress != p.conf.RTMPAddress ||
918
+ newConf.DumpPackets != p.conf.DumpPackets ||
919
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
920
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
921
+ newConf.RTSPAddress != p.conf.RTSPAddress ||
922
+ !reflect.DeepEqual(newConf.RTMPTrustedProxies, p.conf.RTMPTrustedProxies) ||
923
+ newConf.RunOnConnect != p.conf.RunOnConnect ||
924
+ newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart ||
925
+ newConf.RunOnDisconnect != p.conf.RunOnDisconnect ||
926
+ closeMetrics ||
927
+ closePathManager ||
928
+ closeLogger
929
+
930
+ closeRTMPSServer := newConf == nil ||
931
+ newConf.RTMP != p.conf.RTMP ||
932
+ newConf.RTMPEncryption != p.conf.RTMPEncryption ||
933
+ newConf.RTMPSAddress != p.conf.RTMPSAddress ||
934
+ newConf.DumpPackets != p.conf.DumpPackets ||
935
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
936
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
937
+ newConf.RTMPServerCert != p.conf.RTMPServerCert ||
938
+ newConf.RTMPServerKey != p.conf.RTMPServerKey ||
939
+ newConf.RTSPAddress != p.conf.RTSPAddress ||
940
+ !reflect.DeepEqual(newConf.RTMPTrustedProxies, p.conf.RTMPTrustedProxies) ||
941
+ newConf.RunOnConnect != p.conf.RunOnConnect ||
942
+ newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart ||
943
+ newConf.RunOnDisconnect != p.conf.RunOnDisconnect ||
944
+ closeMetrics ||
945
+ closePathManager ||
946
+ closeLogger
947
+
948
+ closeHLSServer := newConf == nil ||
949
+ newConf.HLS != p.conf.HLS ||
950
+ newConf.HLSAddress != p.conf.HLSAddress ||
951
+ newConf.HLSEncryption != p.conf.HLSEncryption ||
952
+ newConf.HLSServerKey != p.conf.HLSServerKey ||
953
+ newConf.HLSServerCert != p.conf.HLSServerCert ||
954
+ !slices.Equal(newConf.HLSAllowOrigins, p.conf.HLSAllowOrigins) ||
955
+ !reflect.DeepEqual(newConf.HLSTrustedProxies, p.conf.HLSTrustedProxies) ||
956
+ newConf.HLSAlwaysRemux != p.conf.HLSAlwaysRemux ||
957
+ newConf.HLSVariant != p.conf.HLSVariant ||
958
+ newConf.HLSSegmentCount != p.conf.HLSSegmentCount ||
959
+ newConf.HLSSegmentDuration != p.conf.HLSSegmentDuration ||
960
+ newConf.HLSPartDuration != p.conf.HLSPartDuration ||
961
+ newConf.HLSSegmentMaxSize != p.conf.HLSSegmentMaxSize ||
962
+ newConf.HLSDirectory != p.conf.HLSDirectory ||
963
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
964
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
965
+ newConf.HLSMuxerCloseAfter != p.conf.HLSMuxerCloseAfter ||
966
+ newConf.HLSCDNSecret != p.conf.HLSCDNSecret ||
967
+ newConf.DumpPackets != p.conf.DumpPackets ||
968
+ closePathManager ||
969
+ closeMetrics ||
970
+ closeLogger
971
+
972
+ closeWebRTCServer := newConf == nil ||
973
+ newConf.WebRTC != p.conf.WebRTC ||
974
+ newConf.WebRTCAddress != p.conf.WebRTCAddress ||
975
+ newConf.WebRTCEncryption != p.conf.WebRTCEncryption ||
976
+ newConf.WebRTCServerKey != p.conf.WebRTCServerKey ||
977
+ newConf.WebRTCServerCert != p.conf.WebRTCServerCert ||
978
+ !slices.Equal(newConf.WebRTCAllowOrigins, p.conf.WebRTCAllowOrigins) ||
979
+ !reflect.DeepEqual(newConf.WebRTCTrustedProxies, p.conf.WebRTCTrustedProxies) ||
980
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
981
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
982
+ newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize ||
983
+ newConf.WebRTCLocalUDPAddress != p.conf.WebRTCLocalUDPAddress ||
984
+ newConf.WebRTCLocalTCPAddress != p.conf.WebRTCLocalTCPAddress ||
985
+ newConf.WebRTCIPsFromInterfaces != p.conf.WebRTCIPsFromInterfaces ||
986
+ !reflect.DeepEqual(newConf.WebRTCIPsFromInterfacesList, p.conf.WebRTCIPsFromInterfacesList) ||
987
+ !reflect.DeepEqual(newConf.WebRTCAdditionalHosts, p.conf.WebRTCAdditionalHosts) ||
988
+ !reflect.DeepEqual(newConf.WebRTCICEServers2, p.conf.WebRTCICEServers2) ||
989
+ newConf.WebRTCSTUNGatherTimeout != p.conf.WebRTCSTUNGatherTimeout ||
990
+ newConf.WebRTCHandshakeTimeout != p.conf.WebRTCHandshakeTimeout ||
991
+ newConf.WebRTCTrackGatherTimeout != p.conf.WebRTCTrackGatherTimeout ||
992
+ newConf.DumpPackets != p.conf.DumpPackets ||
993
+ closeMetrics ||
994
+ closePathManager ||
995
+ closeLogger
996
+
997
+ closeSRTServer := newConf == nil ||
998
+ newConf.SRT != p.conf.SRT ||
999
+ newConf.SRTAddress != p.conf.SRTAddress ||
1000
+ newConf.RTSPAddress != p.conf.RTSPAddress ||
1001
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
1002
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
1003
+ newConf.UDPMaxPayloadSize != p.conf.UDPMaxPayloadSize ||
1004
+ newConf.RunOnConnect != p.conf.RunOnConnect ||
1005
+ newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart ||
1006
+ newConf.RunOnDisconnect != p.conf.RunOnDisconnect ||
1007
+ closeMetrics ||
1008
+ closePathManager ||
1009
+ closeLogger
1010
+
1011
+ closeMoQServer := newConf == nil ||
1012
+ newConf.MoQ != p.conf.MoQ ||
1013
+ newConf.MoQHTTP2Address != p.conf.MoQHTTP2Address ||
1014
+ newConf.MoQHTTP3Address != p.conf.MoQHTTP3Address ||
1015
+ newConf.MoQServerKey != p.conf.MoQServerKey ||
1016
+ newConf.MoQServerCert != p.conf.MoQServerCert ||
1017
+ !slices.Equal(newConf.MoQAllowOrigins, p.conf.MoQAllowOrigins) ||
1018
+ !reflect.DeepEqual(newConf.MoQTrustedProxies, p.conf.MoQTrustedProxies) ||
1019
+ newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize ||
1020
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
1021
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
1022
+ closeMetrics ||
1023
+ closePathManager ||
1024
+ closeLogger
1025
+
1026
+ closeAPI := newConf == nil ||
1027
+ newConf.API != p.conf.API ||
1028
+ newConf.APIAddress != p.conf.APIAddress ||
1029
+ newConf.APIEncryption != p.conf.APIEncryption ||
1030
+ newConf.APIServerKey != p.conf.APIServerKey ||
1031
+ newConf.APIServerCert != p.conf.APIServerCert ||
1032
+ !slices.Equal(newConf.APIAllowOrigins, p.conf.APIAllowOrigins) ||
1033
+ !reflect.DeepEqual(newConf.APITrustedProxies, p.conf.APITrustedProxies) ||
1034
+ newConf.ReadTimeout != p.conf.ReadTimeout ||
1035
+ newConf.WriteTimeout != p.conf.WriteTimeout ||
1036
+ newConf.DumpPackets != p.conf.DumpPackets ||
1037
+ closeAuthManager ||
1038
+ closePathManager ||
1039
+ closeRTSPServer ||
1040
+ closeRTSPSServer ||
1041
+ closeRTMPServer ||
1042
+ closeRTMPSServer ||
1043
+ closeHLSServer ||
1044
+ closeWebRTCServer ||
1045
+ closeSRTServer ||
1046
+ closeMoQServer ||
1047
+ closeLogger
1048
+
1049
+ if newConf == nil && p.confWatcher != nil {
1050
+ p.confWatcher.Close()
1051
+ p.confWatcher = nil
1052
+ }
1053
+
1054
+ if p.api != nil {
1055
+ if closeAPI {
1056
+ p.api.Close()
1057
+ p.api = nil
1058
+ } else if !calledByAPI { // avoid a loop
1059
+ p.api.ReloadConf(newConf)
1060
+ }
1061
+ }
1062
+
1063
+ if closeSRTServer && p.srtServer != nil {
1064
+ p.srtServer.Close()
1065
+ p.srtServer = nil
1066
+ }
1067
+
1068
+ if closeMoQServer && p.moqServer != nil {
1069
+ p.moqServer.Close()
1070
+ p.moqServer = nil
1071
+ }
1072
+
1073
+ if closeWebRTCServer && p.webRTCServer != nil {
1074
+ p.webRTCServer.Close()
1075
+ p.webRTCServer = nil
1076
+ }
1077
+
1078
+ if closeHLSServer && p.hlsServer != nil {
1079
+ p.hlsServer.Close()
1080
+ p.hlsServer = nil
1081
+ }
1082
+
1083
+ if closeRTMPSServer && p.rtmpsServer != nil {
1084
+ p.rtmpsServer.Close()
1085
+ p.rtmpsServer = nil
1086
+ }
1087
+
1088
+ if closeRTMPServer && p.rtmpServer != nil {
1089
+ p.rtmpServer.Close()
1090
+ p.rtmpServer = nil
1091
+ }
1092
+
1093
+ if closeRTSPSServer && p.rtspsServer != nil {
1094
+ p.rtspsServer.Close()
1095
+ p.rtspsServer = nil
1096
+ }
1097
+
1098
+ if closeRTSPServer && p.rtspServer != nil {
1099
+ p.rtspServer.Close()
1100
+ p.rtspServer = nil
1101
+ }
1102
+
1103
+ if closePathManager && p.pathManager != nil {
1104
+ p.pathManager.close()
1105
+ p.pathManager = nil
1106
+ }
1107
+
1108
+ if closePlaybackServer && p.playbackServer != nil {
1109
+ p.playbackServer.Close()
1110
+ p.playbackServer = nil
1111
+ }
1112
+
1113
+ if closeRecorderCleaner && p.recordCleaner != nil {
1114
+ p.recordCleaner.Close()
1115
+ p.recordCleaner = nil
1116
+ }
1117
+
1118
+ if closePPROF && p.pprof != nil {
1119
+ p.pprof.Close()
1120
+ p.pprof = nil
1121
+ }
1122
+
1123
+ if closeMetrics && p.metrics != nil {
1124
+ p.metrics.Close()
1125
+ p.metrics = nil
1126
+ }
1127
+
1128
+ if closeAuthManager && p.authManager != nil {
1129
+ p.authManager = nil
1130
+ }
1131
+
1132
+ if newConf == nil && p.externalCmdPool != nil {
1133
+ p.Log(logger.Info, "waiting for running hooks")
1134
+ p.externalCmdPool.Close()
1135
+ }
1136
+
1137
+ if closeLogger && p.logger != nil {
1138
+ if newConf == nil {
1139
+ p.logger.Close()
1140
+ }
1141
+ p.logger = nil
1142
+ }
1143
+ }
1144
+
1145
+ func (p *Core) reloadConf(newConf *conf.Conf, calledByAPI bool) error {
1146
+ oldLogger := p.logger
1147
+
1148
+ p.closeResources(newConf, calledByAPI)
1149
+
1150
+ p.conf = newConf
1151
+
1152
+ err := p.createResources(false)
1153
+ if err != nil {
1154
+ p.logger = oldLogger
1155
+ return err
1156
+ }
1157
+
1158
+ if p.logger != oldLogger {
1159
+ oldLogger.Close()
1160
+ }
1161
+
1162
+ return nil
1163
+ }
1164
+
1165
+ // APIConfigSet implements apiParent.
1166
+ func (p *Core) APIConfigSet(conf *conf.Conf) {
1167
+ select {
1168
+ case p.chAPIConfigSet <- conf:
1169
+ case <-p.ctx.Done():
1170
+ }
1171
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core_test.go ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "os"
5
+ "path/filepath"
6
+ "testing"
7
+ "time"
8
+
9
+ "github.com/bluenviron/gortsplib/v5"
10
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
11
+ "github.com/bluenviron/mediamtx/internal/test"
12
+ "github.com/stretchr/testify/require"
13
+ )
14
+
15
+ func newInstance(t *testing.T, conf string) (*Core, bool) {
16
+ if conf == "" {
17
+ return New([]string{})
18
+ }
19
+
20
+ tmpf := test.CreateTempFile(t, []byte(conf))
21
+
22
+ return New([]string{tmpf})
23
+ }
24
+
25
+ func TestCoreErrors(t *testing.T) {
26
+ for _, ca := range []struct {
27
+ name string
28
+ conf string
29
+ }{
30
+ {
31
+ "logger",
32
+ "logDestinations: [file]\n" +
33
+ "logFile: /nonexisting/nonexist\n" +
34
+ "sysLogPrefix: /mediamtx\n",
35
+ },
36
+ {
37
+ "metrics",
38
+ "metrics: yes\n" +
39
+ "metricsAddress: invalid\n",
40
+ },
41
+ {
42
+ "pprof",
43
+ "pprof: yes\n" +
44
+ "pprofAddress: invalid\n",
45
+ },
46
+ {
47
+ "playback",
48
+ "playback: yes\n" +
49
+ "playbackAddress: invalid\n",
50
+ },
51
+ {
52
+ "rtsp",
53
+ "rtspAddress: invalid\n",
54
+ },
55
+ {
56
+ "rtsps",
57
+ "rtspEncryption: strict\n" +
58
+ "rtspAddress: invalid\n",
59
+ },
60
+ {
61
+ "rtmp",
62
+ "rtmpAddress: invalid\n",
63
+ },
64
+ {
65
+ "rtmps",
66
+ "rtmpEncryption: strict\n" +
67
+ "rtmpAddress: invalid\n",
68
+ },
69
+ {
70
+ "hls",
71
+ "hlsAddress: invalid\n",
72
+ },
73
+ {
74
+ "webrtc",
75
+ "webrtcAddress: invalid\n",
76
+ },
77
+ {
78
+ "srt",
79
+ "srtAddress: invalid\n",
80
+ },
81
+ {
82
+ "api",
83
+ "api: yes\n" +
84
+ "apiAddress: invalid\n",
85
+ },
86
+ } {
87
+ t.Run(ca.name, func(t *testing.T) {
88
+ _, ok := newInstance(t, ca.conf)
89
+ require.Equal(t, false, ok)
90
+ })
91
+ }
92
+ }
93
+
94
+ func TestCoreHotReloading(t *testing.T) {
95
+ confPath := filepath.Join(t.TempDir(), "rtsp-conf")
96
+
97
+ err := os.WriteFile(confPath, []byte("paths:\n"+
98
+ " test1:\n"+
99
+ " publishUser: myuser\n"+
100
+ " publishPass: mypass\n"),
101
+ 0o644)
102
+ require.NoError(t, err)
103
+
104
+ p, ok := New([]string{confPath})
105
+ require.Equal(t, true, ok)
106
+ defer p.Close()
107
+
108
+ func() {
109
+ c := gortsplib.Client{}
110
+ err = c.StartRecording("rtsp://localhost:8554/test1",
111
+ &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
112
+ require.EqualError(t, err, "bad status code: 401 (Unauthorized)")
113
+ }()
114
+
115
+ err = os.WriteFile(confPath, []byte("paths:\n"+
116
+ " test1:\n"),
117
+ 0o644)
118
+ require.NoError(t, err)
119
+
120
+ time.Sleep(1 * time.Second)
121
+
122
+ func() {
123
+ conn := gortsplib.Client{}
124
+ err = conn.StartRecording("rtsp://localhost:8554/test1",
125
+ &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
126
+ require.NoError(t, err)
127
+ defer conn.Close()
128
+ }()
129
+ }
130
+
131
+ func TestCoreHotReloadingAndLoggerError(t *testing.T) {
132
+ confPath := filepath.Join(t.TempDir(), "rtsp-conf")
133
+
134
+ err := os.WriteFile(confPath, []byte(""),
135
+ 0o644)
136
+ require.NoError(t, err)
137
+
138
+ p, ok := New([]string{confPath})
139
+ require.Equal(t, true, ok)
140
+ defer p.Close()
141
+
142
+ err = os.WriteFile(confPath, []byte("logDestinations: [file]\n"+
143
+ "logFile: /nonexisting/nonexist\n"),
144
+ 0o644)
145
+ require.NoError(t, err)
146
+
147
+ p.Wait()
148
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/metrics_test.go ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "bufio"
5
+ "context"
6
+ "crypto/tls"
7
+ "io"
8
+ "net/http"
9
+ "net/url"
10
+ "sync"
11
+ "testing"
12
+ "time"
13
+
14
+ "github.com/bluenviron/gortmplib"
15
+ rtmpcodecs "github.com/bluenviron/gortmplib/pkg/codecs"
16
+ "github.com/bluenviron/gortsplib/v5"
17
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
18
+ "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts"
19
+ tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs"
20
+ srt "github.com/datarhei/gosrt"
21
+ "github.com/pion/rtp"
22
+ pwebrtc "github.com/pion/webrtc/v4"
23
+ "github.com/stretchr/testify/require"
24
+
25
+ "github.com/bluenviron/mediamtx/internal/protocols/webrtc"
26
+ "github.com/bluenviron/mediamtx/internal/protocols/whip"
27
+ "github.com/bluenviron/mediamtx/internal/test"
28
+ )
29
+
30
+ func httpPullFile(t *testing.T, hc *http.Client, u string) []byte {
31
+ res, err := hc.Get(u)
32
+ require.NoError(t, err)
33
+ defer res.Body.Close()
34
+
35
+ if res.StatusCode != http.StatusOK {
36
+ t.Errorf("bad status code: %v", res.StatusCode)
37
+ }
38
+
39
+ byts, err := io.ReadAll(res.Body)
40
+ require.NoError(t, err)
41
+
42
+ return byts
43
+ }
44
+
45
+ func TestMetrics(t *testing.T) {
46
+ serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
47
+ serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
48
+
49
+ p, ok := newInstance(t, "api: yes\n"+
50
+ "hlsAlwaysRemux: yes\n"+
51
+ "metrics: yes\n"+
52
+ "webrtcServerCert: "+serverCertFpath+"\n"+
53
+ "webrtcServerKey: "+serverKeyFpath+"\n"+
54
+ "rtspEncryption: optional\n"+
55
+ "rtspServerCert: "+serverCertFpath+"\n"+
56
+ "rtspServerKey: "+serverKeyFpath+"\n"+
57
+ "rtmpEncryption: optional\n"+
58
+ "rtmpServerCert: "+serverCertFpath+"\n"+
59
+ "rtmpServerKey: "+serverKeyFpath+"\n"+
60
+ "paths:\n"+
61
+ " all_others:\n")
62
+ require.Equal(t, true, ok)
63
+ defer p.Close()
64
+
65
+ tr := &http.Transport{}
66
+ defer tr.CloseIdleConnections()
67
+ hc := &http.Client{Transport: tr}
68
+
69
+ t.Run("initial", func(t *testing.T) {
70
+ bo := httpPullFile(t, hc, "http://localhost:9998/metrics")
71
+
72
+ require.Equal(t, `# Paths
73
+ paths 0
74
+ paths_inbound_bytes 0
75
+ paths_outbound_bytes 0
76
+ paths_inbound_frames_in_error 0
77
+
78
+ # Paths (deprecated)
79
+ paths_bytes_received 0
80
+ paths_bytes_sent 0
81
+ paths_readers 0
82
+
83
+ # HLS sessions
84
+ hls_sessions 0
85
+ hls_sessions_outbound_bytes 0
86
+
87
+ # HLS muxers
88
+ hls_muxers 0
89
+ hls_muxers_outbound_bytes 0
90
+ hls_muxers_outbound_frames_discarded 0
91
+
92
+ # HLS muxers (deprecated)
93
+ hls_muxers_bytes_sent 0
94
+
95
+ # RTSP connections
96
+ rtsp_conns 0
97
+ rtsp_conns_inbound_bytes 0
98
+ rtsp_conns_outbound_bytes 0
99
+
100
+ # RTSP connections (deprecated)
101
+ rtsp_conns_bytes_received 0
102
+ rtsp_conns_bytes_sent 0
103
+
104
+ # RTSP sessions
105
+ rtsp_sessions 0
106
+ rtsp_sessions_inbound_bytes 0
107
+ rtsp_sessions_inbound_rtp_packets 0
108
+ rtsp_sessions_inbound_rtp_packets_lost 0
109
+ rtsp_sessions_inbound_rtp_packets_in_error 0
110
+ rtsp_sessions_inbound_rtp_packets_jitter 0
111
+ rtsp_sessions_inbound_rtcp_packets 0
112
+ rtsp_sessions_inbound_rtcp_packets_in_error 0
113
+ rtsp_sessions_outbound_bytes 0
114
+ rtsp_sessions_outbound_rtp_packets 0
115
+ rtsp_sessions_outbound_rtp_packets_reported_lost 0
116
+ rtsp_sessions_outbound_rtp_packets_discarded 0
117
+ rtsp_sessions_outbound_rtcp_packets 0
118
+
119
+ # RTSP sessions (deprecated)
120
+ rtsp_sessions_bytes_received 0
121
+ rtsp_sessions_bytes_sent 0
122
+ rtsp_sessions_rtp_packets_received 0
123
+ rtsp_sessions_rtp_packets_sent 0
124
+ rtsp_sessions_rtp_packets_lost 0
125
+ rtsp_sessions_rtp_packets_in_error 0
126
+ rtsp_sessions_rtp_packets_jitter 0
127
+ rtsp_sessions_rtcp_packets_received 0
128
+ rtsp_sessions_rtcp_packets_sent 0
129
+ rtsp_sessions_rtcp_packets_in_error 0
130
+
131
+ # RTSPS connections
132
+ rtsps_conns 0
133
+ rtsps_conns_inbound_bytes 0
134
+ rtsps_conns_outbound_bytes 0
135
+
136
+ # RTSPS connections (deprecated)
137
+ rtsps_conns_bytes_received 0
138
+ rtsps_conns_bytes_sent 0
139
+
140
+ # RTSPS sessions
141
+ rtsps_sessions 0
142
+ rtsps_sessions_inbound_bytes 0
143
+ rtsps_sessions_inbound_rtp_packets 0
144
+ rtsps_sessions_inbound_rtp_packets_lost 0
145
+ rtsps_sessions_inbound_rtp_packets_in_error 0
146
+ rtsps_sessions_inbound_rtp_packets_jitter 0
147
+ rtsps_sessions_inbound_rtcp_packets 0
148
+ rtsps_sessions_inbound_rtcp_packets_in_error 0
149
+ rtsps_sessions_outbound_bytes 0
150
+ rtsps_sessions_outbound_rtp_packets 0
151
+ rtsps_sessions_outbound_rtp_packets_reported_lost 0
152
+ rtsps_sessions_outbound_rtp_packets_discarded 0
153
+ rtsps_sessions_outbound_rtcp_packets 0
154
+
155
+ # RTSPS sessions (deprecated)
156
+ rtsps_sessions_bytes_received 0
157
+ rtsps_sessions_bytes_sent 0
158
+ rtsps_sessions_rtp_packets_received 0
159
+ rtsps_sessions_rtp_packets_sent 0
160
+ rtsps_sessions_rtp_packets_lost 0
161
+ rtsps_sessions_rtp_packets_in_error 0
162
+ rtsps_sessions_rtp_packets_jitter 0
163
+ rtsps_sessions_rtcp_packets_received 0
164
+ rtsps_sessions_rtcp_packets_sent 0
165
+ rtsps_sessions_rtcp_packets_in_error 0
166
+
167
+ # RTMP connections
168
+ rtmp_conns 0
169
+ rtmp_conns_inbound_bytes 0
170
+ rtmp_conns_outbound_bytes 0
171
+ rtmp_conns_outbound_frames_discarded 0
172
+
173
+ # RTMP connections (deprecated)
174
+ rtmp_conns_bytes_received 0
175
+ rtmp_conns_bytes_sent 0
176
+
177
+ # RTMPS connections
178
+ rtmps_conns 0
179
+ rtmps_conns_inbound_bytes 0
180
+ rtmps_conns_outbound_bytes 0
181
+ rtmps_conns_outbound_frames_discarded 0
182
+
183
+ # RTMPS connections (deprecated)
184
+ rtmps_conns_bytes_received 0
185
+ rtmps_conns_bytes_sent 0
186
+
187
+ # SRT connections
188
+ srt_conns 0
189
+ srt_conns_packets_sent 0
190
+ srt_conns_packets_received 0
191
+ srt_conns_packets_sent_unique 0
192
+ srt_conns_packets_received_unique 0
193
+ srt_conns_packets_send_loss 0
194
+ srt_conns_packets_received_loss 0
195
+ srt_conns_packets_retrans 0
196
+ srt_conns_packets_received_retrans 0
197
+ srt_conns_packets_sent_ack 0
198
+ srt_conns_packets_received_ack 0
199
+ srt_conns_packets_sent_nak 0
200
+ srt_conns_packets_received_nak 0
201
+ srt_conns_packets_sent_km 0
202
+ srt_conns_packets_received_km 0
203
+ srt_conns_us_snd_duration 0
204
+ srt_conns_packets_received_belated 0
205
+ srt_conns_packets_send_drop 0
206
+ srt_conns_packets_received_drop 0
207
+ srt_conns_packets_received_undecrypt 0
208
+ srt_conns_bytes_sent 0
209
+ srt_conns_bytes_received 0
210
+ srt_conns_bytes_sent_unique 0
211
+ srt_conns_bytes_received_unique 0
212
+ srt_conns_bytes_received_loss 0
213
+ srt_conns_bytes_retrans 0
214
+ srt_conns_bytes_received_retrans 0
215
+ srt_conns_bytes_received_belated 0
216
+ srt_conns_bytes_send_drop 0
217
+ srt_conns_bytes_received_drop 0
218
+ srt_conns_bytes_received_undecrypt 0
219
+ srt_conns_us_packets_send_period 0
220
+ srt_conns_packets_flow_window 0
221
+ srt_conns_packets_flight_size 0
222
+ srt_conns_ms_rtt 0
223
+ srt_conns_mbps_send_rate 0
224
+ srt_conns_mbps_receive_rate 0
225
+ srt_conns_mbps_link_capacity 0
226
+ srt_conns_bytes_avail_send_buf 0
227
+ srt_conns_bytes_avail_receive_buf 0
228
+ srt_conns_mbps_max_bw 0
229
+ srt_conns_bytes_mss 0
230
+ srt_conns_packets_send_buf 0
231
+ srt_conns_bytes_send_buf 0
232
+ srt_conns_ms_send_buf 0
233
+ srt_conns_ms_send_tsb_pd_delay 0
234
+ srt_conns_packets_receive_buf 0
235
+ srt_conns_bytes_receive_buf 0
236
+ srt_conns_ms_receive_buf 0
237
+ srt_conns_ms_receive_tsb_pd_delay 0
238
+ srt_conns_packets_reorder_tolerance 0
239
+ srt_conns_packets_received_avg_belated_time 0
240
+ srt_conns_packets_send_loss_rate 0
241
+ srt_conns_packets_received_loss_rate 0
242
+ srt_conns_outbound_frames_discarded 0
243
+
244
+ # WebRTC sessions
245
+ webrtc_sessions 0
246
+ webrtc_sessions_inbound_bytes 0
247
+ webrtc_sessions_inbound_rtp_packets 0
248
+ webrtc_sessions_inbound_rtp_packets_lost 0
249
+ webrtc_sessions_inbound_rtp_packets_jitter 0
250
+ webrtc_sessions_inbound_rtcp_packets 0
251
+ webrtc_sessions_outbound_bytes 0
252
+ webrtc_sessions_outbound_rtp_packets 0
253
+ webrtc_sessions_outbound_rtcp_packets 0
254
+ webrtc_sessions_outbound_frames_discarded 0
255
+
256
+ # WebRTC sessions (deprecated)
257
+ webrtc_sessions_bytes_received 0
258
+ webrtc_sessions_bytes_sent 0
259
+ webrtc_sessions_rtp_packets_received 0
260
+ webrtc_sessions_rtp_packets_sent 0
261
+ webrtc_sessions_rtp_packets_lost 0
262
+ webrtc_sessions_rtp_packets_jitter 0
263
+ webrtc_sessions_rtcp_packets_received 0
264
+ webrtc_sessions_rtcp_packets_sent 0
265
+
266
+ # MoQ sessions
267
+ moq_sessions 0
268
+ moq_sessions_inbound_bytes 0
269
+ moq_sessions_outbound_bytes 0
270
+
271
+ `, string(bo))
272
+ })
273
+
274
+ t.Run("with data", func(t *testing.T) {
275
+ terminate := make(chan struct{})
276
+ var wg sync.WaitGroup
277
+ wg.Add(6)
278
+
279
+ go func() {
280
+ defer wg.Done()
281
+ source := gortsplib.Client{}
282
+ err2 := source.StartRecording("rtsp://localhost:8554/rtsp_path",
283
+ &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
284
+ require.NoError(t, err2)
285
+ defer source.Close()
286
+ <-terminate
287
+ }()
288
+
289
+ go func() {
290
+ defer wg.Done()
291
+ source2 := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}}
292
+ err2 := source2.StartRecording("rtsps://localhost:8322/rtsps_path",
293
+ &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
294
+ require.NoError(t, err2)
295
+ defer source2.Close()
296
+ <-terminate
297
+ }()
298
+
299
+ go func() {
300
+ defer wg.Done()
301
+
302
+ u, err2 := url.Parse("rtmp://localhost:1935/rtmp_path")
303
+ require.NoError(t, err2)
304
+
305
+ conn := &gortmplib.Client{
306
+ URL: u,
307
+ Publish: true,
308
+ }
309
+ err2 = conn.Initialize(context.Background())
310
+ require.NoError(t, err2)
311
+ defer conn.Close()
312
+
313
+ track := &gortmplib.Track{
314
+ Codec: &rtmpcodecs.H264{
315
+ SPS: test.FormatH264.SPS,
316
+ PPS: test.FormatH264.PPS,
317
+ },
318
+ }
319
+
320
+ w := &gortmplib.Writer{
321
+ Conn: conn,
322
+ Tracks: []*gortmplib.Track{track},
323
+ }
324
+ err2 = w.Initialize()
325
+ require.NoError(t, err2)
326
+
327
+ err2 = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}})
328
+ require.NoError(t, err2)
329
+
330
+ <-terminate
331
+ }()
332
+
333
+ go func() {
334
+ defer wg.Done()
335
+
336
+ u, err2 := url.Parse("rtmps://localhost:1936/rtmps_path")
337
+ require.NoError(t, err2)
338
+
339
+ conn := &gortmplib.Client{
340
+ URL: u,
341
+ TLSConfig: &tls.Config{InsecureSkipVerify: true},
342
+ Publish: true,
343
+ }
344
+ err2 = conn.Initialize(context.Background())
345
+ require.NoError(t, err2)
346
+ defer conn.Close()
347
+
348
+ track := &gortmplib.Track{
349
+ Codec: &rtmpcodecs.H264{
350
+ SPS: test.FormatH264.SPS,
351
+ PPS: test.FormatH264.PPS,
352
+ },
353
+ }
354
+
355
+ w := &gortmplib.Writer{
356
+ Conn: conn,
357
+ Tracks: []*gortmplib.Track{track},
358
+ }
359
+ err2 = w.Initialize()
360
+ require.NoError(t, err2)
361
+
362
+ err2 = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}})
363
+ require.NoError(t, err2)
364
+
365
+ <-terminate
366
+ }()
367
+
368
+ go func() {
369
+ defer wg.Done()
370
+
371
+ su, err2 := url.Parse("http://localhost:8889/webrtc_path/whip")
372
+ require.NoError(t, err2)
373
+
374
+ tr2 := &http.Transport{}
375
+ defer tr2.CloseIdleConnections()
376
+ hc2 := &http.Client{Transport: tr2}
377
+
378
+ track := &webrtc.OutboundTrack{
379
+ Caps: pwebrtc.RTPCodecCapability{
380
+ MimeType: pwebrtc.MimeTypeH264,
381
+ ClockRate: 90000,
382
+ SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
383
+ },
384
+ }
385
+
386
+ s := &whip.Client{
387
+ HTTPClient: hc2,
388
+ URL: su,
389
+ Log: test.NilLogger,
390
+ Publish: true,
391
+ OutboundTracks: []*webrtc.OutboundTrack{track},
392
+ }
393
+
394
+ err2 = s.Initialize(context.Background())
395
+ require.NoError(t, err2)
396
+ defer checkClose(t, s.Close)
397
+
398
+ err2 = track.WriteRTP(&rtp.Packet{
399
+ Header: rtp.Header{
400
+ Version: 2,
401
+ Marker: true,
402
+ PayloadType: 96,
403
+ SequenceNumber: 123,
404
+ Timestamp: 45343,
405
+ SSRC: 563423,
406
+ },
407
+ Payload: []byte{1},
408
+ })
409
+ require.NoError(t, err2)
410
+ <-terminate
411
+ }()
412
+
413
+ go func() {
414
+ defer wg.Done()
415
+
416
+ srtConf := srt.DefaultConfig()
417
+ address, err2 := srtConf.UnmarshalURL("srt://localhost:8890?streamid=publish:srt_path")
418
+ require.NoError(t, err2)
419
+
420
+ err2 = srtConf.Validate()
421
+ require.NoError(t, err2)
422
+
423
+ publisher, err2 := srt.Dial("srt", address, srtConf)
424
+ require.NoError(t, err2)
425
+ defer publisher.Close()
426
+
427
+ track := &mpegts.Track{
428
+ Codec: &tscodecs.H264{},
429
+ }
430
+
431
+ bw := bufio.NewWriter(publisher)
432
+ w := &mpegts.Writer{W: bw, Tracks: []*mpegts.Track{track}}
433
+ err2 = w.Initialize()
434
+ require.NoError(t, err2)
435
+
436
+ err2 = w.WriteH264(track, 0, 0, [][]byte{
437
+ test.FormatH264.SPS,
438
+ test.FormatH264.PPS,
439
+ {0x05, 1}, // IDR
440
+ })
441
+ require.NoError(t, err2)
442
+
443
+ err2 = bw.Flush()
444
+ require.NoError(t, err2)
445
+ <-terminate
446
+ }()
447
+
448
+ time.Sleep(500*time.Millisecond + 2*time.Second)
449
+
450
+ bo := httpPullFile(t, hc, "http://localhost:9998/metrics")
451
+
452
+ boStr := string(bo)
453
+ require.Contains(t, boStr, "paths{name=\"rtmp_path\",state=\"ready\"} 1\n")
454
+ require.Contains(t, boStr, "paths{name=\"rtmps_path\",state=\"ready\"} 1\n")
455
+ require.Contains(t, boStr, "paths{name=\"rtsp_path\",state=\"ready\"} 1\n")
456
+ require.Contains(t, boStr, "paths{name=\"rtsps_path\",state=\"ready\"} 1\n")
457
+ require.Contains(t, boStr, "paths{name=\"srt_path\",state=\"ready\"} 1\n")
458
+ require.Contains(t, boStr, "paths{name=\"webrtc_path\",state=\"ready\"} 1\n")
459
+ require.Contains(t, boStr, "hls_muxers{name=\"rtmp_path\"} 1\n")
460
+ require.Contains(t, boStr, "hls_muxers{name=\"rtmps_path\"} 1\n")
461
+ require.Contains(t, boStr, "hls_muxers{name=\"rtsp_path\"} 1\n")
462
+ require.Contains(t, boStr, "hls_muxers{name=\"rtsps_path\"} 1\n")
463
+ require.Contains(t, boStr, "hls_muxers{name=\"srt_path\"} 1\n")
464
+ require.Contains(t, boStr, "hls_muxers{name=\"webrtc_path\"} 1\n")
465
+ require.Regexp(t, `(?m)^rtsp_conns\{id=".*?"\} 1$`, boStr)
466
+ require.Regexp(t, `(?m)^rtsp_sessions\{id=".*?",path="rtsp_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
467
+ require.Regexp(t, `(?m)^rtsps_conns\{id=".*?"\} 1$`, boStr)
468
+ require.Regexp(t, `(?m)^rtsps_sessions\{id=".*?",path="rtsps_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
469
+ require.Regexp(t, `(?m)^rtmp_conns\{id=".*?",path="rtmp_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
470
+ require.Regexp(t, `(?m)^rtmps_conns\{id=".*?",path="rtmps_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
471
+ require.Regexp(t, `(?m)^srt_conns\{id=".*?",path="srt_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
472
+ require.Regexp(t, `(?m)^srt_conns_ms_rtt\{id=".*?",path="srt_path",`+
473
+ `remoteAddr=".*?",state="publish"\} [0-9.]+$`, boStr)
474
+ require.Regexp(t, `(?m)^webrtc_sessions\{id=".*?",path="webrtc_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
475
+ require.Regexp(t, `(?m)^webrtc_sessions_rtcp_packets_received\{id=".*?",path="webrtc_path",`+
476
+ `remoteAddr=".*?",state="publish"\} [0-9]+$`, boStr)
477
+
478
+ close(terminate)
479
+ wg.Wait()
480
+ })
481
+
482
+ t.Run("servers disabled", func(t *testing.T) {
483
+ httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/global/patch", map[string]any{
484
+ "rtsp": false,
485
+ "rtmp": false,
486
+ "srt": false,
487
+ "hls": false,
488
+ "webrtc": false,
489
+ }, nil)
490
+
491
+ time.Sleep(500 * time.Millisecond)
492
+
493
+ bo := httpPullFile(t, hc, "http://localhost:9998/metrics")
494
+
495
+ require.Equal(t, "# Paths\n"+
496
+ "paths 0\n"+
497
+ "paths_inbound_bytes 0\n"+
498
+ "paths_outbound_bytes 0\n"+
499
+ "paths_inbound_frames_in_error 0\n"+
500
+ "\n"+
501
+ "# Paths (deprecated)\n"+
502
+ "paths_bytes_received 0\n"+
503
+ "paths_bytes_sent 0\n"+
504
+ "paths_readers 0\n"+
505
+ "\n"+
506
+ "# MoQ sessions\n"+
507
+ "moq_sessions 0\n"+
508
+ "moq_sessions_inbound_bytes 0\n"+
509
+ "moq_sessions_outbound_bytes 0\n"+
510
+ "\n",
511
+ string(bo))
512
+ })
513
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path.go ADDED
@@ -0,0 +1,1116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "context"
5
+ "fmt"
6
+ "net"
7
+ "sort"
8
+ "strconv"
9
+ "sync"
10
+ "sync/atomic"
11
+ "time"
12
+
13
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
14
+
15
+ "github.com/bluenviron/mediamtx/internal/conf"
16
+ "github.com/bluenviron/mediamtx/internal/defs"
17
+ "github.com/bluenviron/mediamtx/internal/externalcmd"
18
+ "github.com/bluenviron/mediamtx/internal/formatlabel"
19
+ "github.com/bluenviron/mediamtx/internal/hooks"
20
+ "github.com/bluenviron/mediamtx/internal/logger"
21
+ "github.com/bluenviron/mediamtx/internal/recorder"
22
+ "github.com/bluenviron/mediamtx/internal/staticsources"
23
+ "github.com/bluenviron/mediamtx/internal/stream"
24
+ )
25
+
26
+ func emptyTimer() *time.Timer {
27
+ t := time.NewTimer(0)
28
+ <-t.C
29
+ return t
30
+ }
31
+
32
+ type pathParent interface {
33
+ logger.Writer
34
+ setPathReady(*path)
35
+ setPathNotReady(*path)
36
+ closePathIfIdle(*path)
37
+ removePath(*path)
38
+ AddReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error)
39
+ }
40
+
41
+ type pathOnDemandState int
42
+
43
+ const (
44
+ pathOnDemandStateInitial pathOnDemandState = iota
45
+ pathOnDemandStateWaitingReady
46
+ pathOnDemandStateReady
47
+ pathOnDemandStateClosing
48
+ )
49
+
50
+ type pathAPIPathsListRes struct {
51
+ data *defs.APIPathList
52
+ paths map[string]*path
53
+ }
54
+
55
+ type pathAPIPathsListReq struct {
56
+ res chan pathAPIPathsListRes
57
+ }
58
+
59
+ type pathAPIPathsGetRes struct {
60
+ path *path
61
+ data *defs.APIPath
62
+ err error
63
+ }
64
+
65
+ type pathAPIPathsGetReq struct {
66
+ name string
67
+ res chan pathAPIPathsGetRes
68
+ }
69
+
70
+ type path struct {
71
+ parentCtx context.Context
72
+ logLevel conf.LogLevel
73
+ dumpPackets bool
74
+ rtspAddress string
75
+ readTimeout conf.Duration
76
+ writeTimeout conf.Duration
77
+ writeQueueSize int
78
+ udpReadBufferSize uint
79
+ rtpMaxPayloadSize int
80
+ conf *conf.Path
81
+ name string
82
+ matches []string
83
+ wg *sync.WaitGroup
84
+ externalCmdPool *externalcmd.Pool
85
+ parent pathParent
86
+
87
+ // accessed by pathManager only
88
+ ready bool
89
+ confName string
90
+
91
+ ctx context.Context
92
+ ctxCancel func()
93
+ pendingRequests atomic.Int64
94
+ confMutex sync.RWMutex
95
+ source defs.Source
96
+ stream *stream.Stream
97
+ recorder *recorder.Recorder
98
+ availableTime time.Time
99
+ onlineTime time.Time
100
+ onUnDemandHook func(string)
101
+ onNotReadyHook func()
102
+ readers map[defs.Reader]struct{}
103
+ describeRequestsOnHold []defs.PathDescribeReq
104
+ readerAddRequestsOnHold []defs.PathAddReaderReq
105
+ onDemandStaticSourceState pathOnDemandState
106
+ onDemandStaticSourceReadyTimer *time.Timer
107
+ onDemandStaticSourceCloseTimer *time.Timer
108
+ onDemandPublisherState pathOnDemandState
109
+ onDemandPublisherReadyTimer *time.Timer
110
+ onDemandPublisherCloseTimer *time.Timer
111
+
112
+ // in
113
+ chReloadConf chan *conf.Path
114
+ chStaticSourceSetReady chan defs.PathSourceStaticSetReadyReq
115
+ chStaticSourceSetNotReady chan defs.PathSourceStaticSetNotReadyReq
116
+ chDescribe chan defs.PathDescribeReq
117
+ chAddPublisher chan defs.PathAddPublisherReq
118
+ chRemovePublisher chan defs.PathRemovePublisherReq
119
+ chAddReader chan defs.PathAddReaderReq
120
+ chRemoveReader chan defs.PathRemoveReaderReq
121
+ chAPIPathsGet chan pathAPIPathsGetReq
122
+
123
+ // out
124
+ done chan struct{}
125
+ }
126
+
127
+ func (pa *path) initialize() {
128
+ ctx, ctxCancel := context.WithCancel(pa.parentCtx)
129
+
130
+ pa.confName = pa.conf.Name
131
+ pa.ctx = ctx
132
+ pa.ctxCancel = ctxCancel
133
+ pa.readers = make(map[defs.Reader]struct{})
134
+ pa.onDemandStaticSourceReadyTimer = emptyTimer()
135
+ pa.onDemandStaticSourceCloseTimer = emptyTimer()
136
+ pa.onDemandPublisherReadyTimer = emptyTimer()
137
+ pa.onDemandPublisherCloseTimer = emptyTimer()
138
+ pa.chReloadConf = make(chan *conf.Path)
139
+ pa.chStaticSourceSetReady = make(chan defs.PathSourceStaticSetReadyReq)
140
+ pa.chStaticSourceSetNotReady = make(chan defs.PathSourceStaticSetNotReadyReq)
141
+ pa.chDescribe = make(chan defs.PathDescribeReq)
142
+ pa.chAddPublisher = make(chan defs.PathAddPublisherReq)
143
+ pa.chRemovePublisher = make(chan defs.PathRemovePublisherReq)
144
+ pa.chAddReader = make(chan defs.PathAddReaderReq)
145
+ pa.chRemoveReader = make(chan defs.PathRemoveReaderReq)
146
+ pa.chAPIPathsGet = make(chan pathAPIPathsGetReq)
147
+ pa.done = make(chan struct{})
148
+
149
+ pa.Log(logger.Debug, "created")
150
+
151
+ pa.wg.Add(1)
152
+ go pa.run()
153
+ }
154
+
155
+ func (pa *path) close() {
156
+ pa.ctxCancel()
157
+ }
158
+
159
+ func (pa *path) wait() {
160
+ <-pa.done
161
+ }
162
+
163
+ // Log implements logger.Writer.
164
+ func (pa *path) Log(level logger.Level, format string, args ...any) {
165
+ pa.parent.Log(level, "[path "+pa.name+"] "+format, args...)
166
+ }
167
+
168
+ func (pa *path) Name() string {
169
+ return pa.name
170
+ }
171
+
172
+ func (pa *path) isAvailable() bool {
173
+ return pa.stream != nil
174
+ }
175
+
176
+ func (pa *path) isOnline() bool {
177
+ return pa.source != nil
178
+ }
179
+
180
+ func (pa *path) run() {
181
+ defer close(pa.done)
182
+ defer pa.wg.Done()
183
+
184
+ if pa.conf.AlwaysAvailable {
185
+ err := pa.setAvailable(nil, "", nil, true)
186
+ if err != nil {
187
+ panic(err)
188
+ }
189
+ }
190
+
191
+ if pa.conf.Source == "redirect" {
192
+ pa.source = &sourceRedirect{}
193
+ } else if pa.conf.HasStaticSource() {
194
+ pa.source = &staticsources.Handler{
195
+ Conf: pa.conf,
196
+ LogLevel: pa.logLevel,
197
+ DumpPackets: pa.dumpPackets,
198
+ ReadTimeout: pa.readTimeout,
199
+ WriteTimeout: pa.writeTimeout,
200
+ WriteQueueSize: pa.writeQueueSize,
201
+ UDPReadBufferSize: pa.udpReadBufferSize,
202
+ RTPMaxPayloadSize: pa.rtpMaxPayloadSize,
203
+ Matches: pa.matches,
204
+ PathManager: pa.parent,
205
+ Parent: pa,
206
+ }
207
+ pa.source.(*staticsources.Handler).Initialize()
208
+
209
+ if !pa.conf.SourceOnDemand {
210
+ pa.source.(*staticsources.Handler).Start(false, "")
211
+ }
212
+ }
213
+
214
+ onUnInitHook := hooks.OnInit(hooks.OnInitParams{
215
+ Logger: pa,
216
+ ExternalCmdPool: pa.externalCmdPool,
217
+ Conf: pa.conf,
218
+ ExternalCmdEnv: pa.ExternalCmdEnv(),
219
+ })
220
+
221
+ err := pa.runInner()
222
+
223
+ // call before destroying context
224
+ pa.parent.removePath(pa)
225
+
226
+ pa.ctxCancel()
227
+
228
+ pa.onDemandStaticSourceReadyTimer.Stop()
229
+ pa.onDemandStaticSourceCloseTimer.Stop()
230
+ pa.onDemandPublisherReadyTimer.Stop()
231
+ pa.onDemandPublisherCloseTimer.Stop()
232
+
233
+ onUnInitHook()
234
+
235
+ for _, req := range pa.describeRequestsOnHold {
236
+ req.Res <- defs.PathDescribeRes{Err: fmt.Errorf("terminated")}
237
+ }
238
+
239
+ for _, req := range pa.readerAddRequestsOnHold {
240
+ req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("terminated")}
241
+ }
242
+
243
+ if pa.stream != nil {
244
+ pa.setNotAvailable()
245
+ }
246
+
247
+ if pa.source != nil {
248
+ if source, ok := pa.source.(*staticsources.Handler); ok {
249
+ if !pa.conf.SourceOnDemand || pa.onDemandStaticSourceState != pathOnDemandStateInitial {
250
+ source.Close("path is closing")
251
+ }
252
+ } else if source, ok2 := pa.source.(defs.Publisher); ok2 {
253
+ source.Close()
254
+ }
255
+ }
256
+
257
+ if pa.onUnDemandHook != nil {
258
+ pa.onUnDemandHook("path destroyed")
259
+ }
260
+
261
+ pa.Log(logger.Debug, "destroyed: %v", err)
262
+ }
263
+
264
+ func (pa *path) runInner() error {
265
+ for {
266
+ select {
267
+ case <-pa.onDemandStaticSourceReadyTimer.C:
268
+ pa.doOnDemandStaticSourceReadyTimer()
269
+
270
+ if pa.shouldClose() {
271
+ pa.parent.closePathIfIdle(pa)
272
+ }
273
+
274
+ case <-pa.onDemandStaticSourceCloseTimer.C:
275
+ pa.doOnDemandStaticSourceCloseTimer()
276
+
277
+ if pa.shouldClose() {
278
+ pa.parent.closePathIfIdle(pa)
279
+ }
280
+
281
+ case <-pa.onDemandPublisherReadyTimer.C:
282
+ pa.doOnDemandPublisherReadyTimer()
283
+
284
+ if pa.shouldClose() {
285
+ pa.parent.closePathIfIdle(pa)
286
+ }
287
+
288
+ case <-pa.onDemandPublisherCloseTimer.C:
289
+ pa.doOnDemandPublisherCloseTimer()
290
+
291
+ case newConf := <-pa.chReloadConf:
292
+ pa.doReloadConf(newConf)
293
+
294
+ case req := <-pa.chStaticSourceSetReady:
295
+ pa.doSourceStaticSetReady(req)
296
+
297
+ case req := <-pa.chStaticSourceSetNotReady:
298
+ pa.doSourceStaticSetNotReady(req)
299
+
300
+ if pa.shouldClose() {
301
+ pa.parent.closePathIfIdle(pa)
302
+ }
303
+
304
+ case req := <-pa.chDescribe:
305
+ pa.doDescribe(req)
306
+
307
+ pa.pendingRequests.Add(-1)
308
+
309
+ if pa.shouldClose() {
310
+ pa.parent.closePathIfIdle(pa)
311
+ }
312
+
313
+ case req := <-pa.chAddPublisher:
314
+ pa.doAddPublisher(req)
315
+
316
+ pa.pendingRequests.Add(-1)
317
+
318
+ if pa.shouldClose() {
319
+ pa.parent.closePathIfIdle(pa)
320
+ }
321
+
322
+ case req := <-pa.chRemovePublisher:
323
+ pa.doRemovePublisher(req)
324
+
325
+ if pa.shouldClose() {
326
+ pa.parent.closePathIfIdle(pa)
327
+ }
328
+
329
+ case req := <-pa.chAddReader:
330
+ pa.doAddReader(req)
331
+
332
+ pa.pendingRequests.Add(-1)
333
+
334
+ if pa.shouldClose() {
335
+ pa.parent.closePathIfIdle(pa)
336
+ }
337
+
338
+ case req := <-pa.chRemoveReader:
339
+ pa.doRemoveReader(req)
340
+
341
+ case req := <-pa.chAPIPathsGet:
342
+ pa.doAPIPathsGet(req)
343
+
344
+ case <-pa.ctx.Done():
345
+ return fmt.Errorf("terminated")
346
+ }
347
+ }
348
+ }
349
+
350
+ func (pa *path) doOnDemandStaticSourceReadyTimer() {
351
+ for _, req := range pa.describeRequestsOnHold {
352
+ req.Res <- defs.PathDescribeRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)}
353
+ }
354
+ pa.describeRequestsOnHold = nil
355
+
356
+ for _, req := range pa.readerAddRequestsOnHold {
357
+ req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)}
358
+ }
359
+ pa.readerAddRequestsOnHold = nil
360
+
361
+ pa.onDemandStaticSourceStop("timed out")
362
+ }
363
+
364
+ func (pa *path) doOnDemandStaticSourceCloseTimer() {
365
+ if pa.conf.AlwaysAvailable {
366
+ panic("should not happen")
367
+ }
368
+ pa.setNotAvailable()
369
+ pa.onDemandStaticSourceStop("not needed by anyone")
370
+ }
371
+
372
+ func (pa *path) doOnDemandPublisherReadyTimer() {
373
+ for _, req := range pa.describeRequestsOnHold {
374
+ req.Res <- defs.PathDescribeRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)}
375
+ }
376
+ pa.describeRequestsOnHold = nil
377
+
378
+ for _, req := range pa.readerAddRequestsOnHold {
379
+ req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)}
380
+ }
381
+ pa.readerAddRequestsOnHold = nil
382
+
383
+ pa.onDemandPublisherStop("timed out")
384
+ }
385
+
386
+ func (pa *path) doOnDemandPublisherCloseTimer() {
387
+ pa.onDemandPublisherStop("not needed by anyone")
388
+ }
389
+
390
+ func (pa *path) doReloadConf(newConf *conf.Path) {
391
+ pa.confMutex.Lock()
392
+ oldConf := pa.conf
393
+ pa.conf = newConf
394
+ pa.confMutex.Unlock()
395
+
396
+ if pa.conf.HasStaticSource() {
397
+ pa.source.(*staticsources.Handler).ReloadConf(newConf)
398
+ }
399
+
400
+ if pa.recorder != nil &&
401
+ (newConf.Record != oldConf.Record ||
402
+ newConf.RecordPath != oldConf.RecordPath ||
403
+ newConf.RecordFormat != oldConf.RecordFormat ||
404
+ newConf.RecordPartDuration != oldConf.RecordPartDuration ||
405
+ newConf.RecordMaxPartSize != oldConf.RecordMaxPartSize ||
406
+ newConf.RecordSegmentDuration != oldConf.RecordSegmentDuration ||
407
+ newConf.RecordDeleteAfter != oldConf.RecordDeleteAfter) {
408
+ pa.recorder.Close()
409
+ pa.recorder = nil
410
+ }
411
+
412
+ if newConf.Record && pa.stream != nil && pa.recorder == nil {
413
+ pa.startRecording()
414
+ }
415
+ }
416
+
417
+ func (pa *path) doSourceStaticSetReady(req defs.PathSourceStaticSetReadyReq) {
418
+ if !pa.conf.AlwaysAvailable {
419
+ err := pa.setAvailable(pa.source, "", req.Desc, req.ReplaceNTP)
420
+ if err != nil {
421
+ req.Res <- defs.PathSourceStaticSetReadyRes{Err: err}
422
+ return
423
+ }
424
+ }
425
+
426
+ subStream := &stream.SubStream{
427
+ Stream: pa.stream,
428
+ UseRTPPackets: req.UseRTPPackets,
429
+ }
430
+
431
+ if pa.conf.AlwaysAvailable {
432
+ subStream.InDesc = req.Desc
433
+ }
434
+
435
+ err := subStream.Initialize()
436
+ if err != nil {
437
+ req.Res <- defs.PathSourceStaticSetReadyRes{Err: err}
438
+ return
439
+ }
440
+
441
+ if pa.conf.AlwaysAvailable {
442
+ pa.onlineTime = time.Now()
443
+ }
444
+
445
+ if pa.conf.HasOnDemandStaticSource() {
446
+ pa.onDemandStaticSourceReadyTimer.Stop()
447
+ pa.onDemandStaticSourceReadyTimer = emptyTimer()
448
+ pa.onDemandStaticSourceScheduleClose()
449
+ }
450
+
451
+ pa.consumeOnHoldRequests()
452
+
453
+ req.Res <- defs.PathSourceStaticSetReadyRes{SubStream: subStream}
454
+ }
455
+
456
+ func (pa *path) doSourceStaticSetNotReady(req defs.PathSourceStaticSetNotReadyReq) {
457
+ if !pa.conf.AlwaysAvailable {
458
+ pa.setNotAvailable()
459
+ } else {
460
+ err := pa.stream.StartOfflineSubStream()
461
+ if err != nil {
462
+ panic("should not happen")
463
+ }
464
+ }
465
+
466
+ // send response before calling onDemandStaticSourceStop()
467
+ // in order to avoid a deadlock due to staticsources.Handler.stop()
468
+ close(req.Res)
469
+
470
+ if pa.conf.HasOnDemandStaticSource() && pa.onDemandStaticSourceState != pathOnDemandStateInitial {
471
+ pa.onDemandStaticSourceStop("an error occurred")
472
+ }
473
+ }
474
+
475
+ func (pa *path) doDescribe(req defs.PathDescribeReq) {
476
+ if _, ok := pa.source.(*sourceRedirect); ok {
477
+ req.Res <- defs.PathDescribeRes{
478
+ Redirect: pa.conf.SourceRedirect,
479
+ }
480
+ return
481
+ }
482
+
483
+ if pa.stream != nil {
484
+ req.Res <- defs.PathDescribeRes{
485
+ Stream: pa.stream,
486
+ }
487
+ return
488
+ }
489
+
490
+ if pa.conf.HasOnDemandStaticSource() {
491
+ if pa.onDemandStaticSourceState == pathOnDemandStateInitial {
492
+ pa.onDemandStaticSourceStart(req.AccessRequest.Query)
493
+ }
494
+ pa.describeRequestsOnHold = append(pa.describeRequestsOnHold, req)
495
+ return
496
+ }
497
+
498
+ if pa.conf.HasOnDemandPublisher() {
499
+ if pa.onDemandPublisherState == pathOnDemandStateInitial {
500
+ pa.onDemandPublisherStart(req.AccessRequest.Query)
501
+ }
502
+ pa.describeRequestsOnHold = append(pa.describeRequestsOnHold, req)
503
+ return
504
+ }
505
+
506
+ if pa.conf.Fallback != nil {
507
+ req.Res <- defs.PathDescribeRes{Redirect: *pa.conf.Fallback}
508
+ return
509
+ }
510
+
511
+ req.Res <- defs.PathDescribeRes{Err: &defs.PathNoStreamAvailableError{PathName: pa.name}}
512
+ }
513
+
514
+ func (pa *path) doRemovePublisher(req defs.PathRemovePublisherReq) {
515
+ if pa.source == req.Author {
516
+ pa.executeRemovePublisher()
517
+ }
518
+ close(req.Res)
519
+ }
520
+
521
+ func (pa *path) doAddPublisher(req defs.PathAddPublisherReq) {
522
+ if pa.conf.Source != "publisher" {
523
+ req.Res <- defs.PathAddPublisherRes{
524
+ Err: fmt.Errorf("can't publish to path '%s' since 'source' is not 'publisher'", pa.name),
525
+ }
526
+ return
527
+ }
528
+
529
+ if pa.source != nil {
530
+ if !pa.conf.OverridePublisher {
531
+ req.Res <- defs.PathAddPublisherRes{Err: fmt.Errorf("someone is already publishing to path '%s'", pa.name)}
532
+ return
533
+ }
534
+
535
+ pa.Log(logger.Info, "closing existing publisher")
536
+ pa.source.(defs.Publisher).Close()
537
+ pa.executeRemovePublisher()
538
+ }
539
+
540
+ if !pa.conf.AlwaysAvailable {
541
+ err := pa.setAvailable(req.Author, req.AccessRequest.Query, req.Desc, req.ReplaceNTP)
542
+ if err != nil {
543
+ req.Res <- defs.PathAddPublisherRes{Err: err}
544
+ return
545
+ }
546
+ }
547
+
548
+ subStream := &stream.SubStream{
549
+ Stream: pa.stream,
550
+ UseRTPPackets: req.UseRTPPackets,
551
+ }
552
+
553
+ if pa.conf.AlwaysAvailable {
554
+ subStream.InDesc = req.Desc
555
+ }
556
+
557
+ err := subStream.Initialize()
558
+ if err != nil {
559
+ req.Res <- defs.PathAddPublisherRes{Err: err}
560
+ return
561
+ }
562
+
563
+ pa.source = req.Author
564
+
565
+ req.Author.Log(logger.Info, "is publishing to path '%s'",
566
+ pa.name)
567
+
568
+ if pa.conf.AlwaysAvailable {
569
+ pa.onlineTime = time.Now()
570
+ }
571
+
572
+ if pa.conf.HasOnDemandPublisher() && pa.onDemandPublisherState != pathOnDemandStateInitial {
573
+ pa.onDemandPublisherReadyTimer.Stop()
574
+ pa.onDemandPublisherReadyTimer = emptyTimer()
575
+ pa.onDemandPublisherScheduleClose()
576
+ }
577
+
578
+ pa.consumeOnHoldRequests()
579
+
580
+ req.Res <- defs.PathAddPublisherRes{SubStream: subStream}
581
+ }
582
+
583
+ func (pa *path) doAddReader(req defs.PathAddReaderReq) {
584
+ if pa.stream != nil {
585
+ pa.addReaderPost(req)
586
+ return
587
+ }
588
+
589
+ if pa.conf.HasOnDemandStaticSource() {
590
+ if pa.onDemandStaticSourceState == pathOnDemandStateInitial {
591
+ pa.onDemandStaticSourceStart(req.AccessRequest.Query)
592
+ }
593
+ pa.readerAddRequestsOnHold = append(pa.readerAddRequestsOnHold, req)
594
+ return
595
+ }
596
+
597
+ if pa.conf.HasOnDemandPublisher() {
598
+ if pa.onDemandPublisherState == pathOnDemandStateInitial {
599
+ pa.onDemandPublisherStart(req.AccessRequest.Query)
600
+ }
601
+ pa.readerAddRequestsOnHold = append(pa.readerAddRequestsOnHold, req)
602
+ return
603
+ }
604
+
605
+ req.Res <- defs.PathAddReaderRes{Err: &defs.PathNoStreamAvailableError{PathName: pa.name}}
606
+ }
607
+
608
+ func (pa *path) doRemoveReader(req defs.PathRemoveReaderReq) {
609
+ if _, ok := pa.readers[req.Author]; ok {
610
+ pa.executeRemoveReader(req.Author)
611
+ }
612
+ close(req.Res)
613
+
614
+ if len(pa.readers) == 0 {
615
+ if pa.conf.HasOnDemandStaticSource() {
616
+ if pa.onDemandStaticSourceState == pathOnDemandStateReady {
617
+ pa.onDemandStaticSourceScheduleClose()
618
+ }
619
+ } else if pa.conf.HasOnDemandPublisher() {
620
+ if pa.onDemandPublisherState == pathOnDemandStateReady {
621
+ pa.onDemandPublisherScheduleClose()
622
+ }
623
+ }
624
+ }
625
+ }
626
+
627
+ func (pa *path) doAPIPathsGet(req pathAPIPathsGetReq) {
628
+ var outDesc *description.Session
629
+ if pa.isAvailable() {
630
+ outDesc = pa.stream.OutDescCopy()
631
+ }
632
+
633
+ req.res <- pathAPIPathsGetRes{
634
+ data: &defs.APIPath{
635
+ Name: pa.name,
636
+ ConfName: pa.conf.Name,
637
+ Ready: pa.isAvailable(),
638
+ ReadyTime: func() *time.Time {
639
+ if !pa.isAvailable() {
640
+ return nil
641
+ }
642
+ v := pa.availableTime
643
+ return &v
644
+ }(),
645
+ Available: pa.isAvailable(),
646
+ AvailableTime: func() *time.Time {
647
+ if !pa.isAvailable() {
648
+ return nil
649
+ }
650
+ v := pa.availableTime
651
+ return &v
652
+ }(),
653
+ Online: pa.isOnline(),
654
+ OnlineTime: func() *time.Time {
655
+ if !pa.isOnline() {
656
+ return nil
657
+ }
658
+ v := pa.onlineTime
659
+ return &v
660
+ }(),
661
+ Source: func() *defs.APIPathSource {
662
+ if pa.source == nil {
663
+ return nil
664
+ }
665
+ v := pa.source.APISourceDescribe()
666
+ return v
667
+ }(),
668
+ Tracks: func() []defs.APIPathTrackCodec {
669
+ if !pa.isAvailable() {
670
+ return []defs.APIPathTrackCodec{}
671
+ }
672
+ return formatlabel.MediasToLabels(outDesc.Medias)
673
+ }(),
674
+ Tracks2: func() []defs.APIPathTrack {
675
+ if !pa.isAvailable() {
676
+ return []defs.APIPathTrack{}
677
+ }
678
+ return defs.MediasToTracks(outDesc.Medias)
679
+ }(),
680
+ InboundBytes: func() uint64 {
681
+ if !pa.isAvailable() {
682
+ return 0
683
+ }
684
+ return pa.stream.InboundBytes()
685
+ }(),
686
+ OutboundBytes: func() uint64 {
687
+ if !pa.isAvailable() {
688
+ return 0
689
+ }
690
+ return pa.stream.OutboundBytes()
691
+ }(),
692
+ InboundFramesInError: func() uint64 {
693
+ if !pa.isAvailable() {
694
+ return 0
695
+ }
696
+ return pa.stream.InboundFramesInError()
697
+ }(),
698
+ BytesReceived: func() uint64 {
699
+ if !pa.isAvailable() {
700
+ return 0
701
+ }
702
+ return pa.stream.InboundBytes()
703
+ }(),
704
+ BytesSent: func() uint64 {
705
+ if !pa.isAvailable() {
706
+ return 0
707
+ }
708
+ return pa.stream.OutboundBytes()
709
+ }(),
710
+ Readers: func() []defs.APIPathReader {
711
+ ret := make([]defs.APIPathReader, 0, len(pa.readers))
712
+
713
+ for r := range pa.readers {
714
+ desc := *r.APIReaderDescribe()
715
+ if desc.Type != defs.APIPathReaderTypeHidden {
716
+ ret = append(ret, desc)
717
+ }
718
+ }
719
+
720
+ sort.Slice(ret, func(i, j int) bool {
721
+ if ret[i].Type != ret[j].Type {
722
+ return ret[i].Type < ret[j].Type
723
+ }
724
+ return ret[i].ID < ret[j].ID
725
+ })
726
+
727
+ return ret
728
+ }(),
729
+ },
730
+ }
731
+ }
732
+
733
+ func (pa *path) SafeConf() *conf.Path {
734
+ pa.confMutex.RLock()
735
+ defer pa.confMutex.RUnlock()
736
+ return pa.conf
737
+ }
738
+
739
+ func (pa *path) ExternalCmdEnv() externalcmd.Environment {
740
+ _, port, _ := net.SplitHostPort(pa.rtspAddress)
741
+ env := externalcmd.Environment{
742
+ "MTX_PATH": pa.name,
743
+ "RTSP_PATH": pa.name, // deprecated
744
+ "RTSP_PORT": port,
745
+ }
746
+
747
+ if len(pa.matches) > 1 {
748
+ for i, ma := range pa.matches[1:] {
749
+ env["G"+strconv.FormatInt(int64(i+1), 10)] = ma
750
+ }
751
+ }
752
+
753
+ return env
754
+ }
755
+
756
+ func (pa *path) shouldClose() bool {
757
+ return pa.conf.Regexp != nil &&
758
+ pa.source == nil &&
759
+ len(pa.readers) == 0 &&
760
+ len(pa.describeRequestsOnHold) == 0 &&
761
+ len(pa.readerAddRequestsOnHold) == 0
762
+ }
763
+
764
+ func (pa *path) onDemandStaticSourceStart(query string) {
765
+ pa.source.(*staticsources.Handler).Start(true, query)
766
+
767
+ pa.onDemandStaticSourceReadyTimer.Stop()
768
+ pa.onDemandStaticSourceReadyTimer = time.NewTimer(time.Duration(pa.conf.SourceOnDemandStartTimeout))
769
+
770
+ pa.onDemandStaticSourceState = pathOnDemandStateWaitingReady
771
+ }
772
+
773
+ func (pa *path) onDemandStaticSourceScheduleClose() {
774
+ pa.onDemandStaticSourceCloseTimer.Stop()
775
+ pa.onDemandStaticSourceCloseTimer = time.NewTimer(time.Duration(pa.conf.SourceOnDemandCloseAfter))
776
+
777
+ pa.onDemandStaticSourceState = pathOnDemandStateClosing
778
+ }
779
+
780
+ func (pa *path) onDemandStaticSourceStop(reason string) {
781
+ if pa.onDemandStaticSourceState == pathOnDemandStateClosing {
782
+ pa.onDemandStaticSourceCloseTimer.Stop()
783
+ pa.onDemandStaticSourceCloseTimer = emptyTimer()
784
+ }
785
+
786
+ pa.onDemandStaticSourceState = pathOnDemandStateInitial
787
+
788
+ pa.source.(*staticsources.Handler).Stop(reason)
789
+ }
790
+
791
+ func (pa *path) onDemandPublisherStart(query string) {
792
+ pa.onUnDemandHook = hooks.OnDemand(hooks.OnDemandParams{
793
+ Logger: pa,
794
+ ExternalCmdPool: pa.externalCmdPool,
795
+ Conf: pa.conf,
796
+ ExternalCmdEnv: pa.ExternalCmdEnv(),
797
+ Query: query,
798
+ })
799
+
800
+ pa.onDemandPublisherReadyTimer.Stop()
801
+ pa.onDemandPublisherReadyTimer = time.NewTimer(time.Duration(pa.conf.RunOnDemandStartTimeout))
802
+
803
+ pa.onDemandPublisherState = pathOnDemandStateWaitingReady
804
+ }
805
+
806
+ func (pa *path) onDemandPublisherScheduleClose() {
807
+ pa.onDemandPublisherCloseTimer.Stop()
808
+ pa.onDemandPublisherCloseTimer = time.NewTimer(time.Duration(pa.conf.RunOnDemandCloseAfter))
809
+
810
+ pa.onDemandPublisherState = pathOnDemandStateClosing
811
+ }
812
+
813
+ func (pa *path) onDemandPublisherStop(reason string) {
814
+ if pa.onDemandPublisherState == pathOnDemandStateClosing {
815
+ pa.onDemandPublisherCloseTimer.Stop()
816
+ pa.onDemandPublisherCloseTimer = emptyTimer()
817
+ }
818
+
819
+ pa.onUnDemandHook(reason)
820
+ pa.onUnDemandHook = nil
821
+
822
+ pa.onDemandPublisherState = pathOnDemandStateInitial
823
+ }
824
+
825
+ func (pa *path) setAvailable(
826
+ source defs.Source,
827
+ publisherQuery string,
828
+ desc *description.Session,
829
+ replaceNTP bool,
830
+ ) error {
831
+ pa.stream = &stream.Stream{
832
+ OrigDesc: desc,
833
+ AlwaysAvailable: pa.conf.AlwaysAvailable,
834
+ AlwaysAvailableTracks: pa.conf.AlwaysAvailableTracks,
835
+ AlwaysAvailableFile: pa.conf.AlwaysAvailableFile,
836
+ WriteQueueSize: pa.writeQueueSize,
837
+ RTPMaxPayloadSize: pa.rtpMaxPayloadSize,
838
+ ReplaceNTP: replaceNTP,
839
+ Parent: pa,
840
+ }
841
+ err := pa.stream.Initialize()
842
+ if err != nil {
843
+ return err
844
+ }
845
+
846
+ pa.availableTime = time.Now()
847
+
848
+ if !pa.conf.AlwaysAvailable {
849
+ pa.onlineTime = time.Now()
850
+ }
851
+
852
+ if pa.conf.Record {
853
+ pa.startRecording()
854
+ }
855
+
856
+ var sourceDesc *defs.APIPathSource
857
+ if source != nil {
858
+ sourceDesc = source.APISourceDescribe()
859
+ }
860
+
861
+ pa.onNotReadyHook = hooks.OnReady(hooks.OnReadyParams{
862
+ Logger: pa,
863
+ ExternalCmdPool: pa.externalCmdPool,
864
+ Conf: pa.conf,
865
+ ExternalCmdEnv: pa.ExternalCmdEnv(),
866
+ Desc: sourceDesc,
867
+ Query: publisherQuery,
868
+ })
869
+
870
+ if pa.conf.AlwaysAvailable {
871
+ pa.Log(logger.Info, "stream is available, %s", defs.MediasInfo(pa.stream.OrigDesc.Medias))
872
+ } else {
873
+ pa.Log(logger.Info, "stream is available and online, %s", defs.MediasInfo(pa.stream.OrigDesc.Medias))
874
+ }
875
+
876
+ pa.parent.setPathReady(pa)
877
+
878
+ return nil
879
+ }
880
+
881
+ func (pa *path) consumeOnHoldRequests() {
882
+ for _, req := range pa.describeRequestsOnHold {
883
+ req.Res <- defs.PathDescribeRes{
884
+ Stream: pa.stream,
885
+ }
886
+ }
887
+ pa.describeRequestsOnHold = nil
888
+
889
+ for _, req := range pa.readerAddRequestsOnHold {
890
+ pa.addReaderPost(req)
891
+ }
892
+ pa.readerAddRequestsOnHold = nil
893
+ }
894
+
895
+ func (pa *path) setNotAvailable() {
896
+ pa.parent.setPathNotReady(pa)
897
+
898
+ for r := range pa.readers {
899
+ pa.executeRemoveReader(r)
900
+ r.Close()
901
+ }
902
+
903
+ pa.onNotReadyHook()
904
+
905
+ if pa.recorder != nil {
906
+ pa.recorder.Close()
907
+ pa.recorder = nil
908
+ }
909
+
910
+ if pa.stream != nil {
911
+ pa.stream.Close()
912
+ pa.stream = nil
913
+ }
914
+ }
915
+
916
+ func (pa *path) startRecording() {
917
+ pa.recorder = &recorder.Recorder{
918
+ PathFormat: pa.conf.RecordPath,
919
+ Format: pa.conf.RecordFormat,
920
+ PartDuration: time.Duration(pa.conf.RecordPartDuration),
921
+ MaxPartSize: pa.conf.RecordMaxPartSize,
922
+ SegmentDuration: time.Duration(pa.conf.RecordSegmentDuration),
923
+ PathName: pa.name,
924
+ Stream: pa.stream,
925
+ OnSegmentCreate: func(segmentPath string) {
926
+ if pa.conf.RunOnRecordSegmentCreate != "" {
927
+ env := pa.ExternalCmdEnv()
928
+ env["MTX_SEGMENT_PATH"] = segmentPath
929
+
930
+ pa.Log(logger.Info, "runOnRecordSegmentCreate command launched")
931
+ cmd := &externalcmd.Cmd{
932
+ Pool: pa.externalCmdPool,
933
+ Cmdstr: pa.conf.RunOnRecordSegmentCreate,
934
+ Restart: false,
935
+ Env: env,
936
+ }
937
+ cmd.Start()
938
+ }
939
+ },
940
+ OnSegmentComplete: func(segmentPath string, segmentDuration time.Duration) {
941
+ if pa.conf.RunOnRecordSegmentComplete != "" {
942
+ env := pa.ExternalCmdEnv()
943
+ env["MTX_SEGMENT_PATH"] = segmentPath
944
+ env["MTX_SEGMENT_DURATION"] = strconv.FormatFloat(segmentDuration.Seconds(), 'f', -1, 64)
945
+
946
+ pa.Log(logger.Info, "runOnRecordSegmentComplete command launched")
947
+ cmd := &externalcmd.Cmd{
948
+ Pool: pa.externalCmdPool,
949
+ Cmdstr: pa.conf.RunOnRecordSegmentComplete,
950
+ Restart: false,
951
+ Env: env,
952
+ }
953
+ cmd.Start()
954
+ }
955
+ },
956
+ Parent: pa,
957
+ }
958
+ pa.recorder.Initialize()
959
+ }
960
+
961
+ func (pa *path) executeRemoveReader(r defs.Reader) {
962
+ delete(pa.readers, r)
963
+ }
964
+
965
+ func (pa *path) executeRemovePublisher() {
966
+ if !pa.conf.AlwaysAvailable {
967
+ pa.setNotAvailable()
968
+ } else {
969
+ err := pa.stream.StartOfflineSubStream()
970
+ if err != nil {
971
+ panic("should not happen")
972
+ }
973
+ }
974
+ pa.source = nil
975
+ }
976
+
977
+ func (pa *path) addReaderPost(req defs.PathAddReaderReq) {
978
+ if _, ok := pa.readers[req.Author]; ok {
979
+ req.Res <- defs.PathAddReaderRes{Stream: pa.stream}
980
+ return
981
+ }
982
+
983
+ if pa.conf.MaxReaders != 0 && len(pa.readers) >= pa.conf.MaxReaders {
984
+ req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("maximum reader count reached")}
985
+ return
986
+ }
987
+
988
+ pa.readers[req.Author] = struct{}{}
989
+
990
+ if pa.conf.HasOnDemandStaticSource() {
991
+ if pa.onDemandStaticSourceState == pathOnDemandStateClosing {
992
+ pa.onDemandStaticSourceState = pathOnDemandStateReady
993
+ pa.onDemandStaticSourceCloseTimer.Stop()
994
+ pa.onDemandStaticSourceCloseTimer = emptyTimer()
995
+ }
996
+ } else if pa.conf.HasOnDemandPublisher() {
997
+ if pa.onDemandPublisherState == pathOnDemandStateClosing {
998
+ pa.onDemandPublisherState = pathOnDemandStateReady
999
+ pa.onDemandPublisherCloseTimer.Stop()
1000
+ pa.onDemandPublisherCloseTimer = emptyTimer()
1001
+ }
1002
+ }
1003
+
1004
+ req.Res <- defs.PathAddReaderRes{Stream: pa.stream}
1005
+ }
1006
+
1007
+ // reloadConf is called by pathManager.
1008
+ func (pa *path) reloadConf(newConf *conf.Path) {
1009
+ select {
1010
+ case pa.chReloadConf <- newConf:
1011
+ case <-pa.ctx.Done():
1012
+ }
1013
+ }
1014
+
1015
+ // StaticSourceHandlerSetReady is called by staticsources.Handler.
1016
+ func (pa *path) StaticSourceHandlerSetReady(
1017
+ ctx context.Context, req defs.PathSourceStaticSetReadyReq,
1018
+ ) {
1019
+ select {
1020
+ case pa.chStaticSourceSetReady <- req:
1021
+
1022
+ case <-pa.ctx.Done():
1023
+ req.Res <- defs.PathSourceStaticSetReadyRes{Err: fmt.Errorf("terminated")}
1024
+
1025
+ // this avoids:
1026
+ // - invalid requests sent after the source has been terminated
1027
+ // - deadlocks caused by <-done inside stop()
1028
+ case <-ctx.Done():
1029
+ req.Res <- defs.PathSourceStaticSetReadyRes{Err: fmt.Errorf("terminated")}
1030
+ }
1031
+ }
1032
+
1033
+ // StaticSourceHandlerSetNotReady is called by staticsources.Handler.
1034
+ func (pa *path) StaticSourceHandlerSetNotReady(
1035
+ ctx context.Context, req defs.PathSourceStaticSetNotReadyReq,
1036
+ ) {
1037
+ select {
1038
+ case pa.chStaticSourceSetNotReady <- req:
1039
+
1040
+ case <-pa.ctx.Done():
1041
+ close(req.Res)
1042
+
1043
+ // this avoids:
1044
+ // - invalid requests sent after the source has been terminated
1045
+ // - deadlocks caused by <-done inside stop()
1046
+ case <-ctx.Done():
1047
+ close(req.Res)
1048
+ }
1049
+ }
1050
+
1051
+ // describe is called by a reader or publisher through pathManager.
1052
+ func (pa *path) describe(req defs.PathDescribeReq) (*defs.PathDescribeRes, error) {
1053
+ select {
1054
+ case pa.chDescribe <- req:
1055
+ res := <-req.Res
1056
+ return &res, res.Err
1057
+
1058
+ case <-pa.ctx.Done():
1059
+ return nil, fmt.Errorf("terminated")
1060
+ }
1061
+ }
1062
+
1063
+ // addPublisher is called by a publisher through pathManager.
1064
+ func (pa *path) addPublisher(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) {
1065
+ select {
1066
+ case pa.chAddPublisher <- req:
1067
+ res := <-req.Res
1068
+ return &res, res.Err
1069
+ case <-pa.ctx.Done():
1070
+ return nil, fmt.Errorf("terminated")
1071
+ }
1072
+ }
1073
+
1074
+ // RemovePublisher is called by a publisher.
1075
+ func (pa *path) RemovePublisher(req defs.PathRemovePublisherReq) {
1076
+ req.Res = make(chan struct{})
1077
+ select {
1078
+ case pa.chRemovePublisher <- req:
1079
+ <-req.Res
1080
+ case <-pa.ctx.Done():
1081
+ }
1082
+ }
1083
+
1084
+ // addReader is called by a reader through pathManager.
1085
+ func (pa *path) addReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) {
1086
+ select {
1087
+ case pa.chAddReader <- req:
1088
+ res := <-req.Res
1089
+ return &res, res.Err
1090
+ case <-pa.ctx.Done():
1091
+ return nil, fmt.Errorf("terminated")
1092
+ }
1093
+ }
1094
+
1095
+ // RemoveReader is called by a reader.
1096
+ func (pa *path) RemoveReader(req defs.PathRemoveReaderReq) {
1097
+ req.Res = make(chan struct{})
1098
+ select {
1099
+ case pa.chRemoveReader <- req:
1100
+ <-req.Res
1101
+ case <-pa.ctx.Done():
1102
+ }
1103
+ }
1104
+
1105
+ // APIPathsGet implements defs.APIPathManager.
1106
+ func (pa *path) APIPathsGet(req pathAPIPathsGetReq) (*defs.APIPath, error) {
1107
+ req.res = make(chan pathAPIPathsGetRes)
1108
+ select {
1109
+ case pa.chAPIPathsGet <- req:
1110
+ res := <-req.res
1111
+ return res.data, res.err
1112
+
1113
+ case <-pa.ctx.Done():
1114
+ return nil, fmt.Errorf("terminated")
1115
+ }
1116
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager.go ADDED
@@ -0,0 +1,690 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "context"
5
+ "fmt"
6
+ "maps"
7
+ "sort"
8
+ "sync"
9
+
10
+ "github.com/bluenviron/mediamtx/internal/auth"
11
+ "github.com/bluenviron/mediamtx/internal/conf"
12
+ "github.com/bluenviron/mediamtx/internal/defs"
13
+ "github.com/bluenviron/mediamtx/internal/externalcmd"
14
+ "github.com/bluenviron/mediamtx/internal/logger"
15
+ "github.com/bluenviron/mediamtx/internal/metrics"
16
+ "github.com/bluenviron/mediamtx/internal/servers/hls"
17
+ )
18
+
19
+ func pathConfCanBeUpdated(oldPathConf *conf.Path, newPathConf *conf.Path) bool {
20
+ clone := oldPathConf.Clone()
21
+
22
+ clone.Name = newPathConf.Name
23
+ clone.Regexp = newPathConf.Regexp
24
+
25
+ clone.Record = newPathConf.Record
26
+ clone.RecordPath = newPathConf.RecordPath
27
+ clone.RecordFormat = newPathConf.RecordFormat
28
+ clone.RecordPartDuration = newPathConf.RecordPartDuration
29
+ clone.RecordMaxPartSize = newPathConf.RecordMaxPartSize
30
+ clone.RecordSegmentDuration = newPathConf.RecordSegmentDuration
31
+ clone.RecordDeleteAfter = newPathConf.RecordDeleteAfter
32
+
33
+ clone.RPICameraBrightness = newPathConf.RPICameraBrightness
34
+ clone.RPICameraContrast = newPathConf.RPICameraContrast
35
+ clone.RPICameraSaturation = newPathConf.RPICameraSaturation
36
+ clone.RPICameraSharpness = newPathConf.RPICameraSharpness
37
+ clone.RPICameraExposure = newPathConf.RPICameraExposure
38
+ clone.RPICameraFlickerPeriod = newPathConf.RPICameraFlickerPeriod
39
+ clone.RPICameraAWB = newPathConf.RPICameraAWB
40
+ clone.RPICameraAWBGains = newPathConf.RPICameraAWBGains
41
+ clone.RPICameraDenoise = newPathConf.RPICameraDenoise
42
+ clone.RPICameraShutter = newPathConf.RPICameraShutter
43
+ clone.RPICameraMetering = newPathConf.RPICameraMetering
44
+ clone.RPICameraGain = newPathConf.RPICameraGain
45
+ clone.RPICameraEV = newPathConf.RPICameraEV
46
+ clone.RPICameraFPS = newPathConf.RPICameraFPS
47
+ clone.RPICameraTextOverlayEnable = newPathConf.RPICameraTextOverlayEnable
48
+ clone.RPICameraTextOverlay = newPathConf.RPICameraTextOverlay
49
+ clone.RPICameraIDRPeriod = newPathConf.RPICameraIDRPeriod
50
+ clone.RPICameraBitrate = newPathConf.RPICameraBitrate
51
+
52
+ return newPathConf.Equal(clone)
53
+ }
54
+
55
+ type pathSetHLSServerRes struct {
56
+ readyPaths []defs.Path
57
+ }
58
+
59
+ type pathSetHLSServerReq struct {
60
+ s *hls.Server
61
+ res chan pathSetHLSServerRes
62
+ }
63
+
64
+ type pathManagerAuthManager interface {
65
+ Authenticate(req *auth.Request) (string, *auth.Error)
66
+ }
67
+
68
+ type pathManagerParent interface {
69
+ logger.Writer
70
+ }
71
+
72
+ type pathManager struct {
73
+ logLevel conf.LogLevel
74
+ rtspAddress string
75
+ dumpPackets bool
76
+ readTimeout conf.Duration
77
+ writeTimeout conf.Duration
78
+ writeQueueSize int
79
+ udpReadBufferSize uint
80
+ rtpMaxPayloadSize int
81
+ pathConfs map[string]*conf.Path
82
+ authManager pathManagerAuthManager
83
+ externalCmdPool *externalcmd.Pool
84
+ metrics *metrics.Metrics
85
+ parent pathManagerParent
86
+
87
+ ctx context.Context
88
+ ctxCancel func()
89
+ wg sync.WaitGroup
90
+ hlsServer *hls.Server
91
+ paths map[string]*path
92
+
93
+ // in
94
+ chReloadConf chan map[string]*conf.Path
95
+ chSetHLSServer chan pathSetHLSServerReq
96
+ chRemovePath chan *path
97
+ chClosePathIfIdle chan *path
98
+ chSetPathReady chan *path
99
+ chSetPathNotReady chan *path
100
+ chFindPathConf chan defs.PathFindPathConfReq
101
+ chDescribe chan defs.PathDescribeReq
102
+ chAddReader chan defs.PathAddReaderReq
103
+ chAddPublisher chan defs.PathAddPublisherReq
104
+ chAPIPathsList chan pathAPIPathsListReq
105
+ chAPIPathsGet chan pathAPIPathsGetReq
106
+ }
107
+
108
+ func (pm *pathManager) initialize() {
109
+ ctx, ctxCancel := context.WithCancel(context.Background())
110
+
111
+ pm.ctx = ctx
112
+ pm.ctxCancel = ctxCancel
113
+ pm.paths = make(map[string]*path)
114
+ pm.chReloadConf = make(chan map[string]*conf.Path)
115
+ pm.chSetHLSServer = make(chan pathSetHLSServerReq)
116
+ pm.chRemovePath = make(chan *path)
117
+ pm.chClosePathIfIdle = make(chan *path)
118
+ pm.chSetPathReady = make(chan *path)
119
+ pm.chSetPathNotReady = make(chan *path)
120
+ pm.chFindPathConf = make(chan defs.PathFindPathConfReq)
121
+ pm.chDescribe = make(chan defs.PathDescribeReq)
122
+ pm.chAddReader = make(chan defs.PathAddReaderReq)
123
+ pm.chAddPublisher = make(chan defs.PathAddPublisherReq)
124
+ pm.chAPIPathsList = make(chan pathAPIPathsListReq)
125
+ pm.chAPIPathsGet = make(chan pathAPIPathsGetReq)
126
+
127
+ for _, pathConf := range pm.pathConfs {
128
+ if pathConf.Regexp == nil {
129
+ pm.createPath(pathConf, pathConf.Name, nil)
130
+ }
131
+ }
132
+
133
+ pm.Log(logger.Debug, "path manager created")
134
+
135
+ pm.wg.Add(1)
136
+ go pm.run()
137
+
138
+ if pm.metrics != nil {
139
+ pm.metrics.SetPathManager(pm)
140
+ }
141
+ }
142
+
143
+ func (pm *pathManager) close() {
144
+ pm.Log(logger.Debug, "path manager is shutting down")
145
+
146
+ if pm.metrics != nil {
147
+ pm.metrics.SetPathManager(nil)
148
+ }
149
+
150
+ pm.ctxCancel()
151
+ pm.wg.Wait()
152
+ }
153
+
154
+ // Log implements logger.Writer.
155
+ func (pm *pathManager) Log(level logger.Level, format string, args ...any) {
156
+ pm.parent.Log(level, format, args...)
157
+ }
158
+
159
+ func (pm *pathManager) run() {
160
+ defer pm.wg.Done()
161
+
162
+ outer:
163
+ for {
164
+ select {
165
+ case newPaths := <-pm.chReloadConf:
166
+ pm.doReloadConf(newPaths)
167
+
168
+ case req := <-pm.chSetHLSServer:
169
+ readyPaths := pm.doSetHLSServer(req.s)
170
+ req.res <- pathSetHLSServerRes{readyPaths: readyPaths}
171
+
172
+ case pa := <-pm.chRemovePath:
173
+ if pa2, ok := pm.paths[pa.name]; ok && pa2 == pa {
174
+ delete(pm.paths, pa.name)
175
+ }
176
+
177
+ case pa := <-pm.chClosePathIfIdle:
178
+ if pa.pendingRequests.Load() == 0 {
179
+ pm.doClosePath(pa)
180
+ }
181
+
182
+ case pa := <-pm.chSetPathReady:
183
+ pm.doSetPathReady(pa)
184
+
185
+ case pa := <-pm.chSetPathNotReady:
186
+ pm.doSetPathNotReady(pa)
187
+
188
+ case req := <-pm.chFindPathConf:
189
+ pm.doFindPathConf(req)
190
+
191
+ case req := <-pm.chDescribe:
192
+ pm.doDescribe(req)
193
+
194
+ case req := <-pm.chAddReader:
195
+ pm.doAddReader(req)
196
+
197
+ case req := <-pm.chAddPublisher:
198
+ pm.doAddPublisher(req)
199
+
200
+ case req := <-pm.chAPIPathsList:
201
+ pm.doAPIPathsList(req)
202
+
203
+ case req := <-pm.chAPIPathsGet:
204
+ pm.doAPIPathsGet(req)
205
+
206
+ case <-pm.ctx.Done():
207
+ break outer
208
+ }
209
+ }
210
+
211
+ pm.ctxCancel()
212
+ }
213
+
214
+ func (pm *pathManager) doReloadConf(newPaths map[string]*conf.Path) {
215
+ confsToRecreate := make(map[string]struct{})
216
+ confsToReload := make(map[string]struct{})
217
+
218
+ for confName, pathConf := range pm.pathConfs {
219
+ if newPath, ok := newPaths[confName]; ok {
220
+ if !newPath.Equal(pathConf) {
221
+ if pathConfCanBeUpdated(pathConf, newPath) {
222
+ confsToReload[confName] = struct{}{}
223
+ } else {
224
+ confsToRecreate[confName] = struct{}{}
225
+ }
226
+ }
227
+ }
228
+ }
229
+
230
+ // process existing paths
231
+ for pathName, pa := range pm.paths {
232
+ newPathConf, _, err := conf.FindPathConf(newPaths, pathName)
233
+ // path does not have a config anymore: delete it
234
+ if err != nil {
235
+ pm.doClosePath(pa)
236
+ continue
237
+ }
238
+
239
+ // path now belongs to a different config
240
+ if newPathConf.Name != pa.confName {
241
+ // path config can be hot reloaded
242
+ oldPathConf := pm.pathConfs[pa.confName]
243
+ if pathConfCanBeUpdated(oldPathConf, newPathConf) {
244
+ pa.confName = newPathConf.Name
245
+ go pa.reloadConf(newPathConf)
246
+ continue
247
+ }
248
+
249
+ // Configuration cannot be hot reloaded: delete the path
250
+ pm.doClosePath(pa)
251
+ continue
252
+ }
253
+
254
+ // path configuration has changed and cannot be hot reloaded: delete path
255
+ if _, ok := confsToRecreate[newPathConf.Name]; ok {
256
+ pm.doClosePath(pa)
257
+ continue
258
+ }
259
+
260
+ // path configuration has changed but can be hot reloaded: reload it
261
+ if _, ok := confsToReload[newPathConf.Name]; ok {
262
+ go pa.reloadConf(newPathConf)
263
+ }
264
+ }
265
+
266
+ pm.pathConfs = newPaths
267
+
268
+ // create new static paths
269
+ for pathConfName, pathConf := range newPaths {
270
+ if pathConf.Regexp == nil {
271
+ if _, ok := pm.paths[pathConfName]; !ok {
272
+ pm.createPath(pathConf, pathConfName, nil)
273
+ }
274
+ }
275
+ }
276
+ }
277
+
278
+ func (pm *pathManager) doClosePath(pa *path) {
279
+ delete(pm.paths, pa.name)
280
+ pa.close()
281
+ pa.wait() // avoid conflicts between sources
282
+ }
283
+
284
+ func (pm *pathManager) doSetHLSServer(m *hls.Server) []defs.Path {
285
+ pm.hlsServer = m
286
+
287
+ var ret []defs.Path
288
+
289
+ for _, pa := range pm.paths {
290
+ if pa.ready {
291
+ ret = append(ret, pa)
292
+ }
293
+ }
294
+
295
+ return ret
296
+ }
297
+
298
+ func (pm *pathManager) doSetPathReady(pa *path) {
299
+ if pa2, ok := pm.paths[pa.name]; !ok || pa2 != pa {
300
+ return
301
+ }
302
+
303
+ pm.paths[pa.name].ready = true
304
+
305
+ if pm.hlsServer != nil {
306
+ pm.hlsServer.PathReady(pa)
307
+ }
308
+ }
309
+
310
+ func (pm *pathManager) doSetPathNotReady(pa *path) {
311
+ if pa2, ok := pm.paths[pa.name]; !ok || pa2 != pa {
312
+ return
313
+ }
314
+
315
+ pm.paths[pa.name].ready = false
316
+
317
+ if pm.hlsServer != nil {
318
+ pm.hlsServer.PathNotReady(pa)
319
+ }
320
+ }
321
+
322
+ func (pm *pathManager) doFindPathConf(req defs.PathFindPathConfReq) {
323
+ pathConf, _, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
324
+ if err != nil {
325
+ req.Res <- defs.PathFindPathConfRes{Err: err}
326
+ return
327
+ }
328
+
329
+ user, err2 := pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
330
+ if err2 != nil {
331
+ req.Res <- defs.PathFindPathConfRes{Err: err2}
332
+ return
333
+ }
334
+
335
+ req.Res <- defs.PathFindPathConfRes{
336
+ Conf: pathConf,
337
+ User: user,
338
+ }
339
+ }
340
+
341
+ func (pm *pathManager) doDescribe(req defs.PathDescribeReq) {
342
+ pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
343
+ if err != nil {
344
+ req.Res <- defs.PathDescribeRes{Err: err}
345
+ return
346
+ }
347
+
348
+ if !req.AccessRequest.SkipAuth {
349
+ _, err2 := pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
350
+ if err2 != nil {
351
+ req.Res <- defs.PathDescribeRes{Err: err2}
352
+ return
353
+ }
354
+ }
355
+
356
+ // create path if it doesn't exist
357
+ if _, ok := pm.paths[req.AccessRequest.Name]; !ok {
358
+ pm.createPath(pathConf, req.AccessRequest.Name, pathMatches)
359
+ }
360
+
361
+ pa := pm.paths[req.AccessRequest.Name]
362
+
363
+ pa.pendingRequests.Add(1)
364
+
365
+ req.Res <- defs.PathDescribeRes{Path: pa}
366
+ }
367
+
368
+ func (pm *pathManager) doAddReader(req defs.PathAddReaderReq) {
369
+ pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
370
+ if err != nil {
371
+ req.Res <- defs.PathAddReaderRes{Err: err}
372
+ return
373
+ }
374
+
375
+ var user string
376
+
377
+ if !req.AccessRequest.SkipAuth {
378
+ var authErr *auth.Error
379
+ user, authErr = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
380
+ if authErr != nil {
381
+ req.Res <- defs.PathAddReaderRes{Err: authErr}
382
+ return
383
+ }
384
+ }
385
+
386
+ // create path if it doesn't exist
387
+ if _, ok := pm.paths[req.AccessRequest.Name]; !ok {
388
+ pm.createPath(pathConf, req.AccessRequest.Name, pathMatches)
389
+ }
390
+
391
+ pa := pm.paths[req.AccessRequest.Name]
392
+
393
+ pa.pendingRequests.Add(1)
394
+
395
+ req.Res <- defs.PathAddReaderRes{
396
+ Path: pa,
397
+ User: user,
398
+ }
399
+ }
400
+
401
+ func (pm *pathManager) doAddPublisher(req defs.PathAddPublisherReq) {
402
+ pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
403
+ if err != nil {
404
+ req.Res <- defs.PathAddPublisherRes{Err: err}
405
+ return
406
+ }
407
+
408
+ if req.ConfToCompare != nil && !pathConf.Equal(req.ConfToCompare) {
409
+ req.Res <- defs.PathAddPublisherRes{Err: fmt.Errorf("configuration has changed")}
410
+ return
411
+ }
412
+
413
+ var user string
414
+
415
+ if !req.AccessRequest.SkipAuth {
416
+ var authErr *auth.Error
417
+ user, authErr = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
418
+ if authErr != nil {
419
+ req.Res <- defs.PathAddPublisherRes{Err: authErr}
420
+ return
421
+ }
422
+ }
423
+
424
+ // create path if it doesn't exist
425
+ if _, ok := pm.paths[req.AccessRequest.Name]; !ok {
426
+ pm.createPath(pathConf, req.AccessRequest.Name, pathMatches)
427
+ }
428
+
429
+ pa := pm.paths[req.AccessRequest.Name]
430
+
431
+ pa.pendingRequests.Add(1)
432
+
433
+ req.Res <- defs.PathAddPublisherRes{
434
+ Path: pa,
435
+ User: user,
436
+ }
437
+ }
438
+
439
+ func (pm *pathManager) doAPIPathsList(req pathAPIPathsListReq) {
440
+ paths := make(map[string]*path)
441
+ maps.Copy(paths, pm.paths)
442
+
443
+ req.res <- pathAPIPathsListRes{paths: paths}
444
+ }
445
+
446
+ func (pm *pathManager) doAPIPathsGet(req pathAPIPathsGetReq) {
447
+ pa, ok := pm.paths[req.name]
448
+ if !ok {
449
+ req.res <- pathAPIPathsGetRes{err: conf.ErrPathNotFound}
450
+ return
451
+ }
452
+
453
+ req.res <- pathAPIPathsGetRes{path: pa}
454
+ }
455
+
456
+ func (pm *pathManager) createPath(
457
+ pathConf *conf.Path,
458
+ name string,
459
+ matches []string,
460
+ ) {
461
+ pa := &path{
462
+ parentCtx: pm.ctx,
463
+ logLevel: pm.logLevel,
464
+ dumpPackets: pm.dumpPackets,
465
+ rtspAddress: pm.rtspAddress,
466
+ readTimeout: pm.readTimeout,
467
+ writeTimeout: pm.writeTimeout,
468
+ writeQueueSize: pm.writeQueueSize,
469
+ udpReadBufferSize: pm.udpReadBufferSize,
470
+ rtpMaxPayloadSize: pm.rtpMaxPayloadSize,
471
+ conf: pathConf,
472
+ name: name,
473
+ matches: matches,
474
+ wg: &pm.wg,
475
+ externalCmdPool: pm.externalCmdPool,
476
+ parent: pm,
477
+ }
478
+ pa.initialize()
479
+ pm.paths[name] = pa
480
+ }
481
+
482
+ // ReloadPathConfs is called by core.
483
+ func (pm *pathManager) ReloadPathConfs(pathConfs map[string]*conf.Path) {
484
+ select {
485
+ case pm.chReloadConf <- pathConfs:
486
+ case <-pm.ctx.Done():
487
+ }
488
+ }
489
+
490
+ // setPathReady is called by path.
491
+ func (pm *pathManager) setPathReady(pa *path) {
492
+ select {
493
+ case pm.chSetPathReady <- pa:
494
+ case <-pm.ctx.Done():
495
+ case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait()
496
+ }
497
+ }
498
+
499
+ // setPathNotReady is called by path.
500
+ func (pm *pathManager) setPathNotReady(pa *path) {
501
+ select {
502
+ case pm.chSetPathNotReady <- pa:
503
+ case <-pm.ctx.Done():
504
+ case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait()
505
+ }
506
+ }
507
+
508
+ // removePath is called by path.
509
+ func (pm *pathManager) removePath(pa *path) {
510
+ select {
511
+ case pm.chRemovePath <- pa:
512
+ case <-pm.ctx.Done():
513
+ case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait()
514
+ }
515
+ }
516
+
517
+ // closePath is called by path.
518
+ func (pm *pathManager) closePathIfIdle(pa *path) {
519
+ select {
520
+ case pm.chClosePathIfIdle <- pa:
521
+ case <-pm.ctx.Done():
522
+ case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait()
523
+ }
524
+ }
525
+
526
+ // FindPathConf is called by a reader or publisher.
527
+ func (pm *pathManager) FindPathConf(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) {
528
+ req.Res = make(chan defs.PathFindPathConfRes)
529
+ select {
530
+ case pm.chFindPathConf <- req:
531
+ res := <-req.Res
532
+
533
+ if res.Err != nil {
534
+ auth.DelayBruteForce(res.Err)
535
+ return nil, res.Err
536
+ }
537
+
538
+ return &res, nil
539
+
540
+ case <-pm.ctx.Done():
541
+ return nil, fmt.Errorf("terminated")
542
+ }
543
+ }
544
+
545
+ // Describe is called by a reader or publisher.
546
+ func (pm *pathManager) Describe(req defs.PathDescribeReq) (*defs.PathDescribeRes, error) {
547
+ req.Res = make(chan defs.PathDescribeRes)
548
+ select {
549
+ case pm.chDescribe <- req:
550
+ res1 := <-req.Res
551
+ if res1.Err != nil {
552
+ auth.DelayBruteForce(res1.Err)
553
+ return nil, res1.Err
554
+ }
555
+
556
+ res2, err := res1.Path.(*path).describe(req)
557
+ if err != nil {
558
+ return nil, err
559
+ }
560
+
561
+ res2.Path = res1.Path
562
+ return res2, nil
563
+
564
+ case <-pm.ctx.Done():
565
+ return nil, fmt.Errorf("terminated")
566
+ }
567
+ }
568
+
569
+ // AddPublisher is called by a publisher.
570
+ func (pm *pathManager) AddPublisher(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) {
571
+ req.Res = make(chan defs.PathAddPublisherRes)
572
+ select {
573
+ case pm.chAddPublisher <- req:
574
+ res1 := <-req.Res
575
+ if res1.Err != nil {
576
+ auth.DelayBruteForce(res1.Err)
577
+ return nil, res1.Err
578
+ }
579
+
580
+ res2, err := res1.Path.(*path).addPublisher(req)
581
+ if err != nil {
582
+ return nil, err
583
+ }
584
+
585
+ res2.Path = res1.Path
586
+ res2.User = res1.User
587
+
588
+ return res2, nil
589
+
590
+ case <-pm.ctx.Done():
591
+ return nil, fmt.Errorf("terminated")
592
+ }
593
+ }
594
+
595
+ // AddReader is called by a reader.
596
+ func (pm *pathManager) AddReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) {
597
+ req.Res = make(chan defs.PathAddReaderRes)
598
+ select {
599
+ case pm.chAddReader <- req:
600
+ res1 := <-req.Res
601
+ if res1.Err != nil {
602
+ auth.DelayBruteForce(res1.Err)
603
+ return nil, res1.Err
604
+ }
605
+
606
+ res2, err := res1.Path.(*path).addReader(req)
607
+ if err != nil {
608
+ return nil, err
609
+ }
610
+
611
+ res2.Path = res1.Path
612
+ res2.User = res1.User
613
+
614
+ return res2, nil
615
+
616
+ case <-pm.ctx.Done():
617
+ return nil, fmt.Errorf("terminated")
618
+ }
619
+ }
620
+
621
+ // SetHLSServer is called by hls.Server.
622
+ func (pm *pathManager) SetHLSServer(s *hls.Server) []defs.Path {
623
+ req := pathSetHLSServerReq{
624
+ s: s,
625
+ res: make(chan pathSetHLSServerRes),
626
+ }
627
+
628
+ select {
629
+ case pm.chSetHLSServer <- req:
630
+ res := <-req.res
631
+ return res.readyPaths
632
+
633
+ case <-pm.ctx.Done():
634
+ return nil
635
+ }
636
+ }
637
+
638
+ // APIPathsList implements defs.APIPathManager.
639
+ func (pm *pathManager) APIPathsList() (*defs.APIPathList, error) {
640
+ req := pathAPIPathsListReq{
641
+ res: make(chan pathAPIPathsListRes),
642
+ }
643
+
644
+ select {
645
+ case pm.chAPIPathsList <- req:
646
+ res := <-req.res
647
+
648
+ res.data = &defs.APIPathList{
649
+ Items: []defs.APIPath{},
650
+ }
651
+
652
+ for _, pa := range res.paths {
653
+ item, err := pa.APIPathsGet(pathAPIPathsGetReq{})
654
+ if err == nil {
655
+ res.data.Items = append(res.data.Items, *item)
656
+ }
657
+ }
658
+
659
+ sort.Slice(res.data.Items, func(i, j int) bool {
660
+ return res.data.Items[i].Name < res.data.Items[j].Name
661
+ })
662
+
663
+ return res.data, nil
664
+
665
+ case <-pm.ctx.Done():
666
+ return nil, fmt.Errorf("terminated")
667
+ }
668
+ }
669
+
670
+ // APIPathsGet implements defs.APIPathManager.
671
+ func (pm *pathManager) APIPathsGet(name string) (*defs.APIPath, error) {
672
+ req := pathAPIPathsGetReq{
673
+ name: name,
674
+ res: make(chan pathAPIPathsGetRes),
675
+ }
676
+
677
+ select {
678
+ case pm.chAPIPathsGet <- req:
679
+ res := <-req.res
680
+ if res.err != nil {
681
+ return nil, res.err
682
+ }
683
+
684
+ data, err := res.path.APIPathsGet(req)
685
+ return data, err
686
+
687
+ case <-pm.ctx.Done():
688
+ return nil, fmt.Errorf("terminated")
689
+ }
690
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager_test.go ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "net/http"
5
+ "regexp"
6
+ "testing"
7
+ "time"
8
+
9
+ "github.com/bluenviron/gortsplib/v5"
10
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
11
+ "github.com/pion/rtp"
12
+ "github.com/stretchr/testify/require"
13
+
14
+ "github.com/bluenviron/mediamtx/internal/conf"
15
+ "github.com/bluenviron/mediamtx/internal/defs"
16
+ "github.com/bluenviron/mediamtx/internal/logger"
17
+ "github.com/bluenviron/mediamtx/internal/test"
18
+ )
19
+
20
+ type dummyPublisher struct{}
21
+
22
+ func (d *dummyPublisher) Close() {}
23
+
24
+ func (d *dummyPublisher) Log(_ logger.Level, _ string, _ ...any) {}
25
+
26
+ func (d *dummyPublisher) APISourceDescribe() *defs.APIPathSource {
27
+ return nil
28
+ }
29
+
30
+ type dummyReader struct{}
31
+
32
+ func (d *dummyReader) Close() {}
33
+
34
+ func (d *dummyReader) Log(_ logger.Level, _ string, _ ...any) {}
35
+
36
+ func (d *dummyReader) APIReaderDescribe() *defs.APIPathReader {
37
+ return nil
38
+ }
39
+
40
+ func TestPathManagerDynamicPathAutoDeletion(t *testing.T) {
41
+ for _, ca := range []string{"describe", "add reader"} {
42
+ t.Run(ca, func(t *testing.T) {
43
+ pathConfs := map[string]*conf.Path{
44
+ "all_others": {
45
+ Regexp: regexp.MustCompile("^.*$"),
46
+ Name: "all_others",
47
+ Source: "publisher",
48
+ },
49
+ }
50
+
51
+ pm := &pathManager{
52
+ authManager: test.NilAuthManager,
53
+ pathConfs: pathConfs,
54
+ parent: test.NilLogger,
55
+ }
56
+ pm.initialize()
57
+ defer pm.close()
58
+
59
+ func() {
60
+ if ca == "describe" {
61
+ _, err := pm.Describe(defs.PathDescribeReq{
62
+ AccessRequest: defs.PathAccessRequest{
63
+ Name: "mypath",
64
+ },
65
+ })
66
+ require.EqualError(t, err, "no stream is available on path 'mypath'")
67
+ } else {
68
+ _, err := pm.AddReader(defs.PathAddReaderReq{
69
+ Author: &dummyReader{},
70
+ AccessRequest: defs.PathAccessRequest{
71
+ Name: "mypath",
72
+ },
73
+ })
74
+ require.EqualError(t, err, "no stream is available on path 'mypath'")
75
+ }
76
+ }()
77
+
78
+ time.Sleep(100 * time.Millisecond)
79
+
80
+ data, err := pm.APIPathsList()
81
+ require.NoError(t, err)
82
+
83
+ require.Empty(t, data.Items)
84
+ })
85
+ }
86
+ }
87
+
88
+ func TestPathManagerDynamicPathDescribeAndPublish(t *testing.T) {
89
+ pathConfs := map[string]*conf.Path{
90
+ "all_others": {
91
+ Regexp: regexp.MustCompile("^.*$"),
92
+ Name: "all_others",
93
+ Source: "publisher",
94
+ },
95
+ }
96
+
97
+ pm := &pathManager{
98
+ authManager: test.NilAuthManager,
99
+ pathConfs: pathConfs,
100
+ parent: test.NilLogger,
101
+ }
102
+ pm.initialize()
103
+ defer pm.close()
104
+
105
+ go func() {
106
+ for range 10 {
107
+ pm.Describe(defs.PathDescribeReq{ //nolint:errcheck
108
+ AccessRequest: defs.PathAccessRequest{
109
+ Name: "mypath",
110
+ },
111
+ })
112
+ }
113
+ }()
114
+
115
+ _, err := pm.AddPublisher(defs.PathAddPublisherReq{
116
+ Author: &dummyPublisher{},
117
+ Desc: &description.Session{},
118
+ AccessRequest: defs.PathAccessRequest{
119
+ Name: "mypath",
120
+ },
121
+ })
122
+ require.NoError(t, err)
123
+ }
124
+
125
+ func TestPathManagerConfigHotReload(t *testing.T) {
126
+ // Start MediaMTX with basic configuration
127
+ p, ok := newInstance(t, "api: yes\n"+
128
+ "paths:\n"+
129
+ " all:\n"+
130
+ " record: no\n")
131
+ require.Equal(t, true, ok)
132
+ defer p.Close()
133
+
134
+ // Set up HTTP client for API calls
135
+ tr := &http.Transport{}
136
+ defer tr.CloseIdleConnections()
137
+ hc := &http.Client{Transport: tr}
138
+
139
+ // Create a publisher that will use the "all" configuration
140
+ media0 := test.UniqueMediaH264()
141
+ source := gortsplib.Client{}
142
+ err := source.StartRecording(
143
+ "rtsp://localhost:8554/undefined_stream",
144
+ &description.Session{Medias: []*description.Media{media0}})
145
+ require.NoError(t, err)
146
+ defer source.Close()
147
+
148
+ // Send some data to establish the stream
149
+ err = source.WritePacketRTP(media0, &rtp.Packet{
150
+ Header: rtp.Header{
151
+ Version: 2,
152
+ PayloadType: 96,
153
+ },
154
+ Payload: []byte{5, 1, 2, 3, 4},
155
+ })
156
+ require.NoError(t, err)
157
+
158
+ time.Sleep(100 * time.Millisecond)
159
+
160
+ // Verify the path exists and is using the "all" configuration
161
+ pathData, err := p.pathManager.APIPathsGet("undefined_stream")
162
+ require.NoError(t, err)
163
+ require.Equal(t, "undefined_stream", pathData.Name)
164
+ require.Equal(t, "all", pathData.ConfName)
165
+
166
+ // Check the current configuration via API
167
+ var allConfig map[string]any
168
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/config/paths/get/all", nil, &allConfig)
169
+ require.Equal(t, false, allConfig["record"]) // Should be false from "all" config
170
+
171
+ // Add a new specific configuration for "undefined_stream" with record enabled
172
+ httpRequest(t, hc, http.MethodPost, "http://localhost:9997/v3/config/paths/add/undefined_stream",
173
+ map[string]any{
174
+ "record": true,
175
+ }, nil)
176
+
177
+ // Give the system time to process the configuration change
178
+ time.Sleep(200 * time.Millisecond)
179
+
180
+ // Verify the path now uses the new specific configuration
181
+ pathData, err = p.pathManager.APIPathsGet("undefined_stream")
182
+ require.NoError(t, err)
183
+ require.Equal(t, "undefined_stream", pathData.Name)
184
+ require.Equal(t, "undefined_stream", pathData.ConfName) // Should now use the specific config
185
+
186
+ // Check the new configuration via API
187
+ var newConfig map[string]any
188
+ httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/config/paths/get/undefined_stream", nil, &newConfig)
189
+ require.Equal(t, true, newConfig["record"]) // Should be true from new config
190
+
191
+ // Verify the stream is still active and working
192
+ err = source.WritePacketRTP(media0, &rtp.Packet{
193
+ Header: rtp.Header{
194
+ Version: 2,
195
+ PayloadType: 96,
196
+ SequenceNumber: 2,
197
+ },
198
+ Payload: []byte{5, 1, 2, 3, 4},
199
+ })
200
+ require.NoError(t, err)
201
+
202
+ // Verify the path is still ready and functional
203
+ require.Equal(t, true, pathData.Ready)
204
+
205
+ // revert configuration
206
+ httpRequest(t, hc, http.MethodDelete, "http://localhost:9997/v3/config/paths/delete/undefined_stream",
207
+ nil, nil)
208
+
209
+ // Give the system time to process the configuration change
210
+ time.Sleep(200 * time.Millisecond)
211
+
212
+ // Verify the path now uses the old configuration
213
+ pathData, err = p.pathManager.APIPathsGet("undefined_stream")
214
+ require.NoError(t, err)
215
+ require.Equal(t, "undefined_stream", pathData.Name)
216
+ require.Equal(t, "all", pathData.ConfName)
217
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_test.go ADDED
@@ -0,0 +1,1035 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "bufio"
5
+ "context"
6
+ "crypto/tls"
7
+ "fmt"
8
+ "net"
9
+ "net/http"
10
+ "net/url"
11
+ "os"
12
+ "path/filepath"
13
+ "strings"
14
+ "testing"
15
+ "time"
16
+
17
+ "github.com/bluenviron/gortmplib"
18
+ "github.com/bluenviron/gortsplib/v5"
19
+ "github.com/bluenviron/gortsplib/v5/pkg/base"
20
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
21
+ "github.com/bluenviron/gortsplib/v5/pkg/headers"
22
+ "github.com/bluenviron/gortsplib/v5/pkg/sdp"
23
+ srt "github.com/datarhei/gosrt"
24
+ "github.com/pion/rtp"
25
+ "github.com/stretchr/testify/require"
26
+
27
+ "github.com/bluenviron/mediamtx/internal/defs"
28
+ "github.com/bluenviron/mediamtx/internal/protocols/whip"
29
+ "github.com/bluenviron/mediamtx/internal/test"
30
+ )
31
+
32
+ type testServer struct {
33
+ onDescribe func(*gortsplib.ServerHandlerOnDescribeCtx) (*base.Response, *gortsplib.ServerStream, error)
34
+ onSetup func(*gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error)
35
+ onPlay func(*gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error)
36
+ }
37
+
38
+ func (sh *testServer) OnDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx,
39
+ ) (*base.Response, *gortsplib.ServerStream, error) {
40
+ return sh.onDescribe(ctx)
41
+ }
42
+
43
+ func (sh *testServer) OnSetup(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
44
+ return sh.onSetup(ctx)
45
+ }
46
+
47
+ func (sh *testServer) OnPlay(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
48
+ return sh.onPlay(ctx)
49
+ }
50
+
51
+ var _ defs.Path = &path{}
52
+
53
+ func TestPathRunOnDemand(t *testing.T) {
54
+ for _, ca := range []string{"describe", "setup", "describe and setup"} {
55
+ t.Run(ca, func(t *testing.T) {
56
+ onDemand := filepath.Join(t.TempDir(), "on_demand")
57
+ onUnDemand := filepath.Join(t.TempDir(), "on_undemand")
58
+
59
+ p1, ok := newInstance(t, fmt.Sprintf("rtmp: no\n"+
60
+ "hls: no\n"+
61
+ "webrtc: no\n"+
62
+ "paths:\n"+
63
+ " '~^(on)demand$':\n"+
64
+ " runOnDemand: sh -c \"ON_DEMAND=%s go run ./test_on_demand/main.go\"\n"+
65
+ " runOnDemandCloseAfter: 1s\n"+
66
+ " runOnUnDemand: touch %s\n", onDemand, onUnDemand))
67
+ require.Equal(t, true, ok)
68
+ defer p1.Close()
69
+
70
+ var control string
71
+
72
+ func() {
73
+ conn, err := net.Dial("tcp", "localhost:8554")
74
+ require.NoError(t, err)
75
+ defer conn.Close()
76
+ br := bufio.NewReader(conn)
77
+
78
+ if ca == "describe" || ca == "describe and setup" {
79
+ var u *base.URL
80
+ u, err = base.ParseURL("rtsp://localhost:8554/ondemand?key1=val1&key2=val2")
81
+ require.NoError(t, err)
82
+
83
+ byts, _ := base.Request{
84
+ Method: base.Describe,
85
+ URL: u,
86
+ Header: base.Header{
87
+ "CSeq": base.HeaderValue{"1"},
88
+ },
89
+ }.Marshal()
90
+ _, err = conn.Write(byts)
91
+ require.NoError(t, err)
92
+
93
+ var res base.Response
94
+ err = res.Unmarshal(br)
95
+ require.NoError(t, err)
96
+ require.Equal(t, base.StatusOK, res.StatusCode)
97
+
98
+ var desc sdp.SessionDescription
99
+ err = desc.Unmarshal(res.Body)
100
+ require.NoError(t, err)
101
+ control, _ = desc.MediaDescriptions[0].Attribute("control")
102
+ control = "rtsp://localhost:8554/ondemand?key1=val1&key2=val2/" + control
103
+ } else {
104
+ control = "rtsp://localhost:8554/ondemand?key1=val1&key2=val2/"
105
+ }
106
+
107
+ if ca == "setup" || ca == "describe and setup" {
108
+ var u *base.URL
109
+ u, err = base.ParseURL(control)
110
+ require.NoError(t, err)
111
+
112
+ byts, _ := base.Request{
113
+ Method: base.Setup,
114
+ URL: u,
115
+ Header: base.Header{
116
+ "CSeq": base.HeaderValue{"2"},
117
+ "Transport": headers.Transport{
118
+ Mode: func() *headers.TransportMode {
119
+ v := headers.TransportModePlay
120
+ return &v
121
+ }(),
122
+ Protocol: headers.TransportProtocolTCP,
123
+ InterleavedIDs: &[2]int{0, 1},
124
+ }.Marshal(),
125
+ },
126
+ }.Marshal()
127
+ _, err = conn.Write(byts)
128
+ require.NoError(t, err)
129
+
130
+ var res base.Response
131
+ err = res.Unmarshal(br)
132
+ require.NoError(t, err)
133
+ require.Equal(t, base.StatusOK, res.StatusCode)
134
+ }
135
+ }()
136
+
137
+ for {
138
+ _, err := os.Stat(onUnDemand)
139
+ if err == nil {
140
+ break
141
+ }
142
+ time.Sleep(100 * time.Millisecond)
143
+ }
144
+
145
+ _, err := os.Stat(onDemand)
146
+ require.NoError(t, err)
147
+ })
148
+ }
149
+ }
150
+
151
+ func TestPathRunOnConnect(t *testing.T) {
152
+ serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
153
+ serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
154
+
155
+ for _, ca := range []string{"rtsp", "rtsps", "rtmp", "rtmps", "srt"} {
156
+ t.Run(ca, func(t *testing.T) {
157
+ onConnect := filepath.Join(t.TempDir(), "on_connect")
158
+ onDisconnect := filepath.Join(t.TempDir(), "on_disconnect")
159
+
160
+ connType := ""
161
+
162
+ func() {
163
+ p, ok := newInstance(t, fmt.Sprintf(
164
+ "rtspEncryption: optional\n"+
165
+ "rtspServerCert: "+serverCertFpath+"\n"+
166
+ "rtspServerKey: "+serverKeyFpath+"\n"+
167
+ "rtmpEncryption: optional\n"+
168
+ "rtmpServerCert: "+serverCertFpath+"\n"+
169
+ "rtmpServerKey: "+serverKeyFpath+"\n"+
170
+ "paths:\n"+
171
+ " test:\n"+
172
+ "runOnConnect: sh -c 'echo \"$MTX_CONN_TYPE $MTX_CONN_ID $RTSP_PORT\" > %s'\n"+
173
+ "runOnDisconnect: sh -c 'echo \"$MTX_CONN_TYPE $MTX_CONN_ID $RTSP_PORT\" > %s'\n",
174
+ onConnect, onDisconnect))
175
+ require.Equal(t, true, ok)
176
+ defer p.Close()
177
+
178
+ switch ca {
179
+ case "rtsp":
180
+ connType = "rtspConn"
181
+
182
+ c := gortsplib.Client{}
183
+
184
+ err := c.StartRecording(
185
+ "rtsp://localhost:8554/test",
186
+ &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
187
+ require.NoError(t, err)
188
+ defer c.Close()
189
+
190
+ case "rtsps":
191
+ connType = "rtspsConn"
192
+
193
+ c := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}}
194
+
195
+ err := c.StartRecording(
196
+ "rtsps://localhost:8322/test",
197
+ &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
198
+ require.NoError(t, err)
199
+ defer c.Close()
200
+
201
+ case "rtmp":
202
+ connType = "rtmpConn"
203
+
204
+ var u *url.URL
205
+ u, err := url.Parse("rtmp://127.0.0.1:1935/test")
206
+ require.NoError(t, err)
207
+
208
+ conn := &gortmplib.Client{
209
+ URL: u,
210
+ Publish: true,
211
+ }
212
+ err = conn.Initialize(context.Background())
213
+ require.NoError(t, err)
214
+ defer conn.Close()
215
+
216
+ case "rtmps":
217
+ connType = "rtmpsConn"
218
+
219
+ var u *url.URL
220
+ u, err := url.Parse("rtmps://127.0.0.1:1936/test")
221
+ require.NoError(t, err)
222
+
223
+ conn := &gortmplib.Client{
224
+ URL: u,
225
+ Publish: true,
226
+ TLSConfig: &tls.Config{InsecureSkipVerify: true},
227
+ }
228
+ err = conn.Initialize(context.Background())
229
+ require.NoError(t, err)
230
+ defer conn.Close()
231
+
232
+ case "srt":
233
+ connType = "srtConn"
234
+
235
+ conf := srt.DefaultConfig()
236
+ var address string
237
+ address, err := conf.UnmarshalURL("srt://localhost:8890?streamid=publish:test")
238
+ require.NoError(t, err)
239
+
240
+ err = conf.Validate()
241
+ require.NoError(t, err)
242
+
243
+ var c srt.Conn
244
+ c, err = srt.Dial("srt", address, conf)
245
+ require.NoError(t, err)
246
+ defer c.Close()
247
+ }
248
+
249
+ time.Sleep(500 * time.Millisecond)
250
+ }()
251
+
252
+ var byts []byte
253
+ byts, err := os.ReadFile(onConnect)
254
+ require.NoError(t, err)
255
+ fields := strings.Split(string(byts[:len(byts)-1]), " ")
256
+ require.Equal(t, connType, fields[0])
257
+ require.NotEmpty(t, fields[1])
258
+ require.Equal(t, "8554", fields[2])
259
+
260
+ byts, err = os.ReadFile(onDisconnect)
261
+ require.NoError(t, err)
262
+ fields = strings.Split(string(byts[:len(byts)-1]), " ")
263
+ require.Equal(t, connType, fields[0])
264
+ require.NotEmpty(t, fields[1])
265
+ require.Equal(t, "8554", fields[2])
266
+ })
267
+ }
268
+ }
269
+
270
+ func TestPathRunOnReady(t *testing.T) {
271
+ onReady := filepath.Join(t.TempDir(), "on_ready")
272
+ onNotReady := filepath.Join(t.TempDir(), "on_unready")
273
+
274
+ func() {
275
+ p, ok := newInstance(t, fmt.Sprintf("rtmp: no\n"+
276
+ "hls: no\n"+
277
+ "webrtc: no\n"+
278
+ "paths:\n"+
279
+ " ~te(st):\n"+
280
+ " runOnReady: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_SOURCE_TYPE $MTX_SOURCE_ID $RTSP_PORT $G1\" > %s'\n"+
281
+ " runOnNotReady: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_SOURCE_TYPE $MTX_SOURCE_ID $RTSP_PORT $G1\" > %s'\n",
282
+ onReady, onNotReady))
283
+ require.Equal(t, true, ok)
284
+ defer p.Close()
285
+
286
+ c := gortsplib.Client{}
287
+
288
+ err := c.StartRecording(
289
+ "rtsp://localhost:8554/test?query=value",
290
+ &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
291
+ require.NoError(t, err)
292
+ defer c.Close()
293
+
294
+ time.Sleep(500 * time.Millisecond)
295
+ }()
296
+
297
+ byts, err := os.ReadFile(onReady)
298
+ require.NoError(t, err)
299
+ fields := strings.Split(string(byts[:len(byts)-1]), " ")
300
+ require.Equal(t, "test", fields[0])
301
+ require.Equal(t, "query%3Dvalue", fields[1])
302
+ require.Equal(t, "rtspSession", fields[2])
303
+ require.NotEmpty(t, fields[3])
304
+ require.Equal(t, "8554", fields[4])
305
+ require.Equal(t, "st", fields[5])
306
+
307
+ byts, err = os.ReadFile(onNotReady)
308
+ require.NoError(t, err)
309
+ fields = strings.Split(string(byts[:len(byts)-1]), " ")
310
+ require.Equal(t, "test", fields[0])
311
+ require.Equal(t, "query%3Dvalue", fields[1])
312
+ require.Equal(t, "rtspSession", fields[2])
313
+ require.NotEmpty(t, fields[3])
314
+ require.Equal(t, "8554", fields[4])
315
+ require.Equal(t, "st", fields[5])
316
+ }
317
+
318
+ func TestPathRunOnReadyQueryInjection(t *testing.T) {
319
+ sentinel := filepath.Join(t.TempDir(), "mediamtx_test_query_injection_sentinel")
320
+
321
+ for _, ca := range []struct {
322
+ name string
323
+ cmdstr string
324
+ query string
325
+ }{
326
+ {
327
+ // $(…) inside double quotes still triggers command substitution.
328
+ // ${IFS} expands to a space, avoiding a literal space in the query string.
329
+ name: "command substitution dollar",
330
+ cmdstr: "sh -c 'echo \"$MTX_QUERY\"'",
331
+ query: "$(touch${IFS}" + sentinel + "1)",
332
+ },
333
+ {
334
+ // > in an unquoted expansion redirects echo's output, creating the file.
335
+ name: "redirect",
336
+ cmdstr: "sh -c 'echo $MTX_QUERY'",
337
+ query: ">" + sentinel + "2",
338
+ },
339
+ {
340
+ // & in an unquoted expansion backgrounds echo and runs touch directly.
341
+ // ${IFS} expands to a space, avoiding a literal space in the query string.
342
+ name: "and operator",
343
+ cmdstr: "sh -c 'echo $MTX_QUERY'",
344
+ query: "&touch${IFS}" + sentinel + "3",
345
+ },
346
+ } {
347
+ t.Run(ca.name, func(t *testing.T) {
348
+ p, ok := newInstance(t, fmt.Sprintf(
349
+ "rtmp: no\nhls: no\nwebrtc: no\npaths:\n test:\n runOnReady: %s\n",
350
+ ca.cmdstr))
351
+ require.Equal(t, true, ok)
352
+ defer p.Close()
353
+
354
+ c := gortsplib.Client{}
355
+ err := c.StartRecording(
356
+ "rtsp://localhost:8554/test?"+ca.query,
357
+ &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
358
+ require.NoError(t, err)
359
+ defer c.Close()
360
+
361
+ time.Sleep(500 * time.Millisecond)
362
+
363
+ _, statErr := os.Stat(sentinel)
364
+ require.ErrorIs(t, statErr, os.ErrNotExist)
365
+ })
366
+ }
367
+ }
368
+
369
+ func TestPathRunOnRead(t *testing.T) {
370
+ serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
371
+ serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
372
+
373
+ for _, ca := range []string{"rtsp", "rtsps", "rtmp", "rtmps", "srt", "webrtc"} {
374
+ t.Run(ca, func(t *testing.T) {
375
+ onRead := filepath.Join(t.TempDir(), "on_read")
376
+ onUnread := filepath.Join(t.TempDir(), "on_unread")
377
+
378
+ func() {
379
+ p, ok := newInstance(t, fmt.Sprintf(
380
+ "rtspEncryption: optional\n"+
381
+ "rtspServerCert: "+serverCertFpath+"\n"+
382
+ "rtspServerKey: "+serverKeyFpath+"\n"+
383
+ "rtmpEncryption: optional\n"+
384
+ "rtmpServerCert: "+serverCertFpath+"\n"+
385
+ "rtmpServerKey: "+serverKeyFpath+"\n"+
386
+ "paths:\n"+
387
+ " ~te(st):\n"+
388
+ " runOnRead: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_READER_TYPE $MTX_READER_ID $RTSP_PORT $G1\" > %s'\n"+
389
+ " runOnUnread: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_READER_TYPE $MTX_READER_ID $RTSP_PORT $G1\" > %s'\n",
390
+ onRead, onUnread))
391
+ require.Equal(t, true, ok)
392
+ defer p.Close()
393
+
394
+ media0 := test.UniqueMediaH264()
395
+
396
+ source := gortsplib.Client{}
397
+
398
+ err := source.StartRecording(
399
+ "rtsp://localhost:8554/test",
400
+ &description.Session{Medias: []*description.Media{media0}})
401
+ require.NoError(t, err)
402
+ defer source.Close()
403
+
404
+ writerDone := make(chan struct{})
405
+ defer func() { <-writerDone }()
406
+
407
+ writerTerminate := make(chan struct{})
408
+ defer close(writerTerminate)
409
+
410
+ go func() {
411
+ defer close(writerDone)
412
+ i := 0
413
+ for {
414
+ select {
415
+ case <-time.After(100 * time.Millisecond):
416
+ case <-writerTerminate:
417
+ return
418
+ }
419
+ err2 := source.WritePacketRTP(media0, &rtp.Packet{
420
+ Header: rtp.Header{
421
+ Version: 2,
422
+ Marker: true,
423
+ PayloadType: 96,
424
+ SequenceNumber: uint16(123 + i),
425
+ Timestamp: uint32(45343 + i*90000),
426
+ SSRC: 563423,
427
+ },
428
+ Payload: []byte{5},
429
+ })
430
+ require.NoError(t, err2)
431
+ i++
432
+ }
433
+ }()
434
+
435
+ switch ca {
436
+ case "rtsp":
437
+ var u *base.URL
438
+ u, err = base.ParseURL("rtsp://127.0.0.1:8554/test?query=value")
439
+ require.NoError(t, err)
440
+
441
+ reader := gortsplib.Client{
442
+ Scheme: u.Scheme,
443
+ Host: u.Host,
444
+ }
445
+
446
+ err = reader.Start()
447
+ require.NoError(t, err)
448
+ defer reader.Close()
449
+
450
+ var desc *description.Session
451
+ desc, _, err = reader.Describe(u)
452
+ require.NoError(t, err)
453
+
454
+ err = reader.SetupAll(desc.BaseURL, desc.Medias)
455
+ require.NoError(t, err)
456
+
457
+ _, err = reader.Play(nil)
458
+ require.NoError(t, err)
459
+
460
+ case "rtsps":
461
+ var u *base.URL
462
+ u, err = base.ParseURL("rtsps://127.0.0.1:8322/test?query=value")
463
+ require.NoError(t, err)
464
+
465
+ reader := gortsplib.Client{
466
+ Scheme: u.Scheme,
467
+ Host: u.Host,
468
+ TLSConfig: &tls.Config{InsecureSkipVerify: true},
469
+ }
470
+
471
+ err = reader.Start()
472
+ require.NoError(t, err)
473
+ defer reader.Close()
474
+
475
+ var desc *description.Session
476
+ desc, _, err = reader.Describe(u)
477
+ require.NoError(t, err)
478
+
479
+ err = reader.SetupAll(desc.BaseURL, desc.Medias)
480
+ require.NoError(t, err)
481
+
482
+ _, err = reader.Play(nil)
483
+ require.NoError(t, err)
484
+
485
+ case "rtmp":
486
+ var u *url.URL
487
+ u, err = url.Parse("rtmp://127.0.0.1:1935/test?query=value")
488
+ require.NoError(t, err)
489
+
490
+ conn := &gortmplib.Client{
491
+ URL: u,
492
+ Publish: false,
493
+ }
494
+ err = conn.Initialize(context.Background())
495
+ require.NoError(t, err)
496
+ defer conn.Close()
497
+
498
+ r := &gortmplib.Reader{
499
+ Conn: conn,
500
+ }
501
+ err = r.Initialize()
502
+ require.NoError(t, err)
503
+
504
+ case "rtmps":
505
+ var u *url.URL
506
+ u, err = url.Parse("rtmps://127.0.0.1:1936/test?query=value")
507
+ require.NoError(t, err)
508
+
509
+ conn := &gortmplib.Client{
510
+ URL: u,
511
+ Publish: false,
512
+ TLSConfig: &tls.Config{InsecureSkipVerify: true},
513
+ }
514
+ err = conn.Initialize(context.Background())
515
+ require.NoError(t, err)
516
+ defer conn.Close()
517
+
518
+ go func() {
519
+ for i := range uint16(3) {
520
+ err2 := source.WritePacketRTP(media0, &rtp.Packet{
521
+ Header: rtp.Header{
522
+ Version: 2,
523
+ Marker: true,
524
+ PayloadType: 96,
525
+ SequenceNumber: 123 + i,
526
+ Timestamp: 45343 + uint32(i)*2*90000,
527
+ SSRC: 563423,
528
+ },
529
+ Payload: []byte{5},
530
+ })
531
+ require.NoError(t, err2)
532
+ }
533
+ }()
534
+
535
+ r := &gortmplib.Reader{
536
+ Conn: conn,
537
+ }
538
+ err = r.Initialize()
539
+ require.NoError(t, err)
540
+
541
+ case "srt":
542
+ conf := srt.DefaultConfig()
543
+ var address string
544
+ address, err = conf.UnmarshalURL("srt://localhost:8890?streamid=read:test:query=value")
545
+ require.NoError(t, err)
546
+
547
+ err = conf.Validate()
548
+ require.NoError(t, err)
549
+
550
+ var reader srt.Conn
551
+ reader, err = srt.Dial("srt", address, conf)
552
+ require.NoError(t, err)
553
+ defer reader.Close()
554
+
555
+ case "webrtc":
556
+ tr := &http.Transport{}
557
+ defer tr.CloseIdleConnections()
558
+ hc := &http.Client{Transport: tr}
559
+
560
+ var u *url.URL
561
+ u, err = url.Parse("http://localhost:8889/test/whep?query=value")
562
+ require.NoError(t, err)
563
+
564
+ c := &whip.Client{
565
+ HTTPClient: hc,
566
+ URL: u,
567
+ Log: test.NilLogger,
568
+ }
569
+
570
+ err = c.Initialize(context.Background())
571
+ require.NoError(t, err)
572
+ defer checkClose(t, c.Close)
573
+ }
574
+
575
+ time.Sleep(500 * time.Millisecond)
576
+ }()
577
+
578
+ var readerType string
579
+
580
+ switch ca {
581
+ case "rtsp":
582
+ readerType = "rtspSession"
583
+ case "rtsps":
584
+ readerType = "rtspsSession"
585
+ case "rtmp":
586
+ readerType = "rtmpConn"
587
+ case "rtmps":
588
+ readerType = "rtmpsConn"
589
+ case "srt":
590
+ readerType = "srtConn"
591
+ case "webrtc":
592
+ readerType = "webRTCSession"
593
+ }
594
+
595
+ var byts []byte
596
+ byts, err := os.ReadFile(onRead)
597
+ require.NoError(t, err)
598
+ fields := strings.Split(string(byts[:len(byts)-1]), " ")
599
+ require.Equal(t, "test", fields[0])
600
+ require.Equal(t, "query%3Dvalue", fields[1])
601
+ require.Equal(t, readerType, fields[2])
602
+ require.NotEmpty(t, fields[3])
603
+ require.Equal(t, "8554", fields[4])
604
+ require.Equal(t, "st", fields[5])
605
+
606
+ byts, err = os.ReadFile(onUnread)
607
+ require.NoError(t, err)
608
+ fields = strings.Split(string(byts[:len(byts)-1]), " ")
609
+ require.Equal(t, "test", fields[0])
610
+ require.Equal(t, "query%3Dvalue", fields[1])
611
+ require.Equal(t, readerType, fields[2])
612
+ require.NotEmpty(t, fields[3])
613
+ require.Equal(t, "8554", fields[4])
614
+ require.Equal(t, "st", fields[5])
615
+ })
616
+ }
617
+ }
618
+
619
+ func TestPathRunOnRecordSegment(t *testing.T) {
620
+ onRecordSegmentCreate := filepath.Join(t.TempDir(), "on_record_segment_create")
621
+ onRecordSegmentComplete := filepath.Join(t.TempDir(), "on_record_segment_complete")
622
+
623
+ recordDir := t.TempDir()
624
+ var err error
625
+
626
+ func() {
627
+ p, ok := newInstance(t, fmt.Sprintf("record: yes\n"+
628
+ "recordPath: %s\n"+
629
+ "paths:\n"+
630
+ " test:\n"+
631
+ " runOnRecordSegmentCreate: sh -c 'echo \"$MTX_SEGMENT_PATH $RTSP_PORT\" > %s'\n"+
632
+ " runOnRecordSegmentComplete: sh -c 'echo \"$MTX_SEGMENT_PATH $MTX_SEGMENT_DURATION $RTSP_PORT\" > %s'\n",
633
+ filepath.Join(recordDir, "%path/%Y-%m-%d_%H-%M-%S-%f"),
634
+ onRecordSegmentCreate,
635
+ onRecordSegmentComplete,
636
+ ))
637
+ require.Equal(t, true, ok)
638
+ defer p.Close()
639
+
640
+ media0 := test.UniqueMediaH264()
641
+
642
+ source := gortsplib.Client{}
643
+
644
+ err = source.StartRecording(
645
+ "rtsp://localhost:8554/test",
646
+ &description.Session{Medias: []*description.Media{media0}})
647
+ require.NoError(t, err)
648
+ defer source.Close()
649
+
650
+ for i := range 4 {
651
+ err = source.WritePacketRTP(media0, &rtp.Packet{
652
+ Header: rtp.Header{
653
+ Version: 2,
654
+ Marker: true,
655
+ PayloadType: 96,
656
+ SequenceNumber: 1123 + uint16(i),
657
+ Timestamp: 45343 + 90000*uint32(i),
658
+ SSRC: 563423,
659
+ },
660
+ Payload: []byte{5},
661
+ })
662
+ require.NoError(t, err)
663
+ }
664
+
665
+ time.Sleep(500 * time.Millisecond)
666
+ }()
667
+
668
+ byts, err := os.ReadFile(onRecordSegmentCreate)
669
+ require.NoError(t, err)
670
+ fields := strings.Split(string(byts[:len(byts)-1]), " ")
671
+ require.True(t, strings.HasPrefix(fields[0], recordDir))
672
+ require.Equal(t, "8554", fields[1])
673
+
674
+ byts, err = os.ReadFile(onRecordSegmentComplete)
675
+ require.NoError(t, err)
676
+ fields = strings.Split(string(byts[:len(byts)-1]), " ")
677
+ require.True(t, strings.HasPrefix(fields[0], recordDir))
678
+ require.Equal(t, "3", fields[1])
679
+ require.Equal(t, "8554", fields[2])
680
+ }
681
+
682
+ func TestPathMaxReaders(t *testing.T) {
683
+ p, ok := newInstance(t, "paths:\n"+
684
+ " all_others:\n"+
685
+ " maxReaders: 1\n")
686
+ require.Equal(t, true, ok)
687
+ defer p.Close()
688
+
689
+ source := gortsplib.Client{}
690
+
691
+ err := source.StartRecording(
692
+ "rtsp://localhost:8554/mystream",
693
+ &description.Session{Medias: []*description.Media{
694
+ test.UniqueMediaH264(),
695
+ test.UniqueMediaMPEG4Audio(),
696
+ }})
697
+ require.NoError(t, err)
698
+ defer source.Close()
699
+
700
+ for i := range 2 {
701
+ var u *base.URL
702
+ u, err = base.ParseURL("rtsp://127.0.0.1:8554/mystream")
703
+ require.NoError(t, err)
704
+
705
+ reader := gortsplib.Client{
706
+ Scheme: u.Scheme,
707
+ Host: u.Host,
708
+ }
709
+
710
+ err = reader.Start()
711
+ require.NoError(t, err)
712
+ defer reader.Close()
713
+
714
+ var desc *description.Session
715
+ desc, _, err = reader.Describe(u)
716
+ require.NoError(t, err)
717
+
718
+ err = reader.SetupAll(desc.BaseURL, desc.Medias)
719
+ if i != 1 {
720
+ require.NoError(t, err)
721
+ } else {
722
+ require.Error(t, err)
723
+ }
724
+ }
725
+ }
726
+
727
+ func TestPathRecord(t *testing.T) {
728
+ dir := t.TempDir()
729
+
730
+ p, ok := newInstance(t, "api: yes\n"+
731
+ "record: yes\n"+
732
+ "recordPath: "+filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f")+"\n"+
733
+ "paths:\n"+
734
+ " all_others:\n"+
735
+ " record: yes\n")
736
+ require.Equal(t, true, ok)
737
+ defer p.Close()
738
+
739
+ media0 := test.UniqueMediaH264()
740
+
741
+ source := gortsplib.Client{}
742
+
743
+ err := source.StartRecording(
744
+ "rtsp://localhost:8554/mystream",
745
+ &description.Session{Medias: []*description.Media{media0}})
746
+ require.NoError(t, err)
747
+ defer source.Close()
748
+
749
+ for i := range 4 {
750
+ err = source.WritePacketRTP(media0, &rtp.Packet{
751
+ Header: rtp.Header{
752
+ Version: 2,
753
+ Marker: true,
754
+ PayloadType: 96,
755
+ SequenceNumber: 1123 + uint16(i),
756
+ Timestamp: 45343 + 90000*uint32(i),
757
+ SSRC: 563423,
758
+ },
759
+ Payload: []byte{5},
760
+ })
761
+ require.NoError(t, err)
762
+ }
763
+
764
+ time.Sleep(500 * time.Millisecond)
765
+
766
+ files, err := os.ReadDir(filepath.Join(dir, "mystream"))
767
+ require.NoError(t, err)
768
+ require.Equal(t, 1, len(files))
769
+
770
+ tr := &http.Transport{}
771
+ defer tr.CloseIdleConnections()
772
+ hc := &http.Client{Transport: tr}
773
+
774
+ httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/paths/patch/all_others", map[string]any{
775
+ "record": false,
776
+ }, nil)
777
+
778
+ time.Sleep(500 * time.Millisecond)
779
+
780
+ httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/paths/patch/all_others", map[string]any{
781
+ "record": true,
782
+ }, nil)
783
+
784
+ time.Sleep(500 * time.Millisecond)
785
+
786
+ for i := 4; i < 8; i++ {
787
+ err = source.WritePacketRTP(media0, &rtp.Packet{
788
+ Header: rtp.Header{
789
+ Version: 2,
790
+ Marker: true,
791
+ PayloadType: 96,
792
+ SequenceNumber: 1123 + uint16(i),
793
+ Timestamp: 45343 + 90000*uint32(i),
794
+ SSRC: 563423,
795
+ },
796
+ Payload: []byte{5},
797
+ })
798
+ require.NoError(t, err)
799
+ }
800
+
801
+ time.Sleep(500 * time.Millisecond)
802
+
803
+ files, err = os.ReadDir(filepath.Join(dir, "mystream"))
804
+ require.NoError(t, err)
805
+ require.Equal(t, 2, len(files))
806
+ }
807
+
808
+ func TestPathFallback(t *testing.T) {
809
+ for _, ca := range []string{
810
+ "absolute",
811
+ "relative",
812
+ "source",
813
+ } {
814
+ t.Run(ca, func(t *testing.T) {
815
+ var cnf string
816
+
817
+ switch ca {
818
+ case "absolute":
819
+ cnf = "paths:\n" +
820
+ " path1:\n" +
821
+ " fallback: rtsp://localhost:8554/path2\n" +
822
+ " path2:\n"
823
+
824
+ case "relative":
825
+ cnf = "paths:\n" +
826
+ " path1:\n" +
827
+ " fallback: /path2\n" +
828
+ " path2:\n"
829
+
830
+ case "source":
831
+ cnf = "paths:\n" +
832
+ " path1:\n" +
833
+ " fallback: /path2\n" +
834
+ " source: rtsp://localhost:3333/nonexistent\n" +
835
+ " path2:\n"
836
+ }
837
+
838
+ p1, ok := newInstance(t, cnf)
839
+ require.Equal(t, true, ok)
840
+ defer p1.Close()
841
+
842
+ source := gortsplib.Client{}
843
+ err := source.StartRecording("rtsp://localhost:8554/path2",
844
+ &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
845
+ require.NoError(t, err)
846
+ defer source.Close()
847
+
848
+ u, err := base.ParseURL("rtsp://localhost:8554/path1")
849
+ require.NoError(t, err)
850
+
851
+ dest := gortsplib.Client{
852
+ Scheme: u.Scheme,
853
+ Host: u.Host,
854
+ }
855
+
856
+ err = dest.Start()
857
+ require.NoError(t, err)
858
+ defer dest.Close()
859
+
860
+ desc, _, err := dest.Describe(u)
861
+ require.NoError(t, err)
862
+ require.Equal(t, 1, len(desc.Medias))
863
+ })
864
+ }
865
+ }
866
+
867
+ func TestPathResolveSource(t *testing.T) {
868
+ var strm *gortsplib.ServerStream
869
+
870
+ s := gortsplib.Server{
871
+ Handler: &testServer{
872
+ onDescribe: func(ctx *gortsplib.ServerHandlerOnDescribeCtx,
873
+ ) (*base.Response, *gortsplib.ServerStream, error) {
874
+ require.Equal(t, "key=val", ctx.Query)
875
+ require.Equal(t, "/a", ctx.Path)
876
+ return &base.Response{
877
+ StatusCode: base.StatusOK,
878
+ }, strm, nil
879
+ },
880
+ onSetup: func(_ *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
881
+ return &base.Response{
882
+ StatusCode: base.StatusOK,
883
+ }, strm, nil
884
+ },
885
+ onPlay: func(_ *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
886
+ return &base.Response{
887
+ StatusCode: base.StatusOK,
888
+ }, nil
889
+ },
890
+ },
891
+ RTSPAddress: "127.0.0.1:8555",
892
+ }
893
+
894
+ err := s.Start()
895
+ require.NoError(t, err)
896
+ defer s.Close()
897
+
898
+ strm = &gortsplib.ServerStream{
899
+ Server: &s,
900
+ Desc: &description.Session{Medias: []*description.Media{test.MediaH264}},
901
+ }
902
+ err = strm.Initialize()
903
+ require.NoError(t, err)
904
+ defer strm.Close()
905
+
906
+ p, ok := newInstance(t,
907
+ "paths:\n"+
908
+ " '~^test_(.+)$':\n"+
909
+ " source: rtsp://127.0.0.1:8555/$G1?$MTX_QUERY\n"+
910
+ " sourceOnDemand: yes\n"+
911
+ " 'all':\n")
912
+ require.Equal(t, true, ok)
913
+ defer p.Close()
914
+
915
+ u, err := base.ParseURL("rtsp://127.0.0.1:8554/test_a?key=val")
916
+ require.NoError(t, err)
917
+
918
+ reader := gortsplib.Client{
919
+ Scheme: u.Scheme,
920
+ Host: u.Host,
921
+ }
922
+
923
+ err = reader.Start()
924
+ require.NoError(t, err)
925
+ defer reader.Close()
926
+
927
+ _, _, err = reader.Describe(u)
928
+ require.NoError(t, err)
929
+ }
930
+
931
+ func TestPathOverridePublisher(t *testing.T) {
932
+ for _, ca := range []string{
933
+ "enabled",
934
+ "disabled",
935
+ } {
936
+ t.Run(ca, func(t *testing.T) {
937
+ cnf := "rtmp: no\n" +
938
+ "paths:\n" +
939
+ " all_others:\n"
940
+
941
+ if ca == "disabled" {
942
+ cnf += " overridePublisher: no\n"
943
+ }
944
+
945
+ p, ok := newInstance(t, cnf)
946
+ require.Equal(t, true, ok)
947
+ defer p.Close()
948
+
949
+ medi := test.UniqueMediaH264()
950
+
951
+ s1 := gortsplib.Client{}
952
+
953
+ err := s1.StartRecording("rtsp://localhost:8554/teststream",
954
+ &description.Session{Medias: []*description.Media{medi}})
955
+ require.NoError(t, err)
956
+ defer s1.Close()
957
+
958
+ s2 := gortsplib.Client{}
959
+
960
+ err = s2.StartRecording("rtsp://localhost:8554/teststream",
961
+ &description.Session{Medias: []*description.Media{medi}})
962
+ if ca == "enabled" {
963
+ require.NoError(t, err)
964
+ defer s2.Close()
965
+ } else {
966
+ require.Error(t, err)
967
+ }
968
+
969
+ frameRecv := make(chan struct{})
970
+
971
+ u, err := base.ParseURL("rtsp://localhost:8554/teststream")
972
+ require.NoError(t, err)
973
+
974
+ c := gortsplib.Client{
975
+ Scheme: u.Scheme,
976
+ Host: u.Host,
977
+ }
978
+
979
+ err = c.Start()
980
+ require.NoError(t, err)
981
+ defer c.Close()
982
+
983
+ desc, _, err := c.Describe(u)
984
+ require.NoError(t, err)
985
+
986
+ err = c.SetupAll(desc.BaseURL, desc.Medias)
987
+ require.NoError(t, err)
988
+
989
+ c.OnPacketRTP(desc.Medias[0], desc.Medias[0].Formats[0], func(pkt *rtp.Packet) {
990
+ if ca == "enabled" {
991
+ require.Equal(t, []byte{5, 15, 16, 17, 18}, pkt.Payload)
992
+ } else {
993
+ require.Equal(t, []byte{5, 11, 12, 13, 14}, pkt.Payload)
994
+ }
995
+ close(frameRecv)
996
+ })
997
+
998
+ _, err = c.Play(nil)
999
+ require.NoError(t, err)
1000
+
1001
+ if ca == "enabled" {
1002
+ err = s1.Wait()
1003
+ require.EqualError(t, err, "EOF")
1004
+
1005
+ err = s2.WritePacketRTP(medi, &rtp.Packet{
1006
+ Header: rtp.Header{
1007
+ Version: 0x02,
1008
+ PayloadType: 96,
1009
+ SequenceNumber: 57899,
1010
+ Timestamp: 345234345,
1011
+ SSRC: 978651231,
1012
+ Marker: true,
1013
+ },
1014
+ Payload: []byte{5, 15, 16, 17, 18},
1015
+ })
1016
+ require.NoError(t, err)
1017
+ } else {
1018
+ err = s1.WritePacketRTP(medi, &rtp.Packet{
1019
+ Header: rtp.Header{
1020
+ Version: 0x02,
1021
+ PayloadType: 96,
1022
+ SequenceNumber: 57899,
1023
+ Timestamp: 345234345,
1024
+ SSRC: 978651231,
1025
+ Marker: true,
1026
+ },
1027
+ Payload: []byte{5, 11, 12, 13, 14},
1028
+ })
1029
+ require.NoError(t, err)
1030
+ }
1031
+
1032
+ <-frameRecv
1033
+ })
1034
+ }
1035
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/source_redirect.go ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package core
2
+
3
+ import (
4
+ "github.com/bluenviron/mediamtx/internal/defs"
5
+ "github.com/bluenviron/mediamtx/internal/logger"
6
+ )
7
+
8
+ // sourceRedirect is a source that redirects to another one.
9
+ type sourceRedirect struct{}
10
+
11
+ func (*sourceRedirect) Log(logger.Level, string, ...any) {
12
+ }
13
+
14
+ // APISourceDescribe implements source.
15
+ func (*sourceRedirect) APISourceDescribe() *defs.APIPathSource {
16
+ return &defs.APIPathSource{
17
+ Type: defs.APIPathSourceTypeRedirect,
18
+ ID: "",
19
+ }
20
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/test_on_demand/main.go ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This is used for testing purposes.
2
+ package main
3
+
4
+ import (
5
+ "os"
6
+ "os/signal"
7
+ "syscall"
8
+
9
+ "github.com/bluenviron/gortsplib/v5"
10
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
11
+ "github.com/bluenviron/gortsplib/v5/pkg/format"
12
+ )
13
+
14
+ func main() {
15
+ if os.Getenv("MTX_QUERY") != "key1%3Dval1%26key2%3Dval2" {
16
+ panic("unexpected MTX_QUERY: " + os.Getenv("MTX_QUERY"))
17
+ }
18
+ if os.Getenv("G1") != "on" {
19
+ panic("unexpected G1: " + os.Getenv("G1"))
20
+ }
21
+
22
+ medi := &description.Media{
23
+ Type: description.MediaTypeVideo,
24
+ Formats: []format.Format{&format.H264{
25
+ PayloadTyp: 96,
26
+ SPS: []byte{
27
+ 0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02,
28
+ 0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
29
+ 0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, 0x20,
30
+ },
31
+ PPS: []byte{0x01, 0x02, 0x03, 0x04},
32
+ PacketizationMode: 1,
33
+ }},
34
+ }
35
+
36
+ source := gortsplib.Client{}
37
+
38
+ err := source.StartRecording(
39
+ "rtsp://localhost:"+os.Getenv("RTSP_PORT")+"/"+os.Getenv("MTX_PATH"),
40
+ &description.Session{Medias: []*description.Media{medi}})
41
+ if err != nil {
42
+ panic(err)
43
+ }
44
+ defer source.Close()
45
+
46
+ c := make(chan os.Signal, 1)
47
+ signal.Notify(c, syscall.SIGINT)
48
+ <-c
49
+
50
+ err = os.WriteFile(os.Getenv("ON_DEMAND"), []byte(""), 0o644)
51
+ if err != nil {
52
+ panic(err)
53
+ }
54
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/versiongetter/main.go ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package main contains an utility to get the server version
2
+ package main
3
+
4
+ import (
5
+ "fmt"
6
+ "log"
7
+ "os"
8
+ "path/filepath"
9
+ "strconv"
10
+ "strings"
11
+
12
+ "github.com/go-git/go-billy/v5/osfs"
13
+ "github.com/go-git/go-git/v5"
14
+ "github.com/go-git/go-git/v5/plumbing"
15
+ "github.com/go-git/go-git/v5/plumbing/cache"
16
+ "github.com/go-git/go-git/v5/plumbing/object"
17
+ "github.com/go-git/go-git/v5/storage/filesystem"
18
+ )
19
+
20
+ // Golang version of git describe --tags
21
+ func gitDescribeTags(repo *git.Repository) (string, error) {
22
+ head, err := repo.Head()
23
+ if err != nil {
24
+ return "", fmt.Errorf("failed to get HEAD: %w", err)
25
+ }
26
+
27
+ tagIterator, err := repo.Tags()
28
+ if err != nil {
29
+ return "", fmt.Errorf("failed to get tags: %w", err)
30
+ }
31
+ defer tagIterator.Close()
32
+
33
+ tags := make(map[plumbing.Hash]*plumbing.Reference)
34
+
35
+ err = tagIterator.ForEach(func(t *plumbing.Reference) error {
36
+ if to, err2 := repo.TagObject(t.Hash()); err2 == nil {
37
+ tags[to.Target] = t
38
+ } else {
39
+ tags[t.Hash()] = t
40
+ }
41
+ return nil
42
+ })
43
+ if err != nil {
44
+ return "", fmt.Errorf("failed to iterate tags: %w", err)
45
+ }
46
+
47
+ cIter, err := repo.Log(&git.LogOptions{From: head.Hash()})
48
+ if err != nil {
49
+ return "", fmt.Errorf("failed to get log: %w", err)
50
+ }
51
+
52
+ i := 0
53
+
54
+ for {
55
+ var commit *object.Commit
56
+ commit, err = cIter.Next()
57
+ if err != nil {
58
+ return "", fmt.Errorf("failed to get next commit: %w", err)
59
+ }
60
+
61
+ if str, ok := tags[commit.Hash]; ok {
62
+ label := strings.TrimPrefix(string(str.Name()), "refs/tags/")
63
+
64
+ if i != 0 {
65
+ label += "-" + strconv.FormatInt(int64(i), 10) + "-" + head.Hash().String()[:8]
66
+ }
67
+
68
+ return label, nil
69
+ }
70
+
71
+ i++
72
+ }
73
+ }
74
+
75
+ func tagFromGit() error {
76
+ // [git.PlainOpen] uses a ChrootOS that limits filesystem access to the .git directory only.
77
+ //
78
+ // Unfortunately, this can cause issues with package build environments such as Arch Linux's,
79
+ // where .git/objects/info/alternates points to a directory outside of the .git directory.
80
+ //
81
+ // To work around this, specify an AlternatesFS that allows access to the entire filesystem.
82
+ dotGitAbs, _ := filepath.Abs("../../.git")
83
+ storerFs := osfs.New(dotGitAbs, osfs.WithBoundOS())
84
+ storer := filesystem.NewStorageWithOptions(storerFs, cache.NewObjectLRUDefault(), filesystem.Options{
85
+ AlternatesFS: osfs.New("/", osfs.WithBoundOS()),
86
+ })
87
+ workTreeAbs, _ := filepath.Abs("../../")
88
+ worktreeFs := osfs.New(workTreeAbs, osfs.WithBoundOS())
89
+ repo, err := git.Open(storer, worktreeFs)
90
+ if err != nil {
91
+ return fmt.Errorf("failed to open repository: %w", err)
92
+ }
93
+
94
+ version, err := gitDescribeTags(repo)
95
+ if err != nil {
96
+ return fmt.Errorf("failed to get version: %w", err)
97
+ }
98
+
99
+ wt, err := repo.Worktree()
100
+ if err != nil {
101
+ return fmt.Errorf("failed to get worktree: %w", err)
102
+ }
103
+
104
+ status, err := wt.Status()
105
+ if err != nil {
106
+ return fmt.Errorf("failed to get status: %w", err)
107
+ }
108
+
109
+ if !status.IsClean() {
110
+ version += "-dirty"
111
+ }
112
+
113
+ err = os.WriteFile("VERSION", []byte(version), 0o644)
114
+ if err != nil {
115
+ return fmt.Errorf("failed to write version file: %w", err)
116
+ }
117
+
118
+ log.Printf("ok (%s)", version)
119
+ return nil
120
+ }
121
+
122
+ func do() error {
123
+ log.Println("getting mediamtx version...")
124
+
125
+ err := tagFromGit()
126
+ if err != nil {
127
+ log.Println("WARN: cannot get tag from .git folder, using v0.0.0 as version")
128
+ err = os.WriteFile("VERSION", []byte("v0.0.0"), 0o644)
129
+ if err != nil {
130
+ return fmt.Errorf("failed to write version file: %w", err)
131
+ }
132
+ }
133
+
134
+ return nil
135
+ }
136
+
137
+ func main() {
138
+ err := do()
139
+ if err != nil {
140
+ log.Printf("ERR: %v", err)
141
+ os.Exit(1)
142
+ }
143
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper.go ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package counterdumper contains a counter that that periodically invokes a callback if the counter is not zero.
2
+ package counterdumper
3
+
4
+ import (
5
+ "sync"
6
+ "time"
7
+ )
8
+
9
+ const (
10
+ callbackPeriod = 1 * time.Second
11
+ )
12
+
13
+ // Dumper is a counter that periodically invokes a callback if the counter is not zero.
14
+ type Dumper struct {
15
+ OnReport func(v uint64)
16
+
17
+ mutex sync.Mutex
18
+ counter uint64
19
+ absCounter uint64
20
+
21
+ terminate chan struct{}
22
+ done chan struct{}
23
+ }
24
+
25
+ // Start starts the counter.
26
+ func (c *Dumper) Start() {
27
+ c.terminate = make(chan struct{})
28
+ c.done = make(chan struct{})
29
+
30
+ go c.run()
31
+ }
32
+
33
+ // Stop stops the counter.
34
+ func (c *Dumper) Stop() {
35
+ close(c.terminate)
36
+ <-c.done
37
+ }
38
+
39
+ // Increase increases the counter value by 1.
40
+ func (c *Dumper) Increase() {
41
+ c.mutex.Lock()
42
+ defer c.mutex.Unlock()
43
+ c.counter++
44
+ c.absCounter++
45
+ }
46
+
47
+ // Add adds value to the counter.
48
+ func (c *Dumper) Add(v uint64) {
49
+ c.mutex.Lock()
50
+ defer c.mutex.Unlock()
51
+ c.counter += v
52
+ c.absCounter += v
53
+ }
54
+
55
+ // Get returns the counter value.
56
+ func (c *Dumper) Get() uint64 {
57
+ c.mutex.Lock()
58
+ defer c.mutex.Unlock()
59
+ return c.absCounter
60
+ }
61
+
62
+ func (c *Dumper) run() {
63
+ defer close(c.done)
64
+
65
+ t := time.NewTicker(callbackPeriod)
66
+ defer t.Stop()
67
+
68
+ for {
69
+ select {
70
+ case <-c.terminate:
71
+ return
72
+
73
+ case <-t.C:
74
+ c.mutex.Lock()
75
+ var v uint64
76
+ v, c.counter = c.counter, 0
77
+ c.mutex.Unlock()
78
+
79
+ if v != 0 {
80
+ c.OnReport(v)
81
+ }
82
+ }
83
+ }
84
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper_test.go ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package counterdumper
2
+
3
+ import (
4
+ "testing"
5
+ "time"
6
+
7
+ "github.com/stretchr/testify/require"
8
+ )
9
+
10
+ func TestDumperReport(t *testing.T) {
11
+ done := make(chan struct{})
12
+
13
+ c := &Dumper{
14
+ OnReport: func(v uint64) {
15
+ require.Equal(t, uint64(3), v)
16
+ close(done)
17
+ },
18
+ }
19
+ c.Start()
20
+ defer c.Stop()
21
+
22
+ c.Add(2)
23
+ c.Increase()
24
+
25
+ select {
26
+ case <-done:
27
+ case <-time.After(2 * time.Second):
28
+ t.Errorf("should not happen")
29
+ }
30
+ }
31
+
32
+ func TestDumperDoNotReport(t *testing.T) {
33
+ c := &Dumper{
34
+ OnReport: func(_ uint64) {
35
+ t.Errorf("should not happen")
36
+ },
37
+ }
38
+ c.Start()
39
+ defer c.Stop()
40
+
41
+ <-time.After(2 * time.Second)
42
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api.go ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "time"
5
+
6
+ "github.com/bluenviron/mediamtx/internal/conf"
7
+ )
8
+
9
+ // APIOKStatus is the status of a successful response.
10
+ type APIOKStatus string
11
+
12
+ // statuses.
13
+ const (
14
+ APIOKStatusOK APIOKStatus = "ok"
15
+ )
16
+
17
+ // APIErrorStatus is the status of an error response.
18
+ type APIErrorStatus string
19
+
20
+ // statuses.
21
+ const (
22
+ APIErrorStatusError APIErrorStatus = "error"
23
+ )
24
+
25
+ // APIOK is returned on success.
26
+ type APIOK struct {
27
+ Status APIOKStatus `json:"status"`
28
+ }
29
+
30
+ // APIError is a generic error.
31
+ type APIError struct {
32
+ Status APIErrorStatus `json:"status"`
33
+ Error string `json:"error"`
34
+ }
35
+
36
+ // APIInfo is a info response.
37
+ type APIInfo struct {
38
+ Version string `json:"version"`
39
+ Started time.Time `json:"started"`
40
+ }
41
+
42
+ // APIPathConfList is a list of path configurations.
43
+ type APIPathConfList struct {
44
+ ItemCount int `json:"itemCount"`
45
+ PageCount int `json:"pageCount"`
46
+ Items []conf.Path `json:"items"`
47
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_hls.go ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "time"
5
+
6
+ "github.com/google/uuid"
7
+ )
8
+
9
+ // APIHLSServer contains methods used by the API and Metrics server.
10
+ type APIHLSServer interface {
11
+ APISessionsList() (*APIHLSSessionList, error)
12
+ APISessionsGet(uuid.UUID) (*APIHLSSession, error)
13
+ APISessionsKick(uuid.UUID) error
14
+ APIMuxersList() (*APIHLSMuxerList, error)
15
+ APIMuxersGet(string) (*APIHLSMuxer, error)
16
+ }
17
+
18
+ // APIHLSSessionList is a list of HLS sessions.
19
+ type APIHLSSessionList struct {
20
+ ItemCount int `json:"itemCount"`
21
+ PageCount int `json:"pageCount"`
22
+ Items []APIHLSSession `json:"items"`
23
+ }
24
+
25
+ // APIHLSSession is an HLS session.
26
+ type APIHLSSession struct {
27
+ ID uuid.UUID `json:"id"`
28
+ Created time.Time `json:"created"`
29
+ RemoteAddr string `json:"remoteAddr"`
30
+ Path string `json:"path"`
31
+ Query string `json:"query"`
32
+ User string `json:"user"`
33
+ UserAgent string `json:"userAgent"`
34
+ IsCDN bool `json:"isCDN"`
35
+ OutboundBytes uint64 `json:"outboundBytes"`
36
+ }
37
+
38
+ // APIHLSMuxerList is a list of HLS muxers.
39
+ type APIHLSMuxerList struct {
40
+ ItemCount int `json:"itemCount"`
41
+ PageCount int `json:"pageCount"`
42
+ Items []APIHLSMuxer `json:"items"`
43
+ }
44
+
45
+ // APIHLSMuxer is an HLS muxer.
46
+ type APIHLSMuxer struct {
47
+ Path string `json:"path"`
48
+ Created time.Time `json:"created"`
49
+ LastRequest time.Time `json:"lastRequest"`
50
+ OutboundBytes uint64 `json:"outboundBytes"`
51
+ OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"`
52
+ // deprecated
53
+ BytesSent uint64 `json:"bytesSent" deprecated:"true"`
54
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_moq.go ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "time"
5
+
6
+ "github.com/google/uuid"
7
+ )
8
+
9
+ // APIMoQServer contains methods used by the API server.
10
+ type APIMoQServer interface {
11
+ APISessionsList() (*APIMoQSessionList, error)
12
+ APISessionsGet(uuid.UUID) (*APIMoQSession, error)
13
+ APISessionsKick(uuid.UUID) error
14
+ }
15
+
16
+ // APIMoQSessionState is the state of a MoQ session.
17
+ type APIMoQSessionState string
18
+
19
+ // states.
20
+ const (
21
+ APIMoQSessionStateIdle APIMoQSessionState = "idle"
22
+ APIMoQSessionStateRead APIMoQSessionState = "read"
23
+ APIMoQSessionStatePublish APIMoQSessionState = "publish"
24
+ )
25
+
26
+ // APIMoQSessionList is a list of MoQ sessions.
27
+ type APIMoQSessionList struct {
28
+ ItemCount int `json:"itemCount"`
29
+ PageCount int `json:"pageCount"`
30
+ Items []APIMoQSession `json:"items"`
31
+ }
32
+
33
+ // APIMoQSession is a MoQ session.
34
+ type APIMoQSession struct {
35
+ ID uuid.UUID `json:"id"`
36
+ Created time.Time `json:"created"`
37
+ RemoteAddr string `json:"remoteAddr"`
38
+ State APIMoQSessionState `json:"state"`
39
+ Path string `json:"path"`
40
+ Query string `json:"query"`
41
+ UserAgent string `json:"userAgent"`
42
+ InboundBytes uint64 `json:"inboundBytes"`
43
+ OutboundBytes uint64 `json:"outboundBytes"`
44
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path.go ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "time"
5
+ )
6
+
7
+ // APIPathManager contains methods used by the API and Metrics server.
8
+ type APIPathManager interface {
9
+ APIPathsList() (*APIPathList, error)
10
+ APIPathsGet(string) (*APIPath, error)
11
+ }
12
+
13
+ // APIPathSourceType is the type of a path source.
14
+ type APIPathSourceType string
15
+
16
+ // source types.
17
+ const (
18
+ APIPathSourceTypeHLSSource APIPathSourceType = "hlsSource"
19
+ APIPathSourceTypeRedirect APIPathSourceType = "redirect"
20
+ APIPathSourceTypeRPICameraSource APIPathSourceType = "rpiCameraSource"
21
+ APIPathSourceTypeRTMPConn APIPathSourceType = "rtmpConn"
22
+ APIPathSourceTypeRTMPSConn APIPathSourceType = "rtmpsConn"
23
+ APIPathSourceTypeRTMPSource APIPathSourceType = "rtmpSource"
24
+ APIPathSourceTypeRTSPSession APIPathSourceType = "rtspSession"
25
+ APIPathSourceTypeRTSPSource APIPathSourceType = "rtspSource"
26
+ APIPathSourceTypeRTSPSSession APIPathSourceType = "rtspsSession"
27
+ APIPathSourceTypeSRTConn APIPathSourceType = "srtConn"
28
+ APIPathSourceTypeSRTSource APIPathSourceType = "srtSource"
29
+ APIPathSourceTypeMPEGTSSource APIPathSourceType = "mpegtsSource"
30
+ APIPathSourceTypeRTPSource APIPathSourceType = "rtpSource"
31
+ APIPathSourceTypeWebRTCSession APIPathSourceType = "webRTCSession"
32
+ APIPathSourceTypeWebRTCSource APIPathSourceType = "webRTCSource"
33
+ APIPathSourceTypeMoQSession APIPathSourceType = "moqSession"
34
+ )
35
+
36
+ // APIPathSource is a source.
37
+ type APIPathSource struct {
38
+ Type APIPathSourceType `json:"type"`
39
+ ID string `json:"id"`
40
+ }
41
+
42
+ // APIPathReaderType is the type of a path reader.
43
+ type APIPathReaderType string
44
+
45
+ // reader types.
46
+ const (
47
+ APIPathReaderTypeHLSSession APIPathReaderType = "hlsSession"
48
+ APIPathReaderTypeRTMPConn APIPathReaderType = "rtmpConn"
49
+ APIPathReaderTypeRTMPSConn APIPathReaderType = "rtmpsConn"
50
+ APIPathReaderTypeRTSPConn APIPathReaderType = "rtspConn"
51
+ APIPathReaderTypeRTSPSession APIPathReaderType = "rtspSession"
52
+ APIPathReaderTypeRTSPSConn APIPathReaderType = "rtspsConn"
53
+ APIPathReaderTypeRTSPSSession APIPathReaderType = "rtspsSession"
54
+ APIPathReaderTypeSRTConn APIPathReaderType = "srtConn"
55
+ APIPathReaderTypeWebRTCSession APIPathReaderType = "webRTCSession"
56
+ APIPathReaderTypeMoQSession APIPathReaderType = "moqSession"
57
+ APIPathReaderTypeHidden APIPathReaderType = "hidden"
58
+ )
59
+
60
+ // APIPathReader is a reader.
61
+ type APIPathReader struct {
62
+ Type APIPathReaderType `json:"type"`
63
+ ID string `json:"id"`
64
+ }
65
+
66
+ // APIPath is a path.
67
+ type APIPath struct {
68
+ Name string `json:"name"`
69
+ ConfName string `json:"confName"`
70
+ Ready bool `json:"ready" deprecated:"true"`
71
+ ReadyTime *time.Time `json:"readyTime" deprecated:"true"`
72
+ Available bool `json:"available"`
73
+ AvailableTime *time.Time `json:"availableTime"`
74
+ Online bool `json:"online"`
75
+ OnlineTime *time.Time `json:"onlineTime"`
76
+ Source *APIPathSource `json:"source"`
77
+ Tracks []APIPathTrackCodec `json:"tracks" deprecated:"true"`
78
+ Tracks2 []APIPathTrack `json:"tracks2"`
79
+ Readers []APIPathReader `json:"readers"`
80
+ InboundBytes uint64 `json:"inboundBytes"`
81
+ OutboundBytes uint64 `json:"outboundBytes"`
82
+ InboundFramesInError uint64 `json:"inboundFramesInError"`
83
+ // deprecated
84
+ BytesReceived uint64 `json:"bytesReceived" deprecated:"true"`
85
+ BytesSent uint64 `json:"bytesSent" deprecated:"true"`
86
+ }
87
+
88
+ // APIPathList is a list of paths.
89
+ type APIPathList struct {
90
+ ItemCount int `json:"itemCount"`
91
+ PageCount int `json:"pageCount"`
92
+ Items []APIPath `json:"items"`
93
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track.go ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
5
+ "github.com/bluenviron/gortsplib/v5/pkg/format"
6
+ "github.com/bluenviron/mediamtx/internal/formatlabel"
7
+ )
8
+
9
+ // APIPathTrack is a track.
10
+ type APIPathTrack struct {
11
+ Codec APIPathTrackCodec `json:"codec"`
12
+ CodecProps APIPathTrackCodecProps `json:"codecProps"`
13
+ }
14
+
15
+ func formatToTrack(outFormat format.Format) APIPathTrack {
16
+ return APIPathTrack{
17
+ Codec: formatlabel.FormatToLabel(outFormat),
18
+ CodecProps: formatToTrackCodecProps(outFormat),
19
+ }
20
+ }
21
+
22
+ func gatherFormats(medias []*description.Media) []format.Format {
23
+ n := 0
24
+ for _, media := range medias {
25
+ n += len(media.Formats)
26
+ }
27
+
28
+ if n == 0 {
29
+ return nil
30
+ }
31
+
32
+ formats := make([]format.Format, n)
33
+ n = 0
34
+
35
+ for _, media := range medias {
36
+ n += copy(formats[n:], media.Formats)
37
+ }
38
+
39
+ return formats
40
+ }
41
+
42
+ func formatsToTracks(outFormats []format.Format) []APIPathTrack {
43
+ ret := make([]APIPathTrack, len(outFormats))
44
+
45
+ for i, outFormat := range outFormats {
46
+ ret[i] = formatToTrack(outFormat)
47
+ }
48
+
49
+ return ret
50
+ }
51
+
52
+ // MediasToTracks returns tracks of given medias.
53
+ func MediasToTracks(outMedias []*description.Media) []APIPathTrack {
54
+ return formatsToTracks(gatherFormats(outMedias))
55
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec.go ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import "github.com/bluenviron/mediamtx/internal/formatlabel"
4
+
5
+ // APIPathTrackCodec is a track codec.
6
+ type APIPathTrackCodec = formatlabel.Label
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec_props.go ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "fmt"
5
+ "strconv"
6
+
7
+ "github.com/bluenviron/gortsplib/v5/pkg/format"
8
+ codecsh264 "github.com/bluenviron/mediacommon/v2/pkg/codecs/h264"
9
+ codecsh265 "github.com/bluenviron/mediacommon/v2/pkg/codecs/h265"
10
+ )
11
+
12
+ // APIPathTrackCodecProps contains codec-specific properties.
13
+ type APIPathTrackCodecProps interface {
14
+ apiPathTrackCodecProps()
15
+ }
16
+
17
+ // APIPathTrackCodecPropsAV1 contains codec-specific properties of AV1.
18
+ type APIPathTrackCodecPropsAV1 struct {
19
+ Width int `json:"width"`
20
+ Height int `json:"height"`
21
+ Profile int `json:"profile"`
22
+ Level int `json:"level"`
23
+ Tier int `json:"tier"`
24
+ }
25
+
26
+ func (*APIPathTrackCodecPropsAV1) apiPathTrackCodecProps() {}
27
+
28
+ // APIPathTrackCodecPropsVP9 contains codec-specific properties of VP9.
29
+ type APIPathTrackCodecPropsVP9 struct {
30
+ Profile int `json:"profile"`
31
+ }
32
+
33
+ func (*APIPathTrackCodecPropsVP9) apiPathTrackCodecProps() {}
34
+
35
+ // APIPathTrackCodecPropsH265 contains codec-specific properties of H265.
36
+ type APIPathTrackCodecPropsH265 struct {
37
+ Width int `json:"width"`
38
+ Height int `json:"height"`
39
+ Profile string `json:"profile"`
40
+ Level string `json:"level"`
41
+ }
42
+
43
+ func (*APIPathTrackCodecPropsH265) apiPathTrackCodecProps() {}
44
+
45
+ // APIPathTrackCodecPropsH264 contains codec-specific properties of H264.
46
+ type APIPathTrackCodecPropsH264 struct {
47
+ Width int `json:"width"`
48
+ Height int `json:"height"`
49
+ Profile string `json:"profile"`
50
+ Level string `json:"level"`
51
+ }
52
+
53
+ func (*APIPathTrackCodecPropsH264) apiPathTrackCodecProps() {}
54
+
55
+ // APIPathTrackCodecPropsOpus contains codec-specific properties of Opus.
56
+ type APIPathTrackCodecPropsOpus struct {
57
+ ChannelCount int `json:"channelCount"`
58
+ }
59
+
60
+ func (*APIPathTrackCodecPropsOpus) apiPathTrackCodecProps() {}
61
+
62
+ // APIPathTrackCodecPropsMPEG4Audio contains codec-specific properties of MPEG4Audio.
63
+ type APIPathTrackCodecPropsMPEG4Audio struct {
64
+ SampleRate int `json:"sampleRate"`
65
+ ChannelCount int `json:"channelCount"`
66
+ }
67
+
68
+ func (*APIPathTrackCodecPropsMPEG4Audio) apiPathTrackCodecProps() {}
69
+
70
+ // APIPathTrackCodecPropsAC3 contains codec-specific properties of AC3.
71
+ type APIPathTrackCodecPropsAC3 struct {
72
+ SampleRate int `json:"sampleRate"`
73
+ ChannelCount int `json:"channelCount"`
74
+ }
75
+
76
+ func (*APIPathTrackCodecPropsAC3) apiPathTrackCodecProps() {}
77
+
78
+ // APIPathTrackCodecPropsG711 contains codec-specific properties of G711.
79
+ type APIPathTrackCodecPropsG711 struct {
80
+ MULaw bool `json:"muLaw"`
81
+ SampleRate int `json:"sampleRate"`
82
+ ChannelCount int `json:"channelCount"`
83
+ }
84
+
85
+ func (*APIPathTrackCodecPropsG711) apiPathTrackCodecProps() {}
86
+
87
+ // APIPathTrackCodecPropsLPCM contains codec-specific properties of LPCM.
88
+ type APIPathTrackCodecPropsLPCM struct {
89
+ BitDepth int `json:"bitDepth"`
90
+ SampleRate int `json:"sampleRate"`
91
+ ChannelCount int `json:"channelCount"`
92
+ }
93
+
94
+ func (*APIPathTrackCodecPropsLPCM) apiPathTrackCodecProps() {}
95
+
96
+ func h264ProfileString(profileIdc uint8) string {
97
+ switch profileIdc {
98
+ case 66:
99
+ return "Baseline"
100
+ case 77:
101
+ return "Main"
102
+ case 88:
103
+ return "Extended"
104
+ case 100:
105
+ return "High"
106
+ case 110:
107
+ return "High 10"
108
+ case 122:
109
+ return "High 4:2:2"
110
+ case 244:
111
+ return "High 4:4:4 Predictive"
112
+ default:
113
+ return strconv.Itoa(int(profileIdc))
114
+ }
115
+ }
116
+
117
+ func h264LevelString(levelIdc uint8) string {
118
+ major := levelIdc / 10
119
+ minor := levelIdc % 10
120
+ if minor == 0 {
121
+ return fmt.Sprintf("%d", major)
122
+ }
123
+ return fmt.Sprintf("%d.%d", major, minor)
124
+ }
125
+
126
+ func h265ProfileString(profileIdc uint8) string {
127
+ switch profileIdc {
128
+ case 1:
129
+ return "Main"
130
+ case 2:
131
+ return "Main 10"
132
+ case 3:
133
+ return "Main Still Picture"
134
+ case 4:
135
+ return "Range Extensions"
136
+ case 5:
137
+ return "High Throughput"
138
+ case 6:
139
+ return "Multiview Main"
140
+ case 7:
141
+ return "Scalable Main"
142
+ case 8:
143
+ return "3D Main"
144
+ case 9:
145
+ return "Screen Content Coding Extensions"
146
+ case 10:
147
+ return "Scalable Range Extensions"
148
+ default:
149
+ return strconv.Itoa(int(profileIdc))
150
+ }
151
+ }
152
+
153
+ func h265LevelString(levelIdc uint8) string {
154
+ // H.265 level_idc = 30 * level, so 3.0 = 90, 4.0 = 120, 4.1 = 123
155
+ level := float64(levelIdc) / 30.0
156
+ // Check if it's a clean level like 3.0, 4.0
157
+ if levelIdc%30 == 0 {
158
+ return fmt.Sprintf("%.0f", level)
159
+ }
160
+ return fmt.Sprintf("%.1f", level)
161
+ }
162
+
163
+ func formatToTrackCodecProps(outFormat format.Format) APIPathTrackCodecProps {
164
+ switch outFormat := outFormat.(type) {
165
+ case *format.AV1:
166
+ props := &APIPathTrackCodecPropsAV1{}
167
+
168
+ if outFormat.Profile != nil {
169
+ props.Profile = *outFormat.Profile
170
+ }
171
+ if outFormat.LevelIdx != nil {
172
+ props.Level = *outFormat.LevelIdx
173
+ }
174
+ if outFormat.Tier != nil {
175
+ props.Tier = *outFormat.Tier
176
+ }
177
+
178
+ return props
179
+
180
+ case *format.VP9:
181
+ props := &APIPathTrackCodecPropsVP9{}
182
+
183
+ if outFormat.ProfileID != nil {
184
+ props.Profile = *outFormat.ProfileID
185
+ }
186
+
187
+ return props
188
+
189
+ case *format.H265:
190
+ props := &APIPathTrackCodecPropsH265{}
191
+
192
+ if outFormat.SPS != nil {
193
+ var s codecsh265.SPS
194
+ if err := s.Unmarshal(outFormat.SPS); err == nil {
195
+ props.Width = s.Width()
196
+ props.Height = s.Height()
197
+ props.Profile = h265ProfileString(s.ProfileTierLevel.GeneralProfileIdc)
198
+ props.Level = h265LevelString(s.ProfileTierLevel.GeneralLevelIdc)
199
+ }
200
+ }
201
+
202
+ return props
203
+
204
+ case *format.H264:
205
+ props := &APIPathTrackCodecPropsH264{}
206
+
207
+ if outFormat.SPS != nil {
208
+ var s codecsh264.SPS
209
+ if err := s.Unmarshal(outFormat.SPS); err == nil {
210
+ props.Width = s.Width()
211
+ props.Height = s.Height()
212
+ props.Profile = h264ProfileString(s.ProfileIdc)
213
+ props.Level = h264LevelString(s.LevelIdc)
214
+ }
215
+ }
216
+
217
+ return props
218
+
219
+ case *format.Opus:
220
+ return &APIPathTrackCodecPropsOpus{
221
+ ChannelCount: outFormat.ChannelCount,
222
+ }
223
+
224
+ case *format.MPEG4Audio:
225
+ props := &APIPathTrackCodecPropsMPEG4Audio{}
226
+
227
+ if outFormat.Config != nil {
228
+ props.SampleRate = outFormat.Config.SampleRate
229
+ props.ChannelCount = int(outFormat.Config.ChannelConfig)
230
+ }
231
+
232
+ return props
233
+
234
+ case *format.AC3:
235
+ return &APIPathTrackCodecPropsAC3{
236
+ SampleRate: outFormat.SampleRate,
237
+ ChannelCount: outFormat.ChannelCount,
238
+ }
239
+
240
+ case *format.G711:
241
+ return &APIPathTrackCodecPropsG711{
242
+ MULaw: outFormat.MULaw,
243
+ SampleRate: outFormat.SampleRate,
244
+ ChannelCount: outFormat.ChannelCount,
245
+ }
246
+
247
+ case *format.LPCM:
248
+ return &APIPathTrackCodecPropsLPCM{
249
+ BitDepth: outFormat.BitDepth,
250
+ SampleRate: outFormat.SampleRate,
251
+ ChannelCount: outFormat.ChannelCount,
252
+ }
253
+
254
+ default:
255
+ return nil
256
+ }
257
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_recording.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import "time"
4
+
5
+ // APIRecordingSegment is a recording segment.
6
+ type APIRecordingSegment struct {
7
+ Start time.Time `json:"start"`
8
+ }
9
+
10
+ // APIRecording is a recording.
11
+ type APIRecording struct {
12
+ Name string `json:"name"`
13
+ Segments []APIRecordingSegment `json:"segments"`
14
+ }
15
+
16
+ // APIRecordingList is a list of recordings.
17
+ type APIRecordingList struct {
18
+ ItemCount int `json:"itemCount"`
19
+ PageCount int `json:"pageCount"`
20
+ Items []APIRecording `json:"items"`
21
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtmp.go ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "time"
5
+
6
+ "github.com/google/uuid"
7
+ )
8
+
9
+ // APIRTMPServer contains methods used by the API and Metrics server.
10
+ type APIRTMPServer interface {
11
+ APIConnsList() (*APIRTMPConnList, error)
12
+ APIConnsGet(uuid.UUID) (*APIRTMPConn, error)
13
+ APIConnsKick(uuid.UUID) error
14
+ }
15
+
16
+ // APIRTMPConnState is the state of a RTMP connection.
17
+ type APIRTMPConnState string
18
+
19
+ // states.
20
+ const (
21
+ APIRTMPConnStateIdle APIRTMPConnState = "idle"
22
+ APIRTMPConnStateRead APIRTMPConnState = "read"
23
+ APIRTMPConnStatePublish APIRTMPConnState = "publish"
24
+ )
25
+
26
+ // APIRTMPConn is a RTMP connection.
27
+ type APIRTMPConn struct {
28
+ ID uuid.UUID `json:"id"`
29
+ Created time.Time `json:"created"`
30
+ RemoteAddr string `json:"remoteAddr"`
31
+ State APIRTMPConnState `json:"state"`
32
+ Path string `json:"path"`
33
+ Query string `json:"query"`
34
+ User string `json:"user"`
35
+ UserAgent string `json:"userAgent"`
36
+ InboundBytes uint64 `json:"inboundBytes"`
37
+ OutboundBytes uint64 `json:"outboundBytes"`
38
+ OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"`
39
+ // deprecated
40
+ BytesReceived uint64 `json:"bytesReceived" deprecated:"true"`
41
+ BytesSent uint64 `json:"bytesSent" deprecated:"true"`
42
+ }
43
+
44
+ // APIRTMPConnList is a list of RTMP connections.
45
+ type APIRTMPConnList struct {
46
+ ItemCount int `json:"itemCount"`
47
+ PageCount int `json:"pageCount"`
48
+ Items []APIRTMPConn `json:"items"`
49
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtsp.go ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "time"
5
+
6
+ "github.com/google/uuid"
7
+ )
8
+
9
+ // APIRTSPServer contains methods used by the API and Metrics server.
10
+ type APIRTSPServer interface {
11
+ APIConnsList() (*APIRTSPConnsList, error)
12
+ APIConnsGet(uuid.UUID) (*APIRTSPConn, error)
13
+ APISessionsList() (*APIRTSPSessionList, error)
14
+ APISessionsGet(uuid.UUID) (*APIRTSPSession, error)
15
+ APISessionsKick(uuid.UUID) error
16
+ }
17
+
18
+ // APIRTSPConn is a RTSP connection.
19
+ type APIRTSPConn struct {
20
+ ID uuid.UUID `json:"id"`
21
+ Created time.Time `json:"created"`
22
+ RemoteAddr string `json:"remoteAddr"`
23
+ Session *uuid.UUID `json:"session"`
24
+ Tunnel string `json:"tunnel"`
25
+ InboundBytes uint64 `json:"inboundBytes"`
26
+ OutboundBytes uint64 `json:"outboundBytes"`
27
+ BytesReceived uint64 `json:"bytesReceived" deprecated:"true"`
28
+ BytesSent uint64 `json:"bytesSent" deprecated:"true"`
29
+ }
30
+
31
+ // APIRTSPConnsList is a list of RTSP connections.
32
+ type APIRTSPConnsList struct {
33
+ ItemCount int `json:"itemCount"`
34
+ PageCount int `json:"pageCount"`
35
+ Items []APIRTSPConn `json:"items"`
36
+ }
37
+
38
+ // APIRTSPSessionState is the state of a RTSP session.
39
+ type APIRTSPSessionState string
40
+
41
+ // states.
42
+ const (
43
+ APIRTSPSessionStateIdle APIRTSPSessionState = "idle"
44
+ APIRTSPSessionStateRead APIRTSPSessionState = "read"
45
+ APIRTSPSessionStatePublish APIRTSPSessionState = "publish"
46
+ )
47
+
48
+ // APIRTSPSession is a RTSP session.
49
+ type APIRTSPSession struct {
50
+ ID uuid.UUID `json:"id"`
51
+ Created time.Time `json:"created"`
52
+ RemoteAddr string `json:"remoteAddr"`
53
+ State APIRTSPSessionState `json:"state"`
54
+ Path string `json:"path"`
55
+ Query string `json:"query"`
56
+ User string `json:"user"`
57
+ UserAgent string `json:"userAgent"`
58
+ Transport *string `json:"transport"`
59
+ Profile *string `json:"profile"`
60
+ Conns []uuid.UUID `json:"conns"`
61
+ InboundBytes uint64 `json:"inboundBytes"`
62
+ InboundRTPPackets uint64 `json:"inboundRTPPackets"`
63
+ InboundRTPPacketsLost uint64 `json:"inboundRTPPacketsLost"`
64
+ InboundRTPPacketsInError uint64 `json:"inboundRTPPacketsInError"`
65
+ InboundRTPPacketsJitter float64 `json:"inboundRTPPacketsJitter"`
66
+ InboundRTCPPackets uint64 `json:"inboundRTCPPackets"`
67
+ InboundRTCPPacketsInError uint64 `json:"inboundRTCPPacketsInError"`
68
+ OutboundBytes uint64 `json:"outboundBytes"`
69
+ OutboundRTPPackets uint64 `json:"outboundRTPPackets"`
70
+ OutboundRTPPacketsReportedLost uint64 `json:"outboundRTPPacketsReportedLost"`
71
+ OutboundRTPPacketsDiscarded uint64 `json:"outboundRTPPacketsDiscarded"`
72
+ OutboundRTCPPackets uint64 `json:"outboundRTCPPackets"`
73
+ // deprecated
74
+ BytesReceived uint64 `json:"bytesReceived" deprecated:"true"`
75
+ BytesSent uint64 `json:"bytesSent" deprecated:"true"`
76
+ RTPPacketsReceived uint64 `json:"rtpPacketsReceived" deprecated:"true"`
77
+ RTPPacketsSent uint64 `json:"rtpPacketsSent" deprecated:"true"`
78
+ RTPPacketsLost uint64 `json:"rtpPacketsLost" deprecated:"true"`
79
+ RTPPacketsInError uint64 `json:"rtpPacketsInError" deprecated:"true"`
80
+ RTPPacketsJitter float64 `json:"rtpPacketsJitter" deprecated:"true"`
81
+ RTCPPacketsReceived uint64 `json:"rtcpPacketsReceived" deprecated:"true"`
82
+ RTCPPacketsSent uint64 `json:"rtcpPacketsSent" deprecated:"true"`
83
+ RTCPPacketsInError uint64 `json:"rtcpPacketsInError" deprecated:"true"`
84
+ }
85
+
86
+ // APIRTSPSessionList is a list of RTSP sessions.
87
+ type APIRTSPSessionList struct {
88
+ ItemCount int `json:"itemCount"`
89
+ PageCount int `json:"pageCount"`
90
+ Items []APIRTSPSession `json:"items"`
91
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_srt.go ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "time"
5
+
6
+ "github.com/google/uuid"
7
+ )
8
+
9
+ // APISRTServer contains methods used by the API and Metrics server.
10
+ type APISRTServer interface {
11
+ APIConnsList() (*APISRTConnList, error)
12
+ APIConnsGet(uuid.UUID) (*APISRTConn, error)
13
+ APIConnsKick(uuid.UUID) error
14
+ }
15
+
16
+ // APISRTConnState is the state of a SRT connection.
17
+ type APISRTConnState string
18
+
19
+ // states.
20
+ const (
21
+ APISRTConnStateIdle APISRTConnState = "idle"
22
+ APISRTConnStateRead APISRTConnState = "read"
23
+ APISRTConnStatePublish APISRTConnState = "publish"
24
+ )
25
+
26
+ // APISRTConn is a SRT connection.
27
+ type APISRTConn struct {
28
+ ID uuid.UUID `json:"id"`
29
+ Created time.Time `json:"created"`
30
+ RemoteAddr string `json:"remoteAddr"`
31
+ State APISRTConnState `json:"state"`
32
+ Path string `json:"path"`
33
+ Query string `json:"query"`
34
+ User string `json:"user"`
35
+
36
+ // The metric names/comments are pulled from GoSRT
37
+
38
+ // The total number of sent DATA packets, including retransmitted packets
39
+ PacketsSent uint64 `json:"packetsSent"`
40
+ // The total number of received DATA packets, including retransmitted packets
41
+ PacketsReceived uint64 `json:"packetsReceived"`
42
+ // The total number of unique DATA packets sent by the SRT sender
43
+ PacketsSentUnique uint64 `json:"packetsSentUnique"`
44
+ // The total number of unique original, retransmitted or recovered by the packet filter DATA packets
45
+ // received in time, decrypted without errors and, as a result, scheduled for delivery to the
46
+ // upstream application by the SRT receiver.
47
+ PacketsReceivedUnique uint64 `json:"packetsReceivedUnique"`
48
+ // The total number of data packets considered or reported as lost at the sender side.
49
+ // Does not correspond to the packets detected as lost at the receiver side.
50
+ PacketsSendLoss uint64 `json:"packetsSendLoss"`
51
+ // The total number of SRT DATA packets detected as presently missing (either reordered or lost) at the receiver side
52
+ PacketsReceivedLoss uint64 `json:"packetsReceivedLoss"`
53
+ // The total number of retransmitted packets sent by the SRT sender
54
+ PacketsRetrans uint64 `json:"packetsRetrans"`
55
+ // The total number of retransmitted packets registered at the receiver side
56
+ PacketsReceivedRetrans uint64 `json:"packetsReceivedRetrans"`
57
+ // The total number of sent ACK (Acknowledgement) control packets
58
+ PacketsSentACK uint64 `json:"packetsSentACK"`
59
+ // The total number of received ACK (Acknowledgement) control packets
60
+ PacketsReceivedACK uint64 `json:"packetsReceivedACK"`
61
+ // The total number of sent NAK (Negative Acknowledgement) control packets
62
+ PacketsSentNAK uint64 `json:"packetsSentNAK"`
63
+ // The total number of received NAK (Negative Acknowledgement) control packets
64
+ PacketsReceivedNAK uint64 `json:"packetsReceivedNAK"`
65
+ // The total number of sent KM (Key Material) control packets
66
+ PacketsSentKM uint64 `json:"packetsSentKM"`
67
+ // The total number of received KM (Key Material) control packets
68
+ PacketsReceivedKM uint64 `json:"packetsReceivedKM"`
69
+ // The total accumulated time in microseconds, during which the SRT sender has some data to transmit,
70
+ // including packets that have been sent, but not yet acknowledged
71
+ UsSndDuration uint64 `json:"usSndDuration"`
72
+ // ??
73
+ PacketsReceivedBelated uint64 `json:"packetsReceivedBelated"`
74
+ // The total number of dropped by the SRT sender DATA packets that have no chance to be delivered in time
75
+ PacketsSendDrop uint64 `json:"packetsSendDrop"`
76
+ // The total number of dropped by the SRT receiver and, as a result,
77
+ // not delivered to the upstream application DATA packets
78
+ PacketsReceivedDrop uint64 `json:"packetsReceivedDrop"`
79
+ // The total number of packets that failed to be decrypted at the receiver side
80
+ PacketsReceivedUndecrypt uint64 `json:"packetsReceivedUndecrypt"`
81
+
82
+ // Same as packetsReceived, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
83
+ BytesReceived uint64 `json:"bytesReceived"`
84
+ // Same as packetsSent, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
85
+ BytesSent uint64 `json:"bytesSent"`
86
+ // Same as packetsSentUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
87
+ BytesSentUnique uint64 `json:"bytesSentUnique"`
88
+ // Same as packetsReceivedUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
89
+ BytesReceivedUnique uint64 `json:"bytesReceivedUnique"`
90
+ // Same as packetsReceivedLoss, but expressed in bytes, including payload and all the headers (IP, TCP, SRT),
91
+ // bytes for the presently missing (either reordered or lost) packets' payloads are estimated
92
+ // based on the average packet size
93
+ BytesReceivedLoss uint64 `json:"bytesReceivedLoss"`
94
+ // Same as packetsRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
95
+ BytesRetrans uint64 `json:"bytesRetrans"`
96
+ // Same as packetsReceivedRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
97
+ BytesReceivedRetrans uint64 `json:"bytesReceivedRetrans"`
98
+ // Same as PacketsReceivedBelated, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
99
+ BytesReceivedBelated uint64 `json:"bytesReceivedBelated"`
100
+ // Same as packetsSendDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
101
+ BytesSendDrop uint64 `json:"bytesSendDrop"`
102
+ // Same as packetsReceivedDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
103
+ BytesReceivedDrop uint64 `json:"bytesReceivedDrop"`
104
+ // Same as packetsReceivedUndecrypt, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
105
+ BytesReceivedUndecrypt uint64 `json:"bytesReceivedUndecrypt"`
106
+
107
+ // Current minimum time interval between which consecutive packets are sent, in microseconds
108
+ UsPacketsSendPeriod float64 `json:"usPacketsSendPeriod"`
109
+ // The maximum number of packets that can be "in flight"
110
+ PacketsFlowWindow uint64 `json:"packetsFlowWindow"`
111
+ // The number of packets in flight
112
+ PacketsFlightSize uint64 `json:"packetsFlightSize"`
113
+ // Smoothed round-trip time (SRTT), an exponentially-weighted moving average (EWMA)
114
+ // of an endpoint's RTT samples, in milliseconds
115
+ MsRTT float64 `json:"msRTT"`
116
+ // Current transmission bandwidth, in Mbps
117
+ MbpsSendRate float64 `json:"mbpsSendRate"`
118
+ // Current receiving bandwidth, in Mbps
119
+ MbpsReceiveRate float64 `json:"mbpsReceiveRate"`
120
+ // Estimated capacity of the network link, in Mbps
121
+ MbpsLinkCapacity float64 `json:"mbpsLinkCapacity"`
122
+ // The available space in the sender's buffer, in bytes
123
+ BytesAvailSendBuf uint64 `json:"bytesAvailSendBuf"`
124
+ // The available space in the receiver's buffer, in bytes
125
+ BytesAvailReceiveBuf uint64 `json:"bytesAvailReceiveBuf"`
126
+ // Transmission bandwidth limit, in Mbps
127
+ MbpsMaxBW float64 `json:"mbpsMaxBW"`
128
+ // Maximum Segment Size (MSS), in bytes
129
+ ByteMSS uint64 `json:"byteMSS"`
130
+ // The number of packets in the sender's buffer that are already scheduled
131
+ // for sending or even possibly sent, but not yet acknowledged
132
+ PacketsSendBuf uint64 `json:"packetsSendBuf"`
133
+ // Instantaneous (current) value of packetsSndBuf, but expressed in bytes,
134
+ // including payload and all headers (IP, TCP, SRT)
135
+ BytesSendBuf uint64 `json:"bytesSendBuf"`
136
+ // The timespan (msec) of packets in the sender's buffer (unacknowledged packets)
137
+ MsSendBuf uint64 `json:"msSendBuf"`
138
+ // Timestamp-based Packet Delivery Delay value of the peer
139
+ MsSendTsbPdDelay uint64 `json:"msSendTsbPdDelay"`
140
+ // The number of acknowledged packets in receiver's buffer
141
+ PacketsReceiveBuf uint64 `json:"packetsReceiveBuf"`
142
+ // Instantaneous (current) value of packetsRcvBuf, expressed in bytes, including payload and all headers (IP, TCP, SRT)
143
+ BytesReceiveBuf uint64 `json:"bytesReceiveBuf"`
144
+ // The timespan (msec) of acknowledged packets in the receiver's buffer
145
+ MsReceiveBuf uint64 `json:"msReceiveBuf"`
146
+ // Timestamp-based Packet Delivery Delay value set on the socket via SRTO_RCVLATENCY or SRTO_LATENCY
147
+ MsReceiveTsbPdDelay uint64 `json:"msReceiveTsbPdDelay"`
148
+ // Instant value of the packet reorder tolerance
149
+ PacketsReorderTolerance uint64 `json:"packetsReorderTolerance"`
150
+ // Accumulated difference between the current time and the time-to-play of a packet that is received late
151
+ PacketsReceivedAvgBelatedTime uint64 `json:"packetsReceivedAvgBelatedTime"`
152
+ // Percentage of resent data vs. sent data
153
+ PacketsSendLossRate float64 `json:"packetsSendLossRate"`
154
+ // Percentage of retransmitted data vs. received data
155
+ PacketsReceivedLossRate float64 `json:"packetsReceivedLossRate"`
156
+
157
+ OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"`
158
+ }
159
+
160
+ // APISRTConnList is a list of SRT connections.
161
+ type APISRTConnList struct {
162
+ ItemCount int `json:"itemCount"`
163
+ PageCount int `json:"pageCount"`
164
+ Items []APISRTConn `json:"items"`
165
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_webrtc.go ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "time"
5
+
6
+ "github.com/google/uuid"
7
+ )
8
+
9
+ // APIWebRTCServer contains methods used by the API and Metrics server.
10
+ type APIWebRTCServer interface {
11
+ APISessionsList() (*APIWebRTCSessionList, error)
12
+ APISessionsGet(uuid.UUID) (*APIWebRTCSession, error)
13
+ APISessionsKick(uuid.UUID) error
14
+ }
15
+
16
+ // APIWebRTCSessionState is the state of a WebRTC connection.
17
+ type APIWebRTCSessionState string
18
+
19
+ // states.
20
+ const (
21
+ APIWebRTCSessionStateRead APIWebRTCSessionState = "read"
22
+ APIWebRTCSessionStatePublish APIWebRTCSessionState = "publish"
23
+ )
24
+
25
+ // APIWebRTCSession is a WebRTC session.
26
+ type APIWebRTCSession struct {
27
+ ID uuid.UUID `json:"id"`
28
+ Created time.Time `json:"created"`
29
+ RemoteAddr string `json:"remoteAddr"`
30
+ PeerConnectionEstablished bool `json:"peerConnectionEstablished"`
31
+ LocalCandidate string `json:"localCandidate"`
32
+ RemoteCandidate string `json:"remoteCandidate"`
33
+ State APIWebRTCSessionState `json:"state"`
34
+ Path string `json:"path"`
35
+ Query string `json:"query"`
36
+ User string `json:"user"`
37
+ UserAgent string `json:"userAgent"`
38
+ InboundBytes uint64 `json:"inboundBytes"`
39
+ InboundRTPPackets uint64 `json:"inboundRTPPackets"`
40
+ InboundRTPPacketsLost uint64 `json:"inboundRTPPacketsLost"`
41
+ InboundRTPPacketsJitter float64 `json:"inboundRTPPacketsJitter"`
42
+ InboundRTCPPackets uint64 `json:"inboundRTCPPackets"`
43
+ OutboundBytes uint64 `json:"outboundBytes"`
44
+ OutboundRTPPackets uint64 `json:"outboundRTPPackets"`
45
+ OutboundRTCPPackets uint64 `json:"outboundRTCPPackets"`
46
+ OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"`
47
+ // deprecated
48
+ BytesReceived uint64 `json:"bytesReceived" deprecated:"true"`
49
+ BytesSent uint64 `json:"bytesSent" deprecated:"true"`
50
+ RTPPacketsReceived uint64 `json:"rtpPacketsReceived" deprecated:"true"`
51
+ RTPPacketsSent uint64 `json:"rtpPacketsSent" deprecated:"true"`
52
+ RTPPacketsLost uint64 `json:"rtpPacketsLost" deprecated:"true"`
53
+ RTPPacketsJitter float64 `json:"rtpPacketsJitter" deprecated:"true"`
54
+ RTCPPacketsReceived uint64 `json:"rtcpPacketsReceived" deprecated:"true"`
55
+ RTCPPacketsSent uint64 `json:"rtcpPacketsSent" deprecated:"true"`
56
+ }
57
+
58
+ // APIWebRTCSessionList is a list of WebRTC sessions.
59
+ type APIWebRTCSessionList struct {
60
+ ItemCount int `json:"itemCount"`
61
+ PageCount int `json:"pageCount"`
62
+ Items []APIWebRTCSession `json:"items"`
63
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/defs.go ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ // Package defs contains shared definitions.
2
+ package defs
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path.go ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "fmt"
5
+
6
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
7
+
8
+ "github.com/bluenviron/mediamtx/internal/conf"
9
+ "github.com/bluenviron/mediamtx/internal/externalcmd"
10
+ "github.com/bluenviron/mediamtx/internal/stream"
11
+ )
12
+
13
+ // PathNoStreamAvailableError is returned when no one is publishing.
14
+ type PathNoStreamAvailableError struct {
15
+ PathName string
16
+ }
17
+
18
+ // Error implements the error interface.
19
+ func (e *PathNoStreamAvailableError) Error() string {
20
+ return fmt.Sprintf("no stream is available on path '%s'", e.PathName)
21
+ }
22
+
23
+ // Path is a path.
24
+ type Path interface {
25
+ Name() string
26
+ SafeConf() *conf.Path
27
+ ExternalCmdEnv() externalcmd.Environment
28
+ RemovePublisher(req PathRemovePublisherReq)
29
+ RemoveReader(req PathRemoveReaderReq)
30
+ }
31
+
32
+ // PathFindPathConfRes contains the response of FindPathConf().
33
+ type PathFindPathConfRes struct {
34
+ Conf *conf.Path
35
+ User string
36
+ Err error
37
+ }
38
+
39
+ // PathFindPathConfReq contains arguments of FindPathConf().
40
+ type PathFindPathConfReq struct {
41
+ AccessRequest PathAccessRequest
42
+ Res chan PathFindPathConfRes
43
+ }
44
+
45
+ // PathDescribeRes contains the response of Describe().
46
+ type PathDescribeRes struct {
47
+ Path Path
48
+ Stream *stream.Stream
49
+ Redirect string
50
+ Err error
51
+ }
52
+
53
+ // PathDescribeReq contains arguments of Describe().
54
+ type PathDescribeReq struct {
55
+ AccessRequest PathAccessRequest
56
+ Res chan PathDescribeRes
57
+ }
58
+
59
+ // PathAddPublisherRes contains the response of AddPublisher().
60
+ type PathAddPublisherRes struct {
61
+ Path Path
62
+ User string
63
+ SubStream *stream.SubStream
64
+ Err error
65
+ }
66
+
67
+ // PathAddPublisherReq contains arguments of AddPublisher().
68
+ type PathAddPublisherReq struct {
69
+ Author Publisher
70
+ Desc *description.Session
71
+ UseRTPPackets bool
72
+ ReplaceNTP bool
73
+ ConfToCompare *conf.Path
74
+ AccessRequest PathAccessRequest
75
+ Res chan PathAddPublisherRes
76
+ }
77
+
78
+ // PathRemovePublisherReq contains arguments of RemovePublisher().
79
+ type PathRemovePublisherReq struct {
80
+ Author Publisher
81
+ Res chan struct{}
82
+ }
83
+
84
+ // PathAddReaderRes contains the response of AddReader().
85
+ type PathAddReaderRes struct {
86
+ Path Path
87
+ User string
88
+ Stream *stream.Stream
89
+ Err error
90
+ }
91
+
92
+ // PathAddReaderReq contains arguments of AddReader().
93
+ type PathAddReaderReq struct {
94
+ Author Reader
95
+ AccessRequest PathAccessRequest
96
+ Res chan PathAddReaderRes
97
+ }
98
+
99
+ // PathRemoveReaderReq contains arguments of RemoveReader().
100
+ type PathRemoveReaderReq struct {
101
+ Author Reader
102
+ Res chan struct{}
103
+ }
104
+
105
+ // PathSourceStaticSetReadyRes contains the response of SetReady().
106
+ type PathSourceStaticSetReadyRes struct {
107
+ SubStream *stream.SubStream
108
+ Err error
109
+ }
110
+
111
+ // PathSourceStaticSetReadyReq contains arguments of SetReady().
112
+ type PathSourceStaticSetReadyReq struct {
113
+ Desc *description.Session
114
+ UseRTPPackets bool
115
+ ReplaceNTP bool
116
+ Res chan PathSourceStaticSetReadyRes
117
+ }
118
+
119
+ // PathSourceStaticSetNotReadyReq contains arguments of SetNotReady().
120
+ type PathSourceStaticSetNotReadyReq struct {
121
+ Res chan struct{}
122
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path_access_request.go ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "net"
5
+
6
+ "github.com/bluenviron/mediamtx/internal/auth"
7
+ "github.com/bluenviron/mediamtx/internal/conf"
8
+ "github.com/google/uuid"
9
+ )
10
+
11
+ // PathAccessRequest is a path access request.
12
+ type PathAccessRequest struct {
13
+ Name string
14
+ Query string
15
+ UserAgent string
16
+ Publish bool
17
+ SkipAuth bool
18
+
19
+ // only if skipAuth = false
20
+ Proto auth.Protocol
21
+ ID *uuid.UUID
22
+ Credentials *auth.Credentials
23
+ IP net.IP
24
+ CustomVerifyFunc func(expectedUser string, expectedPass string) bool
25
+ }
26
+
27
+ // ToAuthRequest converts a path access request into an authentication request.
28
+ func (r *PathAccessRequest) ToAuthRequest() *auth.Request {
29
+ return &auth.Request{
30
+ Action: func() conf.AuthAction {
31
+ if r.Publish {
32
+ return conf.AuthActionPublish
33
+ }
34
+ return conf.AuthActionRead
35
+ }(),
36
+ Path: r.Name,
37
+ Query: r.Query,
38
+ Protocol: r.Proto,
39
+ ID: r.ID,
40
+ UserAgent: r.UserAgent,
41
+ Credentials: r.Credentials,
42
+ IP: r.IP,
43
+ CustomVerifyFunc: r.CustomVerifyFunc,
44
+ }
45
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/publisher.go ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ // Publisher is an entity that can publish a stream.
4
+ type Publisher interface {
5
+ Source
6
+ Close()
7
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/reader.go ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ // Reader is an entity that can read a stream.
4
+ type Reader interface {
5
+ Close()
6
+ APIReaderDescribe() *APIPathReader
7
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/source.go ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "fmt"
5
+ "strings"
6
+
7
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
8
+ "github.com/bluenviron/gortsplib/v5/pkg/format"
9
+
10
+ "github.com/bluenviron/mediamtx/internal/formatlabel"
11
+ "github.com/bluenviron/mediamtx/internal/logger"
12
+ )
13
+
14
+ // Source is an entity that can provide a stream.
15
+ // it can be:
16
+ // - Publisher
17
+ // - staticsources.Handler
18
+ // - core.sourceRedirect
19
+ type Source interface {
20
+ logger.Writer
21
+ APISourceDescribe() *APIPathSource
22
+ }
23
+
24
+ // FormatsInfo returns a description of formats.
25
+ func FormatsInfo(formats []format.Format) string {
26
+ labels := formatlabel.FormatsToLabels(formats)
27
+ codecNames := make([]string, len(labels))
28
+ for i, label := range labels {
29
+ codecNames[i] = string(label)
30
+ }
31
+
32
+ return fmt.Sprintf("%d %s (%s)",
33
+ len(formats),
34
+ func() string {
35
+ if len(formats) == 1 {
36
+ return "track"
37
+ }
38
+ return "tracks"
39
+ }(),
40
+ strings.Join(codecNames, ", "))
41
+ }
42
+
43
+ // MediasInfo returns a description of medias.
44
+ func MediasInfo(medias []*description.Media) string {
45
+ return FormatsInfo(gatherFormats(medias))
46
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/static_source.go ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package defs
2
+
3
+ import (
4
+ "context"
5
+
6
+ "github.com/bluenviron/mediamtx/internal/conf"
7
+ )
8
+
9
+ // StaticSourceRunParams is the set of params passed to Run().
10
+ type StaticSourceRunParams struct {
11
+ Context context.Context
12
+ ResolvedSource string
13
+ Conf *conf.Path
14
+ ReloadConf chan *conf.Path
15
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper.go ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package errordumper contains a counter that that periodically invokes a callback if the counter is not zero.
2
+ package errordumper
3
+
4
+ import (
5
+ "sync"
6
+ "time"
7
+ )
8
+
9
+ const (
10
+ callbackPeriod = 1 * time.Second
11
+ )
12
+
13
+ // Dumper is a counter that periodically invokes a callback if errors were added.
14
+ type Dumper struct {
15
+ OnReport func(v uint64, last error)
16
+
17
+ mutex sync.Mutex
18
+ counter uint64
19
+ absCounter uint64
20
+ last error
21
+
22
+ terminate chan struct{}
23
+ done chan struct{}
24
+ }
25
+
26
+ // Start starts the counter.
27
+ func (c *Dumper) Start() {
28
+ c.terminate = make(chan struct{})
29
+ c.done = make(chan struct{})
30
+
31
+ go c.run()
32
+ }
33
+
34
+ // Stop stops the counter.
35
+ func (c *Dumper) Stop() {
36
+ close(c.terminate)
37
+ <-c.done
38
+ }
39
+
40
+ // Add adds an error to the counter.
41
+ func (c *Dumper) Add(err error) {
42
+ c.mutex.Lock()
43
+ defer c.mutex.Unlock()
44
+ c.counter++
45
+ c.absCounter++
46
+ c.last = err
47
+ }
48
+
49
+ // Get returns the total number of errors.
50
+ func (c *Dumper) Get() uint64 {
51
+ c.mutex.Lock()
52
+ defer c.mutex.Unlock()
53
+ return c.absCounter
54
+ }
55
+
56
+ func (c *Dumper) run() {
57
+ defer close(c.done)
58
+
59
+ t := time.NewTicker(callbackPeriod)
60
+ defer t.Stop()
61
+
62
+ for {
63
+ select {
64
+ case <-c.terminate:
65
+ return
66
+
67
+ case <-t.C:
68
+ c.mutex.Lock()
69
+ var counter uint64
70
+ counter, c.counter = c.counter, 0
71
+ last := c.last
72
+ c.mutex.Unlock()
73
+
74
+ if counter != 0 {
75
+ c.OnReport(counter, last)
76
+ }
77
+ }
78
+ }
79
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper_test.go ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package errordumper
2
+
3
+ import (
4
+ "fmt"
5
+ "testing"
6
+ "time"
7
+
8
+ "github.com/stretchr/testify/require"
9
+ )
10
+
11
+ func TestDumperReport(t *testing.T) {
12
+ done := make(chan struct{})
13
+
14
+ c := &Dumper{
15
+ OnReport: func(v uint64, last error) {
16
+ require.Equal(t, uint64(1), v)
17
+ require.EqualError(t, last, "test error")
18
+ close(done)
19
+ },
20
+ }
21
+ c.Start()
22
+ defer c.Stop()
23
+
24
+ c.Add(fmt.Errorf("test error"))
25
+
26
+ select {
27
+ case <-done:
28
+ case <-time.After(2 * time.Second):
29
+ t.Errorf("should not happen")
30
+ }
31
+ }
32
+
33
+ func TestDumperDoNotReport(t *testing.T) {
34
+ c := &Dumper{
35
+ OnReport: func(_ uint64, _ error) {
36
+ t.Errorf("should not happen")
37
+ },
38
+ }
39
+ c.Start()
40
+ defer c.Stop()
41
+
42
+ <-time.After(2 * time.Second)
43
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd.go ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package externalcmd allows to launch external commands.
2
+ package externalcmd
3
+
4
+ import (
5
+ "errors"
6
+ "fmt"
7
+ "os"
8
+ "time"
9
+ )
10
+
11
+ const (
12
+ restartPause = 5 * time.Second
13
+ )
14
+
15
+ var errTerminated = errors.New("terminated")
16
+
17
+ // OnExitFunc is the prototype of onExit.
18
+ type OnExitFunc func(error)
19
+
20
+ // Environment is a Cmd environment.
21
+ type Environment map[string]string
22
+
23
+ // Cmd is an external command.
24
+ type Cmd struct {
25
+ Pool *Pool
26
+ Cmdstr string
27
+ Restart bool
28
+ Env Environment
29
+ OnExit OnExitFunc
30
+
31
+ // in
32
+ terminate chan struct{}
33
+ }
34
+
35
+ // Start starts the command.
36
+ func (c *Cmd) Start() {
37
+ if c.OnExit == nil {
38
+ c.OnExit = func(_ error) {}
39
+ }
40
+
41
+ c.terminate = make(chan struct{})
42
+
43
+ c.Pool.wg.Add(1)
44
+
45
+ go c.run()
46
+ }
47
+
48
+ // Close closes the command. It doesn't wait for the command to exit.
49
+ func (c *Cmd) Close() {
50
+ close(c.terminate)
51
+ }
52
+
53
+ func expandEnv(s string, env Environment) string {
54
+ return os.Expand(s, func(variable string) string {
55
+ if value, ok := env[variable]; ok {
56
+ return value
57
+ }
58
+ return os.Getenv(variable)
59
+ })
60
+ }
61
+
62
+ func (c *Cmd) run() {
63
+ defer c.Pool.wg.Done()
64
+
65
+ env := append([]string(nil), os.Environ()...)
66
+ for key, val := range c.Env {
67
+ env = append(env, key+"="+val)
68
+ }
69
+
70
+ for {
71
+ err := c.runOSSpecific(c.Cmdstr, env)
72
+ if errors.Is(err, errTerminated) {
73
+ return
74
+ }
75
+
76
+ if !c.Restart {
77
+ if err != nil {
78
+ c.OnExit(err)
79
+ }
80
+ return
81
+ }
82
+
83
+ if err != nil {
84
+ c.OnExit(err)
85
+ } else {
86
+ c.OnExit(fmt.Errorf("command exited with code 0"))
87
+ }
88
+
89
+ select {
90
+ case <-time.After(restartPause):
91
+ case <-c.terminate:
92
+ return
93
+ }
94
+ }
95
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os.go ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //go:build !windows
2
+
3
+ package externalcmd
4
+
5
+ import (
6
+ "errors"
7
+ "fmt"
8
+ "os"
9
+ "os/exec"
10
+ "syscall"
11
+
12
+ "github.com/kballard/go-shellquote"
13
+ )
14
+
15
+ func (c *Cmd) runOSSpecific(cmdstr string, env []string) error {
16
+ cmdParts, err := shellquote.Split(cmdstr)
17
+ if err != nil {
18
+ return err
19
+ }
20
+
21
+ for i, part := range cmdParts {
22
+ cmdParts[i] = expandEnv(part, c.Env)
23
+ }
24
+
25
+ cmd := exec.Command(cmdParts[0], cmdParts[1:]...)
26
+
27
+ cmd.Env = env
28
+ cmd.Stdout = os.Stdout
29
+ cmd.Stderr = os.Stderr
30
+
31
+ // set process group in order to allow killing subprocesses
32
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
33
+
34
+ err = cmd.Start()
35
+ if err != nil {
36
+ return err
37
+ }
38
+
39
+ cmdDone := make(chan int)
40
+ go func() {
41
+ cmdDone <- func() int {
42
+ err2 := cmd.Wait()
43
+ if err2 == nil {
44
+ return 0
45
+ }
46
+ if ee, ok := errors.AsType[*exec.ExitError](err2); ok {
47
+ ee.ExitCode()
48
+ }
49
+ return 0
50
+ }()
51
+ }()
52
+
53
+ select {
54
+ case <-c.terminate:
55
+ // the minus is needed to kill all subprocesses
56
+ syscall.Kill(-cmd.Process.Pid, syscall.SIGINT) //nolint:errcheck
57
+ <-cmdDone
58
+ return errTerminated
59
+
60
+ case c := <-cmdDone:
61
+ if c != 0 {
62
+ return fmt.Errorf("command exited with code %d", c)
63
+ }
64
+ return nil
65
+ }
66
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os_windows.go ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package externalcmd
2
+
3
+ import (
4
+ "fmt"
5
+ "os"
6
+ "os/exec"
7
+ "strings"
8
+ "syscall"
9
+ "unsafe"
10
+
11
+ "github.com/kballard/go-shellquote"
12
+ "golang.org/x/sys/windows"
13
+ )
14
+
15
+ // taken from
16
+ // https://gist.github.com/hallazzang/76f3970bfc949831808bbebc8ca15209
17
+ func createProcessGroup() (windows.Handle, error) {
18
+ h, err := windows.CreateJobObject(nil, nil)
19
+ if err != nil {
20
+ return 0, err
21
+ }
22
+
23
+ info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{
24
+ BasicLimitInformation: windows.JOBOBJECT_BASIC_LIMIT_INFORMATION{
25
+ LimitFlags: windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
26
+ },
27
+ }
28
+ _, err = windows.SetInformationJobObject(
29
+ h,
30
+ windows.JobObjectExtendedLimitInformation,
31
+ uintptr(unsafe.Pointer(&info)),
32
+ uint32(unsafe.Sizeof(info)))
33
+ if err != nil {
34
+ return 0, err
35
+ }
36
+
37
+ return h, nil
38
+ }
39
+
40
+ func closeProcessGroup(h windows.Handle) error {
41
+ return windows.CloseHandle(h)
42
+ }
43
+
44
+ func addProcessToGroup(h windows.Handle, p *os.Process) error {
45
+ // Combine the required access rights
46
+ access := uint32(windows.PROCESS_SET_QUOTA | windows.PROCESS_TERMINATE)
47
+
48
+ processHandle, err := windows.OpenProcess(access, false, uint32(p.Pid))
49
+ if err != nil {
50
+ return fmt.Errorf("failed to open process: %v", err)
51
+ }
52
+ defer windows.CloseHandle(processHandle)
53
+
54
+ err = windows.AssignProcessToJobObject(h, processHandle)
55
+ if err != nil {
56
+ return fmt.Errorf("failed to assign process to job object: %v", err)
57
+ }
58
+
59
+ return nil
60
+ }
61
+
62
+ func (c *Cmd) runOSSpecific(cmdstr string, env []string) error {
63
+ var cmd *exec.Cmd
64
+
65
+ // from Golang documentation:
66
+ // On Windows, processes receive the whole command line as a single string and do their own parsing.
67
+ // Command combines and quotes Args into a command line string with an algorithm compatible with
68
+ // applications using CommandLineToArgvW (which is the most common way). Notable exceptions are
69
+ // msiexec.exe and cmd.exe (and thus, all batch files), which have a different unquoting algorithm.
70
+ // In these or other similar cases, you can do the quoting yourself and provide the full command
71
+ // line in SysProcAttr.CmdLine, leaving Args empty.
72
+ if strings.HasPrefix(cmdstr, "cmd ") || strings.HasPrefix(cmdstr, "cmd.exe ") {
73
+ args := strings.TrimPrefix(strings.TrimPrefix(cmdstr, "cmd "), "cmd.exe ")
74
+ args = expandEnv(args, c.Env)
75
+
76
+ cmd = exec.Command("cmd.exe")
77
+ cmd.SysProcAttr = &syscall.SysProcAttr{
78
+ CmdLine: args,
79
+ }
80
+ } else {
81
+ cmdParts, err := shellquote.Split(cmdstr)
82
+ if err != nil {
83
+ return err
84
+ }
85
+
86
+ for i, part := range cmdParts {
87
+ cmdParts[i] = expandEnv(part, c.Env)
88
+ }
89
+
90
+ cmd = exec.Command(cmdParts[0], cmdParts[1:]...)
91
+ }
92
+
93
+ cmd.Env = env
94
+ cmd.Stdout = os.Stdout
95
+ cmd.Stderr = os.Stderr
96
+
97
+ // create a process group to kill all subprocesses
98
+ g, err := createProcessGroup()
99
+ if err != nil {
100
+ return err
101
+ }
102
+
103
+ err = cmd.Start()
104
+ if err != nil {
105
+ return err
106
+ }
107
+
108
+ err = addProcessToGroup(g, cmd.Process)
109
+ if err != nil {
110
+ return err
111
+ }
112
+
113
+ cmdDone := make(chan int)
114
+ go func() {
115
+ cmdDone <- func() int {
116
+ err := cmd.Wait()
117
+ if err == nil {
118
+ return 0
119
+ }
120
+ ee, ok := err.(*exec.ExitError)
121
+ if !ok {
122
+ return 0
123
+ }
124
+ return ee.ExitCode()
125
+ }()
126
+ }()
127
+
128
+ select {
129
+ case <-c.terminate:
130
+ closeProcessGroup(g)
131
+ <-cmdDone
132
+ return errTerminated
133
+
134
+ case code := <-cmdDone:
135
+ closeProcessGroup(g)
136
+ if code != 0 {
137
+ return fmt.Errorf("command exited with code %d", code)
138
+ }
139
+ return nil
140
+ }
141
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_test.go ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package externalcmd
2
+
3
+ import (
4
+ "os"
5
+ "path/filepath"
6
+ "testing"
7
+ "time"
8
+
9
+ "github.com/stretchr/testify/require"
10
+ )
11
+
12
+ func TestCmdRunExpandAfterSplit(t *testing.T) {
13
+ // if os.Expand runs before shellquote.Split, a variable value containing a
14
+ // single quote produces unbalanced quotes that cause shellquote.Split to fail.
15
+ p := &Pool{}
16
+ p.Initialize()
17
+
18
+ out := filepath.Join(t.TempDir(), "out")
19
+
20
+ cmd := &Cmd{
21
+ Pool: p,
22
+ Cmdstr: "sh -c 'echo \"$MY_VAR\" > " + out + "'",
23
+ Env: Environment{
24
+ "MY_VAR": "it's",
25
+ },
26
+ }
27
+ cmd.Start()
28
+
29
+ poolClosed := make(chan struct{})
30
+ go func() {
31
+ p.Close()
32
+ close(poolClosed)
33
+ }()
34
+
35
+ select {
36
+ case <-poolClosed:
37
+ case <-time.After(10 * time.Second):
38
+ t.Fatal("timeout")
39
+ }
40
+
41
+ byts, err := os.ReadFile(out)
42
+ require.NoError(t, err)
43
+ require.Equal(t, "it's\n", string(byts))
44
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/pool.go ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package externalcmd
2
+
3
+ import (
4
+ "sync"
5
+ )
6
+
7
+ // Pool is a pool of external commands.
8
+ type Pool struct {
9
+ wg sync.WaitGroup
10
+ }
11
+
12
+ // Initialize initializes a Pool.
13
+ func (p *Pool) Initialize() {
14
+ }
15
+
16
+ // Close waits for all external commands to exit.
17
+ func (p *Pool) Close() {
18
+ p.wg.Wait()
19
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label.go ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package formatlabel contains format label definitions.
2
+ package formatlabel
3
+
4
+ import (
5
+ "strings"
6
+
7
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
8
+ "github.com/bluenviron/gortsplib/v5/pkg/format"
9
+ )
10
+
11
+ // Label is a format label.
12
+ type Label string
13
+
14
+ // labels.
15
+ const (
16
+ // video
17
+ AV1 Label = "AV1"
18
+ VP9 Label = "VP9"
19
+ VP8 Label = "VP8"
20
+ H265 Label = "H265"
21
+ H264 Label = "H264"
22
+ MPEG4Video Label = "MPEG-4 Video"
23
+ MPEG1Video Label = "MPEG-1/2 Video"
24
+ MJPEG Label = "M-JPEG"
25
+ // audio
26
+ Opus Label = "Opus"
27
+ FLAC Label = "FLAC"
28
+ Vorbis Label = "Vorbis"
29
+ MPEG4Audio Label = "MPEG-4 Audio"
30
+ MPEG4AudioLATM Label = "MPEG-4 Audio LATM"
31
+ MPEG1Audio Label = "MPEG-1/2 Audio"
32
+ AC3 Label = "AC3"
33
+ Speex Label = "Speex"
34
+ G726 Label = "G726"
35
+ G722 Label = "G722"
36
+ G711 Label = "G711"
37
+ LPCM Label = "LPCM"
38
+ // other
39
+ MPEGTS Label = "MPEG-TS"
40
+ KLV Label = "KLV"
41
+ Generic Label = "Generic"
42
+ )
43
+
44
+ // FormatToLabel returns the label associated with a format.
45
+ func FormatToLabel(forma format.Format) Label {
46
+ switch forma.(type) {
47
+ // video
48
+ case *format.AV1:
49
+ return AV1
50
+ case *format.VP9:
51
+ return VP9
52
+ case *format.VP8:
53
+ return VP8
54
+ case *format.H265:
55
+ return H265
56
+ case *format.H264:
57
+ return H264
58
+ case *format.MPEG4Video:
59
+ return MPEG4Video
60
+ case *format.MPEG1Video:
61
+ return MPEG1Video
62
+ case *format.MJPEG:
63
+ return MJPEG
64
+ // audio
65
+ case *format.Opus:
66
+ return Opus
67
+ case *format.Vorbis:
68
+ return Vorbis
69
+ case *format.MPEG4Audio:
70
+ return MPEG4Audio
71
+ case *format.MPEG4AudioLATM:
72
+ return MPEG4AudioLATM
73
+ case *format.MPEG1Audio:
74
+ return MPEG1Audio
75
+ case *format.AC3:
76
+ return AC3
77
+ case *format.Speex:
78
+ return Speex
79
+ case *format.G726:
80
+ return G726
81
+ case *format.G722:
82
+ return G722
83
+ case *format.G711:
84
+ return G711
85
+ case *format.LPCM:
86
+ return LPCM
87
+ // other
88
+ case *format.MPEGTS:
89
+ return MPEGTS
90
+ case *format.KLV:
91
+ return KLV
92
+ case *format.Generic:
93
+ if strings.HasPrefix(strings.ToLower(forma.RTPMap()), "flac/") {
94
+ return FLAC
95
+ }
96
+ }
97
+
98
+ return Generic
99
+ }
100
+
101
+ func gatherFormats(medias []*description.Media) []format.Format {
102
+ n := 0
103
+ for _, media := range medias {
104
+ n += len(media.Formats)
105
+ }
106
+
107
+ if n == 0 {
108
+ return nil
109
+ }
110
+
111
+ formats := make([]format.Format, n)
112
+ n = 0
113
+
114
+ for _, media := range medias {
115
+ n += copy(formats[n:], media.Formats)
116
+ }
117
+
118
+ return formats
119
+ }
120
+
121
+ // FormatsToLabels returns labels of given formats.
122
+ func FormatsToLabels(formats []format.Format) []Label {
123
+ ret := make([]Label, len(formats))
124
+ for i, forma := range formats {
125
+ ret[i] = FormatToLabel(forma)
126
+ }
127
+ return ret
128
+ }
129
+
130
+ // MediasToLabels returns labels of given medias.
131
+ func MediasToLabels(medias []*description.Media) []Label {
132
+ return FormatsToLabels(gatherFormats(medias))
133
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label_test.go ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package formatlabel
2
+
3
+ import (
4
+ "testing"
5
+
6
+ "github.com/bluenviron/gortsplib/v5/pkg/description"
7
+ "github.com/bluenviron/gortsplib/v5/pkg/format"
8
+ "github.com/stretchr/testify/require"
9
+ )
10
+
11
+ func TestFormatToLabel(t *testing.T) {
12
+ codecs := []Label{
13
+ FormatToLabel(&format.AV1{}),
14
+ FormatToLabel(&format.VP9{}),
15
+ FormatToLabel(&format.VP8{}),
16
+ FormatToLabel(&format.H265{}),
17
+ FormatToLabel(&format.H264{}),
18
+ FormatToLabel(&format.MPEG4Video{}),
19
+ FormatToLabel(&format.MPEG1Video{}),
20
+ FormatToLabel(&format.MJPEG{}),
21
+ FormatToLabel(&format.Opus{}),
22
+ FormatToLabel(&format.Generic{RTPMa: "FLAC/44100/2"}),
23
+ FormatToLabel(&format.Vorbis{}),
24
+ FormatToLabel(&format.MPEG4Audio{}),
25
+ FormatToLabel(&format.MPEG4AudioLATM{}),
26
+ FormatToLabel(&format.MPEG1Audio{}),
27
+ FormatToLabel(&format.AC3{}),
28
+ FormatToLabel(&format.Speex{}),
29
+ FormatToLabel(&format.G726{}),
30
+ FormatToLabel(&format.G722{}),
31
+ FormatToLabel(&format.G711{}),
32
+ FormatToLabel(&format.LPCM{}),
33
+ FormatToLabel(&format.MPEGTS{}),
34
+ FormatToLabel(&format.KLV{}),
35
+ FormatToLabel(&format.Generic{}),
36
+ }
37
+
38
+ require.Equal(t, []Label{
39
+ AV1,
40
+ VP9,
41
+ VP8,
42
+ H265,
43
+ H264,
44
+ MPEG4Video,
45
+ MPEG1Video,
46
+ MJPEG,
47
+ Opus,
48
+ FLAC,
49
+ Vorbis,
50
+ MPEG4Audio,
51
+ MPEG4AudioLATM,
52
+ MPEG1Audio,
53
+ AC3,
54
+ Speex,
55
+ G726,
56
+ G722,
57
+ G711,
58
+ LPCM,
59
+ MPEGTS,
60
+ KLV,
61
+ Generic,
62
+ }, codecs)
63
+ }
64
+
65
+ func TestFormatsToLabels(t *testing.T) {
66
+ require.Equal(t, []Label{
67
+ H264,
68
+ Opus,
69
+ KLV,
70
+ Generic,
71
+ }, FormatsToLabels([]format.Format{
72
+ &format.H264{},
73
+ &format.Opus{},
74
+ &format.KLV{},
75
+ &format.Generic{},
76
+ }))
77
+ }
78
+
79
+ func TestMediasToLabels(t *testing.T) {
80
+ require.Equal(t, []Label{
81
+ H264,
82
+ Opus,
83
+ G711,
84
+ KLV,
85
+ }, MediasToLabels([]*description.Media{
86
+ {Formats: []format.Format{&format.H264{}}},
87
+ {Formats: []format.Format{&format.Opus{}, &format.G711{}}},
88
+ {Formats: []format.Format{&format.KLV{}}},
89
+ }))
90
+ }
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/hooks.go ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ // Package hooks contains hook implementations.
2
+ package hooks
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_connect.go ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package hooks
2
+
3
+ import (
4
+ "net"
5
+
6
+ "github.com/bluenviron/mediamtx/internal/defs"
7
+ "github.com/bluenviron/mediamtx/internal/externalcmd"
8
+ "github.com/bluenviron/mediamtx/internal/logger"
9
+ )
10
+
11
+ // OnConnectParams are the parameters of OnConnect.
12
+ type OnConnectParams struct {
13
+ Logger logger.Writer
14
+ ExternalCmdPool *externalcmd.Pool
15
+ RunOnConnect string
16
+ RunOnConnectRestart bool
17
+ RunOnDisconnect string
18
+ RTSPAddress string
19
+ Desc defs.APIPathReader
20
+ }
21
+
22
+ // OnConnect is the OnConnect hook.
23
+ func OnConnect(params OnConnectParams) func() {
24
+ var env externalcmd.Environment
25
+ var onConnectCmd *externalcmd.Cmd
26
+
27
+ if params.RunOnConnect != "" || params.RunOnDisconnect != "" {
28
+ _, port, _ := net.SplitHostPort(params.RTSPAddress)
29
+ env = externalcmd.Environment{
30
+ "RTSP_PORT": port,
31
+ "MTX_CONN_TYPE": string(params.Desc.Type),
32
+ "MTX_CONN_ID": params.Desc.ID,
33
+ }
34
+ }
35
+
36
+ if params.RunOnConnect != "" {
37
+ params.Logger.Log(logger.Info, "runOnConnect command started")
38
+
39
+ onConnectCmd = &externalcmd.Cmd{
40
+ Pool: params.ExternalCmdPool,
41
+ Cmdstr: params.RunOnConnect,
42
+ Restart: params.RunOnConnectRestart,
43
+ Env: env,
44
+ OnExit: func(err error) {
45
+ params.Logger.Log(logger.Info, "runOnConnect command exited: %v", err)
46
+ },
47
+ }
48
+ onConnectCmd.Start()
49
+ }
50
+
51
+ return func() {
52
+ if onConnectCmd != nil {
53
+ onConnectCmd.Close()
54
+ params.Logger.Log(logger.Info, "runOnConnect command stopped")
55
+ }
56
+
57
+ if params.RunOnDisconnect != "" {
58
+ params.Logger.Log(logger.Info, "runOnDisconnect command launched")
59
+ cmd := &externalcmd.Cmd{
60
+ Pool: params.ExternalCmdPool,
61
+ Cmdstr: params.RunOnDisconnect,
62
+ Restart: false,
63
+ Env: env,
64
+ }
65
+ cmd.Start()
66
+ }
67
+ }
68
+ }