1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
// Package thumb generates thumbnail images.
package thumb
import (
"context"
"fmt"
"math/rand"
"os/exec"
)
// Generator creates a thumbnail for a given media file.
type Generator interface {
Generate(ctx context.Context, inputPath, outputPath string, duration float64) error
}
// FFmpegGenerator uses ffmpeg to extract a random frame.
type FFmpegGenerator struct {
execer func(ctx context.Context, name string, arg ...string) *exec.Cmd
}
// NewFFmpegGenerator creates a new FFmpegGenerator.
func NewFFmpegGenerator() *FFmpegGenerator {
return &FFmpegGenerator{
execer: exec.CommandContext,
}
}
// Generate picks a random offset (at least 1 second if duration > 0) and
// runs ffmpeg to produce a JPEG thumbnail.
func (g *FFmpegGenerator) Generate(ctx context.Context, inputPath, outputPath string, duration float64) error {
offset := 0.0
if duration > 0 {
offset = rand.Float64() * duration
if offset < 1.0 {
offset = 1.0
}
}
cmd := g.execer(ctx, "ffmpeg",
"-ss", fmt.Sprintf("%.3f", offset),
"-i", inputPath,
"-vf", "scale=320:-1",
"-frames:v", "1",
"-q:v", "2",
"-y",
outputPath,
)
if err := cmd.Run(); err != nil {
return fmt.Errorf("ffmpeg generate thumbnail for %s: %w", inputPath, err)
}
return nil
}
// MockGenerator is a test fake for Generator.
type MockGenerator struct {
GenerateFunc func(ctx context.Context, inputPath, outputPath string, duration float64) error
}
// Generate delegates to GenerateFunc or succeeds silently.
func (m *MockGenerator) Generate(ctx context.Context, inputPath, outputPath string, duration float64) error {
if m.GenerateFunc != nil {
return m.GenerateFunc(ctx, inputPath, outputPath, duration)
}
return nil
}
|