summaryrefslogtreecommitdiff
path: root/extra/whisper_binary.go
blob: 1c359527afae3ebfc73b5941acf5517b395910dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
//go:build extra
// +build extra

package extra

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"gf-lt/config"
	"log/slog"
	"os"
	"os/exec"
	"strings"
	"sync"
	"syscall"
	"time"
)

type WhisperBinary struct {
	logger      *slog.Logger
	whisperPath string
	modelPath   string
	lang        string
	// Per-recording fields (protected by mu)
	mu        sync.Mutex
	recording bool
	tempFile  string
	ctx       context.Context
	cancel    context.CancelFunc
	cmd       *exec.Cmd
	cmdMu     sync.Mutex
}

func (w *WhisperBinary) StartRecording() error {
	w.mu.Lock()
	defer w.mu.Unlock()
	if w.recording {
		return errors.New("recording is already in progress")
	}
	// Fresh context for this recording
	ctx, cancel := context.WithCancel(context.Background())
	w.ctx = ctx
	w.cancel = cancel
	// Create temporary file
	tempFile, err := os.CreateTemp("", "recording_*.wav")
	if err != nil {
		cancel()
		return fmt.Errorf("failed to create temp file: %w", err)
	}
	tempFile.Close()
	w.tempFile = tempFile.Name()
	// ffmpeg command: capture from default microphone, write WAV
	args := []string{
		"-f", "alsa", // or "pulse" if preferred
		"-i", "default",
		"-acodec", "pcm_s16le",
		"-ar", "16000",
		"-ac", "1",
		"-y", // overwrite output file
		w.tempFile,
	}
	cmd := exec.CommandContext(w.ctx, "ffmpeg", args...)
	// Capture stderr for debugging (optional, but useful for diagnosing)
	stderr, err := cmd.StderrPipe()
	if err != nil {
		cancel()
		os.Remove(w.tempFile)
		return fmt.Errorf("failed to create stderr pipe: %w", err)
	}
	go func() {
		buf := make([]byte, 1024)
		for {
			n, err := stderr.Read(buf)
			if n > 0 {
				w.logger.Debug("ffmpeg stderr", "output", string(buf[:n]))
			}
			if err != nil {
				break
			}
		}
	}()
	w.cmdMu.Lock()
	w.cmd = cmd
	w.cmdMu.Unlock()
	if err := cmd.Start(); err != nil {
		cancel()
		os.Remove(w.tempFile)
		return fmt.Errorf("failed to start ffmpeg: %w", err)
	}
	w.recording = true
	w.logger.Debug("Recording started", "file", w.tempFile)
	return nil
}

func (w *WhisperBinary) StopRecording() (string, error) {
	w.mu.Lock()
	defer w.mu.Unlock()
	if !w.recording {
		return "", errors.New("not currently recording")
	}
	w.recording = false
	// Gracefully stop ffmpeg
	w.cmdMu.Lock()
	if w.cmd != nil && w.cmd.Process != nil {
		w.logger.Debug("Sending SIGTERM to ffmpeg")
		w.cmd.Process.Signal(syscall.SIGTERM)
		// Wait for process to exit (up to 2 seconds)
		done := make(chan error, 1)
		go func() {
			done <- w.cmd.Wait()
		}()
		select {
		case <-done:
			w.logger.Debug("ffmpeg exited after SIGTERM")
		case <-time.After(2 * time.Second):
			w.logger.Warn("ffmpeg did not exit, sending SIGKILL")
			w.cmd.Process.Kill()
			<-done
		}
	}
	w.cmdMu.Unlock()
	// Cancel context (already done, but for cleanliness)
	if w.cancel != nil {
		w.cancel()
	}
	// Validate temp file
	if w.tempFile == "" {
		return "", errors.New("no recording file")
	}
	defer os.Remove(w.tempFile)
	info, err := os.Stat(w.tempFile)
	if err != nil {
		return "", fmt.Errorf("failed to stat temp file: %w", err)
	}
	if info.Size() < 44 { // WAV header is 44 bytes
		// Log ffmpeg stderr? Already captured in debug logs.
		return "", fmt.Errorf("recording file too small (%d bytes), possibly no audio captured", info.Size())
	}
	// Run whisper.cpp binary
	cmd := exec.Command(w.whisperPath, "-m", w.modelPath, "-l", w.lang, w.tempFile)
	var outBuf, errBuf bytes.Buffer
	cmd.Stdout = &outBuf
	cmd.Stderr = &errBuf
	if err := cmd.Run(); err != nil {
		w.logger.Error("whisper binary failed",
			"error", err,
			"stderr", errBuf.String(),
			"file_size", info.Size())
		return "", fmt.Errorf("whisper binary failed: %w (stderr: %s)", err, errBuf.String())
	}
	result := strings.TrimRight(outBuf.String(), "\n")
	result = specialRE.ReplaceAllString(result, "")
	return strings.TrimSpace(strings.ReplaceAll(result, "\n ", "\n")), nil
}

// IsRecording returns true if a recording is in progress.
func (w *WhisperBinary) IsRecording() bool {
	w.mu.Lock()
	defer w.mu.Unlock()
	return w.recording
}

func NewWhisperBinary(logger *slog.Logger, cfg *config.Config) *WhisperBinary {
	ctx, cancel := context.WithCancel(context.Background())
	// Set ALSA error handler first
	return &WhisperBinary{
		logger:      logger,
		whisperPath: cfg.WhisperBinaryPath,
		modelPath:   cfg.WhisperModelPath,
		lang:        cfg.STT_LANG,
		ctx:         ctx,
		cancel:      cancel,
	}
}