Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
235 lines (206 loc) · 6.22 KB
/
Copy pathmain.go
File metadata and controls
235 lines (206 loc) · 6.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package main
import (
"context"
"log/slog"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"cliamp-server/broadcast"
"cliamp-server/config"
"cliamp-server/geo"
"cliamp-server/library"
"cliamp-server/playlist"
"cliamp-server/scheduler"
"cliamp-server/server"
"cliamp-server/stats"
)
// raiseFileLimit raises the soft file-descriptor limit to the hard limit.
// Each connected listener holds one socket, so the default soft limit of
// 1024 caps the server at roughly 1000 simultaneous listeners.
func raiseFileLimit() {
var rlimit syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {
return
}
if rlimit.Cur < rlimit.Max {
prev := rlimit.Cur
rlimit.Cur = rlimit.Max
if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rlimit); err == nil {
slog.Info("raised file descriptor limit", "from", prev, "to", rlimit.Max)
}
}
}
func main() {
cfg, err := config.Load(config.ConfigPathFromArgs())
if err != nil {
slog.Error("failed to load config", "error", err)
os.Exit(1)
}
if config.ParseFlags(cfg) {
return
}
// Set up structured logging
var level slog.Level
switch cfg.Log.Level {
case "debug":
level = slog.LevelDebug
case "warn":
level = slog.LevelWarn
case "error":
level = slog.LevelError
default:
level = slog.LevelInfo
}
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level})))
raiseFileLimit()
// Validate config
if err := cfg.Validate(); err != nil {
slog.Error("invalid config", "error", err)
os.Exit(1)
}
if _, err := exec.LookPath("ffmpeg"); err != nil {
slog.Error("ffmpeg is required", "error", err)
os.Exit(1)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Build stations
stations := make(map[string]*server.Station, len(cfg.Stations))
for id, stCfg := range cfg.Stations {
slog.Info("scanning library", "station", id, "path", stCfg.Path, "recursive", stCfg.Recursive)
tracks, err := library.Scan(stCfg.Path, stCfg.Recursive)
if err != nil {
slog.Error("failed to scan library", "station", id, "error", err)
os.Exit(1)
}
// Exclude intro file from music rotation
if stCfg.IntroFile != "" {
filtered := tracks[:0]
for _, t := range tracks {
if t.Path != stCfg.IntroFile {
filtered = append(filtered, t)
}
}
tracks = filtered
}
if len(tracks) == 0 {
slog.Error("no MP3 files found", "station", id, "path", stCfg.Path)
os.Exit(1)
}
pl := playlist.New(tracks, stCfg.Shuffle)
var source playlist.TrackSource = pl
if stCfg.AdsPath != "" {
sched, err := scheduler.New(pl, scheduler.Config{
AdsPath: stCfg.AdsPath,
AdEverySongs: stCfg.AdEveryNSongs,
AdEveryMins: stCfg.AdEveryNMins,
AdShuffle: stCfg.AdShuffle,
})
if err != nil {
slog.Error("failed to create scheduler", "station", id, "error", err)
os.Exit(1)
}
source = sched
slog.Info("scheduler enabled", "station", id)
}
hub := broadcast.NewHub(id, source, cfg.Stream.BufferSize, cfg.Stream.MaxListeners)
go hub.Run(ctx)
stations[id] = &server.Station{
Hub: hub,
Config: stCfg,
TrackCount: pl.Len(),
Tracks: tracks,
}
}
// Open optional GeoIP database
var geoDB *geo.DB
if cfg.Geo.DBPath != "" {
var err error
geoDB, err = geo.Open(cfg.Geo.DBPath)
if err != nil {
slog.Error("failed to open geo database", "path", cfg.Geo.DBPath, "error", err)
os.Exit(1)
}
defer geoDB.Close()
slog.Info("geo database loaded", "path", cfg.Geo.DBPath)
}
// Open optional statistics database
var statsDB *stats.DB
if cfg.Stats.DBPath != "" {
var err error
statsDB, err = stats.Open(cfg.Stats.DBPath)
if err != nil {
slog.Error("failed to open stats database", "path", cfg.Stats.DBPath, "error", err)
os.Exit(1)
}
defer statsDB.Close()
slog.Info("statistics database loaded", "path", cfg.Stats.DBPath)
stationIDs := make([]string, 0, len(stations))
for id := range stations {
stationIDs = append(stationIDs, id)
}
peakTracker, err := stats.NewPeakTracker(statsDB, stationIDs)
if err != nil {
slog.Error("failed to initialize listener peak tracking", "error", err)
os.Exit(1)
}
// Minimum session duration to filter out media-player probe connections
// that connect briefly to check stream metadata before the real playback.
minSession := int64(cfg.Stats.MinSession)
if minSession <= 0 {
minSession = 10
}
// Wire disconnect hooks to record sessions
for _, st := range stations {
st.Hub.SetListenerChangeHook(func(stationID string, delta int) {
if err := peakTracker.Change(stationID, delta); err != nil {
slog.Error("failed to record listener peak", "station", stationID, "error", err)
}
})
st.Hub.SetDisconnectHook(func(stationID string, snap broadcast.ListenerSnapshot, disconnectedAt time.Time) {
dur := int64(disconnectedAt.Sub(snap.ConnectedAt).Seconds())
if dur < minSession {
slog.Debug("session too short, not recording", "station", stationID, "duration", dur, "min", minSession)
return
}
if err := statsDB.Record(stats.Session{
Station: stationID,
Country: snap.Info.Country,
CountryCode: snap.Info.CountryCode,
City: snap.Info.City,
Latitude: snap.Info.Latitude,
Longitude: snap.Info.Longitude,
ConnectedAt: snap.ConnectedAt,
DisconnectedAt: disconnectedAt,
DurationSeconds: dur,
}); err != nil {
slog.Error("failed to record listener session", "station", stationID, "error", err)
}
})
}
} else {
slog.Info("statistics disabled (no --stats-db configured)")
}
if cfg.Admin.Password != "" {
slog.Info("admin password protection enabled")
} else {
slog.Warn("admin password not set, status endpoints are public")
}
// Create and start HTTP server
srv := server.New(cfg, stations, geoDB, statsDB)
// Graceful shutdown on SIGINT/SIGTERM
go func() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
sig := <-sigCh
slog.Info("received signal, shutting down", "signal", sig)
cancel()
srv.Shutdown(context.Background())
}()
if err := srv.ListenAndServe(); err != nil && err.Error() != "http: Server closed" {
slog.Error("server error", "error", err)
os.Exit(1)
}
}