Files
Docwell/Server/internal/ai/audio.go
T
tajniak81andClaude Opus 5.5 cad42fbe89
CI / desktop (ubuntu-latest) (push) Successful in 2h34m54s
CI / mobile (push) Failing after 4m52s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / docker (push) Successful in 53m34s
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / go (Media) (push) Successful in 13m0s
CI / go (Server) (push) Successful in 24m4s
CI / go (Web-App) (push) Successful in 12m35s
CI / frontend (push) Failing after 11m51s
Prepare the 0.3.0 release
CHANGELOG.md gets the 0.3.0 notes: everything since 0.2.0 by area, and
the steps for upgrading a 0.2.0 install (new compose files with a stock
PocketBase on 8070, pb_data at /pb/pb_data, the media service, and the
SMTP password to enter once more). The release workflow now uses the
tag's CHANGELOG section as the Gitea release text. A v0.2.0 compose stack
with data was upgraded in place to this commit and kept its data.

Also fixes what CI would have failed on:
- Server lint (golangci-lint v2.14): errors.Is/As for sentinel errors,
  the bbolt/errors package instead of the deprecated bolt error, one
  needless conversion, and commented nolints for gosec false positives.
- SPDX headers on Database/export-schema.sh and Server/entrypoint.sh.
- Prettier on two files; the generated pbschema/schema.json is ignored.
- The editor-bridge dist page rebuilt to match the phone app's copy.

PLAN.md and the upgrade guide point to the release notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:21:57 +01:00

