Files
streamrip-go/internal/audio/convert/convert.go
T
Joren 1b13dace0e fix: audit fixes for credentials, auth races, and silent data loss
- redact credentials from transport errors, verbose request logs, and
  download-start logs; add sid/api_key/sign to sensitive params
- stop forwarding Yandex OAuth headers to API-supplied download hosts and
  give the last.fm mirror an opt-out and a notice
- serialize deezer token state, beatport token snapshots, and qobuz mobile
  KEK access so concurrent workers cannot race login refreshes
- suffix colliding track/video output names instead of overwriting
- propagate deezer/qobuz pagination errors, keep paginating when counts
  are missing, and return a non-zero exit for partial album/playlist rips
- clear failed_downloads rows on success and downloads rows on failure;
  open browse databases read-only; honor independent DB feature flags
- drop the redundant deezer metadata call, paginate Yandex searches,
  bound and rate-limit yt-dlp, and deep-clone the SoundCloud cache
- validate conversion codecs before ripping and isolate the qobuz convert
  smoke test from the real library
- write the config atomically and fix deezer slug-vs-id URL parsing
2026-11-23 10:32:17 +01:00

154 lines
3.7 KiB
Go

package convert
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"streamrip-go/internal/config"
)
type profile struct {
codecLib string
ext string
lossless bool
}
var profiles = map[string]profile{
"FLAC": {codecLib: "flac", ext: "flac", lossless: true},
"ALAC": {codecLib: "alac", ext: "m4a", lossless: true},
"OPUS": {codecLib: "libopus", ext: "opus", lossless: false},
"MP3": {codecLib: "libmp3lame", ext: "mp3", lossless: false},
"VORBIS": {codecLib: "libvorbis", ext: "ogg", lossless: false},
"AAC": {codecLib: "aac", ext: "m4a", lossless: false},
}
// SupportsCodec reports whether codec names a conversion target this build can
// produce. Callers that accept a codec from the command line should check this
// before starting a download, so an invalid target fails immediately instead of
// after the audio has been fetched.
func SupportsCodec(codec string) bool {
_, ok := profiles[strings.ToUpper(strings.TrimSpace(codec))]
return ok
}
func Convert(ctx context.Context, path string, cfg config.ConversionConfig) (string, error) {
if !cfg.Enabled {
return path, nil
}
if _, err := exec.LookPath("ffmpeg"); err != nil {
return path, fmt.Errorf("ffmpeg not found: %w", err)
}
p, ok := profiles[strings.ToUpper(strings.TrimSpace(cfg.Codec))]
if !ok {
return path, fmt.Errorf("unsupported conversion codec: %s", cfg.Codec)
}
base := strings.TrimSuffix(path, filepath.Ext(path))
finalPath := base + "." + p.ext
tmpPath := finalPath + ".tmp." + p.ext
args := buildFFmpegArgs(path, tmpPath, p, cfg)
cmd := exec.CommandContext(ctx, "ffmpeg", args...)
output, err := cmd.CombinedOutput()
if err != nil {
_ = os.Remove(tmpPath)
return path, fmt.Errorf("conversion failed: %w: %s", err, string(output))
}
if err = os.Rename(tmpPath, finalPath); err != nil {
_ = os.Remove(tmpPath)
return path, err
}
if path != finalPath {
_ = os.Remove(path)
}
return finalPath, nil
}
func buildFFmpegArgs(inputPath, outputPath string, p profile, cfg config.ConversionConfig) []string {
args := []string{
"-y",
"-i", inputPath,
"-map", "0:a:0",
"-map_metadata", "0",
"-c:a", p.codecLib,
}
if supportsAttachedPicture(p.ext) {
args = append(args,
"-map", "0:v:0?",
"-c:v", "mjpeg",
"-disposition:v:0", "attached_pic",
)
if p.ext == "mp3" {
args = append(args, "-id3v2_version", "3")
}
}
if p.lossless {
filter := buildLosslessFilter(cfg)
if filter != "" {
args = append(args, "-af", filter)
}
} else {
if cfg.LossyBitrate > 0 {
args = append(args, "-b:a", strconv.Itoa(cfg.LossyBitrate)+"k")
}
}
args = append(args, outputPath)
return args
}
func supportsAttachedPicture(ext string) bool {
switch strings.TrimPrefix(strings.ToLower(ext), ".") {
case "flac", "mp3", "m4a", "mp4":
return true
default:
return false
}
}
func buildLosslessFilter(cfg config.ConversionConfig) string {
parts := make([]string, 0, 2)
if cfg.SamplingRate > 0 {
rates := allowedSampleRates(cfg.SamplingRate)
if len(rates) > 0 {
parts = append(parts, "sample_rates="+strings.Join(rates, "|"))
}
}
if cfg.BitDepth == 16 {
parts = append(parts, "sample_fmts=s16p|s16")
} else if cfg.BitDepth == 24 || cfg.BitDepth == 32 {
parts = append(parts, "sample_fmts=s16p|s16|s32p|s32")
}
if len(parts) == 0 {
return ""
}
return "aformat=" + strings.Join(parts, ":")
}
func allowedSampleRates(max int) []string {
all := []int{44100, 48000, 88200, 96000, 176400, 192000}
out := make([]int, 0, len(all))
for _, r := range all {
if r <= max {
out = append(out, r)
}
}
sort.Ints(out)
str := make([]string, 0, len(out))
for _, r := range out {
str = append(str, strconv.Itoa(r))
}
return str
}