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.

474 line
13KB

  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/viz"
  19. "git.svabi.ch/jan/roadamp/internal/volume"
  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. s.saveResumeState()
  177. s.wa.Stop()
  178. case "next":
  179. s.wa.NextTrack()
  180. case "prev":
  181. s.wa.PrevTrack()
  182. case "seek":
  183. pos := s.wa.GetPosition() + cmd.Delta
  184. if pos < 0 {
  185. pos = 0
  186. }
  187. s.wa.Seek(pos)
  188. case "volume":
  189. _ = volume.Set(cmd.Level)
  190. case "mute":
  191. _ = volume.SetMute(cmd.Muted)
  192. case "killist_add":
  193. if title := s.wa.GetTitle(); title != "" {
  194. _ = s.kl.Add(title)
  195. }
  196. case "jump":
  197. s.wa.JumpToTrack(cmd.Index)
  198. case "killist_remove":
  199. _ = s.kl.Remove(cmd.Title)
  200. case "winamp_start":
  201. if !s.wa.IsRunning() {
  202. if s.cfg.WinampPath != "" {
  203. _ = exec.Command(s.cfg.WinampPath).Start()
  204. }
  205. }
  206. }
  207. // Push a fresh status after any command.
  208. if msg, err := s.statusMsg(); err == nil {
  209. select {
  210. case s.hub.broadcast <- msg:
  211. default:
  212. }
  213. }
  214. }
  215. // ── Shared status builder ─────────────────────────────────────────────────────
  216. type statusMsg struct {
  217. Type string `json:"type"`
  218. Running bool `json:"running"`
  219. State string `json:"state"`
  220. Title string `json:"title"`
  221. Position int `json:"position"`
  222. Length int `json:"length"`
  223. PlaylistPos int `json:"playlist_pos"`
  224. PlaylistLength int `json:"playlist_length"`
  225. Version string `json:"version"`
  226. Volume int `json:"volume"`
  227. Muted bool `json:"muted"`
  228. }
  229. func (s *Server) statusMsg() ([]byte, error) {
  230. msg := statusMsg{Type: "status", Running: s.wa.IsRunning()}
  231. if msg.Running {
  232. switch s.wa.PlayState() {
  233. case 1:
  234. msg.State = "playing"
  235. case 3:
  236. msg.State = "paused"
  237. default:
  238. msg.State = "stopped"
  239. }
  240. msg.Title = s.wa.GetTitle()
  241. // Winamp returns 0xFFFFFFFF when stopped/no track — clamp to 0.
  242. pos := s.wa.GetPosition()
  243. length := s.wa.GetLength()
  244. if pos > 86400 {
  245. pos = 0
  246. } // > 24h → garbage value
  247. if length > 86400 {
  248. length = 0
  249. }
  250. msg.Position = pos
  251. msg.Length = length
  252. msg.PlaylistPos = s.wa.GetPlaylistPosition()
  253. msg.PlaylistLength = s.wa.GetPlaylistLength()
  254. msg.Version = s.wa.GetVersion()
  255. }
  256. if vol, err := volume.Get(); err == nil {
  257. msg.Volume = vol
  258. }
  259. if muted, err := volume.GetMute(); err == nil {
  260. msg.Muted = muted
  261. }
  262. return json.Marshal(msg)
  263. }
  264. // ── Background workers ────────────────────────────────────────────────────────
  265. func (s *Server) killChecker() {
  266. for range time.Tick(2 * time.Second) {
  267. if !s.wa.IsPlaying() {
  268. continue
  269. }
  270. if title := s.wa.GetTitle(); s.kl.Contains(title) {
  271. log.Printf("killist: skipping %q", title)
  272. s.wa.NextTrack()
  273. }
  274. }
  275. }
  276. // saveResumeState persists the current playback position when a track is
  277. // active (playing or paused). Safe to call unconditionally before Stop.
  278. func (s *Server) saveResumeState() {
  279. state := s.wa.PlayState()
  280. if state != 1 && state != 3 { // not playing and not paused
  281. return
  282. }
  283. title := s.wa.GetTitle()
  284. if title == "" {
  285. return
  286. }
  287. _ = resume.Save(s.cfg.ResumeFile, resume.State{
  288. PlaylistLength: s.wa.GetPlaylistLength(),
  289. PlaylistPos: s.wa.GetPlaylistPosition(),
  290. OffsetSeconds: s.wa.GetPosition(),
  291. TrackTitle: title,
  292. })
  293. }
  294. func (s *Server) restoreResume() {
  295. deadline := time.Now().Add(30 * time.Second)
  296. for time.Now().Before(deadline) {
  297. if s.wa.IsRunning() {
  298. break
  299. }
  300. time.Sleep(500 * time.Millisecond)
  301. }
  302. st, err := resume.Load(s.cfg.ResumeFile)
  303. if err != nil || st == nil {
  304. return
  305. }
  306. if s.wa.GetPlaylistLength() != st.PlaylistLength {
  307. log.Printf("resume: playlist length mismatch (saved %d, got %d) — aborting",
  308. st.PlaylistLength, s.wa.GetPlaylistLength())
  309. _ = resume.Delete(s.cfg.ResumeFile)
  310. return
  311. }
  312. // Jump to the saved track (JumpToTrack is 0-based, also starts playback).
  313. if st.PlaylistPos > 0 {
  314. s.wa.JumpToTrack(st.PlaylistPos - 1)
  315. time.Sleep(300 * time.Millisecond) // give Winamp a moment to load
  316. // Validate title to catch same-length playlists with different content.
  317. if st.TrackTitle != "" {
  318. if got := s.wa.GetTitle(); got != "" && got != st.TrackTitle {
  319. log.Printf("resume: title mismatch (expected %q, got %q) — aborting",
  320. st.TrackTitle, got)
  321. s.wa.Stop()
  322. _ = resume.Delete(s.cfg.ResumeFile)
  323. return
  324. }
  325. }
  326. } else {
  327. s.wa.Play()
  328. }
  329. s.wa.Seek(st.OffsetSeconds)
  330. s.wa.Pause()
  331. _ = resume.Delete(s.cfg.ResumeFile)
  332. log.Printf("resume: restored %q at %ds (playlist pos %d)",
  333. st.TrackTitle, st.OffsetSeconds, st.PlaylistPos)
  334. }
  335. // ── REST handlers (for curl/debug) ───────────────────────────────────────────
  336. func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
  337. msg, err := s.statusMsg()
  338. if err != nil {
  339. http.Error(w, err.Error(), 500)
  340. return
  341. }
  342. w.Header().Set("Content-Type", "application/json")
  343. w.Write(msg)
  344. }
  345. func (s *Server) handlePlay(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.Play()) }
  346. func (s *Server) handlePause(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.Pause()) }
  347. func (s *Server) handleNext(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.NextTrack()) }
  348. func (s *Server) handlePrev(w http.ResponseWriter, r *http.Request) { jsonOK(w, s.wa.PrevTrack()) }
  349. func (s *Server) handleStop(w http.ResponseWriter, r *http.Request) {
  350. s.saveResumeState()
  351. jsonOK(w, s.wa.Stop())
  352. }
  353. func (s *Server) handleSeek(w http.ResponseWriter, r *http.Request) {
  354. delta, err := strconv.Atoi(r.URL.Query().Get("delta"))
  355. if err != nil {
  356. http.Error(w, "invalid delta", http.StatusBadRequest)
  357. return
  358. }
  359. pos := s.wa.GetPosition() + delta
  360. if pos < 0 {
  361. pos = 0
  362. }
  363. jsonOK(w, s.wa.Seek(pos))
  364. }
  365. func (s *Server) handleVolume(w http.ResponseWriter, r *http.Request) {
  366. if r.Method == http.MethodGet {
  367. vol, _ := volume.Get()
  368. jsonOK(w, map[string]int{"volume": vol})
  369. return
  370. }
  371. lvl, err := strconv.Atoi(r.URL.Query().Get("level"))
  372. if err != nil {
  373. http.Error(w, "invalid level", http.StatusBadRequest)
  374. return
  375. }
  376. _ = volume.Set(lvl)
  377. jsonOK(w, map[string]int{"volume": lvl})
  378. }
  379. func (s *Server) handleMute(w http.ResponseWriter, r *http.Request) {
  380. if r.Method == http.MethodGet {
  381. muted, _ := volume.GetMute()
  382. jsonOK(w, map[string]bool{"muted": muted})
  383. return
  384. }
  385. val := r.URL.Query().Get("muted")
  386. muted := val == "true" || val == "1"
  387. _ = volume.SetMute(muted)
  388. jsonOK(w, map[string]bool{"muted": muted})
  389. }
  390. func (s *Server) handleKillist(w http.ResponseWriter, r *http.Request) {
  391. switch r.Method {
  392. case http.MethodGet:
  393. jsonOK(w, s.kl.List())
  394. case http.MethodPost:
  395. title := s.wa.GetTitle()
  396. if title == "" {
  397. http.Error(w, "no track playing", http.StatusConflict)
  398. return
  399. }
  400. _ = s.kl.Add(title)
  401. jsonOK(w, map[string]string{"added": title})
  402. case http.MethodDelete:
  403. _ = s.kl.Remove(r.URL.Query().Get("title"))
  404. jsonOK(w, map[string]bool{"ok": true})
  405. }
  406. }
  407. func (s *Server) handlePlaylist(w http.ResponseWriter, r *http.Request) {
  408. jsonOK(w, s.wa.GetPlaylist())
  409. }
  410. func (s *Server) handleWinampStart(w http.ResponseWriter, r *http.Request) {
  411. if s.wa.IsRunning() {
  412. jsonOK(w, map[string]string{"status": "already_running"})
  413. return
  414. }
  415. if s.cfg.WinampPath == "" {
  416. http.Error(w, "winamp_path not configured", http.StatusServiceUnavailable)
  417. return
  418. }
  419. if err := exec.Command(s.cfg.WinampPath).Start(); err != nil {
  420. http.Error(w, err.Error(), 500)
  421. return
  422. }
  423. jsonOK(w, map[string]string{"status": "started"})
  424. }
  425. func jsonOK(w http.ResponseWriter, v any) {
  426. w.Header().Set("Content-Type", "application/json")
  427. json.NewEncoder(w).Encode(v)
  428. }