fix: 恢复MediaMTX按需媒体路径 (#54)

This commit is contained in:
QiuSW
2026-08-13 22:03:19 +08:00
parent 6c6a2454d7
commit d7cd3a5d56
7 changed files with 184 additions and 7 deletions
@@ -20,6 +20,7 @@ type Source struct {
}
type PathStatus struct {
Name string `json:"name"`
Exists bool `json:"exists"`
Ready bool `json:"ready"`
Readers int `json:"readers"`
BytesReceived int64 `json:"bytes_received"`
@@ -46,7 +47,15 @@ func (c *HTTPController) Apply(ctx context.Context, source Source) error {
}
payload := map[string]any{"source": parsed.String(), "sourceOnDemand": true, "rtspTransport": "tcp"}
data, _ := json.Marshal(payload)
endpoint := c.base + "/v3/config/paths/replace/" + url.PathEscape(source.Path)
configured, err := c.configured(ctx, source.Path)
if err != nil {
return err
}
action := "add"
if configured {
action = "replace"
}
endpoint := c.base + "/v3/config/paths/" + action + "/" + url.PathEscape(source.Path)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(data))
if err != nil {
return err
@@ -63,6 +72,39 @@ func (c *HTTPController) Apply(ctx context.Context, source Source) error {
}
return nil
}
func (c *HTTPController) configured(ctx context.Context, path string) (bool, error) {
endpoint := c.base + "/v3/config/paths/get/" + url.PathEscape(path)
deadline := time.Now().Add(5 * time.Second)
var res *http.Response
for {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return false, err
}
res, err = c.client.Do(req)
if err == nil {
break
}
if !time.Now().Before(deadline) {
return false, fmt.Errorf("mediamtx control unavailable: %w", err)
}
select {
case <-ctx.Done():
return false, ctx.Err()
case <-time.After(100 * time.Millisecond):
}
}
defer res.Body.Close()
io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20))
if res.StatusCode == http.StatusNotFound {
return false, nil
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return false, fmt.Errorf("mediamtx config lookup returned %d", res.StatusCode)
}
return true, nil
}
func (c *HTTPController) Status(ctx context.Context, path string) (PathStatus, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.base+"/v3/paths/get/"+url.PathEscape(path), nil)
if err != nil {
@@ -74,7 +116,7 @@ func (c *HTTPController) Status(ctx context.Context, path string) (PathStatus, e
}
defer res.Body.Close()
if res.StatusCode == http.StatusNotFound {
return PathStatus{Name: path}, nil
return PathStatus{Name: path, Exists: false}, nil
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return PathStatus{}, fmt.Errorf("mediamtx status returned %d", res.StatusCode)
@@ -88,5 +130,5 @@ func (c *HTTPController) Status(ctx context.Context, path string) (PathStatus, e
if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&raw); err != nil {
return PathStatus{}, err
}
return PathStatus{Name: raw.Name, Ready: raw.Ready, Readers: len(raw.Readers), BytesReceived: raw.BytesReceived}, nil
return PathStatus{Name: raw.Name, Exists: true, Ready: raw.Ready, Readers: len(raw.Readers), BytesReceived: raw.BytesReceived}, nil
}
@@ -3,18 +3,30 @@ package mediamtx
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { return f(request) }
func TestApplyBuildsCredentialSourceOnlyInTransientBody(t *testing.T) {
var body map[string]any
var appliedPath string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.String(), "password") {
t.Fatal("credential leaked in control URL")
}
if r.Method == http.MethodGet {
http.NotFound(w, r)
return
}
appliedPath = r.URL.Path
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatal(err)
}
@@ -28,6 +40,50 @@ func TestApplyBuildsCredentialSourceOnlyInTransientBody(t *testing.T) {
if body["source"] != "rtsp://fixture-user:fixture-password@camera.invalid/main" {
t.Fatalf("body=%#v", body)
}
if appliedPath != "/v3/config/paths/add/sense_test" {
t.Fatalf("applied path = %q", appliedPath)
}
}
func TestApplyReplacesExistingPath(t *testing.T) {
var appliedPath string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
w.WriteHeader(http.StatusOK)
return
}
appliedPath = r.URL.Path
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
if err := NewHTTPController(server.URL).Apply(context.Background(), Source{Path: "sense_test", URI: "rtsp://camera.invalid/main"}); err != nil {
t.Fatal(err)
}
if appliedPath != "/v3/config/paths/replace/sense_test" {
t.Fatalf("applied path = %q", appliedPath)
}
}
func TestApplyWaitsForNewlyStartedControlAPI(t *testing.T) {
attempts := 0
client := NewHTTPController("http://127.0.0.1:9997")
client.client.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
attempts++
if attempts < 3 {
return nil, errors.New("connection refused")
}
status := http.StatusNotFound
if request.Method == http.MethodPost {
status = http.StatusOK
}
return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader("")), Header: make(http.Header)}, nil
})
if err := client.Apply(context.Background(), Source{Path: "sense_test", URI: "rtsp://camera.invalid/main"}); err != nil {
t.Fatal(err)
}
if attempts != 4 {
t.Fatalf("attempts = %d", attempts)
}
}
func TestApplyRejectsCredentialURI(t *testing.T) {
client := NewHTTPController("http://127.0.0.1")