Web-based Winamp controller for CarPC � Go backend, mobile-first UI
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

446 line
12KB

  1. //go:build windows
  2. // Package server wires together the HTTP API, WebSocket hub, Winamp controller,
  3. // WASAPI viz capture, killist, and resume.
  4. package server
  5. import (
  6. "context"
  7. "encoding/json"
  8. "fmt"
  9. "io/fs"
  10. "log"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "strconv"
  15. "time"
  16. "git.svabi.ch/jan/roadamp/internal/killist"
  17. "git.svabi.ch/jan/roadamp/internal/resume"
  18. "git.svabi.ch/jan/roadamp/internal/volume"
  19. "git.svabi.ch/jan/roadamp/internal/viz"
  20. "git.svabi.ch/jan/roadamp/internal/winamp"
  21. "github.com/gorilla/websocket"
  22. "gopkg.in/yaml.v3"
  23. )
  24. // ── Config ────────────────────────────────────────────────────────────────────
  25. type Config struct {
  26. Host string `yaml:"host"`
  27. Port int `yaml:"port"`
  28. WinampPath string `yaml:"winamp_path"`
  29. KillListFile string `yaml:"killist_file"`
  30. ResumeFile string `yaml:"resume_file"`
  31. }
  32. func loadConfig(path string) (Config, error) {
  33. cfg := Config{
  34. Host: "0.0.0.0",
  35. Port: 8889,
  36. KillListFile: "killist.dat",
  37. ResumeFile: "resume.dat",
  38. }
  39. data, err := os.ReadFile(path)
  40. if os.IsNotExist(err) {
  41. return cfg, nil
  42. }
  43. if err != nil {
  44. return cfg, err
  45. }
  46. return cfg, yaml.Unmarshal(data, &cfg)
  47. }
  48. // ── Server ────────────────────────────────────────────────────────────────────
  49. type Server struct {
  50. cfg Config
  51. wa *winamp.Controller
  52. kl *killist.KillList
  53. hub *hub
  54. mux *http.ServeMux
  55. staticFS fs.FS
  56. }
  57. func New(configPath string, staticFS fs.FS) (*Server, error) {
  58. cfg, err := loadConfig(configPath)
  59. if err != nil {
  60. return nil, fmt.Errorf("config: %w", err)
  61. }
  62. kl, err := killist.Load(cfg.KillListFile)
  63. if err != nil {
  64. return nil, fmt.Errorf("killist: %w", err)
  65. }
  66. s := &Server{cfg: cfg, wa: winamp.New(), kl: kl, mux: http.NewServeMux(), staticFS: staticFS}
  67. s.hub = newHub(s.handleCommand)
  68. s.routes()
  69. return s, nil
  70. }
  71. func (s *Server) Run() error {
  72. go s.hub.run()
  73. go s.broadcastStatus()
  74. go s.broadcastViz()
  75. go s.restoreResume()
  76. go s.killChecker()
  77. addr := fmt.Sprintf("%s:%d", s.cfg.Host, s.cfg.Port)
  78. log.Printf("roadamp listening on http://%s", addr)
  79. return http.ListenAndServe(addr, s.mux)
  80. }
  81. // ── Routes ────────────────────────────────────────────────────────────────────
  82. func (s *Server) routes() {
  83. s.mux.Handle("/", http.FileServer(http.FS(s.staticFS)))
  84. // WebSocket (primary interface)
  85. s.mux.HandleFunc("/ws", s.handleWS)
  86. // REST API (kept for curl/debugging)
  87. s.mux.HandleFunc("/api/status", s.handleStatus)
  88. s.mux.HandleFunc("/api/play", s.handlePlay)
  89. s.mux.HandleFunc("/api/pause", s.handlePause)
  90. s.mux.HandleFunc("/api/stop", s.handleStop)
  91. s.mux.HandleFunc("/api/next", s.handleNext)
  92. s.mux.HandleFunc("/api/prev", s.handlePrev)
  93. s.mux.HandleFunc("/api/seek", s.handleSeek)
  94. s.mux.HandleFunc("/api/volume", s.handleVolume)
  95. s.mux.HandleFunc("/api/mute", s.handleMute)
  96. s.mux.HandleFunc("/api/killist", s.handleKillist)
  97. s.mux.HandleFunc("/api/playlist", s.handlePlaylist)
  98. s.mux.HandleFunc("/api/winamp/start", s.handleWinampStart)
  99. }
  100. // ── WebSocket ─────────────────────────────────────────────────────────────────
  101. var wsUpgrader = websocket.Upgrader{
  102. ReadBufferSize: 1024,
  103. WriteBufferSize: 4096,
  104. CheckOrigin: func(r *http.Request) bool { return true },
  105. }
  106. func (s *Server) handleWS(w http.ResponseWriter, r *http.Request) {
  107. conn, err := wsUpgrader.Upgrade(w, r, nil)
  108. if err != nil {
  109. log.Printf("ws upgrade: %v", err)
  110. return
  111. }
  112. c := &wsClient{hub: s.hub, conn: conn, send: make(chan []byte, 32)}
  113. s.hub.register <- c
  114. // Send current status immediately upon connect.
  115. if msg, err := s.statusMsg(); err == nil {
  116. c.send <- msg
  117. }
  118. go c.writePump()
  119. go c.readPump()
  120. }
  121. // ── WebSocket broadcast workers ───────────────────────────────────────────────
  122. // broadcastStatus pushes a status message to all clients every 500 ms.
  123. func (s *Server) broadcastStatus() {
  124. for range time.Tick(500 * time.Millisecond) {
  125. msg, err := s.statusMsg()
  126. if err != nil {
  127. continue
  128. }
  129. select {
  130. case s.hub.broadcast <- msg:
  131. default:
  132. }
  133. }
  134. }
  135. // broadcastViz starts the WASAPI loopback capturer and forwards spectrum
  136. // frames to all WebSocket clients at ~30 fps.
  137. func (s *Server) broadcastViz() {
  138. cap := viz.NewCapturer()
  139. ctx, cancel := context.WithCancel(context.Background())
  140. defer cancel()
  141. go cap.Start(ctx)
  142. for bars := range cap.C {
  143. data, err := json.Marshal(struct {
  144. Type string `json:"type"`
  145. Bars []float32 `json:"bars"`
  146. }{"viz", bars})
  147. if err != nil {
  148. continue
  149. }
  150. select {
  151. case s.hub.broadcast <- data:
  152. default:
  153. }
  154. }
  155. }
  156. // ── Command dispatcher (WebSocket) ────────────────────────────────────────────
  157. type wsCommand struct {
  158. Cmd string `json:"cmd"`
  159. Delta int `json:"delta"`
  160. Level int `json:"level"`
  161. Muted bool `json:"muted"`
  162. Title string `json:"title"`
  163. Index int `json:"index"` // 0-based track index for "jump"
  164. }
  165. func (s *Server) handleCommand(raw []byte) {
  166. var cmd wsCommand
  167. if err := json.Unmarshal(raw, &cmd); err != nil {
  168. return
  169. }
  170. switch cmd.Cmd {
  171. case "play":
  172. s.wa.Play()
  173. case "pause":
  174. s.wa.Pause()
  175. case "stop":
  176. if s.wa.IsPaused() {
  177. _ = resume.Save(s.cfg.ResumeFile, resume.State{
  178. PlaylistLength: s.wa.GetPlaylistLength(),
  179. PlaylistPos: s.wa.GetPlaylistPosition(),
  180. OffsetSeconds: s.wa.GetPosition(),
  181. TrackTitle: s.wa.GetTitle(),
  182. })
  183. }
  184. s.wa.Stop()
  185. case "next":
  186. s.wa.NextTrack()
  187. case "prev":
  188. s.wa.PrevTrack()
  189. case "seek":
  190. pos := s.wa.GetPosition() + cmd.Delta
  191. if pos < 0 {
  192. pos = 0
  193. }
  194. s.wa.Seek(pos)
  195. case "volume":
  196. _ = volume.Set(cmd.Level)
  197. case "mute":
  198. _ = volume.SetMute(cmd.Muted)
  199. case "killist_add":
  200. if title := s.wa.GetTitle(); title != "" {
  201. _ = s.kl.Add(title)
  202. }
  203. case "jump":
  204. s.wa.JumpToTrack(cmd.Index)
  205. case "killist_remove":
  206. _ = s.kl.Remove(cmd.Title)
  207. case "winamp_start":
  208. if !s.wa.IsRunning() {
  209. if s.cfg.WinampPath != "" {
  210. _ = exec.Command(s.cfg.WinampPath).Start()
  211. }
  212. }
  213. }
  214. // Push a fresh status after any command.
  215. if msg, err := s.statusMsg(); err == nil {
  216. select {
  217. case s.hub.broadcast <- msg:
  218. default:
  219. }
  220. }
  221. }
  222. // ── Shared status builder ─────────────────────────────────────────────────────
  223. type statusMsg struct {
  224. Type string `json:"type"`
  225. Running bool `json:"running"`
  226. State string `json:"state"`
  227. Title string `json:"title"`
  228. Position int `json:"position"`
  229. Length int `json:"length"`
  230. PlaylistPos int `json:"playlist_pos"`
  231. PlaylistLength int `json:"playlist_length"`
  232. Version string `json:"version"`
  233. Volume int `json:"volume"`
  234. Muted bool `json:"muted"`
  235. }
  236. func (s *Server) statusMsg() ([]byte, error) {
  237. msg := statusMsg{Type: "status", Running: s.wa.IsRunning()}
  238. if msg.Running {
  239. switch s.wa.PlayState() {
  240. case 1:
  241. msg.State = "playing"
  242. case 3:
  243. msg.State = "paused"
  244. default:
  245. msg.State = "stopped"
  246. }
  247. msg.Title = s.wa.GetTitle()
  248. // Winamp returns 0xFFFFFFFF when stopped/no track — clamp to 0.
  249. pos := s.wa.GetPosition()
  250. length := s.wa.GetLength()
  251. if pos > 86400 { pos = 0 } // > 24h → garbage value
  252. if length > 86400 { length = 0 }
  253. msg.Position = pos
  254. msg.Length = length
  255. msg.PlaylistPos = s.wa.GetPlaylistPosition()
  256. msg.PlaylistLength = s.wa.GetPlaylistLength()
  257. msg.Version = s.wa.GetVersion()
  258. }
  259. if vol, err := volume.Get(); err == nil {
  260. msg.Volume = vol
  261. }
  262. if muted, err := volume.GetMute(); err == nil {
  263. msg.Muted = muted
  264. }
  265. return json.Marshal(msg)
  266. }
  267. // ── Background workers ────────────────────────────────────────────────────────
  268. func (s *Server) killChecker() {
  269. for range time.Tick(2 * time.Second) {
  270. if !s.wa.IsPlaying() {
  271. continue
  272. }
  273. if title := s.wa.GetTitle(); s.kl.Contains(title) {
  274. log.Printf("killist: skipping %q", title)
  275. s.wa.NextTrack()
  276. }
  277. }
  278. }
  279. func (s *Server) restoreResume() {
  280. deadline := time.Now().Add(30 * time.Second)
  281. for time.Now().Before(deadline) {
  282. if s.wa.IsRunning() {
  283. break
  284. }
  285. time.Sleep(500 * time.Millisecond)
  286. }
  287. st, err := resume.Load(s.cfg.ResumeFile)
  288. if err != nil || st == nil {
  289. return
  290. }
  291. if s.wa.GetPlaylistLength() != st.PlaylistLength {
  292. _ = resume.Delete(s.cfg.ResumeFile)
  293. return
  294. }
  295. s.wa.Play()
  296. s.wa.Seek(st.OffsetSeconds)
  297. s.wa.Pause()
  298. _ = resume.Delete(s.cfg.ResumeFile)
  299. log.Printf("resume: restored %q at %ds", st.TrackTitle, st.OffsetSeconds)
  300. }
  301. // ── REST handlers (for curl/debug) ───────────────────────────────────────────
  302. func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
  303. msg, err := s.statusMsg()
  304. if err != nil {
  305. http.Error(w, err.Error(), 500)
  306. return
  307. }
  308. w.Header().Set("Content-Type", "application/json")
  309. w.Write(msg)
  310. }
  311. func (s *Server) handlePlay(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.Play()) }
  312. func (s *Server) handlePause(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.Pause()) }
  313. func (s *Server) handleNext(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.NextTrack()) }
  314. func (s *Server) handlePrev(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.PrevTrack()) }
  315. func (s *Server) handleStop(w http.ResponseWriter, r *http.Request) {
  316. if s.wa.IsPaused() {
  317. _ = resume.Save(s.cfg.ResumeFile, resume.State{
  318. PlaylistLength: s.wa.GetPlaylistLength(),
  319. PlaylistPos: s.wa.GetPlaylistPosition(),
  320. OffsetSeconds: s.wa.GetPosition(),
  321. TrackTitle: s.wa.GetTitle(),
  322. })
  323. }
  324. jsonOK(w, s.wa.Stop())
  325. }
  326. func (s *Server) handleSeek(w http.ResponseWriter, r *http.Request) {
  327. delta, err := strconv.Atoi(r.URL.Query().Get("delta"))
  328. if err != nil {
  329. http.Error(w, "invalid delta", http.StatusBadRequest)
  330. return
  331. }
  332. pos := s.wa.GetPosition() + delta
  333. if pos < 0 {
  334. pos = 0
  335. }
  336. jsonOK(w, s.wa.Seek(pos))
  337. }
  338. func (s *Server) handleVolume(w http.ResponseWriter, r *http.Request) {
  339. if r.Method == http.MethodGet {
  340. vol, _ := volume.Get()
  341. jsonOK(w, map[string]int{"volume": vol})
  342. return
  343. }
  344. lvl, err := strconv.Atoi(r.URL.Query().Get("level"))
  345. if err != nil {
  346. http.Error(w, "invalid level", http.StatusBadRequest)
  347. return
  348. }
  349. _ = volume.Set(lvl)
  350. jsonOK(w, map[string]int{"volume": lvl})
  351. }
  352. func (s *Server) handleMute(w http.ResponseWriter, r *http.Request) {
  353. if r.Method == http.MethodGet {
  354. muted, _ := volume.GetMute()
  355. jsonOK(w, map[string]bool{"muted": muted})
  356. return
  357. }
  358. val := r.URL.Query().Get("muted")
  359. muted := val == "true" || val == "1"
  360. _ = volume.SetMute(muted)
  361. jsonOK(w, map[string]bool{"muted": muted})
  362. }
  363. func (s *Server) handleKillist(w http.ResponseWriter, r *http.Request) {
  364. switch r.Method {
  365. case http.MethodGet:
  366. jsonOK(w, s.kl.List())
  367. case http.MethodPost:
  368. title := s.wa.GetTitle()
  369. if title == "" {
  370. http.Error(w, "no track playing", http.StatusConflict)
  371. return
  372. }
  373. _ = s.kl.Add(title)
  374. jsonOK(w, map[string]string{"added": title})
  375. case http.MethodDelete:
  376. _ = s.kl.Remove(r.URL.Query().Get("title"))
  377. jsonOK(w, map[string]bool{"ok": true})
  378. }
  379. }
  380. func (s *Server) handlePlaylist(w http.ResponseWriter, r *http.Request) {
  381. jsonOK(w, s.wa.GetPlaylist())
  382. }
  383. func (s *Server) handleWinampStart(w http.ResponseWriter, r *http.Request) {
  384. if s.wa.IsRunning() {
  385. jsonOK(w, map[string]string{"status": "already_running"})
  386. return
  387. }
  388. if s.cfg.WinampPath == "" {
  389. http.Error(w, "winamp_path not configured", http.StatusServiceUnavailable)
  390. return
  391. }
  392. if err := exec.Command(s.cfg.WinampPath).Start(); err != nil {
  393. http.Error(w, err.Error(), 500)
  394. return
  395. }
  396. jsonOK(w, map[string]string{"status": "started"})
  397. }
  398. func jsonOK(w http.ResponseWriter, v any) {
  399. w.Header().Set("Content-Type", "application/json")
  400. json.NewEncoder(w).Encode(v)
  401. }