live-sfu-demo/internal/server/distribution.go

66 lines
2.0 KiB
Go

package server
import (
"context"
"time"
"sync-live/gen"
"sync-live/internal/sfu/cdn"
"sync-live/internal/sfu/cloudflare"
"sync-live/internal/sfu/srs"
)
// distributionManager handles fanout from SRS trunk to distribution channels.
type distributionManager struct {
hub *roomHub
cf *cloudflare.Provider
srsP *srs.Provider
cdnP *cdn.Provider
cfg distributionConfig
}
type distributionConfig struct {
enabled map[string]bool // kind -> enabled (from DistributorList)
}
func newDistributionManager(hub *roomHub, cf *cloudflare.Provider, srsP *srs.Provider, cdnP *cdn.Provider, enabledKinds []string) *distributionManager {
enabled := map[string]bool{}
for _, k := range enabledKinds {
enabled[k] = true
}
return &distributionManager{hub: hub, cf: cf, srsP: srsP, cdnP: cdnP, cfg: distributionConfig{enabled: enabled}}
}
// Ensure fans out the trunk stream to all enabled distribution channels.
func (m *distributionManager) Ensure(ctx context.Context, room, stream string) error {
if m.hub == nil || stream == "" {
return nil
}
now := time.Now().Unix()
// SRS HLS is always ready (remux直出)
if m.cfg.enabled["srs-hls"] {
if res, err := m.srsP.Forward(ctx, room, stream); err == nil {
m.hub.setDistribution(room, &gen.DistributionTarget{
Kind: gen.DistributionKind_DISTRIBUTION_KIND_SRS_HLS, Url: res.URL, Status: res.Status, UpdatedAt: now,
})
}
}
if m.cfg.enabled["cf"] && m.cf != nil && m.cf.Configured() {
if res, err := m.cf.Forward(ctx, room, stream); err == nil {
m.hub.setDistribution(room, &gen.DistributionTarget{
Kind: gen.DistributionKind_DISTRIBUTION_KIND_CF_SFU, Url: res.URL, Status: res.Status, UpdatedAt: now,
})
}
}
if m.cfg.enabled["cdn"] && m.cdnP != nil && m.cdnP.Configured() {
if res, err := m.cdnP.Forward(ctx, room, stream); err == nil {
m.hub.setDistribution(room, &gen.DistributionTarget{
Kind: gen.DistributionKind_DISTRIBUTION_KIND_CDN, Url: res.URL, Status: res.Status, UpdatedAt: now,
})
}
}
return nil
}
var _ DistributionManagerIface = (*distributionManager)(nil)