Buyuk dosyalar ve gorseller (git deposundan haric tutulanlar) (part 2)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/webrtc_ice_server.goAdded+9
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/90b5d1b18dd9f8acAdded+2
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/dc806ec658c460fcAdded+2
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal.goAdded+106
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal_test.goAdded+80
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher.goAdded+122
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher_test.goAdded+145
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/api_test.goAdded+1412
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core.goAdded+1171
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core_test.goAdded+148
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/metrics_test.goAdded+513
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path.goAdded+1116
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager.goAdded+690
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager_test.goAdded+217
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_test.goAdded+1035
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/source_redirect.goAdded+20
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/test_on_demand/main.goAdded+54
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/versiongetter/main.goAdded+143
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper.goAdded+84
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper_test.goAdded+42
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api.goAdded+47
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_hls.goAdded+54
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_moq.goAdded+44
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path.goAdded+93
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track.goAdded+55
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec.goAdded+6
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec_props.goAdded+257
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_recording.goAdded+21
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtmp.goAdded+49
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtsp.goAdded+91
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_srt.goAdded+165
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_webrtc.goAdded+63
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/defs.goAdded+2
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path.goAdded+122
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path_access_request.goAdded+45
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/publisher.goAdded+7
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/reader.goAdded+7
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/source.goAdded+46
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/static_source.goAdded+15
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper.goAdded+79
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper_test.goAdded+43
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd.goAdded+95
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os.goAdded+66
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os_windows.goAdded+141
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_test.goAdded+44
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/pool.goAdded+19
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label.goAdded+133
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label_test.goAdded+90
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/hooks.goAdded+2
- fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_connect.goAdded+68
123456789package conf
// WebRTCICEServer is a WebRTC ICE Server.
type WebRTCICEServer struct {
URL string `json:"url"`
Username string `json:"username"`
Password string `json:"password"`
ClientOnly bool `json:"clientOnly"`
}12go test fuzz v1
[]byte("*0")12go test fuzz v1
[]byte("...")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106// Package yamlwrapper contains a YAML unmarshaler.
package yamlwrapper
import (
"encoding/json"
"fmt"
"github.com/bluenviron/mediamtx/internal/conf/jsonwrapper"
"github.com/goccy/go-yaml"
"github.com/goccy/go-yaml/ast"
"github.com/goccy/go-yaml/parser"
"github.com/goccy/go-yaml/token"
)
// differences with respect to the standard package:
// - some legacy YAML 1.1 boolean values (yes, no) are supported
// - all differences of jsonwrapper are inherited
func convertLegacyBools(node ast.Node) ast.Node {
if node != nil {
switch n := node.(type) {
case *ast.MappingNode:
for _, value := range n.Values {
convertLegacyBools(value)
}
case *ast.MappingValueNode:
n.Key = convertLegacyBools(n.Key).(ast.MapKeyNode)
n.Value = convertLegacyBools(n.Value)
case *ast.SequenceNode:
for i, value := range n.Values {
n.Values[i] = convertLegacyBools(value)
}
case *ast.DocumentNode:
n.Body = convertLegacyBools(n.Body)
case *ast.StringNode:
if n.Token.Type == token.StringType {
var boolVal bool
shouldConvert := false
switch n.Token.Value {
case "yes", "Yes", "YES", "on", "On", "ON":
boolVal = true
shouldConvert = true
case "no", "No", "NO", "off", "Off", "OFF":
boolVal = false
shouldConvert = true
}
if shouldConvert {
newToken := &token.Token{
Type: token.BoolType,
Value: n.Token.Value,
}
if boolVal {
newToken.Value = "true"
} else {
newToken.Value = "false"
}
boolNode := ast.Bool(newToken)
boolNode.Value = boolVal
return boolNode
}
}
}
}
return node
}
// Unmarshal loads the configuration from YAML.
func Unmarshal(buf []byte, dest any) error {
file, err := parser.ParseBytes(buf, parser.ParseComments)
if err != nil {
return err
}
if len(file.Docs) != 1 {
return fmt.Errorf("invalid YAML")
}
file.Docs[0] = convertLegacyBools(file.Docs[0]).(*ast.DocumentNode)
var temp any
if file.Docs[0].Body != nil {
err = yaml.NodeToValue(file.Docs[0].Body, &temp)
if err != nil {
return err
}
}
// convert the generic map into JSON
buf, err = json.Marshal(temp)
if err != nil {
return err
}
// load JSON into destination
return jsonwrapper.Unmarshal(buf, dest)
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980package yamlwrapper
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestUnmarshalIntegerMapKey(t *testing.T) {
buf := []byte(`
1: value
test: value2
`)
var dest any
err := Unmarshal(buf, &dest)
require.NoError(t, err)
require.Equal(t, map[string]any{
"1": "value",
"test": "value2",
}, dest)
}
func TestUnmarshalDuplicateKey(t *testing.T) {
buf := []byte(`
key: value1
key: value2
`)
err := Unmarshal(buf, &map[string]string{})
require.EqualError(t, err, "[3:1] mapping key \"key\" already defined at [2:1]"+
"\n 2 | key: value1\n> 3 | key: value2\n ^\n")
}
func TestUnmarshalUnknownFields(t *testing.T) {
type testStruct struct {
Field1 string `json:"field1"`
Field2 int `json:"field2"`
}
input := []byte(`field1: test
unknownField: value
field2: 456`)
var result testStruct
err := Unmarshal(input, &result)
require.Error(t, err)
require.EqualError(t, err, "json: unknown field \"unknownField\"")
}
func TestUnmarshalLegacyBools(t *testing.T) {
type testStruct struct {
Field1 bool `json:"field1"`
Field2 string `json:"field2"`
}
input := []byte("field1: yes\n" +
"field2: \"yes\"\n")
var result testStruct
err := Unmarshal(input, &result)
require.NoError(t, err)
require.Equal(t, true, result.Field1)
}
func TestUnmarshalEmpty(t *testing.T) {
input := []byte(``)
var result any
err := Unmarshal(input, &result)
require.NoError(t, err)
}
func FuzzUnmarshal(f *testing.F) {
f.Fuzz(func(_ *testing.T, buf []byte) {
var dest any
Unmarshal(buf, &dest) //nolint:errcheck
})
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122// Package confwatcher contains a configuration watcher.
package confwatcher
import (
"os"
"path/filepath"
"time"
"github.com/fsnotify/fsnotify"
)
const (
minInterval = 1 * time.Second
additionalWait = 10 * time.Millisecond
)
// ConfWatcher is a configuration file watcher.
type ConfWatcher struct {
FilePath string
inner *fsnotify.Watcher
absolutePath string
// in
terminate chan struct{}
// out
signal chan struct{}
done chan struct{}
}
// Initialize initializes a ConfWatcher.
func (w *ConfWatcher) Initialize() error {
if _, err := os.Stat(w.FilePath); err != nil {
return err
}
var err error
w.inner, err = fsnotify.NewWatcher()
if err != nil {
return err
}
// use absolute paths to support Darwin
w.absolutePath, _ = filepath.Abs(w.FilePath)
parentPath := filepath.Dir(w.absolutePath)
err = w.inner.Add(parentPath)
if err != nil {
w.inner.Close() //nolint:errcheck
return err
}
w.terminate = make(chan struct{})
w.signal = make(chan struct{})
w.done = make(chan struct{})
go w.run()
return nil
}
// Close closes a ConfWatcher.
func (w *ConfWatcher) Close() {
close(w.terminate)
<-w.done
}
func (w *ConfWatcher) run() {
defer close(w.done)
var lastCalled time.Time
previousWatchedPath, _ := filepath.EvalSymlinks(w.absolutePath)
outer:
for {
select {
case event := <-w.inner.Events:
if time.Since(lastCalled) < minInterval {
continue
}
currentWatchedPath, _ := filepath.EvalSymlinks(w.absolutePath)
eventPath, _ := filepath.Abs(event.Name)
eventPath, _ = filepath.EvalSymlinks(eventPath)
if currentWatchedPath == "" {
// watched file was removed; wait for write event to trigger reload
previousWatchedPath = ""
} else if currentWatchedPath != previousWatchedPath ||
(eventPath == currentWatchedPath &&
((event.Op&fsnotify.Write) == fsnotify.Write ||
(event.Op&fsnotify.Create) == fsnotify.Create)) {
// wait some additional time to allow the writer to complete its job
time.Sleep(additionalWait)
previousWatchedPath = currentWatchedPath
lastCalled = time.Now()
select {
case w.signal <- struct{}{}:
case <-w.terminate:
break outer
}
}
case <-w.inner.Errors:
break outer
case <-w.terminate:
break outer
}
}
close(w.signal)
w.inner.Close() //nolint:errcheck
}
// Watch returns a channel that is called after the configuration file has changed.
func (w *ConfWatcher) Watch() chan struct{} {
return w.signal
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145package confwatcher
import (
"os"
"testing"
"time"
"github.com/bluenviron/mediamtx/internal/test"
"github.com/stretchr/testify/require"
)
func TestNoFile(t *testing.T) {
w := &ConfWatcher{FilePath: "/nonexistent"}
err := w.Initialize()
require.Error(t, err)
}
func TestWrite(t *testing.T) {
fpath := test.CreateTempFile(t, []byte("{}"))
w := &ConfWatcher{FilePath: fpath}
err := w.Initialize()
require.NoError(t, err)
defer w.Close()
func() {
var f *os.File
f, err = os.Create(fpath)
require.NoError(t, err)
defer f.Close()
_, err = f.Write([]byte("{}"))
require.NoError(t, err)
}()
select {
case <-w.Watch():
case <-time.After(500 * time.Millisecond):
t.Errorf("timed out")
return
}
}
func TestWriteMultipleTimes(t *testing.T) {
fpath := test.CreateTempFile(t, []byte("{}"))
w := &ConfWatcher{FilePath: fpath}
err := w.Initialize()
require.NoError(t, err)
defer w.Close()
func() {
f, err2 := os.Create(fpath)
require.NoError(t, err2)
defer f.Close()
_, err2 = f.Write([]byte("{}"))
require.NoError(t, err2)
}()
time.Sleep(10 * time.Millisecond)
func() {
f, err2 := os.Create(fpath)
require.NoError(t, err2)
defer f.Close()
_, err2 = f.Write([]byte("{}"))
require.NoError(t, err2)
}()
select {
case <-w.Watch():
case <-time.After(500 * time.Millisecond):
t.Errorf("timed out")
return
}
select {
case <-time.After(500 * time.Millisecond):
case <-w.Watch():
t.Errorf("should not happen")
return
}
}
func TestDeleteCreate(t *testing.T) {
fpath := test.CreateTempFile(t, []byte("{}"))
w := &ConfWatcher{FilePath: fpath}
err := w.Initialize()
require.NoError(t, err)
defer w.Close()
os.Remove(fpath)
time.Sleep(10 * time.Millisecond)
func() {
var f *os.File
f, err = os.Create(fpath)
require.NoError(t, err)
defer f.Close()
_, err = f.Write([]byte("{}"))
require.NoError(t, err)
}()
select {
case <-w.Watch():
case <-time.After(500 * time.Millisecond):
t.Errorf("timed out")
return
}
}
func TestSymlinkDeleteCreate(t *testing.T) {
fpath := test.CreateTempFile(t, []byte("{}"))
err := os.Symlink(fpath, fpath+"-sym")
require.NoError(t, err)
w := &ConfWatcher{FilePath: fpath + "-sym"}
err = w.Initialize()
require.NoError(t, err)
defer w.Close()
os.Remove(fpath)
func() {
f, err2 := os.Create(fpath)
require.NoError(t, err2)
defer f.Close()
_, err2 = f.Write([]byte("{}"))
require.NoError(t, err2)
}()
select {
case <-w.Watch():
case <-time.After(500 * time.Millisecond):
t.Errorf("timed out")
return
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412//nolint:dupl,lll
package core
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"encoding/json"
"io"
"net/http"
"net/url"
"testing"
"time"
"github.com/bluenviron/gohlslib/v2"
"github.com/bluenviron/gortmplib"
rtmpcodecs "github.com/bluenviron/gortmplib/pkg/codecs"
"github.com/bluenviron/gortsplib/v5"
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/bluenviron/gortsplib/v5/pkg/format"
"github.com/bluenviron/gortsplib/v5/pkg/format/rtph264"
"github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts"
tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs"
srt "github.com/datarhei/gosrt"
"github.com/google/uuid"
"github.com/pion/rtp"
pwebrtc "github.com/pion/webrtc/v4"
"github.com/stretchr/testify/require"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/formatlabel"
"github.com/bluenviron/mediamtx/internal/protocols/webrtc"
"github.com/bluenviron/mediamtx/internal/protocols/whip"
"github.com/bluenviron/mediamtx/internal/test"
)
func checkClose(t *testing.T, closeFunc func() error) {
require.NoError(t, closeFunc())
}
func httpRequest(t *testing.T, hc *http.Client, method string, ur string, in any, out any) {
buf := func() io.Reader {
if in == nil {
return nil
}
byts, err := json.Marshal(in)
require.NoError(t, err)
return bytes.NewBuffer(byts)
}()
req, err := http.NewRequest(method, ur, buf)
require.NoError(t, err)
res, err := hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Errorf("bad status code: %d", res.StatusCode)
}
if out == nil {
return
}
err = json.NewDecoder(res.Body).Decode(out)
require.NoError(t, err)
}
func checkError(t *testing.T, msg string, body io.Reader) {
var resErr map[string]any
err := json.NewDecoder(body).Decode(&resErr)
require.NoError(t, err)
require.Equal(t, map[string]any{"status": "error", "error": msg}, resErr)
}
func TestAPIPathsList(t *testing.T) {
type pathSource struct {
Type string `json:"type"`
}
type path struct {
Name string `json:"name"`
Source pathSource `json:"source"`
Ready bool `json:"ready"`
Tracks []defs.APIPathTrackCodec `json:"tracks"`
InboundBytes uint64 `json:"inboundBytes"`
OutboundBytes uint64 `json:"outboundBytes"`
InboundFramesInError uint64 `json:"inboundFramesInError"`
BytesReceived uint64 `json:"bytesReceived"`
BytesSent uint64 `json:"bytesSent"`
}
type pathList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []path `json:"items"`
}
t.Run("rtsp session", func(t *testing.T) {
p, ok := newInstance(t, "api: yes\n"+
"paths:\n"+
" mypath:\n")
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
media0 := test.UniqueMediaH264()
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:8554/mypath",
&description.Session{Medias: []*description.Media{
media0,
test.MediaMPEG4Audio,
}})
require.NoError(t, err)
defer source.Close()
err = source.WritePacketRTP(media0, &rtp.Packet{
Header: rtp.Header{
Version: 2,
PayloadType: 96,
},
Payload: []byte{5, 1, 2, 3, 4},
})
require.NoError(t, err)
var out pathList
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out)
require.Equal(t, pathList{
ItemCount: 1,
PageCount: 1,
Items: []path{{
Name: "mypath",
Source: pathSource{
Type: "rtspSession",
},
Ready: true,
Tracks: []defs.APIPathTrackCodec{formatlabel.H264, formatlabel.MPEG4Audio},
InboundBytes: 17,
InboundFramesInError: 0,
BytesReceived: 17,
}},
}, out)
})
t.Run("rtsps session", func(t *testing.T) {
serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
p, ok := newInstance(t, "api: yes\n"+
"rtspEncryption: optional\n"+
"rtspServerCert: "+serverCertFpath+"\n"+
"rtspServerKey: "+serverKeyFpath+"\n"+
"paths:\n"+
" mypath:\n")
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
source := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}}
err := source.StartRecording("rtsps://localhost:8322/mypath",
&description.Session{Medias: []*description.Media{
test.UniqueMediaH264(),
test.UniqueMediaMPEG4Audio(),
}})
require.NoError(t, err)
defer source.Close()
var out pathList
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out)
require.Equal(t, pathList{
ItemCount: 1,
PageCount: 1,
Items: []path{{
Name: "mypath",
Source: pathSource{
Type: "rtspsSession",
},
Ready: true,
Tracks: []defs.APIPathTrackCodec{formatlabel.H264, formatlabel.MPEG4Audio},
}},
}, out)
})
t.Run("rtsp source", func(t *testing.T) {
p, ok := newInstance(t, "api: yes\n"+
"paths:\n"+
" mypath:\n"+
" source: rtsp://127.0.0.1:1234/mypath\n"+
" sourceOnDemand: yes\n")
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var out pathList
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out)
require.Equal(t, pathList{
ItemCount: 1,
PageCount: 1,
Items: []path{{
Name: "mypath",
Source: pathSource{
Type: "rtspSource",
},
Ready: false,
Tracks: []defs.APIPathTrackCodec{},
}},
}, out)
})
t.Run("rtmp source", func(t *testing.T) {
p, ok := newInstance(t, "api: yes\n"+
"paths:\n"+
" mypath:\n"+
" source: rtmp://127.0.0.1:1234/mypath\n"+
" sourceOnDemand: yes\n")
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var out pathList
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out)
require.Equal(t, pathList{
ItemCount: 1,
PageCount: 1,
Items: []path{{
Name: "mypath",
Source: pathSource{
Type: "rtmpSource",
},
Ready: false,
Tracks: []defs.APIPathTrackCodec{},
}},
}, out)
})
t.Run("hls source", func(t *testing.T) {
p, ok := newInstance(t, "api: yes\n"+
"paths:\n"+
" mypath:\n"+
" source: http://127.0.0.1:1234/mypath\n"+
" sourceOnDemand: yes\n")
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var out pathList
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/list", nil, &out)
require.Equal(t, pathList{
ItemCount: 1,
PageCount: 1,
Items: []path{{
Name: "mypath",
Source: pathSource{
Type: "hlsSource",
},
Ready: false,
Tracks: []defs.APIPathTrackCodec{},
}},
}, out)
})
}
func TestAPIPathsGet(t *testing.T) {
p, ok := newInstance(t, "api: yes\n"+
"paths:\n"+
" all_others:\n")
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
for _, ca := range []string{"ok", "ok-nested", "not found"} {
t.Run(ca, func(t *testing.T) {
type pathSource struct {
Type string `json:"type"`
}
type path struct {
Name string `json:"name"`
Source pathSource `json:"source"`
Ready bool `json:"Ready"`
Tracks []defs.APIPathTrackCodec `json:"tracks"`
InboundBytes uint64 `json:"inboundBytes"`
OutboundBytes uint64 `json:"outboundBytes"`
InboundFramesInError uint64 `json:"inboundFramesInError"`
BytesReceived uint64 `json:"bytesReceived"`
BytesSent uint64 `json:"bytesSent"`
}
var pathName string
switch ca {
case "ok":
pathName = "mypath"
case "ok-nested":
pathName = "my/nested/path"
case "not found":
pathName = "nonexisting"
}
if ca == "ok" || ca == "ok-nested" {
source := gortsplib.Client{}
err := source.StartRecording("rtsp://localhost:8554/"+pathName,
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer source.Close()
var out path
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/paths/get/"+pathName, nil, &out)
require.Equal(t, path{
Name: pathName,
Source: pathSource{
Type: "rtspSession",
},
Ready: true,
Tracks: []defs.APIPathTrackCodec{formatlabel.H264},
}, out)
} else {
res, err := hc.Get("http://localhost:9997/v3/paths/get/" + pathName)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusNotFound, res.StatusCode)
checkError(t, "path not found", res.Body)
}
})
}
}
func TestAPIProtocolListGet(t *testing.T) {
serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
for _, ca := range []string{
"rtsp conns",
"rtsp sessions",
"rtsps conns",
"rtsps sessions",
"rtmp",
"rtmps",
"hls sessions",
"hls muxers",
"webrtc",
"srt",
} {
t.Run(ca, func(t *testing.T) {
cnf := "api: yes\n"
switch ca {
case "rtsps conns", "rtsps sessions":
cnf += "rtspEncryption: strict\n" +
"rtspServerCert: " + serverCertFpath + "\n" +
"rtspServerKey: " + serverKeyFpath + "\n"
case "rtmps":
cnf += "rtmpEncryption: strict\n" +
"rtmpServerCert: " + serverCertFpath + "\n" +
"rtmpServerKey: " + serverKeyFpath + "\n"
}
cnf += "paths:\n" +
" all_others:\n"
p, ok := newInstance(t, cnf)
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
medi := test.UniqueMediaH264()
switch ca { //nolint:dupl
case "rtsp conns", "rtsp sessions":
source := gortsplib.Client{}
err := source.StartRecording("rtsp://localhost:8554/mypath?key=val",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
case "rtsps conns", "rtsps sessions":
source := gortsplib.Client{
TLSConfig: &tls.Config{InsecureSkipVerify: true},
}
err := source.StartRecording("rtsps://localhost:8322/mypath?key=val",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
case "rtmp", "rtmps":
var port string
if ca == "rtmp" {
port = "1935"
} else {
port = "1936"
}
var rawURL string
if ca == "rtmps" {
rawURL = "rtmps://"
} else {
rawURL = "rtmp://"
}
rawURL += "127.0.0.1:" + port + "/mypath?key=val"
var u *url.URL
u, err := url.Parse(rawURL)
require.NoError(t, err)
conn := &gortmplib.Client{
URL: u,
TLSConfig: &tls.Config{InsecureSkipVerify: true},
Publish: true,
}
err = conn.Initialize(context.Background())
require.NoError(t, err)
defer conn.Close()
track := &gortmplib.Track{
Codec: &rtmpcodecs.H264{
SPS: test.FormatH264.SPS,
PPS: test.FormatH264.PPS,
},
}
w := &gortmplib.Writer{
Conn: conn,
Tracks: []*gortmplib.Track{track},
}
err = w.Initialize()
require.NoError(t, err)
err = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}})
require.NoError(t, err)
time.Sleep(500 * time.Millisecond)
case "hls sessions", "hls muxers":
source := gortsplib.Client{}
err := source.StartRecording("rtsp://localhost:8554/mypath",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
go func() {
time.Sleep(500 * time.Millisecond)
for i := range 3 {
/*source.WritePacketRTP(medi, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 123 + uint16(i),
Timestamp: 45343 + uint32(i)*90000,
SSRC: 563423,
},
Payload: []byte{
testSPS,
0x05,
},
})
[]byte{ // 1920x1080 baseline
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02,
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, 0x20,
},*/
err2 := source.WritePacketRTP(medi, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 123 + uint16(i),
Timestamp: 45343 + uint32(i)*90000,
SSRC: 563423,
},
Payload: []byte{
// testSPS,
0x05,
},
})
require.NoError(t, err2)
}
}()
func() {
res, err2 := hc.Get("http://localhost:8888/mypath/index.m3u8")
require.NoError(t, err2)
defer res.Body.Close()
require.Equal(t, 200, res.StatusCode)
}()
case "webrtc":
source := gortsplib.Client{}
err := source.StartRecording("rtsp://localhost:8554/mypath",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
var u *url.URL
u, err = url.Parse("http://localhost:8889/mypath/whep?key=val")
require.NoError(t, err)
go func() {
time.Sleep(500 * time.Millisecond)
err2 := source.WritePacketRTP(medi, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 123,
Timestamp: 45343,
SSRC: 563423,
},
Payload: []byte{5, 1, 2, 3, 4},
})
require.NoError(t, err2)
}()
c := &whip.Client{
HTTPClient: hc,
URL: u,
Log: test.NilLogger,
}
err = c.Initialize(context.Background())
require.NoError(t, err)
defer checkClose(t, c.Close)
case "srt":
conf := srt.DefaultConfig()
conf.StreamId = "publish:mypath:::key=val"
var conn srt.Conn
conn, err := srt.Dial("srt", "localhost:8890", conf)
require.NoError(t, err)
defer conn.Close()
track := &mpegts.Track{
Codec: &tscodecs.H264{},
}
bw := bufio.NewWriter(conn)
w := &mpegts.Writer{W: bw, Tracks: []*mpegts.Track{track}}
err = w.Initialize()
require.NoError(t, err)
err = w.WriteH264(track, 0, 0, [][]byte{{1}})
require.NoError(t, err)
err = bw.Flush()
require.NoError(t, err)
time.Sleep(500 * time.Millisecond)
}
var pa string
switch ca {
case "rtsp conns":
pa = "rtspconns"
case "rtsp sessions":
pa = "rtspsessions"
case "rtsps conns":
pa = "rtspsconns"
case "rtsps sessions":
pa = "rtspssessions"
case "rtmp":
pa = "rtmpconns"
case "rtmps":
pa = "rtmpsconns"
case "hls sessions":
pa = "hlssessions"
case "hls muxers":
pa = "hlsmuxers"
case "webrtc":
pa = "webrtcsessions"
case "srt":
pa = "srtconns"
}
var out1 any
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/list", nil, &out1)
switch ca {
case "rtsp conns":
require.Equal(t, map[string]any{
"pageCount": float64(1),
"itemCount": float64(1),
"items": []any{
map[string]any{
"inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
"outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
"bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
"bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
"created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
"id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
"remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
"session": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["session"],
"tunnel": "none",
},
},
}, out1)
case "rtsp sessions":
require.Equal(t, map[string]any{
"pageCount": float64(1),
"itemCount": float64(1),
"items": []any{
map[string]any{
"inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
"inboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"],
"inboundRTPPacketsLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"],
"inboundRTPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsInError"],
"inboundRTPPacketsJitter": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"],
"inboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"],
"inboundRTCPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPacketsInError"],
"outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
"outboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"],
"outboundRTPPacketsReportedLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsReportedLost"],
"outboundRTPPacketsDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsDiscarded"],
"outboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"],
"bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
"bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
"created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
"id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
"path": "mypath",
"query": "key=val",
"user": "",
"remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
"state": "publish",
"transport": "UDP",
"profile": "AVP",
"rtpPacketsReceived": float64(0),
"rtpPacketsSent": float64(0),
"rtpPacketsLost": float64(0),
"rtpPacketsInError": float64(0),
"rtpPacketsJitter": float64(0),
"rtcpPacketsReceived": float64(0),
"rtcpPacketsSent": float64(0),
"rtcpPacketsInError": float64(0),
"conns": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["conns"],
"userAgent": "gortsplib",
},
},
}, out1)
case "rtsps conns":
require.Equal(t, map[string]any{
"pageCount": float64(1),
"itemCount": float64(1),
"items": []any{
map[string]any{
"inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
"outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
"bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
"bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
"created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
"id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
"remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
"session": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["session"],
"tunnel": "none",
},
},
}, out1)
case "rtsps sessions":
require.Equal(t, map[string]any{
"pageCount": float64(1),
"itemCount": float64(1),
"items": []any{
map[string]any{
"inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
"inboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"],
"inboundRTPPacketsLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"],
"inboundRTPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsInError"],
"inboundRTPPacketsJitter": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"],
"inboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"],
"inboundRTCPPacketsInError": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPacketsInError"],
"outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
"outboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"],
"outboundRTPPacketsReportedLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsReportedLost"],
"outboundRTPPacketsDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsDiscarded"],
"outboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"],
"bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
"bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
"created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
"id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
"path": "mypath",
"query": "key=val",
"user": "",
"remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
"state": "publish",
"transport": "UDP",
"profile": "SAVP",
"rtpPacketsReceived": float64(0),
"rtpPacketsSent": float64(0),
"rtpPacketsLost": float64(0),
"rtpPacketsInError": float64(0),
"rtpPacketsJitter": float64(0),
"rtcpPacketsReceived": float64(0),
"rtcpPacketsSent": float64(0),
"rtcpPacketsInError": float64(0),
"conns": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["conns"],
"userAgent": "gortsplib",
},
},
}, out1)
case "rtmp":
require.Equal(t, map[string]any{
"pageCount": float64(1),
"itemCount": float64(1),
"items": []any{
map[string]any{
"inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
"outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
"outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"],
"bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
"bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
"created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
"id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
"path": "mypath",
"query": "key=val",
"user": "",
"remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
"state": "publish",
"userAgent": "LNX 9,0,124,2",
},
},
}, out1)
case "rtmps":
require.Equal(t, map[string]any{
"pageCount": float64(1),
"itemCount": float64(1),
"items": []any{
map[string]any{
"inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
"outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
"outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"],
"bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
"bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
"created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
"id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
"path": "mypath",
"query": "key=val",
"user": "",
"remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
"state": "publish",
"userAgent": "LNX 9,0,124,2",
},
},
}, out1)
case "hls sessions":
require.Equal(t, map[string]any{
"itemCount": float64(1),
"pageCount": float64(1),
"items": []any{
map[string]any{
"id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
"created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
"remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
"path": "mypath",
"query": "",
"user": "",
"isCDN": false,
"outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
"userAgent": "Go-http-client/1.1",
},
},
}, out1)
case "hls muxers":
require.Equal(t, map[string]any{
"itemCount": float64(1),
"pageCount": float64(1),
"items": []any{
map[string]any{
"outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
"outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"],
"bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
"created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
"lastRequest": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["lastRequest"],
"path": "mypath",
},
},
}, out1)
case "webrtc":
require.Equal(t, map[string]any{
"itemCount": float64(1),
"pageCount": float64(1),
"items": []any{
map[string]any{
"inboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"],
"inboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"],
"inboundRTPPacketsLost": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"],
"inboundRTPPacketsJitter": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"],
"inboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"],
"outboundBytes": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"],
"outboundRTPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"],
"outboundRTCPPackets": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"],
"outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"],
"bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
"bytesSent": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"],
"created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
"id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
"localCandidate": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["localCandidate"],
"path": "mypath",
"peerConnectionEstablished": true,
"query": "key=val",
"remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
"remoteCandidate": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteCandidate"],
"state": "read",
"user": "",
"rtcpPacketsReceived": float64(0),
"rtcpPacketsSent": float64(2),
"rtpPacketsJitter": float64(0),
"rtpPacketsLost": float64(0),
"rtpPacketsReceived": float64(0),
"rtpPacketsSent": float64(1),
"userAgent": "Go-http-client/1.1",
},
},
}, out1)
case "srt":
require.Equal(t, map[string]any{
"itemCount": float64(1),
"pageCount": float64(1),
"items": []any{
map[string]any{
"byteMSS": float64(1500),
"bytesAvailReceiveBuf": float64(0),
"bytesAvailSendBuf": float64(0),
"bytesReceiveBuf": float64(0),
"bytesReceived": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"],
"bytesReceivedBelated": float64(0),
"bytesReceivedDrop": float64(0),
"bytesReceivedLoss": float64(0),
"bytesReceivedRetrans": float64(0),
"bytesReceivedUndecrypt": float64(0),
"outboundFramesDiscarded": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"],
"bytesReceivedUnique": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceivedUnique"],
"bytesRetrans": float64(0),
"bytesSendBuf": float64(0),
"bytesSendDrop": float64(0),
"bytesSent": float64(0),
"bytesSentUnique": float64(0),
"created": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["created"],
"id": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"],
"mbpsLinkCapacity": float64(0),
"mbpsMaxBW": float64(-1),
"mbpsReceiveRate": float64(0),
"mbpsSendRate": float64(0),
"msRTT": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["msRTT"],
"msReceiveBuf": float64(0),
"msReceiveTsbPdDelay": float64(120),
"msSendBuf": float64(0),
"msSendTsbPdDelay": float64(120),
"packetsFlightSize": float64(0),
"packetsFlowWindow": float64(25600),
"packetsReceiveBuf": float64(0),
"packetsReceived": float64(1),
"packetsReceivedACK": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsReceivedACK"],
"packetsReceivedAvgBelatedTime": float64(0),
"packetsReceivedBelated": float64(0),
"packetsReceivedDrop": float64(0),
"packetsReceivedKM": float64(0),
"packetsReceivedLoss": float64(0),
"packetsReceivedLossRate": float64(0),
"packetsReceivedNAK": float64(0),
"packetsReceivedRetrans": float64(0),
"packetsReceivedUndecrypt": float64(0),
"packetsReceivedUnique": float64(1),
"packetsReorderTolerance": float64(0),
"packetsRetrans": float64(0),
"packetsSendBuf": float64(0),
"packetsSendDrop": float64(0),
"packetsSendLoss": float64(0),
"packetsSendLossRate": float64(0),
"packetsSent": float64(0),
"packetsSentACK": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsSentACK"],
"packetsSentKM": float64(0),
"packetsSentNAK": float64(0),
"packetsSentUnique": float64(0),
"path": "mypath",
"query": "key=val",
"remoteAddr": out1.(map[string]any)["items"].([]any)[0].(map[string]any)["remoteAddr"],
"state": "publish",
"user": "",
"usPacketsSendPeriod": float64(10.967254638671875),
"usSndDuration": float64(0),
},
},
}, out1)
}
var out2 any
if ca == "hls muxers" {
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/get/"+
out1.(map[string]any)["items"].([]any)[0].(map[string]any)["path"].(string),
nil, &out2)
} else {
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/get/"+
out1.(map[string]any)["items"].([]any)[0].(map[string]any)["id"].(string),
nil, &out2)
}
switch ca {
case "rtsp conns", "rtsps conns":
out2.(map[string]any)["inboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"]
out2.(map[string]any)["outboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"]
out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"]
out2.(map[string]any)["bytesSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"]
case "rtsp sessions", "rtsps sessions":
out2.(map[string]any)["inboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"]
out2.(map[string]any)["inboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"]
out2.(map[string]any)["inboundRTPPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"]
out2.(map[string]any)["inboundRTPPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsInError"]
out2.(map[string]any)["inboundRTPPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"]
out2.(map[string]any)["inboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"]
out2.(map[string]any)["inboundRTCPPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPacketsInError"]
out2.(map[string]any)["outboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"]
out2.(map[string]any)["outboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"]
out2.(map[string]any)["outboundRTPPacketsReportedLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsReportedLost"]
out2.(map[string]any)["outboundRTPPacketsDiscarded"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPacketsDiscarded"]
out2.(map[string]any)["outboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"]
out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"]
out2.(map[string]any)["bytesSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"]
out2.(map[string]any)["rtpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsReceived"]
out2.(map[string]any)["rtpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsSent"]
out2.(map[string]any)["rtpPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsLost"]
out2.(map[string]any)["rtpPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsInError"]
out2.(map[string]any)["rtpPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsJitter"]
out2.(map[string]any)["rtcpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsReceived"]
out2.(map[string]any)["rtcpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsSent"]
out2.(map[string]any)["rtcpPacketsInError"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsInError"]
case "webrtc":
out2.(map[string]any)["inboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundBytes"]
out2.(map[string]any)["inboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPackets"]
out2.(map[string]any)["inboundRTPPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsLost"]
out2.(map[string]any)["inboundRTPPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTPPacketsJitter"]
out2.(map[string]any)["inboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["inboundRTCPPackets"]
out2.(map[string]any)["outboundBytes"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundBytes"]
out2.(map[string]any)["outboundRTPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTPPackets"]
out2.(map[string]any)["outboundRTCPPackets"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundRTCPPackets"]
out2.(map[string]any)["outboundFramesDiscarded"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["outboundFramesDiscarded"]
out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"]
out2.(map[string]any)["bytesSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesSent"]
out2.(map[string]any)["rtpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsReceived"]
out2.(map[string]any)["rtpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsSent"]
out2.(map[string]any)["rtpPacketsLost"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsLost"]
out2.(map[string]any)["rtpPacketsJitter"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtpPacketsJitter"]
out2.(map[string]any)["rtcpPacketsReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsReceived"]
out2.(map[string]any)["rtcpPacketsSent"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["rtcpPacketsSent"]
case "hls muxers":
out2.(map[string]any)["lastRequest"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["lastRequest"]
case "srt":
out2.(map[string]any)["bytesReceived"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceived"]
out2.(map[string]any)["bytesReceivedUnique"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["bytesReceivedUnique"]
out2.(map[string]any)["packetsReceivedACK"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsReceivedACK"]
out2.(map[string]any)["packetsSentACK"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["packetsSentACK"]
out2.(map[string]any)["msRTT"] = out1.(map[string]any)["items"].([]any)[0].(map[string]any)["msRTT"]
}
require.Equal(t, out1.(map[string]any)["items"].([]any)[0], out2)
})
}
}
func TestAPIProtocolGetNotFound(t *testing.T) {
serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
for _, ca := range []string{
"rtsp conns",
"rtsp sessions",
"rtsps conns",
"rtsps sessions",
"rtmp",
"rtmps",
"hls sessions",
"hls muxers",
"webrtc",
"srt",
} {
t.Run(ca, func(t *testing.T) {
cnf := "api: yes\n"
switch ca {
case "rtsps conns", "rtsps sessions":
cnf += "rtspTransports: [tcp]\n" +
"rtspEncryption: strict\n" +
"rtspServerCert: " + serverCertFpath + "\n" +
"rtspServerKey: " + serverKeyFpath + "\n"
case "rtmps":
cnf += "rtmpEncryption: strict\n" +
"rtmpServerCert: " + serverCertFpath + "\n" +
"rtmpServerKey: " + serverKeyFpath + "\n"
}
cnf += "paths:\n" +
" all_others:\n"
p, ok := newInstance(t, cnf)
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var pa string
switch ca {
case "rtsp conns":
pa = "rtspconns"
case "rtsp sessions":
pa = "rtspsessions"
case "rtsps conns":
pa = "rtspsconns"
case "rtsps sessions":
pa = "rtspssessions"
case "rtmp":
pa = "rtmpconns"
case "rtmps":
pa = "rtmpsconns"
case "hls sessions":
pa = "hlssessions"
case "hls muxers":
pa = "hlsmuxers"
case "webrtc":
pa = "webrtcsessions"
case "srt":
pa = "srtconns"
}
func() {
var req *http.Request
req, err := http.NewRequest(http.MethodGet, "http://localhost:9997/v3/"+pa+"/get/"+uuid.New().String(), nil)
require.NoError(t, err)
var res *http.Response
res, err = hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusNotFound, res.StatusCode)
switch ca {
case "rtsp conns", "rtsps conns", "rtmp", "rtmps", "srt":
checkError(t, "connection not found", res.Body)
case "rtsp sessions", "rtsps sessions", "hls sessions", "webrtc":
checkError(t, "session not found", res.Body)
case "hls muxers":
checkError(t, "muxer not found", res.Body)
}
}()
})
}
}
func TestAPIProtocolKick(t *testing.T) {
serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
for _, ca := range []string{
"rtsp",
"rtsps",
"rtmp",
"hls",
"webrtc",
"srt",
} {
t.Run(ca, func(t *testing.T) {
cnf := "api: yes\n"
if ca == "rtsps" {
cnf += "rtspTransports: [tcp]\n" +
"rtspEncryption: strict\n" +
"rtspServerCert: " + serverCertFpath + "\n" +
"rtspServerKey: " + serverKeyFpath + "\n"
}
cnf += "paths:\n" +
" all_others:\n"
p, ok := newInstance(t, cnf)
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
medi := test.MediaH264
switch ca {
case "rtsp":
source := gortsplib.Client{}
err := source.StartRecording("rtsp://localhost:8554/mypath",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
case "rtsps":
source := gortsplib.Client{
TLSConfig: &tls.Config{InsecureSkipVerify: true},
}
err := source.StartRecording("rtsps://localhost:8322/mypath",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
case "rtmp":
var u *url.URL
u, err := url.Parse("rtmp://localhost:1935/mypath")
require.NoError(t, err)
conn := &gortmplib.Client{
URL: u,
Publish: true,
}
err = conn.Initialize(context.Background())
require.NoError(t, err)
defer conn.Close()
track := &gortmplib.Track{
Codec: &rtmpcodecs.H264{
SPS: test.FormatH264.SPS,
PPS: test.FormatH264.PPS,
},
}
w := &gortmplib.Writer{
Conn: conn,
Tracks: []*gortmplib.Track{track},
}
err = w.Initialize()
require.NoError(t, err)
err = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}})
require.NoError(t, err)
case "hls":
source := gortsplib.Client{}
err := source.StartRecording("rtsp://localhost:8554/mypath",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
var enc *rtph264.Encoder
enc, err = medi.Formats[0].(*format.H264).CreateEncoder()
require.NoError(t, err)
tracksReceived := make(chan struct{})
client := &gohlslib.Client{
URI: "http://localhost:8888/mypath/index.m3u8",
OnTracks: func(_ []*gohlslib.Track) error {
close(tracksReceived)
return nil
},
}
err = client.Start()
require.NoError(t, err)
defer client.Close()
time.Sleep(500 * time.Millisecond)
for i := range 2 {
var pkts []*rtp.Packet
pkts, err = enc.Encode([][]byte{{5, 2, 3, 4}})
require.NoError(t, err)
pkts[0].Timestamp = uint32(i * 90000)
err = source.WritePacketRTP(medi, pkts[0])
require.NoError(t, err)
}
<-tracksReceived
case "webrtc":
var u *url.URL
u, err := url.Parse("http://localhost:8889/mypath/whip")
require.NoError(t, err)
track := &webrtc.OutboundTrack{
Caps: pwebrtc.RTPCodecCapability{
MimeType: pwebrtc.MimeTypeH264,
ClockRate: 90000,
SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
},
}
c := &whip.Client{
HTTPClient: hc,
URL: u,
Log: test.NilLogger,
Publish: true,
OutboundTracks: []*webrtc.OutboundTrack{track},
}
err = c.Initialize(context.Background())
require.NoError(t, err)
defer func() {
require.Error(t, c.Close())
}()
case "srt":
conf := srt.DefaultConfig()
conf.StreamId = "publish:mypath"
var conn srt.Conn
conn, err := srt.Dial("srt", "localhost:8890", conf)
require.NoError(t, err)
defer conn.Close()
track := &mpegts.Track{
Codec: &tscodecs.H264{},
}
bw := bufio.NewWriter(conn)
w := &mpegts.Writer{W: bw, Tracks: []*mpegts.Track{track}}
err = w.Initialize()
require.NoError(t, err)
err = w.WriteH264(track, 0, 0, [][]byte{{1}})
require.NoError(t, err)
err = bw.Flush()
require.NoError(t, err)
}
var pa string
switch ca {
case "rtsp":
pa = "rtspsessions"
case "rtsps":
pa = "rtspssessions"
case "rtmp":
pa = "rtmpconns"
case "hls":
pa = "hlssessions"
case "webrtc":
pa = "webrtcsessions"
case "srt":
pa = "srtconns"
}
var out1 struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
}
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/list", nil, &out1)
require.NotEmpty(t, out1.Items)
httpRequest(t, hc, http.MethodPost, "http://localhost:9997/v3/"+pa+"/kick/"+out1.Items[0].ID, nil, nil)
var out2 struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
}
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/"+pa+"/list", nil, &out2)
require.Empty(t, out2.Items)
})
}
}
func TestAPIProtocolKickNotFound(t *testing.T) {
serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
for _, ca := range []string{
"rtsp",
"rtsps",
"rtmp",
"hls",
"webrtc",
"srt",
} {
t.Run(ca, func(t *testing.T) {
cnf := "api: yes\n"
if ca == "rtsps" {
cnf += "rtspTransports: [tcp]\n" +
"rtspEncryption: strict\n" +
"rtspServerCert: " + serverCertFpath + "\n" +
"rtspServerKey: " + serverKeyFpath + "\n"
}
cnf += "paths:\n" +
" all_others:\n"
p, ok := newInstance(t, cnf)
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var pa string
switch ca {
case "rtsp":
pa = "rtspsessions"
case "rtsps":
pa = "rtspssessions"
case "rtmp":
pa = "rtmpconns"
case "hls":
pa = "hlssessions"
case "webrtc":
pa = "webrtcsessions"
case "srt":
pa = "srtconns"
}
func() {
var req *http.Request
req, err := http.NewRequest(http.MethodPost, "http://localhost:9997/v3/"+pa+"/kick/"+uuid.New().String(), nil)
require.NoError(t, err)
var res *http.Response
res, err = hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusNotFound, res.StatusCode)
switch ca {
case "rtsp conns", "rtsps conns", "rtmp", "rtmps", "srt":
checkError(t, "connection not found", res.Body)
case "rtsp sessions", "rtsps sessions", "hls", "webrtc":
checkError(t, "session not found", res.Body)
}
}()
})
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171// Package core contains the main struct of the software.
package core
import (
"context"
_ "embed"
"fmt"
"os"
"os/signal"
"path/filepath"
"reflect"
"runtime"
"runtime/debug"
"slices"
"strings"
"syscall"
"time"
"github.com/alecthomas/kong"
"github.com/gin-gonic/gin"
"github.com/bluenviron/mediamtx/internal/api"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/confwatcher"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/metrics"
"github.com/bluenviron/mediamtx/internal/playback"
"github.com/bluenviron/mediamtx/internal/pprof"
"github.com/bluenviron/mediamtx/internal/recordcleaner"
"github.com/bluenviron/mediamtx/internal/rlimit"
"github.com/bluenviron/mediamtx/internal/servers/hls"
"github.com/bluenviron/mediamtx/internal/servers/moq"
"github.com/bluenviron/mediamtx/internal/servers/rtmp"
"github.com/bluenviron/mediamtx/internal/servers/rtsp"
"github.com/bluenviron/mediamtx/internal/servers/srt"
"github.com/bluenviron/mediamtx/internal/servers/webrtc"
"github.com/bluenviron/mediamtx/internal/upgrade"
)
//go:generate go run ./versiongetter
//go:embed VERSION
var version []byte
var started = time.Now()
var defaultConfPaths = []string{
"rtsp-simple-server.yml",
"mediamtx.yml",
}
var defaultConfPathsNotWin = []string{
"/usr/local/etc/mediamtx.yml",
"/usr/etc/mediamtx.yml",
"/etc/mediamtx/mediamtx.yml",
}
func goArm() string {
bi, _ := debug.ReadBuildInfo()
for _, bs := range bi.Settings {
if bs.Key == "GOARM" {
return bs.Value
}
}
return ""
}
func getArch() string {
var arch string
if runtime.GOARCH == "arm" {
arch = "armv" + goArm()
} else {
arch = runtime.GOARCH
}
return arch
}
func atLeastOneRecordDeleteAfter(pathConfs map[string]*conf.Path) bool {
for _, e := range pathConfs {
if e.RecordDeleteAfter != 0 {
return true
}
}
return false
}
func getRTPMaxPayloadSize(udpMaxPayloadSize int, rtspEncryption conf.Encryption) int {
// UDP max payload size - 12 (RTP header)
v := udpMaxPayloadSize - 12
// 10 (SRTP HMAC SHA1 authentication tag)
if rtspEncryption == conf.EncryptionOptional || rtspEncryption == conf.EncryptionStrict {
v -= 10
}
return v
}
var cli struct {
Confpath string `arg:"" default:""`
Version bool `help:"print version"`
CheckVersion bool `help:"check whether a new version is available"`
Upgrade bool `help:"upgrade executable to the latest version"`
}
// Core is an instance of MediaMTX.
type Core struct {
ctx context.Context
ctxCancel func()
confPath string
conf *conf.Conf
logger *logger.Logger
externalCmdPool *externalcmd.Pool
authManager *auth.Manager
metrics *metrics.Metrics
pprof *pprof.PPROF
recordCleaner *recordcleaner.Cleaner
playbackServer *playback.Server
pathManager *pathManager
rtspServer *rtsp.Server
rtspsServer *rtsp.Server
rtmpServer *rtmp.Server
rtmpsServer *rtmp.Server
hlsServer *hls.Server
webRTCServer *webrtc.Server
srtServer *srt.Server
moqServer *moq.Server
api *api.API
confWatcher *confwatcher.ConfWatcher
// in
chAPIConfigSet chan *conf.Conf
// out
done chan struct{}
}
// New allocates a Core.
func New(args []string) (*Core, bool) {
parser, err := kong.New(&cli,
kong.Description("MediaMTX "+string(version)+", "+runtime.GOOS+", "+getArch()),
kong.UsageOnError(),
kong.ValueFormatter(func(value *kong.Value) string {
switch value.Name {
case "confpath":
return "path to a config file. The default is mediamtx.yml."
default:
return kong.DefaultHelpValueFormatter(value)
}
}))
if err != nil {
panic(err)
}
_, err = parser.Parse(args)
parser.FatalIfErrorf(err)
if cli.Version {
fmt.Println(string(version))
os.Exit(0)
}
if cli.CheckVersion {
var newVersionAvailable bool
newVersionAvailable, err = upgrade.CheckVersion(string(version), getArch())
if err != nil {
fmt.Printf("ERR: %v\n", err)
os.Exit(1)
}
if newVersionAvailable {
os.Exit(2)
}
os.Exit(0)
}
if cli.Upgrade {
err = upgrade.Upgrade(string(version), getArch())
if err != nil {
fmt.Printf("ERR: %v\n", err)
os.Exit(1)
}
os.Exit(0)
}
ctx, ctxCancel := context.WithCancel(context.Background())
p := &Core{
ctx: ctx,
ctxCancel: ctxCancel,
chAPIConfigSet: make(chan *conf.Conf),
done: make(chan struct{}),
}
tempLogger := &logger.Logger{
Level: logger.Warn,
Destinations: []logger.Destination{logger.DestinationStdout},
Structured: false,
File: "",
SysLogPrefix: "",
}
tempLogger.Initialize() //nolint:errcheck
confPaths := append([]string(nil), defaultConfPaths...)
if runtime.GOOS != "windows" {
confPaths = append(confPaths, defaultConfPathsNotWin...)
}
p.conf, p.confPath, err = conf.Load(cli.Confpath, confPaths, tempLogger)
if err != nil {
fmt.Printf("ERR: %s\n", err)
return nil, false
}
err = p.createResources(true)
if err != nil {
if p.logger != nil {
p.Log(logger.Error, "%s", err)
} else {
fmt.Printf("ERR: %s\n", err)
}
p.closeResources(nil, false)
return nil, false
}
go p.run()
return p, true
}
// Close closes Core and waits for all goroutines to return.
func (p *Core) Close() {
p.ctxCancel()
<-p.done
}
// Wait waits for the Core to exit.
func (p *Core) Wait() {
<-p.done
}
// Log implements logger.Writer.
func (p *Core) Log(level logger.Level, format string, args ...any) {
p.logger.Log(level, format, args...)
}
func (p *Core) run() {
defer close(p.done)
confChanged := func() chan struct{} {
if p.confWatcher != nil {
return p.confWatcher.Watch()
}
return make(chan struct{})
}()
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
if runtime.GOOS == "linux" {
signal.Notify(interrupt, syscall.SIGTERM)
}
outer:
for {
select {
case <-confChanged:
p.Log(logger.Info, "reloading configuration (file changed)")
newConf, _, err := conf.Load(p.confPath, nil, p.logger)
if err != nil {
p.Log(logger.Error, "%s", err)
break outer
}
err = p.reloadConf(newConf, false)
if err != nil {
p.Log(logger.Error, "%s", err)
break outer
}
case newConf := <-p.chAPIConfigSet:
p.Log(logger.Info, "reloading configuration (API request)")
err := p.reloadConf(newConf, true)
if err != nil {
p.Log(logger.Error, "%s", err)
break outer
}
case <-interrupt:
p.Log(logger.Info, "shutting down gracefully")
break outer
case <-p.ctx.Done():
break outer
}
}
p.ctxCancel()
p.closeResources(nil, false)
}
func (p *Core) createResources(initial bool) error {
var err error
if p.logger == nil {
i := &logger.Logger{
Level: logger.Level(p.conf.LogLevel),
Destinations: p.conf.LogDestinations.ToDestinations(),
Structured: p.conf.LogStructured,
File: p.conf.LogFile,
SysLogPrefix: p.conf.SysLogPrefix,
}
err = i.Initialize()
if err != nil {
return err
}
p.logger = i
}
if initial {
p.Log(logger.Info, "MediaMTX %s, %s, %s", string(version), runtime.GOOS, getArch())
if p.confPath != "" {
a, _ := filepath.Abs(p.confPath)
p.Log(logger.Info, "configuration loaded from %s", a)
} else {
list := make([]string, len(defaultConfPaths))
for i, pa := range defaultConfPaths {
a, _ := filepath.Abs(pa)
list[i] = a
}
p.Log(logger.Warn,
"configuration file not found (looked in %s), using an empty configuration",
strings.Join(list, ", "))
}
// on Linux, try to raise the number of file descriptors that can be opened
// to allow the maximum possible number of clients.
rlimit.Raise() //nolint:errcheck
gin.SetMode(gin.ReleaseMode)
p.externalCmdPool = &externalcmd.Pool{}
p.externalCmdPool.Initialize()
}
if p.authManager == nil {
p.authManager = &auth.Manager{
Method: p.conf.AuthMethod,
InternalUsers: p.conf.AuthInternalUsers,
HTTPAddress: p.conf.AuthHTTPAddress,
HTTPFingerprint: p.conf.AuthHTTPFingerprint,
HTTPExclude: p.conf.AuthHTTPExclude,
JWTJWKS: p.conf.AuthJWTJWKS,
JWTJWKSFingerprint: p.conf.AuthJWTJWKSFingerprint,
JWTClaimKey: p.conf.AuthJWTClaimKey,
JWTExclude: p.conf.AuthJWTExclude,
JWTInHTTPQuery: p.conf.AuthJWTInHTTPQuery,
JWTIssuer: p.conf.AuthJWTIssuer,
JWTAudience: p.conf.AuthJWTAudience,
ReadTimeout: time.Duration(p.conf.ReadTimeout),
}
}
if p.conf.Metrics &&
p.metrics == nil {
i := &metrics.Metrics{
Address: p.conf.MetricsAddress,
DumpPackets: p.conf.DumpPackets,
Encryption: p.conf.MetricsEncryption,
ServerKey: p.conf.MetricsServerKey,
ServerCert: p.conf.MetricsServerCert,
AllowOrigins: p.conf.MetricsAllowOrigins,
TrustedProxies: p.conf.MetricsTrustedProxies,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
AuthManager: p.authManager,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.metrics = i
}
if p.conf.PPROF &&
p.pprof == nil {
i := &pprof.PPROF{
Address: p.conf.PPROFAddress,
DumpPackets: p.conf.DumpPackets,
Encryption: p.conf.PPROFEncryption,
ServerKey: p.conf.PPROFServerKey,
ServerCert: p.conf.PPROFServerCert,
AllowOrigins: p.conf.PPROFAllowOrigins,
TrustedProxies: p.conf.PPROFTrustedProxies,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
AuthManager: p.authManager,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.pprof = i
}
if p.recordCleaner == nil &&
atLeastOneRecordDeleteAfter(p.conf.Paths) {
p.recordCleaner = &recordcleaner.Cleaner{
PathConfs: p.conf.Paths,
Parent: p,
}
p.recordCleaner.Initialize()
}
if p.conf.Playback &&
p.playbackServer == nil {
i := &playback.Server{
Address: p.conf.PlaybackAddress,
DumpPackets: p.conf.DumpPackets,
Encryption: p.conf.PlaybackEncryption,
ServerKey: p.conf.PlaybackServerKey,
ServerCert: p.conf.PlaybackServerCert,
AllowOrigins: p.conf.PlaybackAllowOrigins,
TrustedProxies: p.conf.PlaybackTrustedProxies,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
PathConfs: p.conf.Paths,
AuthManager: p.authManager,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.playbackServer = i
}
if p.pathManager == nil {
rtpMaxPayloadSize := getRTPMaxPayloadSize(p.conf.UDPMaxPayloadSize, p.conf.RTSPEncryption)
p.pathManager = &pathManager{
logLevel: p.conf.LogLevel,
dumpPackets: p.conf.DumpPackets,
rtspAddress: p.conf.RTSPAddress,
readTimeout: p.conf.ReadTimeout,
writeTimeout: p.conf.WriteTimeout,
writeQueueSize: p.conf.WriteQueueSize,
udpReadBufferSize: p.conf.UDPReadBufferSize,
rtpMaxPayloadSize: rtpMaxPayloadSize,
pathConfs: p.conf.Paths,
authManager: p.authManager,
externalCmdPool: p.externalCmdPool,
metrics: p.metrics,
parent: p,
}
p.pathManager.initialize()
}
if p.conf.RTSP &&
(p.conf.RTSPEncryption == conf.EncryptionNo ||
p.conf.RTSPEncryption == conf.EncryptionOptional) &&
p.rtspServer == nil {
udpReadBufferSize := p.conf.UDPReadBufferSize
if p.conf.RTSPUDPReadBufferSize != nil {
udpReadBufferSize = *p.conf.RTSPUDPReadBufferSize
}
i := &rtsp.Server{
Address: p.conf.RTSPAddress,
AuthMethods: p.conf.RTSPAuthMethods.ToAuthMethods(),
DumpPackets: p.conf.DumpPackets,
UDPReadBufferSize: udpReadBufferSize,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
WriteQueueSize: p.conf.WriteQueueSize,
RTSPTransports: p.conf.RTSPTransports,
RTPAddress: p.conf.RTPAddress,
RTCPAddress: p.conf.RTCPAddress,
MulticastIPRange: p.conf.MulticastIPRange,
MulticastRTPPort: p.conf.MulticastRTPPort,
MulticastRTCPPort: p.conf.MulticastRTCPPort,
Encryption: false,
ServerCert: "",
ServerKey: "",
RTSPAddress: p.conf.RTSPAddress,
TrustedProxies: p.conf.RTSPTrustedProxies,
Transports: p.conf.RTSPTransports,
RunOnConnect: p.conf.RunOnConnect,
RunOnConnectRestart: p.conf.RunOnConnectRestart,
RunOnDisconnect: p.conf.RunOnDisconnect,
ExternalCmdPool: p.externalCmdPool,
Metrics: p.metrics,
PathManager: p.pathManager,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.rtspServer = i
}
if p.conf.RTSP &&
(p.conf.RTSPEncryption == conf.EncryptionStrict ||
p.conf.RTSPEncryption == conf.EncryptionOptional) &&
p.rtspsServer == nil {
udpReadBufferSize := p.conf.UDPReadBufferSize
if p.conf.RTSPUDPReadBufferSize != nil {
udpReadBufferSize = *p.conf.RTSPUDPReadBufferSize
}
i := &rtsp.Server{
Address: p.conf.RTSPSAddress,
AuthMethods: p.conf.RTSPAuthMethods.ToAuthMethods(),
DumpPackets: p.conf.DumpPackets,
UDPReadBufferSize: udpReadBufferSize,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
WriteQueueSize: p.conf.WriteQueueSize,
RTSPTransports: p.conf.RTSPTransports,
RTPAddress: p.conf.SRTPAddress,
RTCPAddress: p.conf.SRTCPAddress,
MulticastIPRange: p.conf.MulticastIPRange,
MulticastRTPPort: p.conf.MulticastSRTPPort,
MulticastRTCPPort: p.conf.MulticastSRTCPPort,
Encryption: true,
ServerCert: p.conf.RTSPServerCert,
ServerKey: p.conf.RTSPServerKey,
RTSPAddress: p.conf.RTSPAddress,
TrustedProxies: p.conf.RTSPTrustedProxies,
Transports: p.conf.RTSPTransports,
RunOnConnect: p.conf.RunOnConnect,
RunOnConnectRestart: p.conf.RunOnConnectRestart,
RunOnDisconnect: p.conf.RunOnDisconnect,
ExternalCmdPool: p.externalCmdPool,
Metrics: p.metrics,
PathManager: p.pathManager,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.rtspsServer = i
}
if p.conf.RTMP &&
(p.conf.RTMPEncryption == conf.EncryptionNo ||
p.conf.RTMPEncryption == conf.EncryptionOptional) &&
p.rtmpServer == nil {
i := &rtmp.Server{
Address: p.conf.RTMPAddress,
DumpPackets: p.conf.DumpPackets,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
Encryption: false,
ServerCert: "",
ServerKey: "",
RTSPAddress: p.conf.RTSPAddress,
TrustedProxies: p.conf.RTMPTrustedProxies,
RunOnConnect: p.conf.RunOnConnect,
RunOnConnectRestart: p.conf.RunOnConnectRestart,
RunOnDisconnect: p.conf.RunOnDisconnect,
ExternalCmdPool: p.externalCmdPool,
Metrics: p.metrics,
PathManager: p.pathManager,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.rtmpServer = i
}
if p.conf.RTMP &&
(p.conf.RTMPEncryption == conf.EncryptionStrict ||
p.conf.RTMPEncryption == conf.EncryptionOptional) &&
p.rtmpsServer == nil {
i := &rtmp.Server{
Address: p.conf.RTMPSAddress,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
Encryption: true,
ServerCert: p.conf.RTMPServerCert,
ServerKey: p.conf.RTMPServerKey,
DumpPackets: p.conf.DumpPackets,
RTSPAddress: p.conf.RTSPAddress,
TrustedProxies: p.conf.RTMPTrustedProxies,
RunOnConnect: p.conf.RunOnConnect,
RunOnConnectRestart: p.conf.RunOnConnectRestart,
RunOnDisconnect: p.conf.RunOnDisconnect,
ExternalCmdPool: p.externalCmdPool,
Metrics: p.metrics,
PathManager: p.pathManager,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.rtmpsServer = i
}
if p.conf.HLS &&
p.hlsServer == nil {
i := &hls.Server{
Address: p.conf.HLSAddress,
DumpPackets: p.conf.DumpPackets,
Encryption: p.conf.HLSEncryption,
ServerKey: p.conf.HLSServerKey,
ServerCert: p.conf.HLSServerCert,
AllowOrigins: p.conf.HLSAllowOrigins,
TrustedProxies: p.conf.HLSTrustedProxies,
AlwaysRemux: p.conf.HLSAlwaysRemux,
Variant: p.conf.HLSVariant,
SegmentCount: p.conf.HLSSegmentCount,
SegmentDuration: p.conf.HLSSegmentDuration,
PartDuration: p.conf.HLSPartDuration,
SegmentMaxSize: p.conf.HLSSegmentMaxSize,
Directory: p.conf.HLSDirectory,
CDNSecret: p.conf.HLSCDNSecret,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
MuxerCloseAfter: p.conf.HLSMuxerCloseAfter,
ExternalCmdPool: p.externalCmdPool,
Metrics: p.metrics,
PathManager: p.pathManager,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.hlsServer = i
}
if p.conf.WebRTC &&
p.webRTCServer == nil {
i := &webrtc.Server{
Address: p.conf.WebRTCAddress,
DumpPackets: p.conf.DumpPackets,
Encryption: p.conf.WebRTCEncryption,
ServerKey: p.conf.WebRTCServerKey,
ServerCert: p.conf.WebRTCServerCert,
AllowOrigins: p.conf.WebRTCAllowOrigins,
TrustedProxies: p.conf.WebRTCTrustedProxies,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
UDPReadBufferSize: p.conf.UDPReadBufferSize,
LocalUDPAddress: p.conf.WebRTCLocalUDPAddress,
LocalTCPAddress: p.conf.WebRTCLocalTCPAddress,
IPsFromInterfaces: p.conf.WebRTCIPsFromInterfaces,
IPsFromInterfacesList: p.conf.WebRTCIPsFromInterfacesList,
AdditionalHosts: p.conf.WebRTCAdditionalHosts,
ICEServers: p.conf.WebRTCICEServers2,
STUNGatherTimeout: p.conf.WebRTCSTUNGatherTimeout,
HandshakeTimeout: p.conf.WebRTCHandshakeTimeout,
TrackGatherTimeout: p.conf.WebRTCTrackGatherTimeout,
ExternalCmdPool: p.externalCmdPool,
Metrics: p.metrics,
PathManager: p.pathManager,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.webRTCServer = i
}
if p.conf.SRT &&
p.srtServer == nil {
i := &srt.Server{
Address: p.conf.SRTAddress,
RTSPAddress: p.conf.RTSPAddress,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
UDPMaxPayloadSize: p.conf.UDPMaxPayloadSize,
RunOnConnect: p.conf.RunOnConnect,
RunOnConnectRestart: p.conf.RunOnConnectRestart,
RunOnDisconnect: p.conf.RunOnDisconnect,
ExternalCmdPool: p.externalCmdPool,
Metrics: p.metrics,
PathManager: p.pathManager,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.srtServer = i
}
if p.conf.MoQ &&
p.moqServer == nil {
i := &moq.Server{
HTTP2Address: p.conf.MoQHTTP2Address,
HTTP3Address: p.conf.MoQHTTP3Address,
ServerKey: p.conf.MoQServerKey,
ServerCert: p.conf.MoQServerCert,
AllowOrigins: p.conf.MoQAllowOrigins,
TrustedProxies: p.conf.MoQTrustedProxies,
UDPReadBufferSize: p.conf.UDPReadBufferSize,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
PathManager: p.pathManager,
Metrics: p.metrics,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.moqServer = i
}
if p.conf.API &&
p.api == nil {
i := &api.API{
Version: string(version),
Started: started,
Address: p.conf.APIAddress,
DumpPackets: p.conf.DumpPackets,
Encryption: p.conf.APIEncryption,
ServerKey: p.conf.APIServerKey,
ServerCert: p.conf.APIServerCert,
AllowOrigins: p.conf.APIAllowOrigins,
TrustedProxies: p.conf.APITrustedProxies,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
Conf: p.conf,
AuthManager: p.authManager,
PathManager: p.pathManager,
RTSPServer: p.rtspServer,
RTSPSServer: p.rtspsServer,
RTMPServer: p.rtmpServer,
RTMPSServer: p.rtmpsServer,
HLSServer: p.hlsServer,
WebRTCServer: p.webRTCServer,
SRTServer: p.srtServer,
MoQServer: p.moqServer,
Parent: p,
}
err = i.Initialize()
if err != nil {
return err
}
p.api = i
}
if initial && p.confPath != "" {
cf := &confwatcher.ConfWatcher{FilePath: p.confPath}
err = cf.Initialize()
if err != nil {
return err
}
p.confWatcher = cf
}
return nil
}
func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) {
closeLogger := newConf == nil ||
newConf.LogLevel != p.conf.LogLevel ||
!reflect.DeepEqual(newConf.LogDestinations, p.conf.LogDestinations) ||
newConf.LogFile != p.conf.LogFile ||
newConf.SysLogPrefix != p.conf.SysLogPrefix ||
newConf.LogStructured != p.conf.LogStructured
closeAuthManager := newConf == nil ||
newConf.AuthMethod != p.conf.AuthMethod ||
newConf.AuthHTTPAddress != p.conf.AuthHTTPAddress ||
newConf.AuthHTTPFingerprint != p.conf.AuthHTTPFingerprint ||
!reflect.DeepEqual(newConf.AuthHTTPExclude, p.conf.AuthHTTPExclude) ||
newConf.AuthJWTJWKS != p.conf.AuthJWTJWKS ||
newConf.AuthJWTJWKSFingerprint != p.conf.AuthJWTJWKSFingerprint ||
newConf.AuthJWTClaimKey != p.conf.AuthJWTClaimKey ||
!reflect.DeepEqual(newConf.AuthJWTExclude, p.conf.AuthJWTExclude) ||
!reflect.DeepEqual(newConf.AuthJWTInHTTPQuery, p.conf.AuthJWTInHTTPQuery) ||
newConf.AuthJWTIssuer != p.conf.AuthJWTIssuer ||
newConf.AuthJWTAudience != p.conf.AuthJWTAudience ||
newConf.ReadTimeout != p.conf.ReadTimeout
if !closeAuthManager && !reflect.DeepEqual(newConf.AuthInternalUsers, p.conf.AuthInternalUsers) {
p.authManager.ReloadInternalUsers(newConf.AuthInternalUsers)
}
closeMetrics := newConf == nil ||
newConf.Metrics != p.conf.Metrics ||
newConf.MetricsAddress != p.conf.MetricsAddress ||
newConf.MetricsEncryption != p.conf.MetricsEncryption ||
newConf.MetricsServerKey != p.conf.MetricsServerKey ||
newConf.MetricsServerCert != p.conf.MetricsServerCert ||
!slices.Equal(newConf.MetricsAllowOrigins, p.conf.MetricsAllowOrigins) ||
!reflect.DeepEqual(newConf.MetricsTrustedProxies, p.conf.MetricsTrustedProxies) ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.DumpPackets != p.conf.DumpPackets ||
closeAuthManager ||
closeLogger
closePPROF := newConf == nil ||
newConf.PPROF != p.conf.PPROF ||
newConf.PPROFAddress != p.conf.PPROFAddress ||
newConf.PPROFEncryption != p.conf.PPROFEncryption ||
newConf.PPROFServerKey != p.conf.PPROFServerKey ||
newConf.PPROFServerCert != p.conf.PPROFServerCert ||
!slices.Equal(newConf.PPROFAllowOrigins, p.conf.PPROFAllowOrigins) ||
!reflect.DeepEqual(newConf.PPROFTrustedProxies, p.conf.PPROFTrustedProxies) ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.DumpPackets != p.conf.DumpPackets ||
closeAuthManager ||
closeLogger
closeRecorderCleaner := newConf == nil ||
atLeastOneRecordDeleteAfter(newConf.Paths) != atLeastOneRecordDeleteAfter(p.conf.Paths) ||
closeLogger
if !closeRecorderCleaner && p.recordCleaner != nil && !reflect.DeepEqual(newConf.Paths, p.conf.Paths) {
p.recordCleaner.ReloadPathConfs(newConf.Paths)
}
closePlaybackServer := newConf == nil ||
newConf.Playback != p.conf.Playback ||
newConf.PlaybackAddress != p.conf.PlaybackAddress ||
newConf.PlaybackEncryption != p.conf.PlaybackEncryption ||
newConf.PlaybackServerKey != p.conf.PlaybackServerKey ||
newConf.PlaybackServerCert != p.conf.PlaybackServerCert ||
!slices.Equal(newConf.PlaybackAllowOrigins, p.conf.PlaybackAllowOrigins) ||
!reflect.DeepEqual(newConf.PlaybackTrustedProxies, p.conf.PlaybackTrustedProxies) ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.DumpPackets != p.conf.DumpPackets ||
closeAuthManager ||
closeLogger
if !closePlaybackServer && p.playbackServer != nil && !reflect.DeepEqual(newConf.Paths, p.conf.Paths) {
p.playbackServer.ReloadPathConfs(newConf.Paths)
}
closePathManager := newConf == nil ||
newConf.LogLevel != p.conf.LogLevel ||
newConf.DumpPackets != p.conf.DumpPackets ||
newConf.RTSPAddress != p.conf.RTSPAddress ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.WriteQueueSize != p.conf.WriteQueueSize ||
newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize ||
newConf.UDPMaxPayloadSize != p.conf.UDPMaxPayloadSize ||
newConf.RTSPEncryption != p.conf.RTSPEncryption ||
closeMetrics ||
closeAuthManager ||
closeLogger
if !closePathManager && !reflect.DeepEqual(newConf.Paths, p.conf.Paths) {
p.pathManager.ReloadPathConfs(newConf.Paths)
}
closeRTSPServer := newConf == nil ||
newConf.RTSP != p.conf.RTSP ||
newConf.RTSPEncryption != p.conf.RTSPEncryption ||
newConf.RTSPAddress != p.conf.RTSPAddress ||
!reflect.DeepEqual(newConf.RTSPAuthMethods, p.conf.RTSPAuthMethods) ||
newConf.RTSPUDPReadBufferSize != p.conf.RTSPUDPReadBufferSize ||
newConf.DumpPackets != p.conf.DumpPackets ||
newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.WriteQueueSize != p.conf.WriteQueueSize ||
newConf.RTPAddress != p.conf.RTPAddress ||
newConf.RTCPAddress != p.conf.RTCPAddress ||
newConf.MulticastIPRange != p.conf.MulticastIPRange ||
newConf.MulticastRTPPort != p.conf.MulticastRTPPort ||
newConf.MulticastRTCPPort != p.conf.MulticastRTCPPort ||
!reflect.DeepEqual(newConf.RTSPTransports, p.conf.RTSPTransports) ||
!reflect.DeepEqual(newConf.RTSPTrustedProxies, p.conf.RTSPTrustedProxies) ||
newConf.RunOnConnect != p.conf.RunOnConnect ||
newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart ||
newConf.RunOnDisconnect != p.conf.RunOnDisconnect ||
closeMetrics ||
closePathManager ||
closeLogger
closeRTSPSServer := newConf == nil ||
newConf.RTSP != p.conf.RTSP ||
newConf.RTSPEncryption != p.conf.RTSPEncryption ||
newConf.RTSPSAddress != p.conf.RTSPSAddress ||
!reflect.DeepEqual(newConf.RTSPAuthMethods, p.conf.RTSPAuthMethods) ||
newConf.RTSPUDPReadBufferSize != p.conf.RTSPUDPReadBufferSize ||
newConf.DumpPackets != p.conf.DumpPackets ||
newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.WriteQueueSize != p.conf.WriteQueueSize ||
newConf.RTSPServerCert != p.conf.RTSPServerCert ||
newConf.RTSPServerKey != p.conf.RTSPServerKey ||
newConf.RTSPAddress != p.conf.RTSPAddress ||
!reflect.DeepEqual(newConf.RTSPTransports, p.conf.RTSPTransports) ||
!reflect.DeepEqual(newConf.RTSPTrustedProxies, p.conf.RTSPTrustedProxies) ||
newConf.RunOnConnect != p.conf.RunOnConnect ||
newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart ||
newConf.RunOnDisconnect != p.conf.RunOnDisconnect ||
closeMetrics ||
closePathManager ||
closeLogger
closeRTMPServer := newConf == nil ||
newConf.RTMP != p.conf.RTMP ||
newConf.RTMPEncryption != p.conf.RTMPEncryption ||
newConf.RTMPAddress != p.conf.RTMPAddress ||
newConf.DumpPackets != p.conf.DumpPackets ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.RTSPAddress != p.conf.RTSPAddress ||
!reflect.DeepEqual(newConf.RTMPTrustedProxies, p.conf.RTMPTrustedProxies) ||
newConf.RunOnConnect != p.conf.RunOnConnect ||
newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart ||
newConf.RunOnDisconnect != p.conf.RunOnDisconnect ||
closeMetrics ||
closePathManager ||
closeLogger
closeRTMPSServer := newConf == nil ||
newConf.RTMP != p.conf.RTMP ||
newConf.RTMPEncryption != p.conf.RTMPEncryption ||
newConf.RTMPSAddress != p.conf.RTMPSAddress ||
newConf.DumpPackets != p.conf.DumpPackets ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.RTMPServerCert != p.conf.RTMPServerCert ||
newConf.RTMPServerKey != p.conf.RTMPServerKey ||
newConf.RTSPAddress != p.conf.RTSPAddress ||
!reflect.DeepEqual(newConf.RTMPTrustedProxies, p.conf.RTMPTrustedProxies) ||
newConf.RunOnConnect != p.conf.RunOnConnect ||
newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart ||
newConf.RunOnDisconnect != p.conf.RunOnDisconnect ||
closeMetrics ||
closePathManager ||
closeLogger
closeHLSServer := newConf == nil ||
newConf.HLS != p.conf.HLS ||
newConf.HLSAddress != p.conf.HLSAddress ||
newConf.HLSEncryption != p.conf.HLSEncryption ||
newConf.HLSServerKey != p.conf.HLSServerKey ||
newConf.HLSServerCert != p.conf.HLSServerCert ||
!slices.Equal(newConf.HLSAllowOrigins, p.conf.HLSAllowOrigins) ||
!reflect.DeepEqual(newConf.HLSTrustedProxies, p.conf.HLSTrustedProxies) ||
newConf.HLSAlwaysRemux != p.conf.HLSAlwaysRemux ||
newConf.HLSVariant != p.conf.HLSVariant ||
newConf.HLSSegmentCount != p.conf.HLSSegmentCount ||
newConf.HLSSegmentDuration != p.conf.HLSSegmentDuration ||
newConf.HLSPartDuration != p.conf.HLSPartDuration ||
newConf.HLSSegmentMaxSize != p.conf.HLSSegmentMaxSize ||
newConf.HLSDirectory != p.conf.HLSDirectory ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.HLSMuxerCloseAfter != p.conf.HLSMuxerCloseAfter ||
newConf.HLSCDNSecret != p.conf.HLSCDNSecret ||
newConf.DumpPackets != p.conf.DumpPackets ||
closePathManager ||
closeMetrics ||
closeLogger
closeWebRTCServer := newConf == nil ||
newConf.WebRTC != p.conf.WebRTC ||
newConf.WebRTCAddress != p.conf.WebRTCAddress ||
newConf.WebRTCEncryption != p.conf.WebRTCEncryption ||
newConf.WebRTCServerKey != p.conf.WebRTCServerKey ||
newConf.WebRTCServerCert != p.conf.WebRTCServerCert ||
!slices.Equal(newConf.WebRTCAllowOrigins, p.conf.WebRTCAllowOrigins) ||
!reflect.DeepEqual(newConf.WebRTCTrustedProxies, p.conf.WebRTCTrustedProxies) ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize ||
newConf.WebRTCLocalUDPAddress != p.conf.WebRTCLocalUDPAddress ||
newConf.WebRTCLocalTCPAddress != p.conf.WebRTCLocalTCPAddress ||
newConf.WebRTCIPsFromInterfaces != p.conf.WebRTCIPsFromInterfaces ||
!reflect.DeepEqual(newConf.WebRTCIPsFromInterfacesList, p.conf.WebRTCIPsFromInterfacesList) ||
!reflect.DeepEqual(newConf.WebRTCAdditionalHosts, p.conf.WebRTCAdditionalHosts) ||
!reflect.DeepEqual(newConf.WebRTCICEServers2, p.conf.WebRTCICEServers2) ||
newConf.WebRTCSTUNGatherTimeout != p.conf.WebRTCSTUNGatherTimeout ||
newConf.WebRTCHandshakeTimeout != p.conf.WebRTCHandshakeTimeout ||
newConf.WebRTCTrackGatherTimeout != p.conf.WebRTCTrackGatherTimeout ||
newConf.DumpPackets != p.conf.DumpPackets ||
closeMetrics ||
closePathManager ||
closeLogger
closeSRTServer := newConf == nil ||
newConf.SRT != p.conf.SRT ||
newConf.SRTAddress != p.conf.SRTAddress ||
newConf.RTSPAddress != p.conf.RTSPAddress ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.UDPMaxPayloadSize != p.conf.UDPMaxPayloadSize ||
newConf.RunOnConnect != p.conf.RunOnConnect ||
newConf.RunOnConnectRestart != p.conf.RunOnConnectRestart ||
newConf.RunOnDisconnect != p.conf.RunOnDisconnect ||
closeMetrics ||
closePathManager ||
closeLogger
closeMoQServer := newConf == nil ||
newConf.MoQ != p.conf.MoQ ||
newConf.MoQHTTP2Address != p.conf.MoQHTTP2Address ||
newConf.MoQHTTP3Address != p.conf.MoQHTTP3Address ||
newConf.MoQServerKey != p.conf.MoQServerKey ||
newConf.MoQServerCert != p.conf.MoQServerCert ||
!slices.Equal(newConf.MoQAllowOrigins, p.conf.MoQAllowOrigins) ||
!reflect.DeepEqual(newConf.MoQTrustedProxies, p.conf.MoQTrustedProxies) ||
newConf.UDPReadBufferSize != p.conf.UDPReadBufferSize ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
closeMetrics ||
closePathManager ||
closeLogger
closeAPI := newConf == nil ||
newConf.API != p.conf.API ||
newConf.APIAddress != p.conf.APIAddress ||
newConf.APIEncryption != p.conf.APIEncryption ||
newConf.APIServerKey != p.conf.APIServerKey ||
newConf.APIServerCert != p.conf.APIServerCert ||
!slices.Equal(newConf.APIAllowOrigins, p.conf.APIAllowOrigins) ||
!reflect.DeepEqual(newConf.APITrustedProxies, p.conf.APITrustedProxies) ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.DumpPackets != p.conf.DumpPackets ||
closeAuthManager ||
closePathManager ||
closeRTSPServer ||
closeRTSPSServer ||
closeRTMPServer ||
closeRTMPSServer ||
closeHLSServer ||
closeWebRTCServer ||
closeSRTServer ||
closeMoQServer ||
closeLogger
if newConf == nil && p.confWatcher != nil {
p.confWatcher.Close()
p.confWatcher = nil
}
if p.api != nil {
if closeAPI {
p.api.Close()
p.api = nil
} else if !calledByAPI { // avoid a loop
p.api.ReloadConf(newConf)
}
}
if closeSRTServer && p.srtServer != nil {
p.srtServer.Close()
p.srtServer = nil
}
if closeMoQServer && p.moqServer != nil {
p.moqServer.Close()
p.moqServer = nil
}
if closeWebRTCServer && p.webRTCServer != nil {
p.webRTCServer.Close()
p.webRTCServer = nil
}
if closeHLSServer && p.hlsServer != nil {
p.hlsServer.Close()
p.hlsServer = nil
}
if closeRTMPSServer && p.rtmpsServer != nil {
p.rtmpsServer.Close()
p.rtmpsServer = nil
}
if closeRTMPServer && p.rtmpServer != nil {
p.rtmpServer.Close()
p.rtmpServer = nil
}
if closeRTSPSServer && p.rtspsServer != nil {
p.rtspsServer.Close()
p.rtspsServer = nil
}
if closeRTSPServer && p.rtspServer != nil {
p.rtspServer.Close()
p.rtspServer = nil
}
if closePathManager && p.pathManager != nil {
p.pathManager.close()
p.pathManager = nil
}
if closePlaybackServer && p.playbackServer != nil {
p.playbackServer.Close()
p.playbackServer = nil
}
if closeRecorderCleaner && p.recordCleaner != nil {
p.recordCleaner.Close()
p.recordCleaner = nil
}
if closePPROF && p.pprof != nil {
p.pprof.Close()
p.pprof = nil
}
if closeMetrics && p.metrics != nil {
p.metrics.Close()
p.metrics = nil
}
if closeAuthManager && p.authManager != nil {
p.authManager = nil
}
if newConf == nil && p.externalCmdPool != nil {
p.Log(logger.Info, "waiting for running hooks")
p.externalCmdPool.Close()
}
if closeLogger && p.logger != nil {
if newConf == nil {
p.logger.Close()
}
p.logger = nil
}
}
func (p *Core) reloadConf(newConf *conf.Conf, calledByAPI bool) error {
oldLogger := p.logger
p.closeResources(newConf, calledByAPI)
p.conf = newConf
err := p.createResources(false)
if err != nil {
p.logger = oldLogger
return err
}
if p.logger != oldLogger {
oldLogger.Close()
}
return nil
}
// APIConfigSet implements apiParent.
func (p *Core) APIConfigSet(conf *conf.Conf) {
select {
case p.chAPIConfigSet <- conf:
case <-p.ctx.Done():
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148package core
import (
"os"
"path/filepath"
"testing"
"time"
"github.com/bluenviron/gortsplib/v5"
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/bluenviron/mediamtx/internal/test"
"github.com/stretchr/testify/require"
)
func newInstance(t *testing.T, conf string) (*Core, bool) {
if conf == "" {
return New([]string{})
}
tmpf := test.CreateTempFile(t, []byte(conf))
return New([]string{tmpf})
}
func TestCoreErrors(t *testing.T) {
for _, ca := range []struct {
name string
conf string
}{
{
"logger",
"logDestinations: [file]\n" +
"logFile: /nonexisting/nonexist\n" +
"sysLogPrefix: /mediamtx\n",
},
{
"metrics",
"metrics: yes\n" +
"metricsAddress: invalid\n",
},
{
"pprof",
"pprof: yes\n" +
"pprofAddress: invalid\n",
},
{
"playback",
"playback: yes\n" +
"playbackAddress: invalid\n",
},
{
"rtsp",
"rtspAddress: invalid\n",
},
{
"rtsps",
"rtspEncryption: strict\n" +
"rtspAddress: invalid\n",
},
{
"rtmp",
"rtmpAddress: invalid\n",
},
{
"rtmps",
"rtmpEncryption: strict\n" +
"rtmpAddress: invalid\n",
},
{
"hls",
"hlsAddress: invalid\n",
},
{
"webrtc",
"webrtcAddress: invalid\n",
},
{
"srt",
"srtAddress: invalid\n",
},
{
"api",
"api: yes\n" +
"apiAddress: invalid\n",
},
} {
t.Run(ca.name, func(t *testing.T) {
_, ok := newInstance(t, ca.conf)
require.Equal(t, false, ok)
})
}
}
func TestCoreHotReloading(t *testing.T) {
confPath := filepath.Join(t.TempDir(), "rtsp-conf")
err := os.WriteFile(confPath, []byte("paths:\n"+
" test1:\n"+
" publishUser: myuser\n"+
" publishPass: mypass\n"),
0o644)
require.NoError(t, err)
p, ok := New([]string{confPath})
require.Equal(t, true, ok)
defer p.Close()
func() {
c := gortsplib.Client{}
err = c.StartRecording("rtsp://localhost:8554/test1",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.EqualError(t, err, "bad status code: 401 (Unauthorized)")
}()
err = os.WriteFile(confPath, []byte("paths:\n"+
" test1:\n"),
0o644)
require.NoError(t, err)
time.Sleep(1 * time.Second)
func() {
conn := gortsplib.Client{}
err = conn.StartRecording("rtsp://localhost:8554/test1",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer conn.Close()
}()
}
func TestCoreHotReloadingAndLoggerError(t *testing.T) {
confPath := filepath.Join(t.TempDir(), "rtsp-conf")
err := os.WriteFile(confPath, []byte(""),
0o644)
require.NoError(t, err)
p, ok := New([]string{confPath})
require.Equal(t, true, ok)
defer p.Close()
err = os.WriteFile(confPath, []byte("logDestinations: [file]\n"+
"logFile: /nonexisting/nonexist\n"),
0o644)
require.NoError(t, err)
p.Wait()
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513package core
import (
"bufio"
"context"
"crypto/tls"
"io"
"net/http"
"net/url"
"sync"
"testing"
"time"
"github.com/bluenviron/gortmplib"
rtmpcodecs "github.com/bluenviron/gortmplib/pkg/codecs"
"github.com/bluenviron/gortsplib/v5"
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts"
tscodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts/codecs"
srt "github.com/datarhei/gosrt"
"github.com/pion/rtp"
pwebrtc "github.com/pion/webrtc/v4"
"github.com/stretchr/testify/require"
"github.com/bluenviron/mediamtx/internal/protocols/webrtc"
"github.com/bluenviron/mediamtx/internal/protocols/whip"
"github.com/bluenviron/mediamtx/internal/test"
)
func httpPullFile(t *testing.T, hc *http.Client, u string) []byte {
res, err := hc.Get(u)
require.NoError(t, err)
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Errorf("bad status code: %v", res.StatusCode)
}
byts, err := io.ReadAll(res.Body)
require.NoError(t, err)
return byts
}
func TestMetrics(t *testing.T) {
serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
p, ok := newInstance(t, "api: yes\n"+
"hlsAlwaysRemux: yes\n"+
"metrics: yes\n"+
"webrtcServerCert: "+serverCertFpath+"\n"+
"webrtcServerKey: "+serverKeyFpath+"\n"+
"rtspEncryption: optional\n"+
"rtspServerCert: "+serverCertFpath+"\n"+
"rtspServerKey: "+serverKeyFpath+"\n"+
"rtmpEncryption: optional\n"+
"rtmpServerCert: "+serverCertFpath+"\n"+
"rtmpServerKey: "+serverKeyFpath+"\n"+
"paths:\n"+
" all_others:\n")
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
t.Run("initial", func(t *testing.T) {
bo := httpPullFile(t, hc, "http://localhost:9998/metrics")
require.Equal(t, `# Paths
paths 0
paths_inbound_bytes 0
paths_outbound_bytes 0
paths_inbound_frames_in_error 0
# Paths (deprecated)
paths_bytes_received 0
paths_bytes_sent 0
paths_readers 0
# HLS sessions
hls_sessions 0
hls_sessions_outbound_bytes 0
# HLS muxers
hls_muxers 0
hls_muxers_outbound_bytes 0
hls_muxers_outbound_frames_discarded 0
# HLS muxers (deprecated)
hls_muxers_bytes_sent 0
# RTSP connections
rtsp_conns 0
rtsp_conns_inbound_bytes 0
rtsp_conns_outbound_bytes 0
# RTSP connections (deprecated)
rtsp_conns_bytes_received 0
rtsp_conns_bytes_sent 0
# RTSP sessions
rtsp_sessions 0
rtsp_sessions_inbound_bytes 0
rtsp_sessions_inbound_rtp_packets 0
rtsp_sessions_inbound_rtp_packets_lost 0
rtsp_sessions_inbound_rtp_packets_in_error 0
rtsp_sessions_inbound_rtp_packets_jitter 0
rtsp_sessions_inbound_rtcp_packets 0
rtsp_sessions_inbound_rtcp_packets_in_error 0
rtsp_sessions_outbound_bytes 0
rtsp_sessions_outbound_rtp_packets 0
rtsp_sessions_outbound_rtp_packets_reported_lost 0
rtsp_sessions_outbound_rtp_packets_discarded 0
rtsp_sessions_outbound_rtcp_packets 0
# RTSP sessions (deprecated)
rtsp_sessions_bytes_received 0
rtsp_sessions_bytes_sent 0
rtsp_sessions_rtp_packets_received 0
rtsp_sessions_rtp_packets_sent 0
rtsp_sessions_rtp_packets_lost 0
rtsp_sessions_rtp_packets_in_error 0
rtsp_sessions_rtp_packets_jitter 0
rtsp_sessions_rtcp_packets_received 0
rtsp_sessions_rtcp_packets_sent 0
rtsp_sessions_rtcp_packets_in_error 0
# RTSPS connections
rtsps_conns 0
rtsps_conns_inbound_bytes 0
rtsps_conns_outbound_bytes 0
# RTSPS connections (deprecated)
rtsps_conns_bytes_received 0
rtsps_conns_bytes_sent 0
# RTSPS sessions
rtsps_sessions 0
rtsps_sessions_inbound_bytes 0
rtsps_sessions_inbound_rtp_packets 0
rtsps_sessions_inbound_rtp_packets_lost 0
rtsps_sessions_inbound_rtp_packets_in_error 0
rtsps_sessions_inbound_rtp_packets_jitter 0
rtsps_sessions_inbound_rtcp_packets 0
rtsps_sessions_inbound_rtcp_packets_in_error 0
rtsps_sessions_outbound_bytes 0
rtsps_sessions_outbound_rtp_packets 0
rtsps_sessions_outbound_rtp_packets_reported_lost 0
rtsps_sessions_outbound_rtp_packets_discarded 0
rtsps_sessions_outbound_rtcp_packets 0
# RTSPS sessions (deprecated)
rtsps_sessions_bytes_received 0
rtsps_sessions_bytes_sent 0
rtsps_sessions_rtp_packets_received 0
rtsps_sessions_rtp_packets_sent 0
rtsps_sessions_rtp_packets_lost 0
rtsps_sessions_rtp_packets_in_error 0
rtsps_sessions_rtp_packets_jitter 0
rtsps_sessions_rtcp_packets_received 0
rtsps_sessions_rtcp_packets_sent 0
rtsps_sessions_rtcp_packets_in_error 0
# RTMP connections
rtmp_conns 0
rtmp_conns_inbound_bytes 0
rtmp_conns_outbound_bytes 0
rtmp_conns_outbound_frames_discarded 0
# RTMP connections (deprecated)
rtmp_conns_bytes_received 0
rtmp_conns_bytes_sent 0
# RTMPS connections
rtmps_conns 0
rtmps_conns_inbound_bytes 0
rtmps_conns_outbound_bytes 0
rtmps_conns_outbound_frames_discarded 0
# RTMPS connections (deprecated)
rtmps_conns_bytes_received 0
rtmps_conns_bytes_sent 0
# SRT connections
srt_conns 0
srt_conns_packets_sent 0
srt_conns_packets_received 0
srt_conns_packets_sent_unique 0
srt_conns_packets_received_unique 0
srt_conns_packets_send_loss 0
srt_conns_packets_received_loss 0
srt_conns_packets_retrans 0
srt_conns_packets_received_retrans 0
srt_conns_packets_sent_ack 0
srt_conns_packets_received_ack 0
srt_conns_packets_sent_nak 0
srt_conns_packets_received_nak 0
srt_conns_packets_sent_km 0
srt_conns_packets_received_km 0
srt_conns_us_snd_duration 0
srt_conns_packets_received_belated 0
srt_conns_packets_send_drop 0
srt_conns_packets_received_drop 0
srt_conns_packets_received_undecrypt 0
srt_conns_bytes_sent 0
srt_conns_bytes_received 0
srt_conns_bytes_sent_unique 0
srt_conns_bytes_received_unique 0
srt_conns_bytes_received_loss 0
srt_conns_bytes_retrans 0
srt_conns_bytes_received_retrans 0
srt_conns_bytes_received_belated 0
srt_conns_bytes_send_drop 0
srt_conns_bytes_received_drop 0
srt_conns_bytes_received_undecrypt 0
srt_conns_us_packets_send_period 0
srt_conns_packets_flow_window 0
srt_conns_packets_flight_size 0
srt_conns_ms_rtt 0
srt_conns_mbps_send_rate 0
srt_conns_mbps_receive_rate 0
srt_conns_mbps_link_capacity 0
srt_conns_bytes_avail_send_buf 0
srt_conns_bytes_avail_receive_buf 0
srt_conns_mbps_max_bw 0
srt_conns_bytes_mss 0
srt_conns_packets_send_buf 0
srt_conns_bytes_send_buf 0
srt_conns_ms_send_buf 0
srt_conns_ms_send_tsb_pd_delay 0
srt_conns_packets_receive_buf 0
srt_conns_bytes_receive_buf 0
srt_conns_ms_receive_buf 0
srt_conns_ms_receive_tsb_pd_delay 0
srt_conns_packets_reorder_tolerance 0
srt_conns_packets_received_avg_belated_time 0
srt_conns_packets_send_loss_rate 0
srt_conns_packets_received_loss_rate 0
srt_conns_outbound_frames_discarded 0
# WebRTC sessions
webrtc_sessions 0
webrtc_sessions_inbound_bytes 0
webrtc_sessions_inbound_rtp_packets 0
webrtc_sessions_inbound_rtp_packets_lost 0
webrtc_sessions_inbound_rtp_packets_jitter 0
webrtc_sessions_inbound_rtcp_packets 0
webrtc_sessions_outbound_bytes 0
webrtc_sessions_outbound_rtp_packets 0
webrtc_sessions_outbound_rtcp_packets 0
webrtc_sessions_outbound_frames_discarded 0
# WebRTC sessions (deprecated)
webrtc_sessions_bytes_received 0
webrtc_sessions_bytes_sent 0
webrtc_sessions_rtp_packets_received 0
webrtc_sessions_rtp_packets_sent 0
webrtc_sessions_rtp_packets_lost 0
webrtc_sessions_rtp_packets_jitter 0
webrtc_sessions_rtcp_packets_received 0
webrtc_sessions_rtcp_packets_sent 0
# MoQ sessions
moq_sessions 0
moq_sessions_inbound_bytes 0
moq_sessions_outbound_bytes 0
`, string(bo))
})
t.Run("with data", func(t *testing.T) {
terminate := make(chan struct{})
var wg sync.WaitGroup
wg.Add(6)
go func() {
defer wg.Done()
source := gortsplib.Client{}
err2 := source.StartRecording("rtsp://localhost:8554/rtsp_path",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err2)
defer source.Close()
<-terminate
}()
go func() {
defer wg.Done()
source2 := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}}
err2 := source2.StartRecording("rtsps://localhost:8322/rtsps_path",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err2)
defer source2.Close()
<-terminate
}()
go func() {
defer wg.Done()
u, err2 := url.Parse("rtmp://localhost:1935/rtmp_path")
require.NoError(t, err2)
conn := &gortmplib.Client{
URL: u,
Publish: true,
}
err2 = conn.Initialize(context.Background())
require.NoError(t, err2)
defer conn.Close()
track := &gortmplib.Track{
Codec: &rtmpcodecs.H264{
SPS: test.FormatH264.SPS,
PPS: test.FormatH264.PPS,
},
}
w := &gortmplib.Writer{
Conn: conn,
Tracks: []*gortmplib.Track{track},
}
err2 = w.Initialize()
require.NoError(t, err2)
err2 = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}})
require.NoError(t, err2)
<-terminate
}()
go func() {
defer wg.Done()
u, err2 := url.Parse("rtmps://localhost:1936/rtmps_path")
require.NoError(t, err2)
conn := &gortmplib.Client{
URL: u,
TLSConfig: &tls.Config{InsecureSkipVerify: true},
Publish: true,
}
err2 = conn.Initialize(context.Background())
require.NoError(t, err2)
defer conn.Close()
track := &gortmplib.Track{
Codec: &rtmpcodecs.H264{
SPS: test.FormatH264.SPS,
PPS: test.FormatH264.PPS,
},
}
w := &gortmplib.Writer{
Conn: conn,
Tracks: []*gortmplib.Track{track},
}
err2 = w.Initialize()
require.NoError(t, err2)
err2 = w.WriteH264(track, 2*time.Second, 2*time.Second, [][]byte{{5, 2, 3, 4}})
require.NoError(t, err2)
<-terminate
}()
go func() {
defer wg.Done()
su, err2 := url.Parse("http://localhost:8889/webrtc_path/whip")
require.NoError(t, err2)
tr2 := &http.Transport{}
defer tr2.CloseIdleConnections()
hc2 := &http.Client{Transport: tr2}
track := &webrtc.OutboundTrack{
Caps: pwebrtc.RTPCodecCapability{
MimeType: pwebrtc.MimeTypeH264,
ClockRate: 90000,
SDPFmtpLine: "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
},
}
s := &whip.Client{
HTTPClient: hc2,
URL: su,
Log: test.NilLogger,
Publish: true,
OutboundTracks: []*webrtc.OutboundTrack{track},
}
err2 = s.Initialize(context.Background())
require.NoError(t, err2)
defer checkClose(t, s.Close)
err2 = track.WriteRTP(&rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 123,
Timestamp: 45343,
SSRC: 563423,
},
Payload: []byte{1},
})
require.NoError(t, err2)
<-terminate
}()
go func() {
defer wg.Done()
srtConf := srt.DefaultConfig()
address, err2 := srtConf.UnmarshalURL("srt://localhost:8890?streamid=publish:srt_path")
require.NoError(t, err2)
err2 = srtConf.Validate()
require.NoError(t, err2)
publisher, err2 := srt.Dial("srt", address, srtConf)
require.NoError(t, err2)
defer publisher.Close()
track := &mpegts.Track{
Codec: &tscodecs.H264{},
}
bw := bufio.NewWriter(publisher)
w := &mpegts.Writer{W: bw, Tracks: []*mpegts.Track{track}}
err2 = w.Initialize()
require.NoError(t, err2)
err2 = w.WriteH264(track, 0, 0, [][]byte{
test.FormatH264.SPS,
test.FormatH264.PPS,
{0x05, 1}, // IDR
})
require.NoError(t, err2)
err2 = bw.Flush()
require.NoError(t, err2)
<-terminate
}()
time.Sleep(500*time.Millisecond + 2*time.Second)
bo := httpPullFile(t, hc, "http://localhost:9998/metrics")
boStr := string(bo)
require.Contains(t, boStr, "paths{name=\"rtmp_path\",state=\"ready\"} 1\n")
require.Contains(t, boStr, "paths{name=\"rtmps_path\",state=\"ready\"} 1\n")
require.Contains(t, boStr, "paths{name=\"rtsp_path\",state=\"ready\"} 1\n")
require.Contains(t, boStr, "paths{name=\"rtsps_path\",state=\"ready\"} 1\n")
require.Contains(t, boStr, "paths{name=\"srt_path\",state=\"ready\"} 1\n")
require.Contains(t, boStr, "paths{name=\"webrtc_path\",state=\"ready\"} 1\n")
require.Contains(t, boStr, "hls_muxers{name=\"rtmp_path\"} 1\n")
require.Contains(t, boStr, "hls_muxers{name=\"rtmps_path\"} 1\n")
require.Contains(t, boStr, "hls_muxers{name=\"rtsp_path\"} 1\n")
require.Contains(t, boStr, "hls_muxers{name=\"rtsps_path\"} 1\n")
require.Contains(t, boStr, "hls_muxers{name=\"srt_path\"} 1\n")
require.Contains(t, boStr, "hls_muxers{name=\"webrtc_path\"} 1\n")
require.Regexp(t, `(?m)^rtsp_conns\{id=".*?"\} 1$`, boStr)
require.Regexp(t, `(?m)^rtsp_sessions\{id=".*?",path="rtsp_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
require.Regexp(t, `(?m)^rtsps_conns\{id=".*?"\} 1$`, boStr)
require.Regexp(t, `(?m)^rtsps_sessions\{id=".*?",path="rtsps_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
require.Regexp(t, `(?m)^rtmp_conns\{id=".*?",path="rtmp_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
require.Regexp(t, `(?m)^rtmps_conns\{id=".*?",path="rtmps_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
require.Regexp(t, `(?m)^srt_conns\{id=".*?",path="srt_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
require.Regexp(t, `(?m)^srt_conns_ms_rtt\{id=".*?",path="srt_path",`+
`remoteAddr=".*?",state="publish"\} [0-9.]+$`, boStr)
require.Regexp(t, `(?m)^webrtc_sessions\{id=".*?",path="webrtc_path",remoteAddr=".*?",state="publish"\} 1$`, boStr)
require.Regexp(t, `(?m)^webrtc_sessions_rtcp_packets_received\{id=".*?",path="webrtc_path",`+
`remoteAddr=".*?",state="publish"\} [0-9]+$`, boStr)
close(terminate)
wg.Wait()
})
t.Run("servers disabled", func(t *testing.T) {
httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/global/patch", map[string]any{
"rtsp": false,
"rtmp": false,
"srt": false,
"hls": false,
"webrtc": false,
}, nil)
time.Sleep(500 * time.Millisecond)
bo := httpPullFile(t, hc, "http://localhost:9998/metrics")
require.Equal(t, "# Paths\n"+
"paths 0\n"+
"paths_inbound_bytes 0\n"+
"paths_outbound_bytes 0\n"+
"paths_inbound_frames_in_error 0\n"+
"\n"+
"# Paths (deprecated)\n"+
"paths_bytes_received 0\n"+
"paths_bytes_sent 0\n"+
"paths_readers 0\n"+
"\n"+
"# MoQ sessions\n"+
"moq_sessions 0\n"+
"moq_sessions_inbound_bytes 0\n"+
"moq_sessions_outbound_bytes 0\n"+
"\n",
string(bo))
})
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116package core
import (
"context"
"fmt"
"net"
"sort"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/formatlabel"
"github.com/bluenviron/mediamtx/internal/hooks"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/recorder"
"github.com/bluenviron/mediamtx/internal/staticsources"
"github.com/bluenviron/mediamtx/internal/stream"
)
func emptyTimer() *time.Timer {
t := time.NewTimer(0)
<-t.C
return t
}
type pathParent interface {
logger.Writer
setPathReady(*path)
setPathNotReady(*path)
closePathIfIdle(*path)
removePath(*path)
AddReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error)
}
type pathOnDemandState int
const (
pathOnDemandStateInitial pathOnDemandState = iota
pathOnDemandStateWaitingReady
pathOnDemandStateReady
pathOnDemandStateClosing
)
type pathAPIPathsListRes struct {
data *defs.APIPathList
paths map[string]*path
}
type pathAPIPathsListReq struct {
res chan pathAPIPathsListRes
}
type pathAPIPathsGetRes struct {
path *path
data *defs.APIPath
err error
}
type pathAPIPathsGetReq struct {
name string
res chan pathAPIPathsGetRes
}
type path struct {
parentCtx context.Context
logLevel conf.LogLevel
dumpPackets bool
rtspAddress string
readTimeout conf.Duration
writeTimeout conf.Duration
writeQueueSize int
udpReadBufferSize uint
rtpMaxPayloadSize int
conf *conf.Path
name string
matches []string
wg *sync.WaitGroup
externalCmdPool *externalcmd.Pool
parent pathParent
// accessed by pathManager only
ready bool
confName string
ctx context.Context
ctxCancel func()
pendingRequests atomic.Int64
confMutex sync.RWMutex
source defs.Source
stream *stream.Stream
recorder *recorder.Recorder
availableTime time.Time
onlineTime time.Time
onUnDemandHook func(string)
onNotReadyHook func()
readers map[defs.Reader]struct{}
describeRequestsOnHold []defs.PathDescribeReq
readerAddRequestsOnHold []defs.PathAddReaderReq
onDemandStaticSourceState pathOnDemandState
onDemandStaticSourceReadyTimer *time.Timer
onDemandStaticSourceCloseTimer *time.Timer
onDemandPublisherState pathOnDemandState
onDemandPublisherReadyTimer *time.Timer
onDemandPublisherCloseTimer *time.Timer
// in
chReloadConf chan *conf.Path
chStaticSourceSetReady chan defs.PathSourceStaticSetReadyReq
chStaticSourceSetNotReady chan defs.PathSourceStaticSetNotReadyReq
chDescribe chan defs.PathDescribeReq
chAddPublisher chan defs.PathAddPublisherReq
chRemovePublisher chan defs.PathRemovePublisherReq
chAddReader chan defs.PathAddReaderReq
chRemoveReader chan defs.PathRemoveReaderReq
chAPIPathsGet chan pathAPIPathsGetReq
// out
done chan struct{}
}
func (pa *path) initialize() {
ctx, ctxCancel := context.WithCancel(pa.parentCtx)
pa.confName = pa.conf.Name
pa.ctx = ctx
pa.ctxCancel = ctxCancel
pa.readers = make(map[defs.Reader]struct{})
pa.onDemandStaticSourceReadyTimer = emptyTimer()
pa.onDemandStaticSourceCloseTimer = emptyTimer()
pa.onDemandPublisherReadyTimer = emptyTimer()
pa.onDemandPublisherCloseTimer = emptyTimer()
pa.chReloadConf = make(chan *conf.Path)
pa.chStaticSourceSetReady = make(chan defs.PathSourceStaticSetReadyReq)
pa.chStaticSourceSetNotReady = make(chan defs.PathSourceStaticSetNotReadyReq)
pa.chDescribe = make(chan defs.PathDescribeReq)
pa.chAddPublisher = make(chan defs.PathAddPublisherReq)
pa.chRemovePublisher = make(chan defs.PathRemovePublisherReq)
pa.chAddReader = make(chan defs.PathAddReaderReq)
pa.chRemoveReader = make(chan defs.PathRemoveReaderReq)
pa.chAPIPathsGet = make(chan pathAPIPathsGetReq)
pa.done = make(chan struct{})
pa.Log(logger.Debug, "created")
pa.wg.Add(1)
go pa.run()
}
func (pa *path) close() {
pa.ctxCancel()
}
func (pa *path) wait() {
<-pa.done
}
// Log implements logger.Writer.
func (pa *path) Log(level logger.Level, format string, args ...any) {
pa.parent.Log(level, "[path "+pa.name+"] "+format, args...)
}
func (pa *path) Name() string {
return pa.name
}
func (pa *path) isAvailable() bool {
return pa.stream != nil
}
func (pa *path) isOnline() bool {
return pa.source != nil
}
func (pa *path) run() {
defer close(pa.done)
defer pa.wg.Done()
if pa.conf.AlwaysAvailable {
err := pa.setAvailable(nil, "", nil, true)
if err != nil {
panic(err)
}
}
if pa.conf.Source == "redirect" {
pa.source = &sourceRedirect{}
} else if pa.conf.HasStaticSource() {
pa.source = &staticsources.Handler{
Conf: pa.conf,
LogLevel: pa.logLevel,
DumpPackets: pa.dumpPackets,
ReadTimeout: pa.readTimeout,
WriteTimeout: pa.writeTimeout,
WriteQueueSize: pa.writeQueueSize,
UDPReadBufferSize: pa.udpReadBufferSize,
RTPMaxPayloadSize: pa.rtpMaxPayloadSize,
Matches: pa.matches,
PathManager: pa.parent,
Parent: pa,
}
pa.source.(*staticsources.Handler).Initialize()
if !pa.conf.SourceOnDemand {
pa.source.(*staticsources.Handler).Start(false, "")
}
}
onUnInitHook := hooks.OnInit(hooks.OnInitParams{
Logger: pa,
ExternalCmdPool: pa.externalCmdPool,
Conf: pa.conf,
ExternalCmdEnv: pa.ExternalCmdEnv(),
})
err := pa.runInner()
// call before destroying context
pa.parent.removePath(pa)
pa.ctxCancel()
pa.onDemandStaticSourceReadyTimer.Stop()
pa.onDemandStaticSourceCloseTimer.Stop()
pa.onDemandPublisherReadyTimer.Stop()
pa.onDemandPublisherCloseTimer.Stop()
onUnInitHook()
for _, req := range pa.describeRequestsOnHold {
req.Res <- defs.PathDescribeRes{Err: fmt.Errorf("terminated")}
}
for _, req := range pa.readerAddRequestsOnHold {
req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("terminated")}
}
if pa.stream != nil {
pa.setNotAvailable()
}
if pa.source != nil {
if source, ok := pa.source.(*staticsources.Handler); ok {
if !pa.conf.SourceOnDemand || pa.onDemandStaticSourceState != pathOnDemandStateInitial {
source.Close("path is closing")
}
} else if source, ok2 := pa.source.(defs.Publisher); ok2 {
source.Close()
}
}
if pa.onUnDemandHook != nil {
pa.onUnDemandHook("path destroyed")
}
pa.Log(logger.Debug, "destroyed: %v", err)
}
func (pa *path) runInner() error {
for {
select {
case <-pa.onDemandStaticSourceReadyTimer.C:
pa.doOnDemandStaticSourceReadyTimer()
if pa.shouldClose() {
pa.parent.closePathIfIdle(pa)
}
case <-pa.onDemandStaticSourceCloseTimer.C:
pa.doOnDemandStaticSourceCloseTimer()
if pa.shouldClose() {
pa.parent.closePathIfIdle(pa)
}
case <-pa.onDemandPublisherReadyTimer.C:
pa.doOnDemandPublisherReadyTimer()
if pa.shouldClose() {
pa.parent.closePathIfIdle(pa)
}
case <-pa.onDemandPublisherCloseTimer.C:
pa.doOnDemandPublisherCloseTimer()
case newConf := <-pa.chReloadConf:
pa.doReloadConf(newConf)
case req := <-pa.chStaticSourceSetReady:
pa.doSourceStaticSetReady(req)
case req := <-pa.chStaticSourceSetNotReady:
pa.doSourceStaticSetNotReady(req)
if pa.shouldClose() {
pa.parent.closePathIfIdle(pa)
}
case req := <-pa.chDescribe:
pa.doDescribe(req)
pa.pendingRequests.Add(-1)
if pa.shouldClose() {
pa.parent.closePathIfIdle(pa)
}
case req := <-pa.chAddPublisher:
pa.doAddPublisher(req)
pa.pendingRequests.Add(-1)
if pa.shouldClose() {
pa.parent.closePathIfIdle(pa)
}
case req := <-pa.chRemovePublisher:
pa.doRemovePublisher(req)
if pa.shouldClose() {
pa.parent.closePathIfIdle(pa)
}
case req := <-pa.chAddReader:
pa.doAddReader(req)
pa.pendingRequests.Add(-1)
if pa.shouldClose() {
pa.parent.closePathIfIdle(pa)
}
case req := <-pa.chRemoveReader:
pa.doRemoveReader(req)
case req := <-pa.chAPIPathsGet:
pa.doAPIPathsGet(req)
case <-pa.ctx.Done():
return fmt.Errorf("terminated")
}
}
}
func (pa *path) doOnDemandStaticSourceReadyTimer() {
for _, req := range pa.describeRequestsOnHold {
req.Res <- defs.PathDescribeRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)}
}
pa.describeRequestsOnHold = nil
for _, req := range pa.readerAddRequestsOnHold {
req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)}
}
pa.readerAddRequestsOnHold = nil
pa.onDemandStaticSourceStop("timed out")
}
func (pa *path) doOnDemandStaticSourceCloseTimer() {
if pa.conf.AlwaysAvailable {
panic("should not happen")
}
pa.setNotAvailable()
pa.onDemandStaticSourceStop("not needed by anyone")
}
func (pa *path) doOnDemandPublisherReadyTimer() {
for _, req := range pa.describeRequestsOnHold {
req.Res <- defs.PathDescribeRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)}
}
pa.describeRequestsOnHold = nil
for _, req := range pa.readerAddRequestsOnHold {
req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("source of path '%s' has timed out", pa.name)}
}
pa.readerAddRequestsOnHold = nil
pa.onDemandPublisherStop("timed out")
}
func (pa *path) doOnDemandPublisherCloseTimer() {
pa.onDemandPublisherStop("not needed by anyone")
}
func (pa *path) doReloadConf(newConf *conf.Path) {
pa.confMutex.Lock()
oldConf := pa.conf
pa.conf = newConf
pa.confMutex.Unlock()
if pa.conf.HasStaticSource() {
pa.source.(*staticsources.Handler).ReloadConf(newConf)
}
if pa.recorder != nil &&
(newConf.Record != oldConf.Record ||
newConf.RecordPath != oldConf.RecordPath ||
newConf.RecordFormat != oldConf.RecordFormat ||
newConf.RecordPartDuration != oldConf.RecordPartDuration ||
newConf.RecordMaxPartSize != oldConf.RecordMaxPartSize ||
newConf.RecordSegmentDuration != oldConf.RecordSegmentDuration ||
newConf.RecordDeleteAfter != oldConf.RecordDeleteAfter) {
pa.recorder.Close()
pa.recorder = nil
}
if newConf.Record && pa.stream != nil && pa.recorder == nil {
pa.startRecording()
}
}
func (pa *path) doSourceStaticSetReady(req defs.PathSourceStaticSetReadyReq) {
if !pa.conf.AlwaysAvailable {
err := pa.setAvailable(pa.source, "", req.Desc, req.ReplaceNTP)
if err != nil {
req.Res <- defs.PathSourceStaticSetReadyRes{Err: err}
return
}
}
subStream := &stream.SubStream{
Stream: pa.stream,
UseRTPPackets: req.UseRTPPackets,
}
if pa.conf.AlwaysAvailable {
subStream.InDesc = req.Desc
}
err := subStream.Initialize()
if err != nil {
req.Res <- defs.PathSourceStaticSetReadyRes{Err: err}
return
}
if pa.conf.AlwaysAvailable {
pa.onlineTime = time.Now()
}
if pa.conf.HasOnDemandStaticSource() {
pa.onDemandStaticSourceReadyTimer.Stop()
pa.onDemandStaticSourceReadyTimer = emptyTimer()
pa.onDemandStaticSourceScheduleClose()
}
pa.consumeOnHoldRequests()
req.Res <- defs.PathSourceStaticSetReadyRes{SubStream: subStream}
}
func (pa *path) doSourceStaticSetNotReady(req defs.PathSourceStaticSetNotReadyReq) {
if !pa.conf.AlwaysAvailable {
pa.setNotAvailable()
} else {
err := pa.stream.StartOfflineSubStream()
if err != nil {
panic("should not happen")
}
}
// send response before calling onDemandStaticSourceStop()
// in order to avoid a deadlock due to staticsources.Handler.stop()
close(req.Res)
if pa.conf.HasOnDemandStaticSource() && pa.onDemandStaticSourceState != pathOnDemandStateInitial {
pa.onDemandStaticSourceStop("an error occurred")
}
}
func (pa *path) doDescribe(req defs.PathDescribeReq) {
if _, ok := pa.source.(*sourceRedirect); ok {
req.Res <- defs.PathDescribeRes{
Redirect: pa.conf.SourceRedirect,
}
return
}
if pa.stream != nil {
req.Res <- defs.PathDescribeRes{
Stream: pa.stream,
}
return
}
if pa.conf.HasOnDemandStaticSource() {
if pa.onDemandStaticSourceState == pathOnDemandStateInitial {
pa.onDemandStaticSourceStart(req.AccessRequest.Query)
}
pa.describeRequestsOnHold = append(pa.describeRequestsOnHold, req)
return
}
if pa.conf.HasOnDemandPublisher() {
if pa.onDemandPublisherState == pathOnDemandStateInitial {
pa.onDemandPublisherStart(req.AccessRequest.Query)
}
pa.describeRequestsOnHold = append(pa.describeRequestsOnHold, req)
return
}
if pa.conf.Fallback != nil {
req.Res <- defs.PathDescribeRes{Redirect: *pa.conf.Fallback}
return
}
req.Res <- defs.PathDescribeRes{Err: &defs.PathNoStreamAvailableError{PathName: pa.name}}
}
func (pa *path) doRemovePublisher(req defs.PathRemovePublisherReq) {
if pa.source == req.Author {
pa.executeRemovePublisher()
}
close(req.Res)
}
func (pa *path) doAddPublisher(req defs.PathAddPublisherReq) {
if pa.conf.Source != "publisher" {
req.Res <- defs.PathAddPublisherRes{
Err: fmt.Errorf("can't publish to path '%s' since 'source' is not 'publisher'", pa.name),
}
return
}
if pa.source != nil {
if !pa.conf.OverridePublisher {
req.Res <- defs.PathAddPublisherRes{Err: fmt.Errorf("someone is already publishing to path '%s'", pa.name)}
return
}
pa.Log(logger.Info, "closing existing publisher")
pa.source.(defs.Publisher).Close()
pa.executeRemovePublisher()
}
if !pa.conf.AlwaysAvailable {
err := pa.setAvailable(req.Author, req.AccessRequest.Query, req.Desc, req.ReplaceNTP)
if err != nil {
req.Res <- defs.PathAddPublisherRes{Err: err}
return
}
}
subStream := &stream.SubStream{
Stream: pa.stream,
UseRTPPackets: req.UseRTPPackets,
}
if pa.conf.AlwaysAvailable {
subStream.InDesc = req.Desc
}
err := subStream.Initialize()
if err != nil {
req.Res <- defs.PathAddPublisherRes{Err: err}
return
}
pa.source = req.Author
req.Author.Log(logger.Info, "is publishing to path '%s'",
pa.name)
if pa.conf.AlwaysAvailable {
pa.onlineTime = time.Now()
}
if pa.conf.HasOnDemandPublisher() && pa.onDemandPublisherState != pathOnDemandStateInitial {
pa.onDemandPublisherReadyTimer.Stop()
pa.onDemandPublisherReadyTimer = emptyTimer()
pa.onDemandPublisherScheduleClose()
}
pa.consumeOnHoldRequests()
req.Res <- defs.PathAddPublisherRes{SubStream: subStream}
}
func (pa *path) doAddReader(req defs.PathAddReaderReq) {
if pa.stream != nil {
pa.addReaderPost(req)
return
}
if pa.conf.HasOnDemandStaticSource() {
if pa.onDemandStaticSourceState == pathOnDemandStateInitial {
pa.onDemandStaticSourceStart(req.AccessRequest.Query)
}
pa.readerAddRequestsOnHold = append(pa.readerAddRequestsOnHold, req)
return
}
if pa.conf.HasOnDemandPublisher() {
if pa.onDemandPublisherState == pathOnDemandStateInitial {
pa.onDemandPublisherStart(req.AccessRequest.Query)
}
pa.readerAddRequestsOnHold = append(pa.readerAddRequestsOnHold, req)
return
}
req.Res <- defs.PathAddReaderRes{Err: &defs.PathNoStreamAvailableError{PathName: pa.name}}
}
func (pa *path) doRemoveReader(req defs.PathRemoveReaderReq) {
if _, ok := pa.readers[req.Author]; ok {
pa.executeRemoveReader(req.Author)
}
close(req.Res)
if len(pa.readers) == 0 {
if pa.conf.HasOnDemandStaticSource() {
if pa.onDemandStaticSourceState == pathOnDemandStateReady {
pa.onDemandStaticSourceScheduleClose()
}
} else if pa.conf.HasOnDemandPublisher() {
if pa.onDemandPublisherState == pathOnDemandStateReady {
pa.onDemandPublisherScheduleClose()
}
}
}
}
func (pa *path) doAPIPathsGet(req pathAPIPathsGetReq) {
var outDesc *description.Session
if pa.isAvailable() {
outDesc = pa.stream.OutDescCopy()
}
req.res <- pathAPIPathsGetRes{
data: &defs.APIPath{
Name: pa.name,
ConfName: pa.conf.Name,
Ready: pa.isAvailable(),
ReadyTime: func() *time.Time {
if !pa.isAvailable() {
return nil
}
v := pa.availableTime
return &v
}(),
Available: pa.isAvailable(),
AvailableTime: func() *time.Time {
if !pa.isAvailable() {
return nil
}
v := pa.availableTime
return &v
}(),
Online: pa.isOnline(),
OnlineTime: func() *time.Time {
if !pa.isOnline() {
return nil
}
v := pa.onlineTime
return &v
}(),
Source: func() *defs.APIPathSource {
if pa.source == nil {
return nil
}
v := pa.source.APISourceDescribe()
return v
}(),
Tracks: func() []defs.APIPathTrackCodec {
if !pa.isAvailable() {
return []defs.APIPathTrackCodec{}
}
return formatlabel.MediasToLabels(outDesc.Medias)
}(),
Tracks2: func() []defs.APIPathTrack {
if !pa.isAvailable() {
return []defs.APIPathTrack{}
}
return defs.MediasToTracks(outDesc.Medias)
}(),
InboundBytes: func() uint64 {
if !pa.isAvailable() {
return 0
}
return pa.stream.InboundBytes()
}(),
OutboundBytes: func() uint64 {
if !pa.isAvailable() {
return 0
}
return pa.stream.OutboundBytes()
}(),
InboundFramesInError: func() uint64 {
if !pa.isAvailable() {
return 0
}
return pa.stream.InboundFramesInError()
}(),
BytesReceived: func() uint64 {
if !pa.isAvailable() {
return 0
}
return pa.stream.InboundBytes()
}(),
BytesSent: func() uint64 {
if !pa.isAvailable() {
return 0
}
return pa.stream.OutboundBytes()
}(),
Readers: func() []defs.APIPathReader {
ret := make([]defs.APIPathReader, 0, len(pa.readers))
for r := range pa.readers {
desc := *r.APIReaderDescribe()
if desc.Type != defs.APIPathReaderTypeHidden {
ret = append(ret, desc)
}
}
sort.Slice(ret, func(i, j int) bool {
if ret[i].Type != ret[j].Type {
return ret[i].Type < ret[j].Type
}
return ret[i].ID < ret[j].ID
})
return ret
}(),
},
}
}
func (pa *path) SafeConf() *conf.Path {
pa.confMutex.RLock()
defer pa.confMutex.RUnlock()
return pa.conf
}
func (pa *path) ExternalCmdEnv() externalcmd.Environment {
_, port, _ := net.SplitHostPort(pa.rtspAddress)
env := externalcmd.Environment{
"MTX_PATH": pa.name,
"RTSP_PATH": pa.name, // deprecated
"RTSP_PORT": port,
}
if len(pa.matches) > 1 {
for i, ma := range pa.matches[1:] {
env["G"+strconv.FormatInt(int64(i+1), 10)] = ma
}
}
return env
}
func (pa *path) shouldClose() bool {
return pa.conf.Regexp != nil &&
pa.source == nil &&
len(pa.readers) == 0 &&
len(pa.describeRequestsOnHold) == 0 &&
len(pa.readerAddRequestsOnHold) == 0
}
func (pa *path) onDemandStaticSourceStart(query string) {
pa.source.(*staticsources.Handler).Start(true, query)
pa.onDemandStaticSourceReadyTimer.Stop()
pa.onDemandStaticSourceReadyTimer = time.NewTimer(time.Duration(pa.conf.SourceOnDemandStartTimeout))
pa.onDemandStaticSourceState = pathOnDemandStateWaitingReady
}
func (pa *path) onDemandStaticSourceScheduleClose() {
pa.onDemandStaticSourceCloseTimer.Stop()
pa.onDemandStaticSourceCloseTimer = time.NewTimer(time.Duration(pa.conf.SourceOnDemandCloseAfter))
pa.onDemandStaticSourceState = pathOnDemandStateClosing
}
func (pa *path) onDemandStaticSourceStop(reason string) {
if pa.onDemandStaticSourceState == pathOnDemandStateClosing {
pa.onDemandStaticSourceCloseTimer.Stop()
pa.onDemandStaticSourceCloseTimer = emptyTimer()
}
pa.onDemandStaticSourceState = pathOnDemandStateInitial
pa.source.(*staticsources.Handler).Stop(reason)
}
func (pa *path) onDemandPublisherStart(query string) {
pa.onUnDemandHook = hooks.OnDemand(hooks.OnDemandParams{
Logger: pa,
ExternalCmdPool: pa.externalCmdPool,
Conf: pa.conf,
ExternalCmdEnv: pa.ExternalCmdEnv(),
Query: query,
})
pa.onDemandPublisherReadyTimer.Stop()
pa.onDemandPublisherReadyTimer = time.NewTimer(time.Duration(pa.conf.RunOnDemandStartTimeout))
pa.onDemandPublisherState = pathOnDemandStateWaitingReady
}
func (pa *path) onDemandPublisherScheduleClose() {
pa.onDemandPublisherCloseTimer.Stop()
pa.onDemandPublisherCloseTimer = time.NewTimer(time.Duration(pa.conf.RunOnDemandCloseAfter))
pa.onDemandPublisherState = pathOnDemandStateClosing
}
func (pa *path) onDemandPublisherStop(reason string) {
if pa.onDemandPublisherState == pathOnDemandStateClosing {
pa.onDemandPublisherCloseTimer.Stop()
pa.onDemandPublisherCloseTimer = emptyTimer()
}
pa.onUnDemandHook(reason)
pa.onUnDemandHook = nil
pa.onDemandPublisherState = pathOnDemandStateInitial
}
func (pa *path) setAvailable(
source defs.Source,
publisherQuery string,
desc *description.Session,
replaceNTP bool,
) error {
pa.stream = &stream.Stream{
OrigDesc: desc,
AlwaysAvailable: pa.conf.AlwaysAvailable,
AlwaysAvailableTracks: pa.conf.AlwaysAvailableTracks,
AlwaysAvailableFile: pa.conf.AlwaysAvailableFile,
WriteQueueSize: pa.writeQueueSize,
RTPMaxPayloadSize: pa.rtpMaxPayloadSize,
ReplaceNTP: replaceNTP,
Parent: pa,
}
err := pa.stream.Initialize()
if err != nil {
return err
}
pa.availableTime = time.Now()
if !pa.conf.AlwaysAvailable {
pa.onlineTime = time.Now()
}
if pa.conf.Record {
pa.startRecording()
}
var sourceDesc *defs.APIPathSource
if source != nil {
sourceDesc = source.APISourceDescribe()
}
pa.onNotReadyHook = hooks.OnReady(hooks.OnReadyParams{
Logger: pa,
ExternalCmdPool: pa.externalCmdPool,
Conf: pa.conf,
ExternalCmdEnv: pa.ExternalCmdEnv(),
Desc: sourceDesc,
Query: publisherQuery,
})
if pa.conf.AlwaysAvailable {
pa.Log(logger.Info, "stream is available, %s", defs.MediasInfo(pa.stream.OrigDesc.Medias))
} else {
pa.Log(logger.Info, "stream is available and online, %s", defs.MediasInfo(pa.stream.OrigDesc.Medias))
}
pa.parent.setPathReady(pa)
return nil
}
func (pa *path) consumeOnHoldRequests() {
for _, req := range pa.describeRequestsOnHold {
req.Res <- defs.PathDescribeRes{
Stream: pa.stream,
}
}
pa.describeRequestsOnHold = nil
for _, req := range pa.readerAddRequestsOnHold {
pa.addReaderPost(req)
}
pa.readerAddRequestsOnHold = nil
}
func (pa *path) setNotAvailable() {
pa.parent.setPathNotReady(pa)
for r := range pa.readers {
pa.executeRemoveReader(r)
r.Close()
}
pa.onNotReadyHook()
if pa.recorder != nil {
pa.recorder.Close()
pa.recorder = nil
}
if pa.stream != nil {
pa.stream.Close()
pa.stream = nil
}
}
func (pa *path) startRecording() {
pa.recorder = &recorder.Recorder{
PathFormat: pa.conf.RecordPath,
Format: pa.conf.RecordFormat,
PartDuration: time.Duration(pa.conf.RecordPartDuration),
MaxPartSize: pa.conf.RecordMaxPartSize,
SegmentDuration: time.Duration(pa.conf.RecordSegmentDuration),
PathName: pa.name,
Stream: pa.stream,
OnSegmentCreate: func(segmentPath string) {
if pa.conf.RunOnRecordSegmentCreate != "" {
env := pa.ExternalCmdEnv()
env["MTX_SEGMENT_PATH"] = segmentPath
pa.Log(logger.Info, "runOnRecordSegmentCreate command launched")
cmd := &externalcmd.Cmd{
Pool: pa.externalCmdPool,
Cmdstr: pa.conf.RunOnRecordSegmentCreate,
Restart: false,
Env: env,
}
cmd.Start()
}
},
OnSegmentComplete: func(segmentPath string, segmentDuration time.Duration) {
if pa.conf.RunOnRecordSegmentComplete != "" {
env := pa.ExternalCmdEnv()
env["MTX_SEGMENT_PATH"] = segmentPath
env["MTX_SEGMENT_DURATION"] = strconv.FormatFloat(segmentDuration.Seconds(), 'f', -1, 64)
pa.Log(logger.Info, "runOnRecordSegmentComplete command launched")
cmd := &externalcmd.Cmd{
Pool: pa.externalCmdPool,
Cmdstr: pa.conf.RunOnRecordSegmentComplete,
Restart: false,
Env: env,
}
cmd.Start()
}
},
Parent: pa,
}
pa.recorder.Initialize()
}
func (pa *path) executeRemoveReader(r defs.Reader) {
delete(pa.readers, r)
}
func (pa *path) executeRemovePublisher() {
if !pa.conf.AlwaysAvailable {
pa.setNotAvailable()
} else {
err := pa.stream.StartOfflineSubStream()
if err != nil {
panic("should not happen")
}
}
pa.source = nil
}
func (pa *path) addReaderPost(req defs.PathAddReaderReq) {
if _, ok := pa.readers[req.Author]; ok {
req.Res <- defs.PathAddReaderRes{Stream: pa.stream}
return
}
if pa.conf.MaxReaders != 0 && len(pa.readers) >= pa.conf.MaxReaders {
req.Res <- defs.PathAddReaderRes{Err: fmt.Errorf("maximum reader count reached")}
return
}
pa.readers[req.Author] = struct{}{}
if pa.conf.HasOnDemandStaticSource() {
if pa.onDemandStaticSourceState == pathOnDemandStateClosing {
pa.onDemandStaticSourceState = pathOnDemandStateReady
pa.onDemandStaticSourceCloseTimer.Stop()
pa.onDemandStaticSourceCloseTimer = emptyTimer()
}
} else if pa.conf.HasOnDemandPublisher() {
if pa.onDemandPublisherState == pathOnDemandStateClosing {
pa.onDemandPublisherState = pathOnDemandStateReady
pa.onDemandPublisherCloseTimer.Stop()
pa.onDemandPublisherCloseTimer = emptyTimer()
}
}
req.Res <- defs.PathAddReaderRes{Stream: pa.stream}
}
// reloadConf is called by pathManager.
func (pa *path) reloadConf(newConf *conf.Path) {
select {
case pa.chReloadConf <- newConf:
case <-pa.ctx.Done():
}
}
// StaticSourceHandlerSetReady is called by staticsources.Handler.
func (pa *path) StaticSourceHandlerSetReady(
ctx context.Context, req defs.PathSourceStaticSetReadyReq,
) {
select {
case pa.chStaticSourceSetReady <- req:
case <-pa.ctx.Done():
req.Res <- defs.PathSourceStaticSetReadyRes{Err: fmt.Errorf("terminated")}
// this avoids:
// - invalid requests sent after the source has been terminated
// - deadlocks caused by <-done inside stop()
case <-ctx.Done():
req.Res <- defs.PathSourceStaticSetReadyRes{Err: fmt.Errorf("terminated")}
}
}
// StaticSourceHandlerSetNotReady is called by staticsources.Handler.
func (pa *path) StaticSourceHandlerSetNotReady(
ctx context.Context, req defs.PathSourceStaticSetNotReadyReq,
) {
select {
case pa.chStaticSourceSetNotReady <- req:
case <-pa.ctx.Done():
close(req.Res)
// this avoids:
// - invalid requests sent after the source has been terminated
// - deadlocks caused by <-done inside stop()
case <-ctx.Done():
close(req.Res)
}
}
// describe is called by a reader or publisher through pathManager.
func (pa *path) describe(req defs.PathDescribeReq) (*defs.PathDescribeRes, error) {
select {
case pa.chDescribe <- req:
res := <-req.Res
return &res, res.Err
case <-pa.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
// addPublisher is called by a publisher through pathManager.
func (pa *path) addPublisher(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) {
select {
case pa.chAddPublisher <- req:
res := <-req.Res
return &res, res.Err
case <-pa.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
// RemovePublisher is called by a publisher.
func (pa *path) RemovePublisher(req defs.PathRemovePublisherReq) {
req.Res = make(chan struct{})
select {
case pa.chRemovePublisher <- req:
<-req.Res
case <-pa.ctx.Done():
}
}
// addReader is called by a reader through pathManager.
func (pa *path) addReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) {
select {
case pa.chAddReader <- req:
res := <-req.Res
return &res, res.Err
case <-pa.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
// RemoveReader is called by a reader.
func (pa *path) RemoveReader(req defs.PathRemoveReaderReq) {
req.Res = make(chan struct{})
select {
case pa.chRemoveReader <- req:
<-req.Res
case <-pa.ctx.Done():
}
}
// APIPathsGet implements defs.APIPathManager.
func (pa *path) APIPathsGet(req pathAPIPathsGetReq) (*defs.APIPath, error) {
req.res = make(chan pathAPIPathsGetRes)
select {
case pa.chAPIPathsGet <- req:
res := <-req.res
return res.data, res.err
case <-pa.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690package core
import (
"context"
"fmt"
"maps"
"sort"
"sync"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/metrics"
"github.com/bluenviron/mediamtx/internal/servers/hls"
)
func pathConfCanBeUpdated(oldPathConf *conf.Path, newPathConf *conf.Path) bool {
clone := oldPathConf.Clone()
clone.Name = newPathConf.Name
clone.Regexp = newPathConf.Regexp
clone.Record = newPathConf.Record
clone.RecordPath = newPathConf.RecordPath
clone.RecordFormat = newPathConf.RecordFormat
clone.RecordPartDuration = newPathConf.RecordPartDuration
clone.RecordMaxPartSize = newPathConf.RecordMaxPartSize
clone.RecordSegmentDuration = newPathConf.RecordSegmentDuration
clone.RecordDeleteAfter = newPathConf.RecordDeleteAfter
clone.RPICameraBrightness = newPathConf.RPICameraBrightness
clone.RPICameraContrast = newPathConf.RPICameraContrast
clone.RPICameraSaturation = newPathConf.RPICameraSaturation
clone.RPICameraSharpness = newPathConf.RPICameraSharpness
clone.RPICameraExposure = newPathConf.RPICameraExposure
clone.RPICameraFlickerPeriod = newPathConf.RPICameraFlickerPeriod
clone.RPICameraAWB = newPathConf.RPICameraAWB
clone.RPICameraAWBGains = newPathConf.RPICameraAWBGains
clone.RPICameraDenoise = newPathConf.RPICameraDenoise
clone.RPICameraShutter = newPathConf.RPICameraShutter
clone.RPICameraMetering = newPathConf.RPICameraMetering
clone.RPICameraGain = newPathConf.RPICameraGain
clone.RPICameraEV = newPathConf.RPICameraEV
clone.RPICameraFPS = newPathConf.RPICameraFPS
clone.RPICameraTextOverlayEnable = newPathConf.RPICameraTextOverlayEnable
clone.RPICameraTextOverlay = newPathConf.RPICameraTextOverlay
clone.RPICameraIDRPeriod = newPathConf.RPICameraIDRPeriod
clone.RPICameraBitrate = newPathConf.RPICameraBitrate
return newPathConf.Equal(clone)
}
type pathSetHLSServerRes struct {
readyPaths []defs.Path
}
type pathSetHLSServerReq struct {
s *hls.Server
res chan pathSetHLSServerRes
}
type pathManagerAuthManager interface {
Authenticate(req *auth.Request) (string, *auth.Error)
}
type pathManagerParent interface {
logger.Writer
}
type pathManager struct {
logLevel conf.LogLevel
rtspAddress string
dumpPackets bool
readTimeout conf.Duration
writeTimeout conf.Duration
writeQueueSize int
udpReadBufferSize uint
rtpMaxPayloadSize int
pathConfs map[string]*conf.Path
authManager pathManagerAuthManager
externalCmdPool *externalcmd.Pool
metrics *metrics.Metrics
parent pathManagerParent
ctx context.Context
ctxCancel func()
wg sync.WaitGroup
hlsServer *hls.Server
paths map[string]*path
// in
chReloadConf chan map[string]*conf.Path
chSetHLSServer chan pathSetHLSServerReq
chRemovePath chan *path
chClosePathIfIdle chan *path
chSetPathReady chan *path
chSetPathNotReady chan *path
chFindPathConf chan defs.PathFindPathConfReq
chDescribe chan defs.PathDescribeReq
chAddReader chan defs.PathAddReaderReq
chAddPublisher chan defs.PathAddPublisherReq
chAPIPathsList chan pathAPIPathsListReq
chAPIPathsGet chan pathAPIPathsGetReq
}
func (pm *pathManager) initialize() {
ctx, ctxCancel := context.WithCancel(context.Background())
pm.ctx = ctx
pm.ctxCancel = ctxCancel
pm.paths = make(map[string]*path)
pm.chReloadConf = make(chan map[string]*conf.Path)
pm.chSetHLSServer = make(chan pathSetHLSServerReq)
pm.chRemovePath = make(chan *path)
pm.chClosePathIfIdle = make(chan *path)
pm.chSetPathReady = make(chan *path)
pm.chSetPathNotReady = make(chan *path)
pm.chFindPathConf = make(chan defs.PathFindPathConfReq)
pm.chDescribe = make(chan defs.PathDescribeReq)
pm.chAddReader = make(chan defs.PathAddReaderReq)
pm.chAddPublisher = make(chan defs.PathAddPublisherReq)
pm.chAPIPathsList = make(chan pathAPIPathsListReq)
pm.chAPIPathsGet = make(chan pathAPIPathsGetReq)
for _, pathConf := range pm.pathConfs {
if pathConf.Regexp == nil {
pm.createPath(pathConf, pathConf.Name, nil)
}
}
pm.Log(logger.Debug, "path manager created")
pm.wg.Add(1)
go pm.run()
if pm.metrics != nil {
pm.metrics.SetPathManager(pm)
}
}
func (pm *pathManager) close() {
pm.Log(logger.Debug, "path manager is shutting down")
if pm.metrics != nil {
pm.metrics.SetPathManager(nil)
}
pm.ctxCancel()
pm.wg.Wait()
}
// Log implements logger.Writer.
func (pm *pathManager) Log(level logger.Level, format string, args ...any) {
pm.parent.Log(level, format, args...)
}
func (pm *pathManager) run() {
defer pm.wg.Done()
outer:
for {
select {
case newPaths := <-pm.chReloadConf:
pm.doReloadConf(newPaths)
case req := <-pm.chSetHLSServer:
readyPaths := pm.doSetHLSServer(req.s)
req.res <- pathSetHLSServerRes{readyPaths: readyPaths}
case pa := <-pm.chRemovePath:
if pa2, ok := pm.paths[pa.name]; ok && pa2 == pa {
delete(pm.paths, pa.name)
}
case pa := <-pm.chClosePathIfIdle:
if pa.pendingRequests.Load() == 0 {
pm.doClosePath(pa)
}
case pa := <-pm.chSetPathReady:
pm.doSetPathReady(pa)
case pa := <-pm.chSetPathNotReady:
pm.doSetPathNotReady(pa)
case req := <-pm.chFindPathConf:
pm.doFindPathConf(req)
case req := <-pm.chDescribe:
pm.doDescribe(req)
case req := <-pm.chAddReader:
pm.doAddReader(req)
case req := <-pm.chAddPublisher:
pm.doAddPublisher(req)
case req := <-pm.chAPIPathsList:
pm.doAPIPathsList(req)
case req := <-pm.chAPIPathsGet:
pm.doAPIPathsGet(req)
case <-pm.ctx.Done():
break outer
}
}
pm.ctxCancel()
}
func (pm *pathManager) doReloadConf(newPaths map[string]*conf.Path) {
confsToRecreate := make(map[string]struct{})
confsToReload := make(map[string]struct{})
for confName, pathConf := range pm.pathConfs {
if newPath, ok := newPaths[confName]; ok {
if !newPath.Equal(pathConf) {
if pathConfCanBeUpdated(pathConf, newPath) {
confsToReload[confName] = struct{}{}
} else {
confsToRecreate[confName] = struct{}{}
}
}
}
}
// process existing paths
for pathName, pa := range pm.paths {
newPathConf, _, err := conf.FindPathConf(newPaths, pathName)
// path does not have a config anymore: delete it
if err != nil {
pm.doClosePath(pa)
continue
}
// path now belongs to a different config
if newPathConf.Name != pa.confName {
// path config can be hot reloaded
oldPathConf := pm.pathConfs[pa.confName]
if pathConfCanBeUpdated(oldPathConf, newPathConf) {
pa.confName = newPathConf.Name
go pa.reloadConf(newPathConf)
continue
}
// Configuration cannot be hot reloaded: delete the path
pm.doClosePath(pa)
continue
}
// path configuration has changed and cannot be hot reloaded: delete path
if _, ok := confsToRecreate[newPathConf.Name]; ok {
pm.doClosePath(pa)
continue
}
// path configuration has changed but can be hot reloaded: reload it
if _, ok := confsToReload[newPathConf.Name]; ok {
go pa.reloadConf(newPathConf)
}
}
pm.pathConfs = newPaths
// create new static paths
for pathConfName, pathConf := range newPaths {
if pathConf.Regexp == nil {
if _, ok := pm.paths[pathConfName]; !ok {
pm.createPath(pathConf, pathConfName, nil)
}
}
}
}
func (pm *pathManager) doClosePath(pa *path) {
delete(pm.paths, pa.name)
pa.close()
pa.wait() // avoid conflicts between sources
}
func (pm *pathManager) doSetHLSServer(m *hls.Server) []defs.Path {
pm.hlsServer = m
var ret []defs.Path
for _, pa := range pm.paths {
if pa.ready {
ret = append(ret, pa)
}
}
return ret
}
func (pm *pathManager) doSetPathReady(pa *path) {
if pa2, ok := pm.paths[pa.name]; !ok || pa2 != pa {
return
}
pm.paths[pa.name].ready = true
if pm.hlsServer != nil {
pm.hlsServer.PathReady(pa)
}
}
func (pm *pathManager) doSetPathNotReady(pa *path) {
if pa2, ok := pm.paths[pa.name]; !ok || pa2 != pa {
return
}
pm.paths[pa.name].ready = false
if pm.hlsServer != nil {
pm.hlsServer.PathNotReady(pa)
}
}
func (pm *pathManager) doFindPathConf(req defs.PathFindPathConfReq) {
pathConf, _, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
if err != nil {
req.Res <- defs.PathFindPathConfRes{Err: err}
return
}
user, err2 := pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
if err2 != nil {
req.Res <- defs.PathFindPathConfRes{Err: err2}
return
}
req.Res <- defs.PathFindPathConfRes{
Conf: pathConf,
User: user,
}
}
func (pm *pathManager) doDescribe(req defs.PathDescribeReq) {
pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
if err != nil {
req.Res <- defs.PathDescribeRes{Err: err}
return
}
if !req.AccessRequest.SkipAuth {
_, err2 := pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
if err2 != nil {
req.Res <- defs.PathDescribeRes{Err: err2}
return
}
}
// create path if it doesn't exist
if _, ok := pm.paths[req.AccessRequest.Name]; !ok {
pm.createPath(pathConf, req.AccessRequest.Name, pathMatches)
}
pa := pm.paths[req.AccessRequest.Name]
pa.pendingRequests.Add(1)
req.Res <- defs.PathDescribeRes{Path: pa}
}
func (pm *pathManager) doAddReader(req defs.PathAddReaderReq) {
pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
if err != nil {
req.Res <- defs.PathAddReaderRes{Err: err}
return
}
var user string
if !req.AccessRequest.SkipAuth {
var authErr *auth.Error
user, authErr = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
if authErr != nil {
req.Res <- defs.PathAddReaderRes{Err: authErr}
return
}
}
// create path if it doesn't exist
if _, ok := pm.paths[req.AccessRequest.Name]; !ok {
pm.createPath(pathConf, req.AccessRequest.Name, pathMatches)
}
pa := pm.paths[req.AccessRequest.Name]
pa.pendingRequests.Add(1)
req.Res <- defs.PathAddReaderRes{
Path: pa,
User: user,
}
}
func (pm *pathManager) doAddPublisher(req defs.PathAddPublisherReq) {
pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
if err != nil {
req.Res <- defs.PathAddPublisherRes{Err: err}
return
}
if req.ConfToCompare != nil && !pathConf.Equal(req.ConfToCompare) {
req.Res <- defs.PathAddPublisherRes{Err: fmt.Errorf("configuration has changed")}
return
}
var user string
if !req.AccessRequest.SkipAuth {
var authErr *auth.Error
user, authErr = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
if authErr != nil {
req.Res <- defs.PathAddPublisherRes{Err: authErr}
return
}
}
// create path if it doesn't exist
if _, ok := pm.paths[req.AccessRequest.Name]; !ok {
pm.createPath(pathConf, req.AccessRequest.Name, pathMatches)
}
pa := pm.paths[req.AccessRequest.Name]
pa.pendingRequests.Add(1)
req.Res <- defs.PathAddPublisherRes{
Path: pa,
User: user,
}
}
func (pm *pathManager) doAPIPathsList(req pathAPIPathsListReq) {
paths := make(map[string]*path)
maps.Copy(paths, pm.paths)
req.res <- pathAPIPathsListRes{paths: paths}
}
func (pm *pathManager) doAPIPathsGet(req pathAPIPathsGetReq) {
pa, ok := pm.paths[req.name]
if !ok {
req.res <- pathAPIPathsGetRes{err: conf.ErrPathNotFound}
return
}
req.res <- pathAPIPathsGetRes{path: pa}
}
func (pm *pathManager) createPath(
pathConf *conf.Path,
name string,
matches []string,
) {
pa := &path{
parentCtx: pm.ctx,
logLevel: pm.logLevel,
dumpPackets: pm.dumpPackets,
rtspAddress: pm.rtspAddress,
readTimeout: pm.readTimeout,
writeTimeout: pm.writeTimeout,
writeQueueSize: pm.writeQueueSize,
udpReadBufferSize: pm.udpReadBufferSize,
rtpMaxPayloadSize: pm.rtpMaxPayloadSize,
conf: pathConf,
name: name,
matches: matches,
wg: &pm.wg,
externalCmdPool: pm.externalCmdPool,
parent: pm,
}
pa.initialize()
pm.paths[name] = pa
}
// ReloadPathConfs is called by core.
func (pm *pathManager) ReloadPathConfs(pathConfs map[string]*conf.Path) {
select {
case pm.chReloadConf <- pathConfs:
case <-pm.ctx.Done():
}
}
// setPathReady is called by path.
func (pm *pathManager) setPathReady(pa *path) {
select {
case pm.chSetPathReady <- pa:
case <-pm.ctx.Done():
case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait()
}
}
// setPathNotReady is called by path.
func (pm *pathManager) setPathNotReady(pa *path) {
select {
case pm.chSetPathNotReady <- pa:
case <-pm.ctx.Done():
case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait()
}
}
// removePath is called by path.
func (pm *pathManager) removePath(pa *path) {
select {
case pm.chRemovePath <- pa:
case <-pm.ctx.Done():
case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait()
}
}
// closePath is called by path.
func (pm *pathManager) closePathIfIdle(pa *path) {
select {
case pm.chClosePathIfIdle <- pa:
case <-pm.ctx.Done():
case <-pa.ctx.Done(): // in case pathManager is blocked by path.wait()
}
}
// FindPathConf is called by a reader or publisher.
func (pm *pathManager) FindPathConf(req defs.PathFindPathConfReq) (*defs.PathFindPathConfRes, error) {
req.Res = make(chan defs.PathFindPathConfRes)
select {
case pm.chFindPathConf <- req:
res := <-req.Res
if res.Err != nil {
auth.DelayBruteForce(res.Err)
return nil, res.Err
}
return &res, nil
case <-pm.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
// Describe is called by a reader or publisher.
func (pm *pathManager) Describe(req defs.PathDescribeReq) (*defs.PathDescribeRes, error) {
req.Res = make(chan defs.PathDescribeRes)
select {
case pm.chDescribe <- req:
res1 := <-req.Res
if res1.Err != nil {
auth.DelayBruteForce(res1.Err)
return nil, res1.Err
}
res2, err := res1.Path.(*path).describe(req)
if err != nil {
return nil, err
}
res2.Path = res1.Path
return res2, nil
case <-pm.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
// AddPublisher is called by a publisher.
func (pm *pathManager) AddPublisher(req defs.PathAddPublisherReq) (*defs.PathAddPublisherRes, error) {
req.Res = make(chan defs.PathAddPublisherRes)
select {
case pm.chAddPublisher <- req:
res1 := <-req.Res
if res1.Err != nil {
auth.DelayBruteForce(res1.Err)
return nil, res1.Err
}
res2, err := res1.Path.(*path).addPublisher(req)
if err != nil {
return nil, err
}
res2.Path = res1.Path
res2.User = res1.User
return res2, nil
case <-pm.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
// AddReader is called by a reader.
func (pm *pathManager) AddReader(req defs.PathAddReaderReq) (*defs.PathAddReaderRes, error) {
req.Res = make(chan defs.PathAddReaderRes)
select {
case pm.chAddReader <- req:
res1 := <-req.Res
if res1.Err != nil {
auth.DelayBruteForce(res1.Err)
return nil, res1.Err
}
res2, err := res1.Path.(*path).addReader(req)
if err != nil {
return nil, err
}
res2.Path = res1.Path
res2.User = res1.User
return res2, nil
case <-pm.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
// SetHLSServer is called by hls.Server.
func (pm *pathManager) SetHLSServer(s *hls.Server) []defs.Path {
req := pathSetHLSServerReq{
s: s,
res: make(chan pathSetHLSServerRes),
}
select {
case pm.chSetHLSServer <- req:
res := <-req.res
return res.readyPaths
case <-pm.ctx.Done():
return nil
}
}
// APIPathsList implements defs.APIPathManager.
func (pm *pathManager) APIPathsList() (*defs.APIPathList, error) {
req := pathAPIPathsListReq{
res: make(chan pathAPIPathsListRes),
}
select {
case pm.chAPIPathsList <- req:
res := <-req.res
res.data = &defs.APIPathList{
Items: []defs.APIPath{},
}
for _, pa := range res.paths {
item, err := pa.APIPathsGet(pathAPIPathsGetReq{})
if err == nil {
res.data.Items = append(res.data.Items, *item)
}
}
sort.Slice(res.data.Items, func(i, j int) bool {
return res.data.Items[i].Name < res.data.Items[j].Name
})
return res.data, nil
case <-pm.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
// APIPathsGet implements defs.APIPathManager.
func (pm *pathManager) APIPathsGet(name string) (*defs.APIPath, error) {
req := pathAPIPathsGetReq{
name: name,
res: make(chan pathAPIPathsGetRes),
}
select {
case pm.chAPIPathsGet <- req:
res := <-req.res
if res.err != nil {
return nil, res.err
}
data, err := res.path.APIPathsGet(req)
return data, err
case <-pm.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217package core
import (
"net/http"
"regexp"
"testing"
"time"
"github.com/bluenviron/gortsplib/v5"
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/pion/rtp"
"github.com/stretchr/testify/require"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/test"
)
type dummyPublisher struct{}
func (d *dummyPublisher) Close() {}
func (d *dummyPublisher) Log(_ logger.Level, _ string, _ ...any) {}
func (d *dummyPublisher) APISourceDescribe() *defs.APIPathSource {
return nil
}
type dummyReader struct{}
func (d *dummyReader) Close() {}
func (d *dummyReader) Log(_ logger.Level, _ string, _ ...any) {}
func (d *dummyReader) APIReaderDescribe() *defs.APIPathReader {
return nil
}
func TestPathManagerDynamicPathAutoDeletion(t *testing.T) {
for _, ca := range []string{"describe", "add reader"} {
t.Run(ca, func(t *testing.T) {
pathConfs := map[string]*conf.Path{
"all_others": {
Regexp: regexp.MustCompile("^.*$"),
Name: "all_others",
Source: "publisher",
},
}
pm := &pathManager{
authManager: test.NilAuthManager,
pathConfs: pathConfs,
parent: test.NilLogger,
}
pm.initialize()
defer pm.close()
func() {
if ca == "describe" {
_, err := pm.Describe(defs.PathDescribeReq{
AccessRequest: defs.PathAccessRequest{
Name: "mypath",
},
})
require.EqualError(t, err, "no stream is available on path 'mypath'")
} else {
_, err := pm.AddReader(defs.PathAddReaderReq{
Author: &dummyReader{},
AccessRequest: defs.PathAccessRequest{
Name: "mypath",
},
})
require.EqualError(t, err, "no stream is available on path 'mypath'")
}
}()
time.Sleep(100 * time.Millisecond)
data, err := pm.APIPathsList()
require.NoError(t, err)
require.Empty(t, data.Items)
})
}
}
func TestPathManagerDynamicPathDescribeAndPublish(t *testing.T) {
pathConfs := map[string]*conf.Path{
"all_others": {
Regexp: regexp.MustCompile("^.*$"),
Name: "all_others",
Source: "publisher",
},
}
pm := &pathManager{
authManager: test.NilAuthManager,
pathConfs: pathConfs,
parent: test.NilLogger,
}
pm.initialize()
defer pm.close()
go func() {
for range 10 {
pm.Describe(defs.PathDescribeReq{ //nolint:errcheck
AccessRequest: defs.PathAccessRequest{
Name: "mypath",
},
})
}
}()
_, err := pm.AddPublisher(defs.PathAddPublisherReq{
Author: &dummyPublisher{},
Desc: &description.Session{},
AccessRequest: defs.PathAccessRequest{
Name: "mypath",
},
})
require.NoError(t, err)
}
func TestPathManagerConfigHotReload(t *testing.T) {
// Start MediaMTX with basic configuration
p, ok := newInstance(t, "api: yes\n"+
"paths:\n"+
" all:\n"+
" record: no\n")
require.Equal(t, true, ok)
defer p.Close()
// Set up HTTP client for API calls
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
// Create a publisher that will use the "all" configuration
media0 := test.UniqueMediaH264()
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:8554/undefined_stream",
&description.Session{Medias: []*description.Media{media0}})
require.NoError(t, err)
defer source.Close()
// Send some data to establish the stream
err = source.WritePacketRTP(media0, &rtp.Packet{
Header: rtp.Header{
Version: 2,
PayloadType: 96,
},
Payload: []byte{5, 1, 2, 3, 4},
})
require.NoError(t, err)
time.Sleep(100 * time.Millisecond)
// Verify the path exists and is using the "all" configuration
pathData, err := p.pathManager.APIPathsGet("undefined_stream")
require.NoError(t, err)
require.Equal(t, "undefined_stream", pathData.Name)
require.Equal(t, "all", pathData.ConfName)
// Check the current configuration via API
var allConfig map[string]any
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/config/paths/get/all", nil, &allConfig)
require.Equal(t, false, allConfig["record"]) // Should be false from "all" config
// Add a new specific configuration for "undefined_stream" with record enabled
httpRequest(t, hc, http.MethodPost, "http://localhost:9997/v3/config/paths/add/undefined_stream",
map[string]any{
"record": true,
}, nil)
// Give the system time to process the configuration change
time.Sleep(200 * time.Millisecond)
// Verify the path now uses the new specific configuration
pathData, err = p.pathManager.APIPathsGet("undefined_stream")
require.NoError(t, err)
require.Equal(t, "undefined_stream", pathData.Name)
require.Equal(t, "undefined_stream", pathData.ConfName) // Should now use the specific config
// Check the new configuration via API
var newConfig map[string]any
httpRequest(t, hc, http.MethodGet, "http://localhost:9997/v3/config/paths/get/undefined_stream", nil, &newConfig)
require.Equal(t, true, newConfig["record"]) // Should be true from new config
// Verify the stream is still active and working
err = source.WritePacketRTP(media0, &rtp.Packet{
Header: rtp.Header{
Version: 2,
PayloadType: 96,
SequenceNumber: 2,
},
Payload: []byte{5, 1, 2, 3, 4},
})
require.NoError(t, err)
// Verify the path is still ready and functional
require.Equal(t, true, pathData.Ready)
// revert configuration
httpRequest(t, hc, http.MethodDelete, "http://localhost:9997/v3/config/paths/delete/undefined_stream",
nil, nil)
// Give the system time to process the configuration change
time.Sleep(200 * time.Millisecond)
// Verify the path now uses the old configuration
pathData, err = p.pathManager.APIPathsGet("undefined_stream")
require.NoError(t, err)
require.Equal(t, "undefined_stream", pathData.Name)
require.Equal(t, "all", pathData.ConfName)
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035package core
import (
"bufio"
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/bluenviron/gortmplib"
"github.com/bluenviron/gortsplib/v5"
"github.com/bluenviron/gortsplib/v5/pkg/base"
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/bluenviron/gortsplib/v5/pkg/headers"
"github.com/bluenviron/gortsplib/v5/pkg/sdp"
srt "github.com/datarhei/gosrt"
"github.com/pion/rtp"
"github.com/stretchr/testify/require"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/protocols/whip"
"github.com/bluenviron/mediamtx/internal/test"
)
type testServer struct {
onDescribe func(*gortsplib.ServerHandlerOnDescribeCtx) (*base.Response, *gortsplib.ServerStream, error)
onSetup func(*gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error)
onPlay func(*gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error)
}
func (sh *testServer) OnDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx,
) (*base.Response, *gortsplib.ServerStream, error) {
return sh.onDescribe(ctx)
}
func (sh *testServer) OnSetup(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
return sh.onSetup(ctx)
}
func (sh *testServer) OnPlay(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
return sh.onPlay(ctx)
}
var _ defs.Path = &path{}
func TestPathRunOnDemand(t *testing.T) {
for _, ca := range []string{"describe", "setup", "describe and setup"} {
t.Run(ca, func(t *testing.T) {
onDemand := filepath.Join(t.TempDir(), "on_demand")
onUnDemand := filepath.Join(t.TempDir(), "on_undemand")
p1, ok := newInstance(t, fmt.Sprintf("rtmp: no\n"+
"hls: no\n"+
"webrtc: no\n"+
"paths:\n"+
" '~^(on)demand$':\n"+
" runOnDemand: sh -c \"ON_DEMAND=%s go run ./test_on_demand/main.go\"\n"+
" runOnDemandCloseAfter: 1s\n"+
" runOnUnDemand: touch %s\n", onDemand, onUnDemand))
require.Equal(t, true, ok)
defer p1.Close()
var control string
func() {
conn, err := net.Dial("tcp", "localhost:8554")
require.NoError(t, err)
defer conn.Close()
br := bufio.NewReader(conn)
if ca == "describe" || ca == "describe and setup" {
var u *base.URL
u, err = base.ParseURL("rtsp://localhost:8554/ondemand?key1=val1&key2=val2")
require.NoError(t, err)
byts, _ := base.Request{
Method: base.Describe,
URL: u,
Header: base.Header{
"CSeq": base.HeaderValue{"1"},
},
}.Marshal()
_, err = conn.Write(byts)
require.NoError(t, err)
var res base.Response
err = res.Unmarshal(br)
require.NoError(t, err)
require.Equal(t, base.StatusOK, res.StatusCode)
var desc sdp.SessionDescription
err = desc.Unmarshal(res.Body)
require.NoError(t, err)
control, _ = desc.MediaDescriptions[0].Attribute("control")
control = "rtsp://localhost:8554/ondemand?key1=val1&key2=val2/" + control
} else {
control = "rtsp://localhost:8554/ondemand?key1=val1&key2=val2/"
}
if ca == "setup" || ca == "describe and setup" {
var u *base.URL
u, err = base.ParseURL(control)
require.NoError(t, err)
byts, _ := base.Request{
Method: base.Setup,
URL: u,
Header: base.Header{
"CSeq": base.HeaderValue{"2"},
"Transport": headers.Transport{
Mode: func() *headers.TransportMode {
v := headers.TransportModePlay
return &v
}(),
Protocol: headers.TransportProtocolTCP,
InterleavedIDs: &[2]int{0, 1},
}.Marshal(),
},
}.Marshal()
_, err = conn.Write(byts)
require.NoError(t, err)
var res base.Response
err = res.Unmarshal(br)
require.NoError(t, err)
require.Equal(t, base.StatusOK, res.StatusCode)
}
}()
for {
_, err := os.Stat(onUnDemand)
if err == nil {
break
}
time.Sleep(100 * time.Millisecond)
}
_, err := os.Stat(onDemand)
require.NoError(t, err)
})
}
}
func TestPathRunOnConnect(t *testing.T) {
serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
for _, ca := range []string{"rtsp", "rtsps", "rtmp", "rtmps", "srt"} {
t.Run(ca, func(t *testing.T) {
onConnect := filepath.Join(t.TempDir(), "on_connect")
onDisconnect := filepath.Join(t.TempDir(), "on_disconnect")
connType := ""
func() {
p, ok := newInstance(t, fmt.Sprintf(
"rtspEncryption: optional\n"+
"rtspServerCert: "+serverCertFpath+"\n"+
"rtspServerKey: "+serverKeyFpath+"\n"+
"rtmpEncryption: optional\n"+
"rtmpServerCert: "+serverCertFpath+"\n"+
"rtmpServerKey: "+serverKeyFpath+"\n"+
"paths:\n"+
" test:\n"+
"runOnConnect: sh -c 'echo \"$MTX_CONN_TYPE $MTX_CONN_ID $RTSP_PORT\" > %s'\n"+
"runOnDisconnect: sh -c 'echo \"$MTX_CONN_TYPE $MTX_CONN_ID $RTSP_PORT\" > %s'\n",
onConnect, onDisconnect))
require.Equal(t, true, ok)
defer p.Close()
switch ca {
case "rtsp":
connType = "rtspConn"
c := gortsplib.Client{}
err := c.StartRecording(
"rtsp://localhost:8554/test",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer c.Close()
case "rtsps":
connType = "rtspsConn"
c := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}}
err := c.StartRecording(
"rtsps://localhost:8322/test",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer c.Close()
case "rtmp":
connType = "rtmpConn"
var u *url.URL
u, err := url.Parse("rtmp://127.0.0.1:1935/test")
require.NoError(t, err)
conn := &gortmplib.Client{
URL: u,
Publish: true,
}
err = conn.Initialize(context.Background())
require.NoError(t, err)
defer conn.Close()
case "rtmps":
connType = "rtmpsConn"
var u *url.URL
u, err := url.Parse("rtmps://127.0.0.1:1936/test")
require.NoError(t, err)
conn := &gortmplib.Client{
URL: u,
Publish: true,
TLSConfig: &tls.Config{InsecureSkipVerify: true},
}
err = conn.Initialize(context.Background())
require.NoError(t, err)
defer conn.Close()
case "srt":
connType = "srtConn"
conf := srt.DefaultConfig()
var address string
address, err := conf.UnmarshalURL("srt://localhost:8890?streamid=publish:test")
require.NoError(t, err)
err = conf.Validate()
require.NoError(t, err)
var c srt.Conn
c, err = srt.Dial("srt", address, conf)
require.NoError(t, err)
defer c.Close()
}
time.Sleep(500 * time.Millisecond)
}()
var byts []byte
byts, err := os.ReadFile(onConnect)
require.NoError(t, err)
fields := strings.Split(string(byts[:len(byts)-1]), " ")
require.Equal(t, connType, fields[0])
require.NotEmpty(t, fields[1])
require.Equal(t, "8554", fields[2])
byts, err = os.ReadFile(onDisconnect)
require.NoError(t, err)
fields = strings.Split(string(byts[:len(byts)-1]), " ")
require.Equal(t, connType, fields[0])
require.NotEmpty(t, fields[1])
require.Equal(t, "8554", fields[2])
})
}
}
func TestPathRunOnReady(t *testing.T) {
onReady := filepath.Join(t.TempDir(), "on_ready")
onNotReady := filepath.Join(t.TempDir(), "on_unready")
func() {
p, ok := newInstance(t, fmt.Sprintf("rtmp: no\n"+
"hls: no\n"+
"webrtc: no\n"+
"paths:\n"+
" ~te(st):\n"+
" runOnReady: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_SOURCE_TYPE $MTX_SOURCE_ID $RTSP_PORT $G1\" > %s'\n"+
" runOnNotReady: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_SOURCE_TYPE $MTX_SOURCE_ID $RTSP_PORT $G1\" > %s'\n",
onReady, onNotReady))
require.Equal(t, true, ok)
defer p.Close()
c := gortsplib.Client{}
err := c.StartRecording(
"rtsp://localhost:8554/test?query=value",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer c.Close()
time.Sleep(500 * time.Millisecond)
}()
byts, err := os.ReadFile(onReady)
require.NoError(t, err)
fields := strings.Split(string(byts[:len(byts)-1]), " ")
require.Equal(t, "test", fields[0])
require.Equal(t, "query%3Dvalue", fields[1])
require.Equal(t, "rtspSession", fields[2])
require.NotEmpty(t, fields[3])
require.Equal(t, "8554", fields[4])
require.Equal(t, "st", fields[5])
byts, err = os.ReadFile(onNotReady)
require.NoError(t, err)
fields = strings.Split(string(byts[:len(byts)-1]), " ")
require.Equal(t, "test", fields[0])
require.Equal(t, "query%3Dvalue", fields[1])
require.Equal(t, "rtspSession", fields[2])
require.NotEmpty(t, fields[3])
require.Equal(t, "8554", fields[4])
require.Equal(t, "st", fields[5])
}
func TestPathRunOnReadyQueryInjection(t *testing.T) {
sentinel := filepath.Join(t.TempDir(), "mediamtx_test_query_injection_sentinel")
for _, ca := range []struct {
name string
cmdstr string
query string
}{
{
// $(…) inside double quotes still triggers command substitution.
// ${IFS} expands to a space, avoiding a literal space in the query string.
name: "command substitution dollar",
cmdstr: "sh -c 'echo \"$MTX_QUERY\"'",
query: "$(touch${IFS}" + sentinel + "1)",
},
{
// > in an unquoted expansion redirects echo's output, creating the file.
name: "redirect",
cmdstr: "sh -c 'echo $MTX_QUERY'",
query: ">" + sentinel + "2",
},
{
// & in an unquoted expansion backgrounds echo and runs touch directly.
// ${IFS} expands to a space, avoiding a literal space in the query string.
name: "and operator",
cmdstr: "sh -c 'echo $MTX_QUERY'",
query: "&touch${IFS}" + sentinel + "3",
},
} {
t.Run(ca.name, func(t *testing.T) {
p, ok := newInstance(t, fmt.Sprintf(
"rtmp: no\nhls: no\nwebrtc: no\npaths:\n test:\n runOnReady: %s\n",
ca.cmdstr))
require.Equal(t, true, ok)
defer p.Close()
c := gortsplib.Client{}
err := c.StartRecording(
"rtsp://localhost:8554/test?"+ca.query,
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer c.Close()
time.Sleep(500 * time.Millisecond)
_, statErr := os.Stat(sentinel)
require.ErrorIs(t, statErr, os.ErrNotExist)
})
}
}
func TestPathRunOnRead(t *testing.T) {
serverCertFpath := test.CreateTempFile(t, test.TLSCertPub)
serverKeyFpath := test.CreateTempFile(t, test.TLSCertKey)
for _, ca := range []string{"rtsp", "rtsps", "rtmp", "rtmps", "srt", "webrtc"} {
t.Run(ca, func(t *testing.T) {
onRead := filepath.Join(t.TempDir(), "on_read")
onUnread := filepath.Join(t.TempDir(), "on_unread")
func() {
p, ok := newInstance(t, fmt.Sprintf(
"rtspEncryption: optional\n"+
"rtspServerCert: "+serverCertFpath+"\n"+
"rtspServerKey: "+serverKeyFpath+"\n"+
"rtmpEncryption: optional\n"+
"rtmpServerCert: "+serverCertFpath+"\n"+
"rtmpServerKey: "+serverKeyFpath+"\n"+
"paths:\n"+
" ~te(st):\n"+
" runOnRead: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_READER_TYPE $MTX_READER_ID $RTSP_PORT $G1\" > %s'\n"+
" runOnUnread: sh -c 'echo \"$MTX_PATH $MTX_QUERY $MTX_READER_TYPE $MTX_READER_ID $RTSP_PORT $G1\" > %s'\n",
onRead, onUnread))
require.Equal(t, true, ok)
defer p.Close()
media0 := test.UniqueMediaH264()
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:8554/test",
&description.Session{Medias: []*description.Media{media0}})
require.NoError(t, err)
defer source.Close()
writerDone := make(chan struct{})
defer func() { <-writerDone }()
writerTerminate := make(chan struct{})
defer close(writerTerminate)
go func() {
defer close(writerDone)
i := 0
for {
select {
case <-time.After(100 * time.Millisecond):
case <-writerTerminate:
return
}
err2 := source.WritePacketRTP(media0, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: uint16(123 + i),
Timestamp: uint32(45343 + i*90000),
SSRC: 563423,
},
Payload: []byte{5},
})
require.NoError(t, err2)
i++
}
}()
switch ca {
case "rtsp":
var u *base.URL
u, err = base.ParseURL("rtsp://127.0.0.1:8554/test?query=value")
require.NoError(t, err)
reader := gortsplib.Client{
Scheme: u.Scheme,
Host: u.Host,
}
err = reader.Start()
require.NoError(t, err)
defer reader.Close()
var desc *description.Session
desc, _, err = reader.Describe(u)
require.NoError(t, err)
err = reader.SetupAll(desc.BaseURL, desc.Medias)
require.NoError(t, err)
_, err = reader.Play(nil)
require.NoError(t, err)
case "rtsps":
var u *base.URL
u, err = base.ParseURL("rtsps://127.0.0.1:8322/test?query=value")
require.NoError(t, err)
reader := gortsplib.Client{
Scheme: u.Scheme,
Host: u.Host,
TLSConfig: &tls.Config{InsecureSkipVerify: true},
}
err = reader.Start()
require.NoError(t, err)
defer reader.Close()
var desc *description.Session
desc, _, err = reader.Describe(u)
require.NoError(t, err)
err = reader.SetupAll(desc.BaseURL, desc.Medias)
require.NoError(t, err)
_, err = reader.Play(nil)
require.NoError(t, err)
case "rtmp":
var u *url.URL
u, err = url.Parse("rtmp://127.0.0.1:1935/test?query=value")
require.NoError(t, err)
conn := &gortmplib.Client{
URL: u,
Publish: false,
}
err = conn.Initialize(context.Background())
require.NoError(t, err)
defer conn.Close()
r := &gortmplib.Reader{
Conn: conn,
}
err = r.Initialize()
require.NoError(t, err)
case "rtmps":
var u *url.URL
u, err = url.Parse("rtmps://127.0.0.1:1936/test?query=value")
require.NoError(t, err)
conn := &gortmplib.Client{
URL: u,
Publish: false,
TLSConfig: &tls.Config{InsecureSkipVerify: true},
}
err = conn.Initialize(context.Background())
require.NoError(t, err)
defer conn.Close()
go func() {
for i := range uint16(3) {
err2 := source.WritePacketRTP(media0, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 123 + i,
Timestamp: 45343 + uint32(i)*2*90000,
SSRC: 563423,
},
Payload: []byte{5},
})
require.NoError(t, err2)
}
}()
r := &gortmplib.Reader{
Conn: conn,
}
err = r.Initialize()
require.NoError(t, err)
case "srt":
conf := srt.DefaultConfig()
var address string
address, err = conf.UnmarshalURL("srt://localhost:8890?streamid=read:test:query=value")
require.NoError(t, err)
err = conf.Validate()
require.NoError(t, err)
var reader srt.Conn
reader, err = srt.Dial("srt", address, conf)
require.NoError(t, err)
defer reader.Close()
case "webrtc":
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var u *url.URL
u, err = url.Parse("http://localhost:8889/test/whep?query=value")
require.NoError(t, err)
c := &whip.Client{
HTTPClient: hc,
URL: u,
Log: test.NilLogger,
}
err = c.Initialize(context.Background())
require.NoError(t, err)
defer checkClose(t, c.Close)
}
time.Sleep(500 * time.Millisecond)
}()
var readerType string
switch ca {
case "rtsp":
readerType = "rtspSession"
case "rtsps":
readerType = "rtspsSession"
case "rtmp":
readerType = "rtmpConn"
case "rtmps":
readerType = "rtmpsConn"
case "srt":
readerType = "srtConn"
case "webrtc":
readerType = "webRTCSession"
}
var byts []byte
byts, err := os.ReadFile(onRead)
require.NoError(t, err)
fields := strings.Split(string(byts[:len(byts)-1]), " ")
require.Equal(t, "test", fields[0])
require.Equal(t, "query%3Dvalue", fields[1])
require.Equal(t, readerType, fields[2])
require.NotEmpty(t, fields[3])
require.Equal(t, "8554", fields[4])
require.Equal(t, "st", fields[5])
byts, err = os.ReadFile(onUnread)
require.NoError(t, err)
fields = strings.Split(string(byts[:len(byts)-1]), " ")
require.Equal(t, "test", fields[0])
require.Equal(t, "query%3Dvalue", fields[1])
require.Equal(t, readerType, fields[2])
require.NotEmpty(t, fields[3])
require.Equal(t, "8554", fields[4])
require.Equal(t, "st", fields[5])
})
}
}
func TestPathRunOnRecordSegment(t *testing.T) {
onRecordSegmentCreate := filepath.Join(t.TempDir(), "on_record_segment_create")
onRecordSegmentComplete := filepath.Join(t.TempDir(), "on_record_segment_complete")
recordDir := t.TempDir()
var err error
func() {
p, ok := newInstance(t, fmt.Sprintf("record: yes\n"+
"recordPath: %s\n"+
"paths:\n"+
" test:\n"+
" runOnRecordSegmentCreate: sh -c 'echo \"$MTX_SEGMENT_PATH $RTSP_PORT\" > %s'\n"+
" runOnRecordSegmentComplete: sh -c 'echo \"$MTX_SEGMENT_PATH $MTX_SEGMENT_DURATION $RTSP_PORT\" > %s'\n",
filepath.Join(recordDir, "%path/%Y-%m-%d_%H-%M-%S-%f"),
onRecordSegmentCreate,
onRecordSegmentComplete,
))
require.Equal(t, true, ok)
defer p.Close()
media0 := test.UniqueMediaH264()
source := gortsplib.Client{}
err = source.StartRecording(
"rtsp://localhost:8554/test",
&description.Session{Medias: []*description.Media{media0}})
require.NoError(t, err)
defer source.Close()
for i := range 4 {
err = source.WritePacketRTP(media0, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 1123 + uint16(i),
Timestamp: 45343 + 90000*uint32(i),
SSRC: 563423,
},
Payload: []byte{5},
})
require.NoError(t, err)
}
time.Sleep(500 * time.Millisecond)
}()
byts, err := os.ReadFile(onRecordSegmentCreate)
require.NoError(t, err)
fields := strings.Split(string(byts[:len(byts)-1]), " ")
require.True(t, strings.HasPrefix(fields[0], recordDir))
require.Equal(t, "8554", fields[1])
byts, err = os.ReadFile(onRecordSegmentComplete)
require.NoError(t, err)
fields = strings.Split(string(byts[:len(byts)-1]), " ")
require.True(t, strings.HasPrefix(fields[0], recordDir))
require.Equal(t, "3", fields[1])
require.Equal(t, "8554", fields[2])
}
func TestPathMaxReaders(t *testing.T) {
p, ok := newInstance(t, "paths:\n"+
" all_others:\n"+
" maxReaders: 1\n")
require.Equal(t, true, ok)
defer p.Close()
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:8554/mystream",
&description.Session{Medias: []*description.Media{
test.UniqueMediaH264(),
test.UniqueMediaMPEG4Audio(),
}})
require.NoError(t, err)
defer source.Close()
for i := range 2 {
var u *base.URL
u, err = base.ParseURL("rtsp://127.0.0.1:8554/mystream")
require.NoError(t, err)
reader := gortsplib.Client{
Scheme: u.Scheme,
Host: u.Host,
}
err = reader.Start()
require.NoError(t, err)
defer reader.Close()
var desc *description.Session
desc, _, err = reader.Describe(u)
require.NoError(t, err)
err = reader.SetupAll(desc.BaseURL, desc.Medias)
if i != 1 {
require.NoError(t, err)
} else {
require.Error(t, err)
}
}
}
func TestPathRecord(t *testing.T) {
dir := t.TempDir()
p, ok := newInstance(t, "api: yes\n"+
"record: yes\n"+
"recordPath: "+filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f")+"\n"+
"paths:\n"+
" all_others:\n"+
" record: yes\n")
require.Equal(t, true, ok)
defer p.Close()
media0 := test.UniqueMediaH264()
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:8554/mystream",
&description.Session{Medias: []*description.Media{media0}})
require.NoError(t, err)
defer source.Close()
for i := range 4 {
err = source.WritePacketRTP(media0, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 1123 + uint16(i),
Timestamp: 45343 + 90000*uint32(i),
SSRC: 563423,
},
Payload: []byte{5},
})
require.NoError(t, err)
}
time.Sleep(500 * time.Millisecond)
files, err := os.ReadDir(filepath.Join(dir, "mystream"))
require.NoError(t, err)
require.Equal(t, 1, len(files))
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/paths/patch/all_others", map[string]any{
"record": false,
}, nil)
time.Sleep(500 * time.Millisecond)
httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/paths/patch/all_others", map[string]any{
"record": true,
}, nil)
time.Sleep(500 * time.Millisecond)
for i := 4; i < 8; i++ {
err = source.WritePacketRTP(media0, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 1123 + uint16(i),
Timestamp: 45343 + 90000*uint32(i),
SSRC: 563423,
},
Payload: []byte{5},
})
require.NoError(t, err)
}
time.Sleep(500 * time.Millisecond)
files, err = os.ReadDir(filepath.Join(dir, "mystream"))
require.NoError(t, err)
require.Equal(t, 2, len(files))
}
func TestPathFallback(t *testing.T) {
for _, ca := range []string{
"absolute",
"relative",
"source",
} {
t.Run(ca, func(t *testing.T) {
var cnf string
switch ca {
case "absolute":
cnf = "paths:\n" +
" path1:\n" +
" fallback: rtsp://localhost:8554/path2\n" +
" path2:\n"
case "relative":
cnf = "paths:\n" +
" path1:\n" +
" fallback: /path2\n" +
" path2:\n"
case "source":
cnf = "paths:\n" +
" path1:\n" +
" fallback: /path2\n" +
" source: rtsp://localhost:3333/nonexistent\n" +
" path2:\n"
}
p1, ok := newInstance(t, cnf)
require.Equal(t, true, ok)
defer p1.Close()
source := gortsplib.Client{}
err := source.StartRecording("rtsp://localhost:8554/path2",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer source.Close()
u, err := base.ParseURL("rtsp://localhost:8554/path1")
require.NoError(t, err)
dest := gortsplib.Client{
Scheme: u.Scheme,
Host: u.Host,
}
err = dest.Start()
require.NoError(t, err)
defer dest.Close()
desc, _, err := dest.Describe(u)
require.NoError(t, err)
require.Equal(t, 1, len(desc.Medias))
})
}
}
func TestPathResolveSource(t *testing.T) {
var strm *gortsplib.ServerStream
s := gortsplib.Server{
Handler: &testServer{
onDescribe: func(ctx *gortsplib.ServerHandlerOnDescribeCtx,
) (*base.Response, *gortsplib.ServerStream, error) {
require.Equal(t, "key=val", ctx.Query)
require.Equal(t, "/a", ctx.Path)
return &base.Response{
StatusCode: base.StatusOK,
}, strm, nil
},
onSetup: func(_ *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
return &base.Response{
StatusCode: base.StatusOK,
}, strm, nil
},
onPlay: func(_ *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
return &base.Response{
StatusCode: base.StatusOK,
}, nil
},
},
RTSPAddress: "127.0.0.1:8555",
}
err := s.Start()
require.NoError(t, err)
defer s.Close()
strm = &gortsplib.ServerStream{
Server: &s,
Desc: &description.Session{Medias: []*description.Media{test.MediaH264}},
}
err = strm.Initialize()
require.NoError(t, err)
defer strm.Close()
p, ok := newInstance(t,
"paths:\n"+
" '~^test_(.+)$':\n"+
" source: rtsp://127.0.0.1:8555/$G1?$MTX_QUERY\n"+
" sourceOnDemand: yes\n"+
" 'all':\n")
require.Equal(t, true, ok)
defer p.Close()
u, err := base.ParseURL("rtsp://127.0.0.1:8554/test_a?key=val")
require.NoError(t, err)
reader := gortsplib.Client{
Scheme: u.Scheme,
Host: u.Host,
}
err = reader.Start()
require.NoError(t, err)
defer reader.Close()
_, _, err = reader.Describe(u)
require.NoError(t, err)
}
func TestPathOverridePublisher(t *testing.T) {
for _, ca := range []string{
"enabled",
"disabled",
} {
t.Run(ca, func(t *testing.T) {
cnf := "rtmp: no\n" +
"paths:\n" +
" all_others:\n"
if ca == "disabled" {
cnf += " overridePublisher: no\n"
}
p, ok := newInstance(t, cnf)
require.Equal(t, true, ok)
defer p.Close()
medi := test.UniqueMediaH264()
s1 := gortsplib.Client{}
err := s1.StartRecording("rtsp://localhost:8554/teststream",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer s1.Close()
s2 := gortsplib.Client{}
err = s2.StartRecording("rtsp://localhost:8554/teststream",
&description.Session{Medias: []*description.Media{medi}})
if ca == "enabled" {
require.NoError(t, err)
defer s2.Close()
} else {
require.Error(t, err)
}
frameRecv := make(chan struct{})
u, err := base.ParseURL("rtsp://localhost:8554/teststream")
require.NoError(t, err)
c := gortsplib.Client{
Scheme: u.Scheme,
Host: u.Host,
}
err = c.Start()
require.NoError(t, err)
defer c.Close()
desc, _, err := c.Describe(u)
require.NoError(t, err)
err = c.SetupAll(desc.BaseURL, desc.Medias)
require.NoError(t, err)
c.OnPacketRTP(desc.Medias[0], desc.Medias[0].Formats[0], func(pkt *rtp.Packet) {
if ca == "enabled" {
require.Equal(t, []byte{5, 15, 16, 17, 18}, pkt.Payload)
} else {
require.Equal(t, []byte{5, 11, 12, 13, 14}, pkt.Payload)
}
close(frameRecv)
})
_, err = c.Play(nil)
require.NoError(t, err)
if ca == "enabled" {
err = s1.Wait()
require.EqualError(t, err, "EOF")
err = s2.WritePacketRTP(medi, &rtp.Packet{
Header: rtp.Header{
Version: 0x02,
PayloadType: 96,
SequenceNumber: 57899,
Timestamp: 345234345,
SSRC: 978651231,
Marker: true,
},
Payload: []byte{5, 15, 16, 17, 18},
})
require.NoError(t, err)
} else {
err = s1.WritePacketRTP(medi, &rtp.Packet{
Header: rtp.Header{
Version: 0x02,
PayloadType: 96,
SequenceNumber: 57899,
Timestamp: 345234345,
SSRC: 978651231,
Marker: true,
},
Payload: []byte{5, 11, 12, 13, 14},
})
require.NoError(t, err)
}
<-frameRecv
})
}
}1234567891011121314151617181920package core
import (
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/logger"
)
// sourceRedirect is a source that redirects to another one.
type sourceRedirect struct{}
func (*sourceRedirect) Log(logger.Level, string, ...any) {
}
// APISourceDescribe implements source.
func (*sourceRedirect) APISourceDescribe() *defs.APIPathSource {
return &defs.APIPathSource{
Type: defs.APIPathSourceTypeRedirect,
ID: "",
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354// This is used for testing purposes.
package main
import (
"os"
"os/signal"
"syscall"
"github.com/bluenviron/gortsplib/v5"
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/bluenviron/gortsplib/v5/pkg/format"
)
func main() {
if os.Getenv("MTX_QUERY") != "key1%3Dval1%26key2%3Dval2" {
panic("unexpected MTX_QUERY: " + os.Getenv("MTX_QUERY"))
}
if os.Getenv("G1") != "on" {
panic("unexpected G1: " + os.Getenv("G1"))
}
medi := &description.Media{
Type: description.MediaTypeVideo,
Formats: []format.Format{&format.H264{
PayloadTyp: 96,
SPS: []byte{
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02,
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, 0x20,
},
PPS: []byte{0x01, 0x02, 0x03, 0x04},
PacketizationMode: 1,
}},
}
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:"+os.Getenv("RTSP_PORT")+"/"+os.Getenv("MTX_PATH"),
&description.Session{Medias: []*description.Media{medi}})
if err != nil {
panic(err)
}
defer source.Close()
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT)
<-c
err = os.WriteFile(os.Getenv("ON_DEMAND"), []byte(""), 0o644)
if err != nil {
panic(err)
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143// Package main contains an utility to get the server version
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/go-git/go-billy/v5/osfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/cache"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/storage/filesystem"
)
// Golang version of git describe --tags
func gitDescribeTags(repo *git.Repository) (string, error) {
head, err := repo.Head()
if err != nil {
return "", fmt.Errorf("failed to get HEAD: %w", err)
}
tagIterator, err := repo.Tags()
if err != nil {
return "", fmt.Errorf("failed to get tags: %w", err)
}
defer tagIterator.Close()
tags := make(map[plumbing.Hash]*plumbing.Reference)
err = tagIterator.ForEach(func(t *plumbing.Reference) error {
if to, err2 := repo.TagObject(t.Hash()); err2 == nil {
tags[to.Target] = t
} else {
tags[t.Hash()] = t
}
return nil
})
if err != nil {
return "", fmt.Errorf("failed to iterate tags: %w", err)
}
cIter, err := repo.Log(&git.LogOptions{From: head.Hash()})
if err != nil {
return "", fmt.Errorf("failed to get log: %w", err)
}
i := 0
for {
var commit *object.Commit
commit, err = cIter.Next()
if err != nil {
return "", fmt.Errorf("failed to get next commit: %w", err)
}
if str, ok := tags[commit.Hash]; ok {
label := strings.TrimPrefix(string(str.Name()), "refs/tags/")
if i != 0 {
label += "-" + strconv.FormatInt(int64(i), 10) + "-" + head.Hash().String()[:8]
}
return label, nil
}
i++
}
}
func tagFromGit() error {
// [git.PlainOpen] uses a ChrootOS that limits filesystem access to the .git directory only.
//
// Unfortunately, this can cause issues with package build environments such as Arch Linux's,
// where .git/objects/info/alternates points to a directory outside of the .git directory.
//
// To work around this, specify an AlternatesFS that allows access to the entire filesystem.
dotGitAbs, _ := filepath.Abs("../../.git")
storerFs := osfs.New(dotGitAbs, osfs.WithBoundOS())
storer := filesystem.NewStorageWithOptions(storerFs, cache.NewObjectLRUDefault(), filesystem.Options{
AlternatesFS: osfs.New("/", osfs.WithBoundOS()),
})
workTreeAbs, _ := filepath.Abs("../../")
worktreeFs := osfs.New(workTreeAbs, osfs.WithBoundOS())
repo, err := git.Open(storer, worktreeFs)
if err != nil {
return fmt.Errorf("failed to open repository: %w", err)
}
version, err := gitDescribeTags(repo)
if err != nil {
return fmt.Errorf("failed to get version: %w", err)
}
wt, err := repo.Worktree()
if err != nil {
return fmt.Errorf("failed to get worktree: %w", err)
}
status, err := wt.Status()
if err != nil {
return fmt.Errorf("failed to get status: %w", err)
}
if !status.IsClean() {
version += "-dirty"
}
err = os.WriteFile("VERSION", []byte(version), 0o644)
if err != nil {
return fmt.Errorf("failed to write version file: %w", err)
}
log.Printf("ok (%s)", version)
return nil
}
func do() error {
log.Println("getting mediamtx version...")
err := tagFromGit()
if err != nil {
log.Println("WARN: cannot get tag from .git folder, using v0.0.0 as version")
err = os.WriteFile("VERSION", []byte("v0.0.0"), 0o644)
if err != nil {
return fmt.Errorf("failed to write version file: %w", err)
}
}
return nil
}
func main() {
err := do()
if err != nil {
log.Printf("ERR: %v", err)
os.Exit(1)
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384// Package counterdumper contains a counter that that periodically invokes a callback if the counter is not zero.
package counterdumper
import (
"sync"
"time"
)
const (
callbackPeriod = 1 * time.Second
)
// Dumper is a counter that periodically invokes a callback if the counter is not zero.
type Dumper struct {
OnReport func(v uint64)
mutex sync.Mutex
counter uint64
absCounter uint64
terminate chan struct{}
done chan struct{}
}
// Start starts the counter.
func (c *Dumper) Start() {
c.terminate = make(chan struct{})
c.done = make(chan struct{})
go c.run()
}
// Stop stops the counter.
func (c *Dumper) Stop() {
close(c.terminate)
<-c.done
}
// Increase increases the counter value by 1.
func (c *Dumper) Increase() {
c.mutex.Lock()
defer c.mutex.Unlock()
c.counter++
c.absCounter++
}
// Add adds value to the counter.
func (c *Dumper) Add(v uint64) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.counter += v
c.absCounter += v
}
// Get returns the counter value.
func (c *Dumper) Get() uint64 {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.absCounter
}
func (c *Dumper) run() {
defer close(c.done)
t := time.NewTicker(callbackPeriod)
defer t.Stop()
for {
select {
case <-c.terminate:
return
case <-t.C:
c.mutex.Lock()
var v uint64
v, c.counter = c.counter, 0
c.mutex.Unlock()
if v != 0 {
c.OnReport(v)
}
}
}
}123456789101112131415161718192021222324252627282930313233343536373839404142package counterdumper
import (
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestDumperReport(t *testing.T) {
done := make(chan struct{})
c := &Dumper{
OnReport: func(v uint64) {
require.Equal(t, uint64(3), v)
close(done)
},
}
c.Start()
defer c.Stop()
c.Add(2)
c.Increase()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Errorf("should not happen")
}
}
func TestDumperDoNotReport(t *testing.T) {
c := &Dumper{
OnReport: func(_ uint64) {
t.Errorf("should not happen")
},
}
c.Start()
defer c.Stop()
<-time.After(2 * time.Second)
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647package defs
import (
"time"
"github.com/bluenviron/mediamtx/internal/conf"
)
// APIOKStatus is the status of a successful response.
type APIOKStatus string
// statuses.
const (
APIOKStatusOK APIOKStatus = "ok"
)
// APIErrorStatus is the status of an error response.
type APIErrorStatus string
// statuses.
const (
APIErrorStatusError APIErrorStatus = "error"
)
// APIOK is returned on success.
type APIOK struct {
Status APIOKStatus `json:"status"`
}
// APIError is a generic error.
type APIError struct {
Status APIErrorStatus `json:"status"`
Error string `json:"error"`
}
// APIInfo is a info response.
type APIInfo struct {
Version string `json:"version"`
Started time.Time `json:"started"`
}
// APIPathConfList is a list of path configurations.
type APIPathConfList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []conf.Path `json:"items"`
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354package defs
import (
"time"
"github.com/google/uuid"
)
// APIHLSServer contains methods used by the API and Metrics server.
type APIHLSServer interface {
APISessionsList() (*APIHLSSessionList, error)
APISessionsGet(uuid.UUID) (*APIHLSSession, error)
APISessionsKick(uuid.UUID) error
APIMuxersList() (*APIHLSMuxerList, error)
APIMuxersGet(string) (*APIHLSMuxer, error)
}
// APIHLSSessionList is a list of HLS sessions.
type APIHLSSessionList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []APIHLSSession `json:"items"`
}
// APIHLSSession is an HLS session.
type APIHLSSession struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
Path string `json:"path"`
Query string `json:"query"`
User string `json:"user"`
UserAgent string `json:"userAgent"`
IsCDN bool `json:"isCDN"`
OutboundBytes uint64 `json:"outboundBytes"`
}
// APIHLSMuxerList is a list of HLS muxers.
type APIHLSMuxerList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []APIHLSMuxer `json:"items"`
}
// APIHLSMuxer is an HLS muxer.
type APIHLSMuxer struct {
Path string `json:"path"`
Created time.Time `json:"created"`
LastRequest time.Time `json:"lastRequest"`
OutboundBytes uint64 `json:"outboundBytes"`
OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"`
// deprecated
BytesSent uint64 `json:"bytesSent" deprecated:"true"`
}1234567891011121314151617181920212223242526272829303132333435363738394041424344package defs
import (
"time"
"github.com/google/uuid"
)
// APIMoQServer contains methods used by the API server.
type APIMoQServer interface {
APISessionsList() (*APIMoQSessionList, error)
APISessionsGet(uuid.UUID) (*APIMoQSession, error)
APISessionsKick(uuid.UUID) error
}
// APIMoQSessionState is the state of a MoQ session.
type APIMoQSessionState string
// states.
const (
APIMoQSessionStateIdle APIMoQSessionState = "idle"
APIMoQSessionStateRead APIMoQSessionState = "read"
APIMoQSessionStatePublish APIMoQSessionState = "publish"
)
// APIMoQSessionList is a list of MoQ sessions.
type APIMoQSessionList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []APIMoQSession `json:"items"`
}
// APIMoQSession is a MoQ session.
type APIMoQSession struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
State APIMoQSessionState `json:"state"`
Path string `json:"path"`
Query string `json:"query"`
UserAgent string `json:"userAgent"`
InboundBytes uint64 `json:"inboundBytes"`
OutboundBytes uint64 `json:"outboundBytes"`
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293package defs
import (
"time"
)
// APIPathManager contains methods used by the API and Metrics server.
type APIPathManager interface {
APIPathsList() (*APIPathList, error)
APIPathsGet(string) (*APIPath, error)
}
// APIPathSourceType is the type of a path source.
type APIPathSourceType string
// source types.
const (
APIPathSourceTypeHLSSource APIPathSourceType = "hlsSource"
APIPathSourceTypeRedirect APIPathSourceType = "redirect"
APIPathSourceTypeRPICameraSource APIPathSourceType = "rpiCameraSource"
APIPathSourceTypeRTMPConn APIPathSourceType = "rtmpConn"
APIPathSourceTypeRTMPSConn APIPathSourceType = "rtmpsConn"
APIPathSourceTypeRTMPSource APIPathSourceType = "rtmpSource"
APIPathSourceTypeRTSPSession APIPathSourceType = "rtspSession"
APIPathSourceTypeRTSPSource APIPathSourceType = "rtspSource"
APIPathSourceTypeRTSPSSession APIPathSourceType = "rtspsSession"
APIPathSourceTypeSRTConn APIPathSourceType = "srtConn"
APIPathSourceTypeSRTSource APIPathSourceType = "srtSource"
APIPathSourceTypeMPEGTSSource APIPathSourceType = "mpegtsSource"
APIPathSourceTypeRTPSource APIPathSourceType = "rtpSource"
APIPathSourceTypeWebRTCSession APIPathSourceType = "webRTCSession"
APIPathSourceTypeWebRTCSource APIPathSourceType = "webRTCSource"
APIPathSourceTypeMoQSession APIPathSourceType = "moqSession"
)
// APIPathSource is a source.
type APIPathSource struct {
Type APIPathSourceType `json:"type"`
ID string `json:"id"`
}
// APIPathReaderType is the type of a path reader.
type APIPathReaderType string
// reader types.
const (
APIPathReaderTypeHLSSession APIPathReaderType = "hlsSession"
APIPathReaderTypeRTMPConn APIPathReaderType = "rtmpConn"
APIPathReaderTypeRTMPSConn APIPathReaderType = "rtmpsConn"
APIPathReaderTypeRTSPConn APIPathReaderType = "rtspConn"
APIPathReaderTypeRTSPSession APIPathReaderType = "rtspSession"
APIPathReaderTypeRTSPSConn APIPathReaderType = "rtspsConn"
APIPathReaderTypeRTSPSSession APIPathReaderType = "rtspsSession"
APIPathReaderTypeSRTConn APIPathReaderType = "srtConn"
APIPathReaderTypeWebRTCSession APIPathReaderType = "webRTCSession"
APIPathReaderTypeMoQSession APIPathReaderType = "moqSession"
APIPathReaderTypeHidden APIPathReaderType = "hidden"
)
// APIPathReader is a reader.
type APIPathReader struct {
Type APIPathReaderType `json:"type"`
ID string `json:"id"`
}
// APIPath is a path.
type APIPath struct {
Name string `json:"name"`
ConfName string `json:"confName"`
Ready bool `json:"ready" deprecated:"true"`
ReadyTime *time.Time `json:"readyTime" deprecated:"true"`
Available bool `json:"available"`
AvailableTime *time.Time `json:"availableTime"`
Online bool `json:"online"`
OnlineTime *time.Time `json:"onlineTime"`
Source *APIPathSource `json:"source"`
Tracks []APIPathTrackCodec `json:"tracks" deprecated:"true"`
Tracks2 []APIPathTrack `json:"tracks2"`
Readers []APIPathReader `json:"readers"`
InboundBytes uint64 `json:"inboundBytes"`
OutboundBytes uint64 `json:"outboundBytes"`
InboundFramesInError uint64 `json:"inboundFramesInError"`
// deprecated
BytesReceived uint64 `json:"bytesReceived" deprecated:"true"`
BytesSent uint64 `json:"bytesSent" deprecated:"true"`
}
// APIPathList is a list of paths.
type APIPathList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []APIPath `json:"items"`
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455package defs
import (
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/bluenviron/gortsplib/v5/pkg/format"
"github.com/bluenviron/mediamtx/internal/formatlabel"
)
// APIPathTrack is a track.
type APIPathTrack struct {
Codec APIPathTrackCodec `json:"codec"`
CodecProps APIPathTrackCodecProps `json:"codecProps"`
}
func formatToTrack(outFormat format.Format) APIPathTrack {
return APIPathTrack{
Codec: formatlabel.FormatToLabel(outFormat),
CodecProps: formatToTrackCodecProps(outFormat),
}
}
func gatherFormats(medias []*description.Media) []format.Format {
n := 0
for _, media := range medias {
n += len(media.Formats)
}
if n == 0 {
return nil
}
formats := make([]format.Format, n)
n = 0
for _, media := range medias {
n += copy(formats[n:], media.Formats)
}
return formats
}
func formatsToTracks(outFormats []format.Format) []APIPathTrack {
ret := make([]APIPathTrack, len(outFormats))
for i, outFormat := range outFormats {
ret[i] = formatToTrack(outFormat)
}
return ret
}
// MediasToTracks returns tracks of given medias.
func MediasToTracks(outMedias []*description.Media) []APIPathTrack {
return formatsToTracks(gatherFormats(outMedias))
}123456package defs
import "github.com/bluenviron/mediamtx/internal/formatlabel"
// APIPathTrackCodec is a track codec.
type APIPathTrackCodec = formatlabel.Label123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257package defs
import (
"fmt"
"strconv"
"github.com/bluenviron/gortsplib/v5/pkg/format"
codecsh264 "github.com/bluenviron/mediacommon/v2/pkg/codecs/h264"
codecsh265 "github.com/bluenviron/mediacommon/v2/pkg/codecs/h265"
)
// APIPathTrackCodecProps contains codec-specific properties.
type APIPathTrackCodecProps interface {
apiPathTrackCodecProps()
}
// APIPathTrackCodecPropsAV1 contains codec-specific properties of AV1.
type APIPathTrackCodecPropsAV1 struct {
Width int `json:"width"`
Height int `json:"height"`
Profile int `json:"profile"`
Level int `json:"level"`
Tier int `json:"tier"`
}
func (*APIPathTrackCodecPropsAV1) apiPathTrackCodecProps() {}
// APIPathTrackCodecPropsVP9 contains codec-specific properties of VP9.
type APIPathTrackCodecPropsVP9 struct {
Profile int `json:"profile"`
}
func (*APIPathTrackCodecPropsVP9) apiPathTrackCodecProps() {}
// APIPathTrackCodecPropsH265 contains codec-specific properties of H265.
type APIPathTrackCodecPropsH265 struct {
Width int `json:"width"`
Height int `json:"height"`
Profile string `json:"profile"`
Level string `json:"level"`
}
func (*APIPathTrackCodecPropsH265) apiPathTrackCodecProps() {}
// APIPathTrackCodecPropsH264 contains codec-specific properties of H264.
type APIPathTrackCodecPropsH264 struct {
Width int `json:"width"`
Height int `json:"height"`
Profile string `json:"profile"`
Level string `json:"level"`
}
func (*APIPathTrackCodecPropsH264) apiPathTrackCodecProps() {}
// APIPathTrackCodecPropsOpus contains codec-specific properties of Opus.
type APIPathTrackCodecPropsOpus struct {
ChannelCount int `json:"channelCount"`
}
func (*APIPathTrackCodecPropsOpus) apiPathTrackCodecProps() {}
// APIPathTrackCodecPropsMPEG4Audio contains codec-specific properties of MPEG4Audio.
type APIPathTrackCodecPropsMPEG4Audio struct {
SampleRate int `json:"sampleRate"`
ChannelCount int `json:"channelCount"`
}
func (*APIPathTrackCodecPropsMPEG4Audio) apiPathTrackCodecProps() {}
// APIPathTrackCodecPropsAC3 contains codec-specific properties of AC3.
type APIPathTrackCodecPropsAC3 struct {
SampleRate int `json:"sampleRate"`
ChannelCount int `json:"channelCount"`
}
func (*APIPathTrackCodecPropsAC3) apiPathTrackCodecProps() {}
// APIPathTrackCodecPropsG711 contains codec-specific properties of G711.
type APIPathTrackCodecPropsG711 struct {
MULaw bool `json:"muLaw"`
SampleRate int `json:"sampleRate"`
ChannelCount int `json:"channelCount"`
}
func (*APIPathTrackCodecPropsG711) apiPathTrackCodecProps() {}
// APIPathTrackCodecPropsLPCM contains codec-specific properties of LPCM.
type APIPathTrackCodecPropsLPCM struct {
BitDepth int `json:"bitDepth"`
SampleRate int `json:"sampleRate"`
ChannelCount int `json:"channelCount"`
}
func (*APIPathTrackCodecPropsLPCM) apiPathTrackCodecProps() {}
func h264ProfileString(profileIdc uint8) string {
switch profileIdc {
case 66:
return "Baseline"
case 77:
return "Main"
case 88:
return "Extended"
case 100:
return "High"
case 110:
return "High 10"
case 122:
return "High 4:2:2"
case 244:
return "High 4:4:4 Predictive"
default:
return strconv.Itoa(int(profileIdc))
}
}
func h264LevelString(levelIdc uint8) string {
major := levelIdc / 10
minor := levelIdc % 10
if minor == 0 {
return fmt.Sprintf("%d", major)
}
return fmt.Sprintf("%d.%d", major, minor)
}
func h265ProfileString(profileIdc uint8) string {
switch profileIdc {
case 1:
return "Main"
case 2:
return "Main 10"
case 3:
return "Main Still Picture"
case 4:
return "Range Extensions"
case 5:
return "High Throughput"
case 6:
return "Multiview Main"
case 7:
return "Scalable Main"
case 8:
return "3D Main"
case 9:
return "Screen Content Coding Extensions"
case 10:
return "Scalable Range Extensions"
default:
return strconv.Itoa(int(profileIdc))
}
}
func h265LevelString(levelIdc uint8) string {
// H.265 level_idc = 30 * level, so 3.0 = 90, 4.0 = 120, 4.1 = 123
level := float64(levelIdc) / 30.0
// Check if it's a clean level like 3.0, 4.0
if levelIdc%30 == 0 {
return fmt.Sprintf("%.0f", level)
}
return fmt.Sprintf("%.1f", level)
}
func formatToTrackCodecProps(outFormat format.Format) APIPathTrackCodecProps {
switch outFormat := outFormat.(type) {
case *format.AV1:
props := &APIPathTrackCodecPropsAV1{}
if outFormat.Profile != nil {
props.Profile = *outFormat.Profile
}
if outFormat.LevelIdx != nil {
props.Level = *outFormat.LevelIdx
}
if outFormat.Tier != nil {
props.Tier = *outFormat.Tier
}
return props
case *format.VP9:
props := &APIPathTrackCodecPropsVP9{}
if outFormat.ProfileID != nil {
props.Profile = *outFormat.ProfileID
}
return props
case *format.H265:
props := &APIPathTrackCodecPropsH265{}
if outFormat.SPS != nil {
var s codecsh265.SPS
if err := s.Unmarshal(outFormat.SPS); err == nil {
props.Width = s.Width()
props.Height = s.Height()
props.Profile = h265ProfileString(s.ProfileTierLevel.GeneralProfileIdc)
props.Level = h265LevelString(s.ProfileTierLevel.GeneralLevelIdc)
}
}
return props
case *format.H264:
props := &APIPathTrackCodecPropsH264{}
if outFormat.SPS != nil {
var s codecsh264.SPS
if err := s.Unmarshal(outFormat.SPS); err == nil {
props.Width = s.Width()
props.Height = s.Height()
props.Profile = h264ProfileString(s.ProfileIdc)
props.Level = h264LevelString(s.LevelIdc)
}
}
return props
case *format.Opus:
return &APIPathTrackCodecPropsOpus{
ChannelCount: outFormat.ChannelCount,
}
case *format.MPEG4Audio:
props := &APIPathTrackCodecPropsMPEG4Audio{}
if outFormat.Config != nil {
props.SampleRate = outFormat.Config.SampleRate
props.ChannelCount = int(outFormat.Config.ChannelConfig)
}
return props
case *format.AC3:
return &APIPathTrackCodecPropsAC3{
SampleRate: outFormat.SampleRate,
ChannelCount: outFormat.ChannelCount,
}
case *format.G711:
return &APIPathTrackCodecPropsG711{
MULaw: outFormat.MULaw,
SampleRate: outFormat.SampleRate,
ChannelCount: outFormat.ChannelCount,
}
case *format.LPCM:
return &APIPathTrackCodecPropsLPCM{
BitDepth: outFormat.BitDepth,
SampleRate: outFormat.SampleRate,
ChannelCount: outFormat.ChannelCount,
}
default:
return nil
}
}123456789101112131415161718192021package defs
import "time"
// APIRecordingSegment is a recording segment.
type APIRecordingSegment struct {
Start time.Time `json:"start"`
}
// APIRecording is a recording.
type APIRecording struct {
Name string `json:"name"`
Segments []APIRecordingSegment `json:"segments"`
}
// APIRecordingList is a list of recordings.
type APIRecordingList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []APIRecording `json:"items"`
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849package defs
import (
"time"
"github.com/google/uuid"
)
// APIRTMPServer contains methods used by the API and Metrics server.
type APIRTMPServer interface {
APIConnsList() (*APIRTMPConnList, error)
APIConnsGet(uuid.UUID) (*APIRTMPConn, error)
APIConnsKick(uuid.UUID) error
}
// APIRTMPConnState is the state of a RTMP connection.
type APIRTMPConnState string
// states.
const (
APIRTMPConnStateIdle APIRTMPConnState = "idle"
APIRTMPConnStateRead APIRTMPConnState = "read"
APIRTMPConnStatePublish APIRTMPConnState = "publish"
)
// APIRTMPConn is a RTMP connection.
type APIRTMPConn struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
State APIRTMPConnState `json:"state"`
Path string `json:"path"`
Query string `json:"query"`
User string `json:"user"`
UserAgent string `json:"userAgent"`
InboundBytes uint64 `json:"inboundBytes"`
OutboundBytes uint64 `json:"outboundBytes"`
OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"`
// deprecated
BytesReceived uint64 `json:"bytesReceived" deprecated:"true"`
BytesSent uint64 `json:"bytesSent" deprecated:"true"`
}
// APIRTMPConnList is a list of RTMP connections.
type APIRTMPConnList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []APIRTMPConn `json:"items"`
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091package defs
import (
"time"
"github.com/google/uuid"
)
// APIRTSPServer contains methods used by the API and Metrics server.
type APIRTSPServer interface {
APIConnsList() (*APIRTSPConnsList, error)
APIConnsGet(uuid.UUID) (*APIRTSPConn, error)
APISessionsList() (*APIRTSPSessionList, error)
APISessionsGet(uuid.UUID) (*APIRTSPSession, error)
APISessionsKick(uuid.UUID) error
}
// APIRTSPConn is a RTSP connection.
type APIRTSPConn struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
Session *uuid.UUID `json:"session"`
Tunnel string `json:"tunnel"`
InboundBytes uint64 `json:"inboundBytes"`
OutboundBytes uint64 `json:"outboundBytes"`
BytesReceived uint64 `json:"bytesReceived" deprecated:"true"`
BytesSent uint64 `json:"bytesSent" deprecated:"true"`
}
// APIRTSPConnsList is a list of RTSP connections.
type APIRTSPConnsList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []APIRTSPConn `json:"items"`
}
// APIRTSPSessionState is the state of a RTSP session.
type APIRTSPSessionState string
// states.
const (
APIRTSPSessionStateIdle APIRTSPSessionState = "idle"
APIRTSPSessionStateRead APIRTSPSessionState = "read"
APIRTSPSessionStatePublish APIRTSPSessionState = "publish"
)
// APIRTSPSession is a RTSP session.
type APIRTSPSession struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
State APIRTSPSessionState `json:"state"`
Path string `json:"path"`
Query string `json:"query"`
User string `json:"user"`
UserAgent string `json:"userAgent"`
Transport *string `json:"transport"`
Profile *string `json:"profile"`
Conns []uuid.UUID `json:"conns"`
InboundBytes uint64 `json:"inboundBytes"`
InboundRTPPackets uint64 `json:"inboundRTPPackets"`
InboundRTPPacketsLost uint64 `json:"inboundRTPPacketsLost"`
InboundRTPPacketsInError uint64 `json:"inboundRTPPacketsInError"`
InboundRTPPacketsJitter float64 `json:"inboundRTPPacketsJitter"`
InboundRTCPPackets uint64 `json:"inboundRTCPPackets"`
InboundRTCPPacketsInError uint64 `json:"inboundRTCPPacketsInError"`
OutboundBytes uint64 `json:"outboundBytes"`
OutboundRTPPackets uint64 `json:"outboundRTPPackets"`
OutboundRTPPacketsReportedLost uint64 `json:"outboundRTPPacketsReportedLost"`
OutboundRTPPacketsDiscarded uint64 `json:"outboundRTPPacketsDiscarded"`
OutboundRTCPPackets uint64 `json:"outboundRTCPPackets"`
// deprecated
BytesReceived uint64 `json:"bytesReceived" deprecated:"true"`
BytesSent uint64 `json:"bytesSent" deprecated:"true"`
RTPPacketsReceived uint64 `json:"rtpPacketsReceived" deprecated:"true"`
RTPPacketsSent uint64 `json:"rtpPacketsSent" deprecated:"true"`
RTPPacketsLost uint64 `json:"rtpPacketsLost" deprecated:"true"`
RTPPacketsInError uint64 `json:"rtpPacketsInError" deprecated:"true"`
RTPPacketsJitter float64 `json:"rtpPacketsJitter" deprecated:"true"`
RTCPPacketsReceived uint64 `json:"rtcpPacketsReceived" deprecated:"true"`
RTCPPacketsSent uint64 `json:"rtcpPacketsSent" deprecated:"true"`
RTCPPacketsInError uint64 `json:"rtcpPacketsInError" deprecated:"true"`
}
// APIRTSPSessionList is a list of RTSP sessions.
type APIRTSPSessionList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []APIRTSPSession `json:"items"`
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165package defs
import (
"time"
"github.com/google/uuid"
)
// APISRTServer contains methods used by the API and Metrics server.
type APISRTServer interface {
APIConnsList() (*APISRTConnList, error)
APIConnsGet(uuid.UUID) (*APISRTConn, error)
APIConnsKick(uuid.UUID) error
}
// APISRTConnState is the state of a SRT connection.
type APISRTConnState string
// states.
const (
APISRTConnStateIdle APISRTConnState = "idle"
APISRTConnStateRead APISRTConnState = "read"
APISRTConnStatePublish APISRTConnState = "publish"
)
// APISRTConn is a SRT connection.
type APISRTConn struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
State APISRTConnState `json:"state"`
Path string `json:"path"`
Query string `json:"query"`
User string `json:"user"`
// The metric names/comments are pulled from GoSRT
// The total number of sent DATA packets, including retransmitted packets
PacketsSent uint64 `json:"packetsSent"`
// The total number of received DATA packets, including retransmitted packets
PacketsReceived uint64 `json:"packetsReceived"`
// The total number of unique DATA packets sent by the SRT sender
PacketsSentUnique uint64 `json:"packetsSentUnique"`
// The total number of unique original, retransmitted or recovered by the packet filter DATA packets
// received in time, decrypted without errors and, as a result, scheduled for delivery to the
// upstream application by the SRT receiver.
PacketsReceivedUnique uint64 `json:"packetsReceivedUnique"`
// The total number of data packets considered or reported as lost at the sender side.
// Does not correspond to the packets detected as lost at the receiver side.
PacketsSendLoss uint64 `json:"packetsSendLoss"`
// The total number of SRT DATA packets detected as presently missing (either reordered or lost) at the receiver side
PacketsReceivedLoss uint64 `json:"packetsReceivedLoss"`
// The total number of retransmitted packets sent by the SRT sender
PacketsRetrans uint64 `json:"packetsRetrans"`
// The total number of retransmitted packets registered at the receiver side
PacketsReceivedRetrans uint64 `json:"packetsReceivedRetrans"`
// The total number of sent ACK (Acknowledgement) control packets
PacketsSentACK uint64 `json:"packetsSentACK"`
// The total number of received ACK (Acknowledgement) control packets
PacketsReceivedACK uint64 `json:"packetsReceivedACK"`
// The total number of sent NAK (Negative Acknowledgement) control packets
PacketsSentNAK uint64 `json:"packetsSentNAK"`
// The total number of received NAK (Negative Acknowledgement) control packets
PacketsReceivedNAK uint64 `json:"packetsReceivedNAK"`
// The total number of sent KM (Key Material) control packets
PacketsSentKM uint64 `json:"packetsSentKM"`
// The total number of received KM (Key Material) control packets
PacketsReceivedKM uint64 `json:"packetsReceivedKM"`
// The total accumulated time in microseconds, during which the SRT sender has some data to transmit,
// including packets that have been sent, but not yet acknowledged
UsSndDuration uint64 `json:"usSndDuration"`
// ??
PacketsReceivedBelated uint64 `json:"packetsReceivedBelated"`
// The total number of dropped by the SRT sender DATA packets that have no chance to be delivered in time
PacketsSendDrop uint64 `json:"packetsSendDrop"`
// The total number of dropped by the SRT receiver and, as a result,
// not delivered to the upstream application DATA packets
PacketsReceivedDrop uint64 `json:"packetsReceivedDrop"`
// The total number of packets that failed to be decrypted at the receiver side
PacketsReceivedUndecrypt uint64 `json:"packetsReceivedUndecrypt"`
// Same as packetsReceived, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceived uint64 `json:"bytesReceived"`
// Same as packetsSent, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesSent uint64 `json:"bytesSent"`
// Same as packetsSentUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesSentUnique uint64 `json:"bytesSentUnique"`
// Same as packetsReceivedUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceivedUnique uint64 `json:"bytesReceivedUnique"`
// Same as packetsReceivedLoss, but expressed in bytes, including payload and all the headers (IP, TCP, SRT),
// bytes for the presently missing (either reordered or lost) packets' payloads are estimated
// based on the average packet size
BytesReceivedLoss uint64 `json:"bytesReceivedLoss"`
// Same as packetsRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesRetrans uint64 `json:"bytesRetrans"`
// Same as packetsReceivedRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceivedRetrans uint64 `json:"bytesReceivedRetrans"`
// Same as PacketsReceivedBelated, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceivedBelated uint64 `json:"bytesReceivedBelated"`
// Same as packetsSendDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesSendDrop uint64 `json:"bytesSendDrop"`
// Same as packetsReceivedDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceivedDrop uint64 `json:"bytesReceivedDrop"`
// Same as packetsReceivedUndecrypt, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceivedUndecrypt uint64 `json:"bytesReceivedUndecrypt"`
// Current minimum time interval between which consecutive packets are sent, in microseconds
UsPacketsSendPeriod float64 `json:"usPacketsSendPeriod"`
// The maximum number of packets that can be "in flight"
PacketsFlowWindow uint64 `json:"packetsFlowWindow"`
// The number of packets in flight
PacketsFlightSize uint64 `json:"packetsFlightSize"`
// Smoothed round-trip time (SRTT), an exponentially-weighted moving average (EWMA)
// of an endpoint's RTT samples, in milliseconds
MsRTT float64 `json:"msRTT"`
// Current transmission bandwidth, in Mbps
MbpsSendRate float64 `json:"mbpsSendRate"`
// Current receiving bandwidth, in Mbps
MbpsReceiveRate float64 `json:"mbpsReceiveRate"`
// Estimated capacity of the network link, in Mbps
MbpsLinkCapacity float64 `json:"mbpsLinkCapacity"`
// The available space in the sender's buffer, in bytes
BytesAvailSendBuf uint64 `json:"bytesAvailSendBuf"`
// The available space in the receiver's buffer, in bytes
BytesAvailReceiveBuf uint64 `json:"bytesAvailReceiveBuf"`
// Transmission bandwidth limit, in Mbps
MbpsMaxBW float64 `json:"mbpsMaxBW"`
// Maximum Segment Size (MSS), in bytes
ByteMSS uint64 `json:"byteMSS"`
// The number of packets in the sender's buffer that are already scheduled
// for sending or even possibly sent, but not yet acknowledged
PacketsSendBuf uint64 `json:"packetsSendBuf"`
// Instantaneous (current) value of packetsSndBuf, but expressed in bytes,
// including payload and all headers (IP, TCP, SRT)
BytesSendBuf uint64 `json:"bytesSendBuf"`
// The timespan (msec) of packets in the sender's buffer (unacknowledged packets)
MsSendBuf uint64 `json:"msSendBuf"`
// Timestamp-based Packet Delivery Delay value of the peer
MsSendTsbPdDelay uint64 `json:"msSendTsbPdDelay"`
// The number of acknowledged packets in receiver's buffer
PacketsReceiveBuf uint64 `json:"packetsReceiveBuf"`
// Instantaneous (current) value of packetsRcvBuf, expressed in bytes, including payload and all headers (IP, TCP, SRT)
BytesReceiveBuf uint64 `json:"bytesReceiveBuf"`
// The timespan (msec) of acknowledged packets in the receiver's buffer
MsReceiveBuf uint64 `json:"msReceiveBuf"`
// Timestamp-based Packet Delivery Delay value set on the socket via SRTO_RCVLATENCY or SRTO_LATENCY
MsReceiveTsbPdDelay uint64 `json:"msReceiveTsbPdDelay"`
// Instant value of the packet reorder tolerance
PacketsReorderTolerance uint64 `json:"packetsReorderTolerance"`
// Accumulated difference between the current time and the time-to-play of a packet that is received late
PacketsReceivedAvgBelatedTime uint64 `json:"packetsReceivedAvgBelatedTime"`
// Percentage of resent data vs. sent data
PacketsSendLossRate float64 `json:"packetsSendLossRate"`
// Percentage of retransmitted data vs. received data
PacketsReceivedLossRate float64 `json:"packetsReceivedLossRate"`
OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"`
}
// APISRTConnList is a list of SRT connections.
type APISRTConnList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []APISRTConn `json:"items"`
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263package defs
import (
"time"
"github.com/google/uuid"
)
// APIWebRTCServer contains methods used by the API and Metrics server.
type APIWebRTCServer interface {
APISessionsList() (*APIWebRTCSessionList, error)
APISessionsGet(uuid.UUID) (*APIWebRTCSession, error)
APISessionsKick(uuid.UUID) error
}
// APIWebRTCSessionState is the state of a WebRTC connection.
type APIWebRTCSessionState string
// states.
const (
APIWebRTCSessionStateRead APIWebRTCSessionState = "read"
APIWebRTCSessionStatePublish APIWebRTCSessionState = "publish"
)
// APIWebRTCSession is a WebRTC session.
type APIWebRTCSession struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
PeerConnectionEstablished bool `json:"peerConnectionEstablished"`
LocalCandidate string `json:"localCandidate"`
RemoteCandidate string `json:"remoteCandidate"`
State APIWebRTCSessionState `json:"state"`
Path string `json:"path"`
Query string `json:"query"`
User string `json:"user"`
UserAgent string `json:"userAgent"`
InboundBytes uint64 `json:"inboundBytes"`
InboundRTPPackets uint64 `json:"inboundRTPPackets"`
InboundRTPPacketsLost uint64 `json:"inboundRTPPacketsLost"`
InboundRTPPacketsJitter float64 `json:"inboundRTPPacketsJitter"`
InboundRTCPPackets uint64 `json:"inboundRTCPPackets"`
OutboundBytes uint64 `json:"outboundBytes"`
OutboundRTPPackets uint64 `json:"outboundRTPPackets"`
OutboundRTCPPackets uint64 `json:"outboundRTCPPackets"`
OutboundFramesDiscarded uint64 `json:"outboundFramesDiscarded"`
// deprecated
BytesReceived uint64 `json:"bytesReceived" deprecated:"true"`
BytesSent uint64 `json:"bytesSent" deprecated:"true"`
RTPPacketsReceived uint64 `json:"rtpPacketsReceived" deprecated:"true"`
RTPPacketsSent uint64 `json:"rtpPacketsSent" deprecated:"true"`
RTPPacketsLost uint64 `json:"rtpPacketsLost" deprecated:"true"`
RTPPacketsJitter float64 `json:"rtpPacketsJitter" deprecated:"true"`
RTCPPacketsReceived uint64 `json:"rtcpPacketsReceived" deprecated:"true"`
RTCPPacketsSent uint64 `json:"rtcpPacketsSent" deprecated:"true"`
}
// APIWebRTCSessionList is a list of WebRTC sessions.
type APIWebRTCSessionList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []APIWebRTCSession `json:"items"`
}12// Package defs contains shared definitions.
package defs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122package defs
import (
"fmt"
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/stream"
)
// PathNoStreamAvailableError is returned when no one is publishing.
type PathNoStreamAvailableError struct {
PathName string
}
// Error implements the error interface.
func (e *PathNoStreamAvailableError) Error() string {
return fmt.Sprintf("no stream is available on path '%s'", e.PathName)
}
// Path is a path.
type Path interface {
Name() string
SafeConf() *conf.Path
ExternalCmdEnv() externalcmd.Environment
RemovePublisher(req PathRemovePublisherReq)
RemoveReader(req PathRemoveReaderReq)
}
// PathFindPathConfRes contains the response of FindPathConf().
type PathFindPathConfRes struct {
Conf *conf.Path
User string
Err error
}
// PathFindPathConfReq contains arguments of FindPathConf().
type PathFindPathConfReq struct {
AccessRequest PathAccessRequest
Res chan PathFindPathConfRes
}
// PathDescribeRes contains the response of Describe().
type PathDescribeRes struct {
Path Path
Stream *stream.Stream
Redirect string
Err error
}
// PathDescribeReq contains arguments of Describe().
type PathDescribeReq struct {
AccessRequest PathAccessRequest
Res chan PathDescribeRes
}
// PathAddPublisherRes contains the response of AddPublisher().
type PathAddPublisherRes struct {
Path Path
User string
SubStream *stream.SubStream
Err error
}
// PathAddPublisherReq contains arguments of AddPublisher().
type PathAddPublisherReq struct {
Author Publisher
Desc *description.Session
UseRTPPackets bool
ReplaceNTP bool
ConfToCompare *conf.Path
AccessRequest PathAccessRequest
Res chan PathAddPublisherRes
}
// PathRemovePublisherReq contains arguments of RemovePublisher().
type PathRemovePublisherReq struct {
Author Publisher
Res chan struct{}
}
// PathAddReaderRes contains the response of AddReader().
type PathAddReaderRes struct {
Path Path
User string
Stream *stream.Stream
Err error
}
// PathAddReaderReq contains arguments of AddReader().
type PathAddReaderReq struct {
Author Reader
AccessRequest PathAccessRequest
Res chan PathAddReaderRes
}
// PathRemoveReaderReq contains arguments of RemoveReader().
type PathRemoveReaderReq struct {
Author Reader
Res chan struct{}
}
// PathSourceStaticSetReadyRes contains the response of SetReady().
type PathSourceStaticSetReadyRes struct {
SubStream *stream.SubStream
Err error
}
// PathSourceStaticSetReadyReq contains arguments of SetReady().
type PathSourceStaticSetReadyReq struct {
Desc *description.Session
UseRTPPackets bool
ReplaceNTP bool
Res chan PathSourceStaticSetReadyRes
}
// PathSourceStaticSetNotReadyReq contains arguments of SetNotReady().
type PathSourceStaticSetNotReadyReq struct {
Res chan struct{}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445package defs
import (
"net"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/google/uuid"
)
// PathAccessRequest is a path access request.
type PathAccessRequest struct {
Name string
Query string
UserAgent string
Publish bool
SkipAuth bool
// only if skipAuth = false
Proto auth.Protocol
ID *uuid.UUID
Credentials *auth.Credentials
IP net.IP
CustomVerifyFunc func(expectedUser string, expectedPass string) bool
}
// ToAuthRequest converts a path access request into an authentication request.
func (r *PathAccessRequest) ToAuthRequest() *auth.Request {
return &auth.Request{
Action: func() conf.AuthAction {
if r.Publish {
return conf.AuthActionPublish
}
return conf.AuthActionRead
}(),
Path: r.Name,
Query: r.Query,
Protocol: r.Proto,
ID: r.ID,
UserAgent: r.UserAgent,
Credentials: r.Credentials,
IP: r.IP,
CustomVerifyFunc: r.CustomVerifyFunc,
}
}1234567package defs
// Publisher is an entity that can publish a stream.
type Publisher interface {
Source
Close()
}1234567package defs
// Reader is an entity that can read a stream.
type Reader interface {
Close()
APIReaderDescribe() *APIPathReader
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546package defs
import (
"fmt"
"strings"
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/bluenviron/gortsplib/v5/pkg/format"
"github.com/bluenviron/mediamtx/internal/formatlabel"
"github.com/bluenviron/mediamtx/internal/logger"
)
// Source is an entity that can provide a stream.
// it can be:
// - Publisher
// - staticsources.Handler
// - core.sourceRedirect
type Source interface {
logger.Writer
APISourceDescribe() *APIPathSource
}
// FormatsInfo returns a description of formats.
func FormatsInfo(formats []format.Format) string {
labels := formatlabel.FormatsToLabels(formats)
codecNames := make([]string, len(labels))
for i, label := range labels {
codecNames[i] = string(label)
}
return fmt.Sprintf("%d %s (%s)",
len(formats),
func() string {
if len(formats) == 1 {
return "track"
}
return "tracks"
}(),
strings.Join(codecNames, ", "))
}
// MediasInfo returns a description of medias.
func MediasInfo(medias []*description.Media) string {
return FormatsInfo(gatherFormats(medias))
}123456789101112131415package defs
import (
"context"
"github.com/bluenviron/mediamtx/internal/conf"
)
// StaticSourceRunParams is the set of params passed to Run().
type StaticSourceRunParams struct {
Context context.Context
ResolvedSource string
Conf *conf.Path
ReloadConf chan *conf.Path
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879// Package errordumper contains a counter that that periodically invokes a callback if the counter is not zero.
package errordumper
import (
"sync"
"time"
)
const (
callbackPeriod = 1 * time.Second
)
// Dumper is a counter that periodically invokes a callback if errors were added.
type Dumper struct {
OnReport func(v uint64, last error)
mutex sync.Mutex
counter uint64
absCounter uint64
last error
terminate chan struct{}
done chan struct{}
}
// Start starts the counter.
func (c *Dumper) Start() {
c.terminate = make(chan struct{})
c.done = make(chan struct{})
go c.run()
}
// Stop stops the counter.
func (c *Dumper) Stop() {
close(c.terminate)
<-c.done
}
// Add adds an error to the counter.
func (c *Dumper) Add(err error) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.counter++
c.absCounter++
c.last = err
}
// Get returns the total number of errors.
func (c *Dumper) Get() uint64 {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.absCounter
}
func (c *Dumper) run() {
defer close(c.done)
t := time.NewTicker(callbackPeriod)
defer t.Stop()
for {
select {
case <-c.terminate:
return
case <-t.C:
c.mutex.Lock()
var counter uint64
counter, c.counter = c.counter, 0
last := c.last
c.mutex.Unlock()
if counter != 0 {
c.OnReport(counter, last)
}
}
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243package errordumper
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestDumperReport(t *testing.T) {
done := make(chan struct{})
c := &Dumper{
OnReport: func(v uint64, last error) {
require.Equal(t, uint64(1), v)
require.EqualError(t, last, "test error")
close(done)
},
}
c.Start()
defer c.Stop()
c.Add(fmt.Errorf("test error"))
select {
case <-done:
case <-time.After(2 * time.Second):
t.Errorf("should not happen")
}
}
func TestDumperDoNotReport(t *testing.T) {
c := &Dumper{
OnReport: func(_ uint64, _ error) {
t.Errorf("should not happen")
},
}
c.Start()
defer c.Stop()
<-time.After(2 * time.Second)
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495// Package externalcmd allows to launch external commands.
package externalcmd
import (
"errors"
"fmt"
"os"
"time"
)
const (
restartPause = 5 * time.Second
)
var errTerminated = errors.New("terminated")
// OnExitFunc is the prototype of onExit.
type OnExitFunc func(error)
// Environment is a Cmd environment.
type Environment map[string]string
// Cmd is an external command.
type Cmd struct {
Pool *Pool
Cmdstr string
Restart bool
Env Environment
OnExit OnExitFunc
// in
terminate chan struct{}
}
// Start starts the command.
func (c *Cmd) Start() {
if c.OnExit == nil {
c.OnExit = func(_ error) {}
}
c.terminate = make(chan struct{})
c.Pool.wg.Add(1)
go c.run()
}
// Close closes the command. It doesn't wait for the command to exit.
func (c *Cmd) Close() {
close(c.terminate)
}
func expandEnv(s string, env Environment) string {
return os.Expand(s, func(variable string) string {
if value, ok := env[variable]; ok {
return value
}
return os.Getenv(variable)
})
}
func (c *Cmd) run() {
defer c.Pool.wg.Done()
env := append([]string(nil), os.Environ()...)
for key, val := range c.Env {
env = append(env, key+"="+val)
}
for {
err := c.runOSSpecific(c.Cmdstr, env)
if errors.Is(err, errTerminated) {
return
}
if !c.Restart {
if err != nil {
c.OnExit(err)
}
return
}
if err != nil {
c.OnExit(err)
} else {
c.OnExit(fmt.Errorf("command exited with code 0"))
}
select {
case <-time.After(restartPause):
case <-c.terminate:
return
}
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566//go:build !windows
package externalcmd
import (
"errors"
"fmt"
"os"
"os/exec"
"syscall"
"github.com/kballard/go-shellquote"
)
func (c *Cmd) runOSSpecific(cmdstr string, env []string) error {
cmdParts, err := shellquote.Split(cmdstr)
if err != nil {
return err
}
for i, part := range cmdParts {
cmdParts[i] = expandEnv(part, c.Env)
}
cmd := exec.Command(cmdParts[0], cmdParts[1:]...)
cmd.Env = env
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// set process group in order to allow killing subprocesses
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
err = cmd.Start()
if err != nil {
return err
}
cmdDone := make(chan int)
go func() {
cmdDone <- func() int {
err2 := cmd.Wait()
if err2 == nil {
return 0
}
if ee, ok := errors.AsType[*exec.ExitError](err2); ok {
ee.ExitCode()
}
return 0
}()
}()
select {
case <-c.terminate:
// the minus is needed to kill all subprocesses
syscall.Kill(-cmd.Process.Pid, syscall.SIGINT) //nolint:errcheck
<-cmdDone
return errTerminated
case c := <-cmdDone:
if c != 0 {
return fmt.Errorf("command exited with code %d", c)
}
return nil
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141package externalcmd
import (
"fmt"
"os"
"os/exec"
"strings"
"syscall"
"unsafe"
"github.com/kballard/go-shellquote"
"golang.org/x/sys/windows"
)
// taken from
// https://gist.github.com/hallazzang/76f3970bfc949831808bbebc8ca15209
func createProcessGroup() (windows.Handle, error) {
h, err := windows.CreateJobObject(nil, nil)
if err != nil {
return 0, err
}
info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{
BasicLimitInformation: windows.JOBOBJECT_BASIC_LIMIT_INFORMATION{
LimitFlags: windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
},
}
_, err = windows.SetInformationJobObject(
h,
windows.JobObjectExtendedLimitInformation,
uintptr(unsafe.Pointer(&info)),
uint32(unsafe.Sizeof(info)))
if err != nil {
return 0, err
}
return h, nil
}
func closeProcessGroup(h windows.Handle) error {
return windows.CloseHandle(h)
}
func addProcessToGroup(h windows.Handle, p *os.Process) error {
// Combine the required access rights
access := uint32(windows.PROCESS_SET_QUOTA | windows.PROCESS_TERMINATE)
processHandle, err := windows.OpenProcess(access, false, uint32(p.Pid))
if err != nil {
return fmt.Errorf("failed to open process: %v", err)
}
defer windows.CloseHandle(processHandle)
err = windows.AssignProcessToJobObject(h, processHandle)
if err != nil {
return fmt.Errorf("failed to assign process to job object: %v", err)
}
return nil
}
func (c *Cmd) runOSSpecific(cmdstr string, env []string) error {
var cmd *exec.Cmd
// from Golang documentation:
// On Windows, processes receive the whole command line as a single string and do their own parsing.
// Command combines and quotes Args into a command line string with an algorithm compatible with
// applications using CommandLineToArgvW (which is the most common way). Notable exceptions are
// msiexec.exe and cmd.exe (and thus, all batch files), which have a different unquoting algorithm.
// In these or other similar cases, you can do the quoting yourself and provide the full command
// line in SysProcAttr.CmdLine, leaving Args empty.
if strings.HasPrefix(cmdstr, "cmd ") || strings.HasPrefix(cmdstr, "cmd.exe ") {
args := strings.TrimPrefix(strings.TrimPrefix(cmdstr, "cmd "), "cmd.exe ")
args = expandEnv(args, c.Env)
cmd = exec.Command("cmd.exe")
cmd.SysProcAttr = &syscall.SysProcAttr{
CmdLine: args,
}
} else {
cmdParts, err := shellquote.Split(cmdstr)
if err != nil {
return err
}
for i, part := range cmdParts {
cmdParts[i] = expandEnv(part, c.Env)
}
cmd = exec.Command(cmdParts[0], cmdParts[1:]...)
}
cmd.Env = env
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// create a process group to kill all subprocesses
g, err := createProcessGroup()
if err != nil {
return err
}
err = cmd.Start()
if err != nil {
return err
}
err = addProcessToGroup(g, cmd.Process)
if err != nil {
return err
}
cmdDone := make(chan int)
go func() {
cmdDone <- func() int {
err := cmd.Wait()
if err == nil {
return 0
}
ee, ok := err.(*exec.ExitError)
if !ok {
return 0
}
return ee.ExitCode()
}()
}()
select {
case <-c.terminate:
closeProcessGroup(g)
<-cmdDone
return errTerminated
case code := <-cmdDone:
closeProcessGroup(g)
if code != 0 {
return fmt.Errorf("command exited with code %d", code)
}
return nil
}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344package externalcmd
import (
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestCmdRunExpandAfterSplit(t *testing.T) {
// if os.Expand runs before shellquote.Split, a variable value containing a
// single quote produces unbalanced quotes that cause shellquote.Split to fail.
p := &Pool{}
p.Initialize()
out := filepath.Join(t.TempDir(), "out")
cmd := &Cmd{
Pool: p,
Cmdstr: "sh -c 'echo \"$MY_VAR\" > " + out + "'",
Env: Environment{
"MY_VAR": "it's",
},
}
cmd.Start()
poolClosed := make(chan struct{})
go func() {
p.Close()
close(poolClosed)
}()
select {
case <-poolClosed:
case <-time.After(10 * time.Second):
t.Fatal("timeout")
}
byts, err := os.ReadFile(out)
require.NoError(t, err)
require.Equal(t, "it's\n", string(byts))
}12345678910111213141516171819package externalcmd
import (
"sync"
)
// Pool is a pool of external commands.
type Pool struct {
wg sync.WaitGroup
}
// Initialize initializes a Pool.
func (p *Pool) Initialize() {
}
// Close waits for all external commands to exit.
func (p *Pool) Close() {
p.wg.Wait()
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133// Package formatlabel contains format label definitions.
package formatlabel
import (
"strings"
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/bluenviron/gortsplib/v5/pkg/format"
)
// Label is a format label.
type Label string
// labels.
const (
// video
AV1 Label = "AV1"
VP9 Label = "VP9"
VP8 Label = "VP8"
H265 Label = "H265"
H264 Label = "H264"
MPEG4Video Label = "MPEG-4 Video"
MPEG1Video Label = "MPEG-1/2 Video"
MJPEG Label = "M-JPEG"
// audio
Opus Label = "Opus"
FLAC Label = "FLAC"
Vorbis Label = "Vorbis"
MPEG4Audio Label = "MPEG-4 Audio"
MPEG4AudioLATM Label = "MPEG-4 Audio LATM"
MPEG1Audio Label = "MPEG-1/2 Audio"
AC3 Label = "AC3"
Speex Label = "Speex"
G726 Label = "G726"
G722 Label = "G722"
G711 Label = "G711"
LPCM Label = "LPCM"
// other
MPEGTS Label = "MPEG-TS"
KLV Label = "KLV"
Generic Label = "Generic"
)
// FormatToLabel returns the label associated with a format.
func FormatToLabel(forma format.Format) Label {
switch forma.(type) {
// video
case *format.AV1:
return AV1
case *format.VP9:
return VP9
case *format.VP8:
return VP8
case *format.H265:
return H265
case *format.H264:
return H264
case *format.MPEG4Video:
return MPEG4Video
case *format.MPEG1Video:
return MPEG1Video
case *format.MJPEG:
return MJPEG
// audio
case *format.Opus:
return Opus
case *format.Vorbis:
return Vorbis
case *format.MPEG4Audio:
return MPEG4Audio
case *format.MPEG4AudioLATM:
return MPEG4AudioLATM
case *format.MPEG1Audio:
return MPEG1Audio
case *format.AC3:
return AC3
case *format.Speex:
return Speex
case *format.G726:
return G726
case *format.G722:
return G722
case *format.G711:
return G711
case *format.LPCM:
return LPCM
// other
case *format.MPEGTS:
return MPEGTS
case *format.KLV:
return KLV
case *format.Generic:
if strings.HasPrefix(strings.ToLower(forma.RTPMap()), "flac/") {
return FLAC
}
}
return Generic
}
func gatherFormats(medias []*description.Media) []format.Format {
n := 0
for _, media := range medias {
n += len(media.Formats)
}
if n == 0 {
return nil
}
formats := make([]format.Format, n)
n = 0
for _, media := range medias {
n += copy(formats[n:], media.Formats)
}
return formats
}
// FormatsToLabels returns labels of given formats.
func FormatsToLabels(formats []format.Format) []Label {
ret := make([]Label, len(formats))
for i, forma := range formats {
ret[i] = FormatToLabel(forma)
}
return ret
}
// MediasToLabels returns labels of given medias.
func MediasToLabels(medias []*description.Media) []Label {
return FormatsToLabels(gatherFormats(medias))
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990package formatlabel
import (
"testing"
"github.com/bluenviron/gortsplib/v5/pkg/description"
"github.com/bluenviron/gortsplib/v5/pkg/format"
"github.com/stretchr/testify/require"
)
func TestFormatToLabel(t *testing.T) {
codecs := []Label{
FormatToLabel(&format.AV1{}),
FormatToLabel(&format.VP9{}),
FormatToLabel(&format.VP8{}),
FormatToLabel(&format.H265{}),
FormatToLabel(&format.H264{}),
FormatToLabel(&format.MPEG4Video{}),
FormatToLabel(&format.MPEG1Video{}),
FormatToLabel(&format.MJPEG{}),
FormatToLabel(&format.Opus{}),
FormatToLabel(&format.Generic{RTPMa: "FLAC/44100/2"}),
FormatToLabel(&format.Vorbis{}),
FormatToLabel(&format.MPEG4Audio{}),
FormatToLabel(&format.MPEG4AudioLATM{}),
FormatToLabel(&format.MPEG1Audio{}),
FormatToLabel(&format.AC3{}),
FormatToLabel(&format.Speex{}),
FormatToLabel(&format.G726{}),
FormatToLabel(&format.G722{}),
FormatToLabel(&format.G711{}),
FormatToLabel(&format.LPCM{}),
FormatToLabel(&format.MPEGTS{}),
FormatToLabel(&format.KLV{}),
FormatToLabel(&format.Generic{}),
}
require.Equal(t, []Label{
AV1,
VP9,
VP8,
H265,
H264,
MPEG4Video,
MPEG1Video,
MJPEG,
Opus,
FLAC,
Vorbis,
MPEG4Audio,
MPEG4AudioLATM,
MPEG1Audio,
AC3,
Speex,
G726,
G722,
G711,
LPCM,
MPEGTS,
KLV,
Generic,
}, codecs)
}
func TestFormatsToLabels(t *testing.T) {
require.Equal(t, []Label{
H264,
Opus,
KLV,
Generic,
}, FormatsToLabels([]format.Format{
&format.H264{},
&format.Opus{},
&format.KLV{},
&format.Generic{},
}))
}
func TestMediasToLabels(t *testing.T) {
require.Equal(t, []Label{
H264,
Opus,
G711,
KLV,
}, MediasToLabels([]*description.Media{
{Formats: []format.Format{&format.H264{}}},
{Formats: []format.Format{&format.Opus{}, &format.G711{}}},
{Formats: []format.Format{&format.KLV{}}},
}))
}12// Package hooks contains hook implementations.
package hooks1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768package hooks
import (
"net"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/logger"
)
// OnConnectParams are the parameters of OnConnect.
type OnConnectParams struct {
Logger logger.Writer
ExternalCmdPool *externalcmd.Pool
RunOnConnect string
RunOnConnectRestart bool
RunOnDisconnect string
RTSPAddress string
Desc defs.APIPathReader
}
// OnConnect is the OnConnect hook.
func OnConnect(params OnConnectParams) func() {
var env externalcmd.Environment
var onConnectCmd *externalcmd.Cmd
if params.RunOnConnect != "" || params.RunOnDisconnect != "" {
_, port, _ := net.SplitHostPort(params.RTSPAddress)
env = externalcmd.Environment{
"RTSP_PORT": port,
"MTX_CONN_TYPE": string(params.Desc.Type),
"MTX_CONN_ID": params.Desc.ID,
}
}
if params.RunOnConnect != "" {
params.Logger.Log(logger.Info, "runOnConnect command started")
onConnectCmd = &externalcmd.Cmd{
Pool: params.ExternalCmdPool,
Cmdstr: params.RunOnConnect,
Restart: params.RunOnConnectRestart,
Env: env,
OnExit: func(err error) {
params.Logger.Log(logger.Info, "runOnConnect command exited: %v", err)
},
}
onConnectCmd.Start()
}
return func() {
if onConnectCmd != nil {
onConnectCmd.Close()
params.Logger.Log(logger.Info, "runOnConnect command stopped")
}
if params.RunOnDisconnect != "" {
params.Logger.Log(logger.Info, "runOnDisconnect command launched")
cmd := &externalcmd.Cmd{
Pool: params.ExternalCmdPool,
Cmdstr: params.RunOnDisconnect,
Restart: false,
Env: env,
}
cmd.Start()
}
}
}fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/webrtc_ice_server.goAdded+9
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/90b5d1b18dd9f8acAdded+2
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/testdata/fuzz/FuzzUnmarshal/dc806ec658c460fcAdded+2
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal.goAdded+106
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/conf/yamlwrapper/unmarshal_test.goAdded+80
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher.goAdded+122
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/confwatcher/confwatcher_test.goAdded+145
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/api_test.goAdded+1412
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core.goAdded+1171
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/core_test.goAdded+148
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/metrics_test.goAdded+513
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path.goAdded+1116
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager.goAdded+690
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_manager_test.goAdded+217
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/path_test.goAdded+1035
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/source_redirect.goAdded+20
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/test_on_demand/main.goAdded+54
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/core/versiongetter/main.goAdded+143
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper.goAdded+84
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/counterdumper/dumper_test.goAdded+42
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api.goAdded+47
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_hls.goAdded+54
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_moq.goAdded+44
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path.goAdded+93
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track.goAdded+55
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec.goAdded+6
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_path_track_codec_props.goAdded+257
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_recording.goAdded+21
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtmp.goAdded+49
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_rtsp.goAdded+91
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_srt.goAdded+165
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/api_webrtc.goAdded+63
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/defs.goAdded+2
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path.goAdded+122
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/path_access_request.goAdded+45
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/publisher.goAdded+7
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/reader.goAdded+7
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/source.goAdded+46
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/defs/static_source.goAdded+15
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper.goAdded+79
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/errordumper/dumper_test.goAdded+43
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd.goAdded+95
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os.goAdded+66
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_os_windows.goAdded+141
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/cmd_test.goAdded+44
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/externalcmd/pool.goAdded+19
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label.goAdded+133
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/formatlabel/label_test.goAdded+90
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/hooks.goAdded+2
fall-down-detection/kamera_yayin_sistemi/mediamtx_bin/mediamtx-main/internal/hooks/on_connect.goAdded+68