// SPDX-License-Identifier: AGPL-3.0-or-later package main import ( "bytes" "context" "errors" "fmt" "os" "os/exec" "path/filepath" "sort" "strings" ) // errUnreadable wraps ffmpeg's complaint about a recording it cannot decode. type errUnreadable struct{ msg string } func (e errUnreadable) Error() string { return e.msg } // inputFormats are the demuxers ffmpeg may use on an upload. Playlists // (hls, concat, …) and image sequences are left out: they open other files. const inputFormats = "mov,mp4,m4a,3gp,mp3,wav,ogg,matroska,webm,flac,aac,mpeg,mpegts,asf,amr,caf,aiff,au,w64" // inputExt returns the extension ffmpeg sees for the upload: only short, // plain ones, so a file name cannot pass anything else to ffmpeg. func inputExt(name string) string { ext := strings.ToLower(filepath.Ext(name)) if len(ext) < 2 || len(ext) > 6 { return ".bin" } for _, r := range ext[1:] { if (r < 'a' || r > 'z') && (r < '0' || r > '9') { return ".bin" } } return ext } // split re-encodes the recording in dir/in to 16 kHz mono MP3 and cuts // it every segment seconds. It returns the pieces in order. func split(ctx context.Context, ffmpeg, in string, segment int) ([][]byte, error) { dir := filepath.Dir(in) // #nosec G204 G702 -- ffmpeg from the config, fixed arguments, paths in our temp dir cmd := exec.CommandContext(ctx, ffmpeg, "-nostdin", "-hide_banner", "-loglevel", "error", "-protocol_whitelist", "file", "-format_whitelist", inputFormats, "-i", in, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "libmp3lame", "-b:a", "32k", "-f", "segment", "-segment_time", fmt.Sprint(segment), "-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() } var exit *exec.ExitError if errors.As(err, &exit) { msg := strings.TrimSpace(stderr.String()) if len(msg) > 200 { msg = msg[:200] } return nil, errUnreadable{msg: "The recording could not be read: " + msg} } return nil, err } files, err := filepath.Glob(filepath.Join(dir, "part*.mp3")) if err != nil { return nil, err } sort.Strings(files) var out [][]byte for _, f := range files { b, err := os.ReadFile(f) // #nosec G304 G703 -- a file ffmpeg wrote into our temp dir if err != nil { return nil, err } if len(b) > 0 { out = append(out, b) } } if len(out) == 0 { return nil, errUnreadable{msg: "The recording has no sound to transcribe."} } return out, nil }