Files
2026-11-16 11:31:37 +01:00

129 lines
2.9 KiB
Go

package ingest
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/fs"
"os/exec"
"strconv"
"strings"
)
type FFprobeProber struct {
Binary string
}
type ffprobeOutput struct {
Format struct {
FormatName string `json:"format_name"`
Duration string `json:"duration"`
BitRate string `json:"bit_rate"`
} `json:"format"`
Streams []struct {
CodecType string `json:"codec_type"`
CodecName string `json:"codec_name"`
Width int `json:"width"`
Height int `json:"height"`
Channels int `json:"channels"`
BitRate string `json:"bit_rate"`
} `json:"streams"`
}
func (p FFprobeProber) Probe(ctx context.Context, path string, _ fs.FileInfo) (Probe, error) {
binary := strings.TrimSpace(p.Binary)
if binary == "" {
binary = "ffprobe"
}
command := exec.CommandContext(ctx, binary,
"-v", "error",
"-print_format", "json",
"-show_format",
"-show_streams",
"-i", path,
)
var stderr bytes.Buffer
command.Stderr = &stderr
output, err := command.Output()
if err != nil {
message := strings.TrimSpace(stderr.String())
if message == "" {
return Probe{}, fmt.Errorf("ffprobe %s : %w", path, err)
}
return Probe{}, fmt.Errorf("ffprobe %s : %w: %s", path, err, message)
}
var parsed ffprobeOutput
if err := json.Unmarshal(output, &parsed); err != nil {
return Probe{}, fmt.Errorf("ffprobe %s : réponse JSON invalide : %w", path, err)
}
probe := Probe{
Mime: mimeForPath(path),
Metadata: make(map[string]any),
}
if parsed.Format.FormatName != "" {
probe.Metadata["container"] = parsed.Format.FormatName
}
if duration := durationMillis(parsed.Format.Duration); duration > 0 {
probe.Metadata["duration_ms"] = duration
}
if bitRate := positiveInt(parsed.Format.BitRate); bitRate > 0 {
probe.Metadata["bit_rate"] = bitRate
}
for _, stream := range parsed.Streams {
switch stream.CodecType {
case "video":
if _, exists := probe.Metadata["video_codec"]; exists {
continue
}
if stream.CodecName != "" {
probe.Metadata["video_codec"] = stream.CodecName
}
if stream.Width > 0 {
probe.Metadata["width"] = int64(stream.Width)
}
if stream.Height > 0 {
probe.Metadata["height"] = int64(stream.Height)
}
if bitRate := positiveInt(stream.BitRate); bitRate > 0 {
probe.Metadata["video_bit_rate"] = bitRate
}
case "audio":
if _, exists := probe.Metadata["audio_codec"]; exists {
continue
}
if stream.CodecName != "" {
probe.Metadata["audio_codec"] = stream.CodecName
}
if stream.Channels > 0 {
probe.Metadata["audio_channels"] = int64(stream.Channels)
}
}
}
return probe, nil
}
func durationMillis(value string) int64 {
seconds, err := strconv.ParseFloat(value, 64)
if err != nil || seconds <= 0 {
return 0
}
return int64(seconds * 1000)
}
func positiveInt(value string) int64 {
parsed, err := strconv.ParseInt(value, 10, 64)
if err != nil || parsed <= 0 {
return 0
}
return parsed
}