1
0

audio.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package app
  2. import (
  3. "encoding/binary"
  4. "math"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "git.monoexp.com/bajdev/mpckit/internal/project"
  9. "git.monoexp.com/bajdev/mpckit/internal/wav"
  10. )
  11. // AudioPrefix is the URL path the preview loads samples from:
  12. // /audio/<slot> serves the pad's source WAV as it is, and
  13. // /audio/<slot>?pcm=1 serves it decoded, for formats the webview cannot
  14. // decode (build plan 4.5 and section 9).
  15. const AudioPrefix = "/audio/"
  16. // AudioMiddleware serves AudioPrefix and passes every other request on.
  17. // It is for main.go's asset server, not the frontend.
  18. //
  19. //wails:ignore
  20. func (s *Service) AudioMiddleware(next http.Handler) http.Handler {
  21. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  22. if !strings.HasPrefix(r.URL.Path, AudioPrefix) {
  23. next.ServeHTTP(w, r)
  24. return
  25. }
  26. s.serveAudio(w, r)
  27. })
  28. }
  29. func (s *Service) serveAudio(w http.ResponseWriter, r *http.Request) {
  30. slot, err := strconv.Atoi(strings.TrimPrefix(r.URL.Path, AudioPrefix))
  31. if err != nil || slot < 0 || slot >= project.Pads {
  32. http.NotFound(w, r)
  33. return
  34. }
  35. // Unlock by defer, so a panic cannot leave the lock held.
  36. v, src, err := func() (project.Pad, string, error) {
  37. s.mu.Lock()
  38. defer s.mu.Unlock()
  39. v, err := s.p.Pad(slot)
  40. return v, s.p.Sources[v.File], err
  41. }()
  42. if err != nil || v.Empty() || src == "" {
  43. http.NotFound(w, r)
  44. return
  45. }
  46. w.Header().Set("Cache-Control", "no-store")
  47. if r.URL.Query().Get("pcm") == "" {
  48. w.Header().Set("Content-Type", "audio/wav")
  49. http.ServeFile(w, r, src)
  50. return
  51. }
  52. // Decoded: a 12-byte header (sample rate, channels, frames as uint32
  53. // little-endian), then each channel's frames as float32 little-endian.
  54. info, chans, err := wav.DecodeFile(src)
  55. if err != nil {
  56. http.Error(w, err.Error(), http.StatusUnprocessableEntity)
  57. return
  58. }
  59. frames := len(chans[0])
  60. buf := make([]byte, 12+4*frames*len(chans))
  61. binary.LittleEndian.PutUint32(buf[0:], uint32(info.SampleRate))
  62. binary.LittleEndian.PutUint32(buf[4:], uint32(len(chans)))
  63. binary.LittleEndian.PutUint32(buf[8:], uint32(frames))
  64. off := 12
  65. for _, ch := range chans {
  66. for _, v := range ch {
  67. binary.LittleEndian.PutUint32(buf[off:], math.Float32bits(v))
  68. off += 4
  69. }
  70. }
  71. w.Header().Set("Content-Type", "application/octet-stream")
  72. w.Write(buf)
  73. }