Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
Decouple the streaming engine from core config and ingest (#4984)
Gabe Kangas8254f203b213
diff --git a/config/config.go b/config/config.goindex 6462edb341..d04ae92e90 100644--- a/config/config.go+++ b/config/config.go@@ -42,6 +42,13 @@ type Config struct {// listener and read by the transcoder when it spins up.InternalHLSListenerPort string+ // InternalHLSListenerHost is the interface the in-process HLS receiver+ // binds to, and the host the transcoder's ffmpeg PUTs finished segments+ // to. Defaults to 127.0.0.1, where receiver and transcoder share one+ // box. A remote-engine deployment that PUTs HLS across the network sets+ // this to a reachable interface.+ InternalHLSListenerHost string+// EnableDebugFeatures prints additional data to help in debugging.EnableDebugFeatures bool@@ -66,6 +73,7 @@ func NewDefault() *Config {WebServerPort: 8080,WebServerIP: "0.0.0.0",InternalHLSListenerPort: "8927",+ InternalHLSListenerHost: "127.0.0.1",EnableDebugFeatures: false,TemporaryStreamKey: "",// FollowerValidationInterval defaults to 0; consumers use theirdiff --git a/config/defaults.go b/config/defaults.goindex d49879966a..72e9dffd4c 100644--- a/config/defaults.go+++ b/config/defaults.go@@ -4,7 +4,6 @@ import ("time""github.com/owncast/owncast/models"- "github.com/owncast/owncast/webserver/handlers/generated")// Defaults will hold default configuration values.@@ -26,7 +25,7 @@ type Defaults struct {WebServerIP stringName stringAdminPassword string- StreamKeys []generated.StreamKey+ StreamKeys []models.StreamKeyStreamVariants []models.StreamOutputVariant@@ -53,7 +52,7 @@ func GetDefaults() Defaults {ServerWelcomeMessage: "",Logo: "logo.svg",AdminPassword: "abc123",- StreamKeys: []generated.StreamKey{+ StreamKeys: []models.StreamKey{{Key: &defaultStreamKey, Comment: &defaultStreamKeyComment},},Tags: []string{diff --git a/models/engineConfig.go b/models/engineConfig.gonew file mode 100644index 0000000000..dea5149e2b--- /dev/null+++ b/models/engineConfig.go@@ -0,0 +1,22 @@+package models++// EngineConfig is the read-only configuration surface consumed by the+// streaming engine packages (rtmp, transcoder, storage). It is the narrow+// seam that lets those packages run outside the core process without linking+// the database-backed configuration repository: the core's ConfigRepository+// satisfies it structurally, while a remote engine satisfies it from a pulled+// config snapshot.+//+// Keep this list to exactly the values the engine packages read. Widening it+// re-couples the engine to core internals.+type EngineConfig interface {+ GetRTMPPortNumber() int+ GetRTMPBindAddress() string+ GetFfMpegPath() string+ GetVideoCodec() string+ GetS3Config() S3+ GetStreamLatencyLevel() LatencyLevel+ GetStreamOutputVariants() []StreamOutputVariant+ GetVideoServingEndpoint() string+ GetStreamKeys() []StreamKey+}diff --git a/models/streamKey.go b/models/streamKey.gonew file mode 100644index 0000000000..0cd826ece4--- /dev/null+++ b/models/streamKey.go@@ -0,0 +1,10 @@+package models++// StreamKey is a valid RTMP stream key plus an optional human-readable+// comment. It is the domain type used throughout config storage and the+// streaming engine. The web layer has its own generated wire type with an+// identical JSON shape; convert at the HTTP edge.+type StreamKey struct {+ Comment *string `json:"comment,omitempty"`+ Key *string `json:"key,omitempty"`+}diff --git a/models/streamKey_test.go b/models/streamKey_test.gonew file mode 100644index 0000000000..ddd4dd839d--- /dev/null+++ b/models/streamKey_test.go@@ -0,0 +1,71 @@+package models++import (+ "encoding/json"+ "testing"+)++func strptr(s string) *string { return &s }++// TestStreamKeyJSONStability locks the on-the-wire / on-disk JSON shape of a+// StreamKey. Stream keys are persisted in the datastore and returned over the+// admin API with this exact shape; a tag change here would make existing+// installs' stored keys unreadable and break the admin client.+func TestStreamKeyJSONStability(t *testing.T) {+ cases := []struct {+ name string+ in StreamKey+ want string+ }{+ {+ name: "key and comment",+ in: StreamKey{Key: strptr("abc123"), Comment: strptr("main key")},+ want: `{"comment":"main key","key":"abc123"}`,+ },+ {+ name: "key only omits comment",+ in: StreamKey{Key: strptr("abc123")},+ want: `{"key":"abc123"}`,+ },+ {+ name: "empty omits all",+ in: StreamKey{},+ want: `{}`,+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got, err := json.Marshal(tc.in)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ if string(got) != tc.want {+ t.Errorf("StreamKey JSON changed.\n got: %s\nwant: %s", got, tc.want)+ }+ })+ }+}++// TestStreamKeyRoundTrip proves a persisted blob decodes back into the same+// fields, i.e. keys written by an older build still load.+func TestStreamKeyRoundTrip(t *testing.T) {+ stored := `[{"key":"k1","comment":"first"},{"key":"k2"}]`++ var keys []StreamKey+ if err := json.Unmarshal([]byte(stored), &keys); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ if len(keys) != 2 {+ t.Fatalf("expected 2 keys, got %d", len(keys))+ }+ if keys[0].Key == nil || *keys[0].Key != "k1" {+ t.Errorf("keys[0].Key = %v, want k1", keys[0].Key)+ }+ if keys[0].Comment == nil || *keys[0].Comment != "first" {+ t.Errorf("keys[0].Comment = %v, want first", keys[0].Comment)+ }+ if keys[1].Comment != nil {+ t.Errorf("keys[1].Comment = %v, want nil", keys[1].Comment)+ }+}diff --git a/persistence/configrepository/configMigrations.go b/persistence/configrepository/configMigrations.goindex 3aa9aac26c..70b33a92db 100644--- a/persistence/configrepository/configMigrations.go+++ b/persistence/configrepository/configMigrations.go@@ -5,8 +5,8 @@ import (log "github.com/sirupsen/logrus"+ "github.com/owncast/owncast/models""github.com/owncast/owncast/services/datastore"- "github.com/owncast/owncast/webserver/handlers/generated")const (@@ -65,7 +65,7 @@ func migrateToDatastoreValues2(datastore *datastore.Datastore, configRepository// Avoids double hashing the password_ = datastore.SetString("admin_password_key", oldAdminPassword)comment := "Default stream key"- _ = configRepository.SetStreamKeys([]generated.StreamKey{+ _ = configRepository.SetStreamKeys([]models.StreamKey{{Key: &oldAdminPassword, Comment: &comment},})}diff --git a/persistence/configrepository/configrepository.go b/persistence/configrepository/configrepository.goindex 23280e134c..5aad1aafb3 100644--- a/persistence/configrepository/configrepository.go+++ b/persistence/configrepository/configrepository.go@@ -5,7 +5,6 @@ import ("github.com/owncast/owncast/models""github.com/owncast/owncast/utils"- "github.com/owncast/owncast/webserver/handlers/generated")type ConfigRepository interface {@@ -121,8 +120,8 @@ type ConfigRepository interface {SetCustomOfflineMessage(message string) errorSetCustomColorVariableValues(variables map[string]string) errorGetCustomColorVariableValues() map[string]string- GetStreamKeys() []generated.StreamKey- SetStreamKeys(actions []generated.StreamKey) error+ GetStreamKeys() []models.StreamKey+ SetStreamKeys(actions []models.StreamKey) errorSetDisableSearchIndexing(disableSearchIndexing bool) errorGetDisableSearchIndexing() boolGetVideoServingEndpoint() stringdiff --git a/persistence/configrepository/engineConfig.go b/persistence/configrepository/engineConfig.gonew file mode 100644index 0000000000..98dc3db039--- /dev/null+++ b/persistence/configrepository/engineConfig.go@@ -0,0 +1,14 @@+package configrepository++import "github.com/owncast/owncast/models"++// Compile-time guarantee that the production config repository satisfies the+// narrow models.EngineConfig surface the streaming engine packages (rtmp,+// transcoder, storage) consume. This structural coupling is what lets those+// packages run without the database-backed repository. If one of the nine+// engine getters is renamed, removed, or its signature drifts, the build fails+// here with a clear message instead of deep inside service wiring.+var (+ _ models.EngineConfig = ConfigRepository(nil)+ _ models.EngineConfig = (*SqlConfigRepository)(nil)+)diff --git a/persistence/configrepository/sqlconfigrepository.go b/persistence/configrepository/sqlconfigrepository.goindex b196033997..6346bbc8d2 100644--- a/persistence/configrepository/sqlconfigrepository.go+++ b/persistence/configrepository/sqlconfigrepository.go@@ -15,7 +15,6 @@ import ("github.com/owncast/owncast/services/datastore""github.com/owncast/owncast/static""github.com/owncast/owncast/utils"- "github.com/owncast/owncast/webserver/handlers/generated")type SqlConfigRepository struct {@@ -1010,22 +1009,22 @@ func (r *SqlConfigRepository) GetCustomColorVariableValues() map[string]string {}// GetStreamKeys will return valid stream keys.-func (r *SqlConfigRepository) GetStreamKeys() []generated.StreamKey {+func (r *SqlConfigRepository) GetStreamKeys() []models.StreamKey {configEntry, err := r.datastore.Get(streamKeysKey)if err != nil {- return []generated.StreamKey{}+ return []models.StreamKey{}}- var streamKeys []generated.StreamKey+ var streamKeys []models.StreamKeyif err := configEntry.GetObject(&streamKeys); err != nil {- return []generated.StreamKey{}+ return []models.StreamKey{}}return streamKeys}// SetStreamKeys will set valid stream keys.-func (r *SqlConfigRepository) SetStreamKeys(actions []generated.StreamKey) error {+func (r *SqlConfigRepository) SetStreamKeys(actions []models.StreamKey) error {configEntry := models.ConfigEntry{Key: streamKeysKey, Value: actions}return r.datastore.Save(configEntry)}diff --git a/services/rtmp/rtmp.go b/services/rtmp/rtmp.goindex 573e82bde2..35aeaf2d54 100644--- a/services/rtmp/rtmp.go+++ b/services/rtmp/rtmp.go@@ -12,7 +12,6 @@ import (log "github.com/sirupsen/logrus""github.com/owncast/owncast/models"- "github.com/owncast/owncast/webserver/handlers/generated")// Start binds the RTMP listener and runs the accept loop. Blocks until@@ -71,7 +70,7 @@ func (s *Service) handleConn(c *rtmp.Conn, nc net.Conn) {// If a stream key override was specified then use that instead.if s.cfg.TemporaryStreamKey != "" {- validStreamingKeys = []generated.StreamKey{{Key: &s.cfg.TemporaryStreamKey}}+ validStreamingKeys = []models.StreamKey{{Key: &s.cfg.TemporaryStreamKey}}}for _, key := range validStreamingKeys {diff --git a/services/rtmp/service.go b/services/rtmp/service.goindex 1604110663..1b5aea309e 100644--- a/services/rtmp/service.go+++ b/services/rtmp/service.go@@ -13,7 +13,6 @@ import ("github.com/owncast/owncast/config""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository")// Service owns the RTMP listener and the single in-flight inbound@@ -44,7 +43,7 @@ type Service struct {// configRepository is consulted at listener bind for the RTMP port and at// connect time for the list of valid stream keys.- configRepository configrepository.ConfigRepository+ configRepository models.EngineConfig// cfg supplies the optional temporary stream key override set at// startup via the --streamkey CLI flag.@@ -53,7 +52,7 @@ type Service struct {// Deps is the explicit dependency contract for the RTMP service.type Deps struct {- ConfigRepository configrepository.ConfigRepository+ ConfigRepository models.EngineConfigConfig *config.Config}diff --git a/services/storage/engineConfig_test.go b/services/storage/engineConfig_test.gonew file mode 100644index 0000000000..1bf174a159--- /dev/null+++ b/services/storage/engineConfig_test.go@@ -0,0 +1,43 @@+package storage++import (+ "testing"++ "github.com/owncast/owncast/models"+)++// fakeEngineConfig is a database-free models.EngineConfig. Its existence is the+// point of the EngineConfig refactor: the storage providers (and the rtmp /+// transcoder packages) now depend only on this narrow read-only surface, so+// they can be constructed without a config repository or datastore.+type fakeEngineConfig struct {+ servingEndpoint string+ s3 models.S3+}++func (f fakeEngineConfig) GetRTMPPortNumber() int { return 1935 }+func (f fakeEngineConfig) GetRTMPBindAddress() string { return "0.0.0.0" }+func (f fakeEngineConfig) GetFfMpegPath() string { return "ffmpeg" }+func (f fakeEngineConfig) GetVideoCodec() string { return "libx264" }+func (f fakeEngineConfig) GetS3Config() models.S3 { return f.s3 }+func (f fakeEngineConfig) GetStreamLatencyLevel() models.LatencyLevel {+ return models.GetLatencyLevel(2)+}+func (f fakeEngineConfig) GetStreamOutputVariants() []models.StreamOutputVariant { return nil }+func (f fakeEngineConfig) GetVideoServingEndpoint() string { return f.servingEndpoint }+func (f fakeEngineConfig) GetStreamKeys() []models.StreamKey { return nil }++var _ models.EngineConfig = fakeEngineConfig{}++// TestLocalStorageBuildsFromEngineConfig proves a storage provider can be+// constructed and set up from a plain EngineConfig with no database behind it,+// and that it reads the configured serving endpoint through the interface.+func TestLocalStorageBuildsFromEngineConfig(t *testing.T) {+ s := NewLocalStorage(fakeEngineConfig{servingEndpoint: "https://cdn.example/"})+ if err := s.Setup(); err != nil {+ t.Fatalf("Setup: %v", err)+ }+ if s.host != "https://cdn.example/" {+ t.Errorf("host = %q, want %q", s.host, "https://cdn.example/")+ }+}diff --git a/services/storage/local.go b/services/storage/local.goindex dc07d431bc..1247e77d86 100644--- a/services/storage/local.go+++ b/services/storage/local.go@@ -7,17 +7,17 @@ import (log "github.com/sirupsen/logrus"- "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/models")// LocalStorage represents an instance of the local storage provider for HLS video.type LocalStorage struct {host string- configRepository configrepository.ConfigRepository+ configRepository models.EngineConfig}// NewLocalStorage returns a new LocalStorage instance.-func NewLocalStorage(configRepository configrepository.ConfigRepository) *LocalStorage {+func NewLocalStorage(configRepository models.EngineConfig) *LocalStorage {return &LocalStorage{configRepository: configRepository}}diff --git a/services/storage/s3Storage.go b/services/storage/s3Storage.goindex 37b9cd4477..4181909e06 100644--- a/services/storage/s3Storage.go+++ b/services/storage/s3Storage.go@@ -16,7 +16,7 @@ import ("github.com/pkg/errors"log "github.com/sirupsen/logrus"- "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/models""github.com/owncast/owncast/utils""github.com/aws/aws-sdk-go-v2/aws"@@ -49,7 +49,7 @@ type S3Storage struct {lock sync.Mutex- configRepository configrepository.ConfigRepository+ configRepository models.EngineConfigperformanceTracker *utils.PerformanceTracker@@ -57,7 +57,7 @@ type S3Storage struct {}// NewS3Storage returns a new S3Storage instance.-func NewS3Storage(configRepository configrepository.ConfigRepository) *S3Storage {+func NewS3Storage(configRepository models.EngineConfig) *S3Storage {return &S3Storage{queuedPlaylistUpdates: make(map[string]string),lock: sync.Mutex{},diff --git a/services/stream/engine.go b/services/stream/engine.gonew file mode 100644index 0000000000..87dd6781bc--- /dev/null+++ b/services/stream/engine.go@@ -0,0 +1,72 @@+package stream++import (+ "io"++ "github.com/owncast/owncast/models"+)++// StreamEngine drives broadcaster ingest and transcoding. The local+// implementation runs RTMP ingest plus ffmpeg in-process (today's behavior);+// a future remote implementation manages a separate engine process. Core+// holds a StreamEngine and reacts to what it reports through StreamEvents, so+// core never needs to know where ingest and transcoding actually happen.+type StreamEngine interface {+ // Start begins accepting an inbound broadcast.+ Start() error+ // Stop force-disconnects any inbound broadcast and tears the engine down.+ Stop() error+}++// StreamEvents are the always-on, core-side reactions an engine drives as a+// broadcast comes and goes. The local engine triggers these in-process; a+// remote engine will call the same methods from its signaling channel, so+// core's handling of a stream going live/offline is identical regardless of+// where ingest happened.+type StreamEvents interface {+ // StreamConnected reports a broadcast going live, carrying the settings+ // it is being transcoded with.+ StreamConnected(broadcast *models.CurrentBroadcast)+ // BroadcasterSet reports the inbound source's metadata (codec, etc.).+ BroadcasterSet(broadcaster models.Broadcaster)+ // StreamDisconnected reports the broadcast ending. err is the transcode+ // exit cause if any, nil for a clean end.+ StreamDisconnected(err error)+}++// Compile-time guarantees for the local wiring.+var (+ _ StreamEngine = (*localStreamEngine)(nil)+ _ StreamEvents = (*Service)(nil)+)++// rtmpListener is the slice of the RTMP service the local engine drives.+// Keeping it an interface (which *rtmp.Service satisfies structurally) lets+// the engine be exercised without binding a real socket.+type rtmpListener interface {+ Start(onConnect func(*io.PipeReader), onBroadcaster func(models.Broadcaster))+ Disconnect()+}++// localStreamEngine is the in-process engine: it binds the RTMP listener and+// hands each inbound connection to the stream service's connect handler, which+// spins up the transcoder. This is today's single-process path expressed+// behind the StreamEngine seam; a remote engine replaces it in a later release.+type localStreamEngine struct {+ rtmp rtmpListener+ onConnect func(*io.PipeReader)+ onBroadcaster func(models.Broadcaster)+}++// Start binds the RTMP listener and begins accepting connections. The accept+// loop runs in its own goroutine, matching the prior inline behavior.+func (e *localStreamEngine) Start() error {+ go e.rtmp.Start(e.onConnect, e.onBroadcaster)+ return nil+}++// Stop force-disconnects the current inbound broadcaster, if any.+func (e *localStreamEngine) Stop() error {+ e.rtmp.Disconnect()+ return nil+}diff --git a/services/stream/engine_test.go b/services/stream/engine_test.gonew file mode 100644index 0000000000..9cb3f99219--- /dev/null+++ b/services/stream/engine_test.go@@ -0,0 +1,112 @@+package stream++import (+ "io"+ "testing"+ "time"++ "github.com/owncast/owncast/models"+)++// fakeRTMP is a stand-in for *rtmp.Service that records how the local engine+// drives it, without binding a real socket.+type fakeRTMP struct {+ started chan struct{}+ onConnect func(*io.PipeReader)+ onBroadcaster func(models.Broadcaster)+ disconnected bool+}++func (f *fakeRTMP) Start(onConnect func(*io.PipeReader), onBroadcaster func(models.Broadcaster)) {+ f.onConnect = onConnect+ f.onBroadcaster = onBroadcaster+ close(f.started)+}++func (f *fakeRTMP) Disconnect() { f.disconnected = true }++var _ rtmpListener = (*fakeRTMP)(nil)++// TestLocalStreamEngineDrivesRTMP proves the local engine starts ingest by+// delegating to the RTMP listener with the service's own callbacks, and tears+// down by disconnecting it.+func TestLocalStreamEngineDrivesRTMP(t *testing.T) {+ f := &fakeRTMP{started: make(chan struct{})}++ connectCalled := false+ broadcasterCalled := false+ e := &localStreamEngine{+ rtmp: f,+ onConnect: func(*io.PipeReader) { connectCalled = true },+ onBroadcaster: func(models.Broadcaster) { broadcasterCalled = true },+ }++ if err := e.Start(); err != nil {+ t.Fatalf("Start: %v", err)+ }++ select {+ case <-f.started:+ case <-time.After(2 * time.Second):+ t.Fatal("engine never started the RTMP listener")+ }++ // The listener must have received the engine's own callbacks verbatim.+ f.onConnect(nil)+ f.onBroadcaster(models.Broadcaster{})+ if !connectCalled {+ t.Error("engine did not wire onConnect through to the listener")+ }+ if !broadcasterCalled {+ t.Error("engine did not wire onBroadcaster through to the listener")+ }++ if err := e.Stop(); err != nil {+ t.Fatalf("Stop: %v", err)+ }+ if !f.disconnected {+ t.Error("Stop did not disconnect the RTMP listener")+ }+}++// TestBroadcasterSetRecordsMetadata proves BroadcasterSet (a StreamEvents+// method) records the inbound metadata that the hot status read returns, with+// no other service dependencies wired.+func TestBroadcasterSetRecordsMetadata(t *testing.T) {+ s := &Service{}+ if s.GetBroadcaster() != nil {+ t.Fatal("expected no broadcaster before any stream")+ }++ s.BroadcasterSet(models.Broadcaster{+ RemoteAddr: "1.2.3.4",+ Time: time.Now(),+ StreamDetails: models.InboundStreamDetails{VideoCodec: "H.264"},+ })++ got := s.GetBroadcaster()+ if got == nil {+ t.Fatal("expected a broadcaster after BroadcasterSet")+ }+ if got.RemoteAddr != "1.2.3.4" {+ t.Errorf("RemoteAddr = %q, want 1.2.3.4", got.RemoteAddr)+ }+ if got.StreamDetails.VideoCodec != "H.264" {+ t.Errorf("VideoCodec = %q, want H.264", got.StreamDetails.VideoCodec)+ }+}++// TestGetCurrentBroadcast proves the in-flight broadcast settings recorded on+// connect are returned to the hot read path.+func TestGetCurrentBroadcast(t *testing.T) {+ s := &Service{}+ if s.GetCurrentBroadcast() != nil {+ t.Fatal("expected no current broadcast before any stream")+ }++ bc := &models.CurrentBroadcast{LatencyLevel: models.GetLatencyLevel(2)}+ s.currentBroadcast = bc+ if s.GetCurrentBroadcast() != bc {+ t.Error("GetCurrentBroadcast did not return the recorded broadcast")+ }+}diff --git a/services/stream/service.go b/services/stream/service.goindex 2d6a73345d..cc9be823bd 100644--- a/services/stream/service.go+++ b/services/stream/service.go@@ -116,6 +116,10 @@ type Service struct {// debug flag) shared with transcoder/thumbnail children spawned by// the stream lifecycle.cfg *config.Config++ // engine drives broadcaster ingest + transcoding. The local engine runs+ // it in-process; lifecycle is reported back via the StreamEvents methods.+ engine StreamEngine}// Deps is the explicit-dependency contract the service requires at@@ -134,7 +138,7 @@ type Deps struct {// New constructs an idle stream Service. Call Start(ctx) to bring up the// storage backend, transcoder, RTMP listener, and associated lifecycle.func New(deps Deps) *Service {- return &Service{+ s := &Service{geoIPClient: geoip.NewClient(),fileWriter: transcoder.NewFileWriterReceiverService(deps.Config),rtmp: deps.Rtmp,@@ -146,4 +150,12 @@ func New(deps Deps) *Service {configRepository: deps.ConfigRepository,cfg: deps.Config,}+ // The local engine binds the in-process RTMP listener and routes inbound+ // connections back through the service's StreamEvents handlers.+ s.engine = &localStreamEngine{+ rtmp: deps.Rtmp,+ onConnect: s.setStreamAsConnected,+ onBroadcaster: s.BroadcasterSet,+ }+ return s}diff --git a/services/stream/status.go b/services/stream/status.goindex a56ad6a897..2421465492 100644--- a/services/stream/status.go+++ b/services/stream/status.go@@ -35,9 +35,10 @@ func (s *Service) GetCurrentBroadcast() *models.CurrentBroadcast {return s.currentBroadcast}-// setBroadcaster records the metadata of the inbound RTMP source. Called-// by the RTMP server's on-connect callback.-func (s *Service) setBroadcaster(broadcaster models.Broadcaster) {+// BroadcasterSet records the metadata of the inbound source. Implements+// StreamEvents; the local engine calls it from the RTMP metadata callback, a+// remote engine from its signaling channel.+func (s *Service) BroadcasterSet(broadcaster models.Broadcaster) {s.broadcaster = &broadcaster}diff --git a/services/stream/stream.go b/services/stream/stream.goindex 56f6c2713f..ba2c7821b1 100644--- a/services/stream/stream.go+++ b/services/stream/stream.go@@ -53,8 +53,12 @@ func (s *Service) Start(_ context.Context) error {log.Errorln(err)}- // start the rtmp server- go s.rtmp.Start(s.setStreamAsConnected, s.setBroadcaster)+ // Begin accepting an inbound broadcast through the stream engine. The+ // local engine binds the in-process RTMP listener; lifecycle is reported+ // back to this service via the StreamEvents methods.+ if err := s.engine.Start(); err != nil {+ return err+ }rtmpPort := s.configRepository.GetRTMPPortNumber()if rtmpPort != 1935 {@@ -127,19 +131,53 @@ func (s *Service) resetDirectories() {}}-// setStreamAsConnected is the RTMP server's on-connect callback.+// setStreamAsConnected is the local engine's RTMP on-connect callback. It+// reports the broadcast online (StreamConnected) and then spins up the+// in-process transcoder + thumbnail generator fed by the inbound RTMP pipe.func (s *Service) setStreamAsConnected(rtmpOut *io.PipeReader) {+ broadcast := &models.CurrentBroadcast{+ LatencyLevel: s.configRepository.GetStreamLatencyLevel(),+ OutputSettings: s.configRepository.GetStreamOutputVariants(),+ }+ s.StreamConnected(broadcast)++ segmentPath := config.HLSStoragePath++ go func() {+ s.transcoder = transcoder.NewTranscoder(s.cfg, s.configRepository)+ s.transcoder.TranscoderCompleted = func(err error) {+ s.StreamDisconnected(err)+ s.transcoder = nil+ }+ s.transcoder.SetStdin(rtmpOut)+ s.transcoder.Start(true)+ }()++ selectedThumbnailVideoQualityIndex, isVideoPassthrough := s.configRepository.FindHighestVideoQualityIndex(broadcast.OutputSettings)+ s.thumbnailGen = transcoder.NewThumbnailGenerator(s.cfg, s.configRepository)+ s.thumbnailGen.Start(segmentPath, selectedThumbnailVideoQualityIndex, isVideoPassthrough)+}++// StreamConnected records a broadcast going live and runs the always-on+// go-live side effects. Implements StreamEvents; the local engine calls it+// in-process, a remote engine over its signaling channel.+func (s *Service) StreamConnected(broadcast *models.CurrentBroadcast) {+ s.currentBroadcast = broadcast+ s.applyStreamOnline()+}++// applyStreamOnline runs the always-on side effects of a stream going live:+// stats, cleanup/notification timers, storage setup, and the chat / webhook /+// federation go-live announcements. It deliberately excludes the transcoder+// and thumbnail pipeline (engine work), so a remote engine can drive just+// these reactions through StreamConnected.+func (s *Service) applyStreamOnline() {now := utils.NullTime{Time: time.Now(), Valid: true}s.stats.StreamConnected = trues.stats.LastDisconnectTime = nils.stats.LastConnectTime = &nows.stats.SessionMaxViewerCount = 0- s.currentBroadcast = &models.CurrentBroadcast{- LatencyLevel: s.configRepository.GetStreamLatencyLevel(),- OutputSettings: s.configRepository.GetStreamOutputVariants(),- }-s.StopOfflineCleanupTimer()s.startOnlineCleanupTimer()@@ -147,27 +185,11 @@ func (s *Service) setStreamAsConnected(rtmpOut *io.PipeReader) {go s.yp.Start()}- segmentPath := config.HLSStoragePath-if err := s.setupStorage(); err != nil {log.Fatalln("failed to setup the storage", err)}- go func() {- s.transcoder = transcoder.NewTranscoder(s.cfg, s.configRepository)- s.transcoder.TranscoderCompleted = func(error) {- s.SetStreamAsDisconnected()- s.transcoder = nil- s.currentBroadcast = nil- }- s.transcoder.SetStdin(rtmpOut)- s.transcoder.Start(true)- }()-go s.webhooks.SendStreamStatusEvent(models.StreamStarted)- selectedThumbnailVideoQualityIndex, isVideoPassthrough := s.configRepository.FindHighestVideoQualityIndex(s.currentBroadcast.OutputSettings)- s.thumbnailGen = transcoder.NewThumbnailGenerator(s.cfg, s.configRepository)- s.thumbnailGen.Start(segmentPath, selectedThumbnailVideoQualityIndex, isVideoPassthrough)_ = s.chat.SendSystemAction("Stay tuned, the stream is **starting**!", true)s.chat.SendAllWelcomeMessage()@@ -187,8 +209,16 @@ func (s *Service) setStreamAsConnected(rtmpOut *io.PipeReader) {}}-// SetStreamAsDisconnected handles cleanup when a live stream ends.-func (s *Service) SetStreamAsDisconnected() {+// StreamDisconnected records a broadcast ending and clears the in-flight+// broadcast settings. Implements StreamEvents; the local engine calls it when+// the transcoder exits, a remote engine when its stream goes offline.+func (s *Service) StreamDisconnected(_ error) {+ s.applyStreamOffline()+ s.currentBroadcast = nil+}++// applyStreamOffline handles the always-on cleanup when a live stream ends.+func (s *Service) applyStreamOffline() {_ = s.chat.SendSystemAction("The stream is ending.", true)now := utils.NullTime{Time: time.Now(), Valid: true}diff --git a/services/transcoder/fileWriterReceiverService.go b/services/transcoder/fileWriterReceiverService.goindex b803fc9591..c52fda432d 100644--- a/services/transcoder/fileWriterReceiverService.go+++ b/services/transcoder/fileWriterReceiverService.go@@ -46,14 +46,21 @@ func (s *FileWriterReceiverService) SetupFileWriterReceiverService(callbacks FilhttpServer := http.NewServeMux()httpServer.HandleFunc("/", s.uploadHandler)- localListenerAddress := "127.0.0.1:0"+ host := s.cfg.InternalHLSListenerHost+ if host == "" {+ host = "127.0.0.1"+ }+ localListenerAddress := net.JoinHostPort(host, "0")listener, err := net.Listen("tcp", localListenerAddress)if err != nil {log.Fatalln("Unable to start internal video writing service", err)}- listenerPort := strings.Split(listener.Addr().String(), ":")[1]+ _, listenerPort, err := net.SplitHostPort(listener.Addr().String())+ if err != nil {+ log.Fatalln("Unable to determine internal video writing service port", err)+ }s.cfg.InternalHLSListenerPort = listenerPortlog.Traceln("Transcoder response service listening on: " + listenerPort)go func() {diff --git a/services/transcoder/listenerHost_test.go b/services/transcoder/listenerHost_test.gonew file mode 100644index 0000000000..892492c62d--- /dev/null+++ b/services/transcoder/listenerHost_test.go@@ -0,0 +1,60 @@+package transcoder++import (+ "path/filepath"+ "strings"+ "testing"++ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/models"+)++func newTestTranscoder() *Transcoder {+ tr := new(Transcoder)+ tr.cfg = &config.Config{LogDirectory: "data/logs"}+ tr.ffmpegPath = filepath.Join("fake", "path", "ffmpeg")+ tr.SetInput("fake.flv")+ tr.SetOutputPath("fakeOutput")+ tr.SetIdentifier("test")+ tr.SetInternalHTTPPort("8123")+ codec := Libx264Codec{}+ tr.SetCodec(codec.Name())+ tr.currentLatencyLevel = models.GetLatencyLevel(2)++ v := HLSVariant{}+ v.videoBitrate = 1200+ v.isAudioPassthrough = true+ v.SetVideoFramerate(30)+ v.SetCPUUsageLevel(2)+ tr.AddVariant(v)+ return tr+}++// TestTranscoderListenerHost proves the ffmpeg HLS PUT target follows the+// configured host: the historical 127.0.0.1 default when unset, an explicit+// address otherwise, and correctly bracketed IPv6. This is the knob the+// push-to-core (remote engine) topology needs.+func TestTranscoderListenerHost(t *testing.T) {+ cases := []struct {+ name string+ host string+ want string+ }{+ {"default when unset", "", "http://127.0.0.1:8123"},+ {"custom ipv4", "10.0.0.5", "http://10.0.0.5:8123"},+ {"ipv6 bracketed", "::1", "http://[::1]:8123"},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ tr := newTestTranscoder()+ if tc.host != "" {+ tr.SetInternalHTTPHost(tc.host)+ }+ cmd := tr.GetString()+ if !strings.Contains(cmd, tc.want) {+ t.Errorf("ffmpeg command missing PUT target %q.\ncommand: %s", tc.want, cmd)+ }+ })+ }+}diff --git a/services/transcoder/receiverHost_test.go b/services/transcoder/receiverHost_test.gonew file mode 100644index 0000000000..25b670ac82--- /dev/null+++ b/services/transcoder/receiverHost_test.go@@ -0,0 +1,49 @@+package transcoder++import (+ "net"+ "strconv"+ "testing"++ "github.com/owncast/owncast/config"+)++type noopReceiverCallbacks struct{}++func (noopReceiverCallbacks) SegmentWritten(string) {}+func (noopReceiverCallbacks) VariantPlaylistWritten(string) {}+func (noopReceiverCallbacks) MasterPlaylistWritten(string) {}++func assertNumericPort(t *testing.T, port string) {+ t.Helper()+ if port == "" {+ t.Fatal("listener port was not recorded")+ }+ if _, err := strconv.Atoi(port); err != nil {+ t.Errorf("listener port %q is not numeric: %v", port, err)+ }+}++// TestReceiverBindHost covers the configurable receiver bind. An empty host+// must fall back to loopback rather than binding every interface, and the+// chosen port must be parsed correctly even for a bracketed IPv6 listener+// address (the old strings.Split(":") parse returned an empty port there).+func TestReceiverBindHost(t *testing.T) {+ t.Run("empty host defaults to loopback and records the port", func(t *testing.T) {+ cfg := &config.Config{}+ NewFileWriterReceiverService(cfg).SetupFileWriterReceiverService(noopReceiverCallbacks{})+ assertNumericPort(t, cfg.InternalHLSListenerPort)+ })++ t.Run("ipv6 host records a numeric port", func(t *testing.T) {+ probe, err := net.Listen("tcp", "[::1]:0")+ if err != nil {+ t.Skip("no IPv6 loopback available")+ }+ _ = probe.Close()++ cfg := &config.Config{InternalHLSListenerHost: "::1"}+ NewFileWriterReceiverService(cfg).SetupFileWriterReceiverService(noopReceiverCallbacks{})+ assertNumericPort(t, cfg.InternalHLSListenerPort)+ })+}diff --git a/services/transcoder/thumbnailGenerator.go b/services/transcoder/thumbnailGenerator.goindex 78e188001b..a360e55cc7 100644--- a/services/transcoder/thumbnailGenerator.go+++ b/services/transcoder/thumbnailGenerator.go@@ -10,7 +10,7 @@ import (log "github.com/sirupsen/logrus""github.com/owncast/owncast/config"- "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/models""github.com/owncast/owncast/utils")@@ -20,11 +20,11 @@ import (type ThumbnailGenerator struct {timer *time.Tickercfg *config.Config- configRepository configrepository.ConfigRepository+ configRepository models.EngineConfig}// NewThumbnailGenerator returns an idle generator. Call Start to begin.-func NewThumbnailGenerator(cfg *config.Config, configRepository configrepository.ConfigRepository) *ThumbnailGenerator {+func NewThumbnailGenerator(cfg *config.Config, configRepository models.EngineConfig) *ThumbnailGenerator {return &ThumbnailGenerator{cfg: cfg, configRepository: configRepository}}diff --git a/services/transcoder/transcoder.go b/services/transcoder/transcoder.goindex e2e799769c..bf9d80d957 100644--- a/services/transcoder/transcoder.go+++ b/services/transcoder/transcoder.go@@ -4,6 +4,7 @@ import ("bufio""fmt""io"+ "net""os/exec""runtime""strconv"@@ -16,7 +17,6 @@ import ("github.com/owncast/owncast/config""github.com/owncast/owncast/logging""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/utils")@@ -44,7 +44,7 @@ type Transcoder struct {// configRepository provides ffmpeg path, latency level, output variants,// and codec selection consulted at Start.- configRepository configrepository.ConfigRepository+ configRepository models.EngineConfigstdin *io.PipeReader@@ -65,6 +65,7 @@ type Transcoder struct {ffmpegPath stringsegmentIdentifier stringinternalListenerPort string+ internalListenerHost stringinput stringsegmentOutputPath stringvariants []HLSVariant@@ -208,8 +209,11 @@ func (t *Transcoder) GetString() string {}func (t *Transcoder) getFlags() *execInfo {- port := t.internalListenerPort- localListenerAddress := "http://127.0.0.1:" + port+ host := t.internalListenerHost+ if host == "" {+ host = "127.0.0.1"+ }+ localListenerAddress := "http://" + net.JoinHostPort(host, t.internalListenerPort)hlsOptionFlags := []string{"program_date_time",@@ -329,7 +333,7 @@ func getVariantFromConfigQuality(quality models.StreamOutputVariant, index int)}// NewTranscoder will return a new Transcoder, populated by the config.-func NewTranscoder(cfg *config.Config, configRepository configrepository.ConfigRepository) *Transcoder {+func NewTranscoder(cfg *config.Config, configRepository models.EngineConfig) *Transcoder {ffmpegPath := utils.ValidatedFfmpegPath(configRepository.GetFfMpegPath())transcoder := new(Transcoder)@@ -337,6 +341,7 @@ func NewTranscoder(cfg *config.Config, configRepository configrepository.ConfigRtranscoder.configRepository = configRepositorytranscoder.ffmpegPath = ffmpegPathtranscoder.internalListenerPort = cfg.InternalHLSListenerPort+ transcoder.internalListenerHost = cfg.InternalHLSListenerHosttranscoder.currentStreamOutputSettings = configRepository.GetStreamOutputVariants()transcoder.currentLatencyLevel = configRepository.GetStreamLatencyLevel()@@ -518,6 +523,12 @@ func (t *Transcoder) SetInternalHTTPPort(port string) {t.internalListenerPort = port}+// SetInternalHTTPHost sets the host the transcoder PUTs finished HLS output+// to. Defaults to 127.0.0.1 when unset.+func (t *Transcoder) SetInternalHTTPHost(host string) {+ t.internalListenerHost = host+}+// SetCodec will set the codec to be used for the transocder.func (t *Transcoder) SetCodec(codecName string) {t.codec = getCodec(codecName)diff --git a/webserver/handlers/admin/config.go b/webserver/handlers/admin/config.goindex ebe69312a2..5f81e64677 100644--- a/webserver/handlers/admin/config.go+++ b/webserver/handlers/admin/config.go@@ -1058,15 +1058,17 @@ func (a *Admin) SetStreamKeys(w http.ResponseWriter, r *http.Request) {return}+ keys := make([]models.StreamKey, 0, len(*streamKeys.Value))for _, streamKey := range *streamKeys.Value {- if *streamKey.Key == "" {+ if streamKey.Key == nil || *streamKey.Key == "" {webutils.WriteSimpleResponse(w, false, "stream key cannot be empty")return}+ keys = append(keys, models.StreamKey{Key: streamKey.Key, Comment: streamKey.Comment})}configRepository := a.configRepository- if err := configRepository.SetStreamKeys(*streamKeys.Value); err != nil {+ if err := configRepository.SetStreamKeys(keys); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}diff --git a/webserver/handlers/admin/serverConfig.go b/webserver/handlers/admin/serverConfig.goindex 299f3d2041..b254c66edf 100644--- a/webserver/handlers/admin/serverConfig.go+++ b/webserver/handlers/admin/serverConfig.go@@ -9,7 +9,6 @@ import ("github.com/owncast/owncast/models""github.com/owncast/owncast/services/transcoder""github.com/owncast/owncast/utils"- "github.com/owncast/owncast/webserver/handlers/generated""github.com/owncast/owncast/webserver/router/middleware")@@ -139,7 +138,7 @@ type serverConfigAdminResponse struct {StyleContributors []models.PluginStyleInfo `json:"styleContributors"`ForbiddenUsernames []string `json:"forbiddenUsernames"`SuggestedUsernames []string `json:"suggestedUsernames"`- StreamKeys []generated.StreamKey `json:"streamKeys"`+ StreamKeys []models.StreamKey `json:"streamKeys"`VideoSettings videoSettings `json:"videoSettings"`RTMPServerPort int `json:"rtmpServerPort"`RTMPServerAddress string `json:"rtmpServerAddress"`