From 3a9c03ac88b6e6476206a87e3703e247c965e7c9 Mon Sep 17 00:00:00 2001 From: Alex McGrath Date: Tue, 23 Sep 2025 10:28:51 +0100 Subject: [PATCH] feat(tags): add ffprobe reader --- tags/ffprobe/ffprobe.go | 62 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 tags/ffprobe/ffprobe.go diff --git a/tags/ffprobe/ffprobe.go b/tags/ffprobe/ffprobe.go new file mode 100644 index 0000000..b0a7c65 --- /dev/null +++ b/tags/ffprobe/ffprobe.go @@ -0,0 +1,62 @@ +package ffprobe + +import ( + "encoding/json" + "fmt" + "os/exec" + "path/filepath" + "strconv" + "strings" + "time" + + "go.senan.xyz/gonic/tags" +) + +var _ tags.Reader = Reader{} + +type Reader struct{} + +func (Reader) CanRead(absPath string) bool { + switch ext := strings.ToLower(filepath.Ext(absPath)); ext { + case ".mp3", ".flac", ".aac", ".m4a", ".m4b", ".ogg", ".opus", ".wma", ".wav", ".wv": + return true + } + return false +} + +func (Reader) Read(absPath string) (tags.Properties, map[string][]string, error) { + out, err := exec.Command("ffprobe", "-hide_banner", "-v", "0", "-i", absPath, "-show_entries", "format", "-of", "json").Output() + if err != nil { + return tags.Properties{}, nil, fmt.Errorf("output: %w", err) + } + + var format struct { + Format struct { + Duration string `json:"duration"` + BitRate string `json:"bit_rate"` + Tags map[string]string `json:"tags"` + } `json:"format"` + } + if err := json.Unmarshal(out, &format); err != nil { + return tags.Properties{}, nil, fmt.Errorf("read json: %w", err) + } + + durationSecs, _ := strconv.ParseFloat(format.Format.Duration, 64) + bitRateBitsPerSec, _ := strconv.Atoi(format.Format.BitRate) + + var tgs = map[string][]string{} + for k, vs := range format.Format.Tags { + switch k { + case "OK": + continue + } + tgs[k] = strings.Split(vs, ";") + } + + props := tags.Properties{ + Length: time.Duration(durationSecs) * time.Second, + Bitrate: uint(bitRateBitsPerSec / 1000), + } + + return props, tgs, nil +}