droboticflow/internal/api/annotation_batch_decode.go

44 lines
1.5 KiB
Go

package api
import (
"context"
"fmt"
"os/exec"
"strings"
)
type annotationFrameSlice struct {
Start, End int
Output string
}
// Each input is decoded once per bounded group, not once per output slice.
// Half-open frame trims preserve exact original frame selection; no fast seek
// or keyframe-only stream copy is used.
func writeFrameAccurateSlices(ctx context.Context, source string, slices []annotationFrameSlice) error {
for offset := 0; offset < len(slices); offset += 8 {
group := slices[offset:min(offset+8, len(slices))]
filters := []string{}
split := fmt.Sprintf("[0:v]split=%d", len(group))
for i := range group {
split += fmt.Sprintf("[in%d]", i)
}
filters = append(filters, split)
for i, s := range group {
if s.Start < 0 || s.End <= s.Start {
return fmt.Errorf("invalid frame slice")
}
filters = append(filters, fmt.Sprintf("[in%d]trim=start_frame=%d:end_frame=%d,setpts=PTS-STARTPTS[out%d]", i, s.Start, s.End, i))
}
args := []string{"-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-threads", "2", "-i", source, "-filter_complex_threads", "1", "-filter_complex", strings.Join(filters, ";")}
for i, s := range group {
args = append(args, "-map", fmt.Sprintf("[out%d]", i), "-an", "-c:v", "libx264", "-threads", "2", "-preset", "ultrafast", "-crf", "23", "-pix_fmt", "yuv420p", s.Output)
}
out, e := exec.CommandContext(ctx, "ffmpeg", args...).CombinedOutput()
if e != nil {
return fmt.Errorf("batch frame slicing: %w: %s", e, out)
}
}
return nil
}