256 lines
7.8 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package ai
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"docwell/server/internal/apperr"
)
// ---- Long recordings ---------------------------------------------------------------
//
// Speech-to-text APIs take files up to 25 MB. Longer recordings are cut into
// pieces that are transcribed one after another. ffmpeg re-encodes any audio
// or video to 16 kHz mono MP3 — what speech models work at anyway — and cuts
// it every 20 minutes. It runs in docwell-media (DOCWELL_MEDIA_URL, media.go),
// which parses uploads away from the database and secrets, or else locally
// when the server has ffmpeg (the all-in-one image). Without either, MP3 is
// cut at frame boundaries and WAV at sample boundaries.
// audioPiece is one piece of a recording.
type audioPiece struct {
Name string
Data []byte
}
const segmentSeconds = 1200
// ffmpegPath is ffmpeg's location, or "" when the server has none.
var ffmpegPath = func() string {
p, err := exec.LookPath("ffmpeg")
if err != nil {
return ""
}
return p
}()
var errNeedsFFmpeg = apperr.Invalid("Recordings over 25 MB need ffmpeg to be cut into pieces: run the docwell-media service (DOCWELL_MEDIA_URL) or install ffmpeg on the server. MP3 and WAV files work without it.")
// splitAudio returns the recording as pieces of at most max bytes.
func splitAudio(ctx context.Context, name string, data []byte, max int) ([]audioPiece, error) {
if len(data) <= max {
return []audioPiece{{Name: name, Data: data}}, nil
}
if ffmpegPath != "" {
return splitWithFFmpeg(ctx, ffmpegPath, name, data, max)
}
base := strings.TrimSuffix(name, filepath.Ext(name))
switch strings.ToLower(filepath.Ext(name)) {
case ".mp3", ".mpga", ".mpeg":
return splitMP3(base, data, max)
case ".wav":
return splitWAV(base, data, max)
}
return nil, errNeedsFFmpeg
}
func splitWithFFmpeg(ctx context.Context, ffmpeg, name string, data []byte, max int) ([]audioPiece, error) {
dir, err := os.MkdirTemp("", "docwell-audio-")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
in := filepath.Join(dir, "in"+strings.ToLower(filepath.Ext(name)))
if err := os.WriteFile(in, data, 0o600); err != nil {
return nil, err
}
cmd := exec.CommandContext(ctx, ffmpeg, "-nostdin", "-hide_banner", "-loglevel", "error", //nolint:gosec // ffmpeg is the configured binary; the arguments are fixed and the input is our own temp file
"-i", in, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "libmp3lame", "-b:a", "32k",
"-f", "segment", "-segment_time", fmt.Sprint(segmentSeconds), "-reset_timestamps", "1",
filepath.Join(dir, "part%03d.mp3"))
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, apperr.Invalid("The recording could not be read: " + truncate(strings.TrimSpace(stderr.String()), 200))
}
files, err := filepath.Glob(filepath.Join(dir, "part*.mp3"))
if err != nil {
return nil, err
}
sort.Strings(files)
var parts [][]byte
for _, f := range files {
b, err := os.ReadFile(f) //nolint:gosec // f comes from a glob inside our own temp dir
if err != nil {
return nil, err
}
parts = append(parts, b)
}
return mp3Pieces(name, parts, max)
}
// mp3Pieces names the MP3 pieces ffmpeg made, after the recording.
func mp3Pieces(name string, parts [][]byte, max int) ([]audioPiece, error) {
base := strings.TrimSuffix(name, filepath.Ext(name))
var out []audioPiece
for i, b := range parts {
if len(b) == 0 {
continue
}
// 20 minutes at 32 kb/s is under 5 MB; a piece can only be too big
// for a very low max, so cut it again as MP3.
if len(b) > max {
more, err := splitMP3(fmt.Sprintf("%s-%03d", base, i+1), b, max)
if err != nil {
return nil, err
}
out = append(out, more...)
continue
}
out = append(out, audioPiece{Name: fmt.Sprintf("%s-%03d.mp3", base, i+1), Data: b})
}
if len(out) == 0 {
return nil, apperr.Invalid("The recording has no sound to transcribe.")
}
return out, nil
}
// ---- MP3 without ffmpeg ----
var (
mp3Bitrates = [2][16]int{ // kbit/s for Layer III: [MPEG-1, MPEG-2/2.5]
{0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0},
{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0},
}
mp3Rates = [4][4]int{ // Hz by version bits (2.5, reserved, 2, 1) and index
{11025, 12000, 8000, 0}, {0, 0, 0, 0}, {22050, 24000, 16000, 0}, {44100, 48000, 32000, 0},
}
)
// mp3FrameLen is the length of the Layer III frame starting at b, or 0.
func mp3FrameLen(b []byte) int {
if len(b) < 4 || b[0] != 0xFF || b[1]&0xE0 != 0xE0 {
return 0
}
version := (b[1] >> 3) & 3
layer := (b[1] >> 1) & 3
if version == 1 || layer != 1 { // reserved version, or not Layer III
return 0
}
brIdx, srIdx, pad := int(b[2]>>4), int((b[2]>>2)&3), int((b[2]>>1)&1)
rate := mp3Rates[version][srIdx]
table := 1
if version == 3 {
table = 0
}
br := mp3Bitrates[table][brIdx]
if rate == 0 || br == 0 {
return 0
}
if version == 3 {
return 144*br*1000/rate + pad
}
return 72*br*1000/rate + pad
}
// splitMP3 cuts an MP3 into pieces of whole frames, each a playable file.
func splitMP3(base string, data []byte, max int) ([]audioPiece, error) {
pos := 0
// Skip an ID3v2 tag.
if len(data) >= 10 && string(data[:3]) == "ID3" {
size := int(data[6]&0x7F)<<21 | int(data[7]&0x7F)<<14 | int(data[8]&0x7F)<<7 | int(data[9]&0x7F)
pos = 10 + size
}
var out []audioPiece
start := pos
frames := 0
for pos < len(data) {
n := mp3FrameLen(data[pos:])
if n <= 0 {
// Not a frame: resync on the next byte (junk, or a trailing tag).
pos++
continue
}
if pos+n > len(data) {
break
}
if pos+n-start > max && frames > 0 {
out = append(out, audioPiece{Name: fmt.Sprintf("%s-%03d.mp3", base, len(out)+1), Data: data[start:pos]})
start, frames = pos, 0
}
pos += n
frames++
}
if frames > 0 {
out = append(out, audioPiece{Name: fmt.Sprintf("%s-%03d.mp3", base, len(out)+1), Data: data[start:pos]})
}
if len(out) == 0 {
return nil, apperr.Invalid("The MP3 file could not be read.")
}
return out, nil
}
// ---- WAV without ffmpeg ----
// splitWAV cuts a PCM WAV file into WAV files of at most max bytes.
func splitWAV(base string, data []byte, max int) ([]audioPiece, error) {
bad := apperr.Invalid("The WAV file could not be read.")
if len(data) < 12 || string(data[:4]) != "RIFF" || string(data[8:12]) != "WAVE" {
return nil, bad
}
var fmtChunk, samples []byte
for pos := 12; pos+8 <= len(data); {
id := string(data[pos : pos+4])
size := int(binary.LittleEndian.Uint32(data[pos+4:]))
body := pos + 8
end := min(body+size, len(data))
switch id {
case "fmt ":
fmtChunk = data[body:end]
case "data":
samples = data[body:end]
}
pos = body + size + size%2
}
if len(fmtChunk) < 16 || samples == nil {
return nil, bad
}
align := int(binary.LittleEndian.Uint16(fmtChunk[12:]))
if align <= 0 {
return nil, bad
}
header := 12 + 8 + len(fmtChunk) + 8
per := (max - header) / align * align
if per <= 0 {
return nil, errors.New("wav: pieces too small")
}
var out []audioPiece
for off := 0; off < len(samples); off += per {
chunk := samples[off:min(off+per, len(samples))]
var b bytes.Buffer
b.WriteString("RIFF")
_ = binary.Write(&b, binary.LittleEndian, uint32(4+8+len(fmtChunk)+8+len(chunk))) //nolint:gosec // pieces are a few MB, far below 4 GB
b.WriteString("WAVEfmt ")
_ = binary.Write(&b, binary.LittleEndian, uint32(len(fmtChunk))) //nolint:gosec // pieces are a few MB, far below 4 GB
b.Write(fmtChunk)
b.WriteString("data")
_ = binary.Write(&b, binary.LittleEndian, uint32(len(chunk))) //nolint:gosec // pieces are a few MB, far below 4 GB
b.Write(chunk)
out = append(out, audioPiece{Name: fmt.Sprintf("%s-%03d.wav", base, len(out)+1), Data: b.Bytes()})
}
return out, nil
}