Web-based Winamp controller for CarPC � Go backend, mobile-first UI
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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