-
Notifications
You must be signed in to change notification settings - Fork 2
/
engine.go
254 lines (242 loc) · 6.4 KB
/
engine.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package giffer
import (
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"github.com/pkg/errors"
)
// Engine implements video and image manipulation.
type Engine struct {
Dir string // Directory to write temporary files.
FFmpeg string // Path to FFmpeg binary.
Convert string // Path to imagemagick Convert binary.
Debug bool // Print commands used.
Out io.Writer // Writer to use if debug is true.
Junk []string // Temporary files to cleanup.
once sync.Once
}
// Cut and merge the target file into the specified time slices.
// Cuts is a slice of int pairs which are start and end times (in seconds)
// respectively.
// Returns a filepath to the merged file.
func (eng *Engine) Cut(video string, cuts ...[2]int) (string, error) {
if err := eng.init(); err != nil {
return "", fmt.Errorf("initializing engine: %w", err)
}
var (
cutfiles []string
entries []string
filelist = eng.path("tmp_file_list.txt")
merged = eng.path(fmt.Sprintf("merged%s", filepath.Ext(video)))
)
defer func() {
eng.Junk = append(eng.Junk, append(cutfiles, filelist, merged)...)
}()
for ii, c := range cuts {
start, end := c[0], c[1]
if start > end {
return "", fmt.Errorf("start > end: %d > %d", start, end)
}
output := eng.path(fmt.Sprintf("tmp_%d%s", ii, filepath.Ext(video)))
cutSlice := eng.command(
eng.FFmpeg,
"-ss", fmt.Sprintf("%d", start),
"-t", fmt.Sprintf("%d", end-start),
"-i", video,
output,
)
if out, err := cutSlice.CombinedOutput(); err != nil {
return "", errors.Wrapf(err, "cutting video: %s", string(out))
}
cutfiles = append(cutfiles, output)
}
for _, f := range cutfiles {
entries = append(entries, fmt.Sprintf("file '%s'", f))
}
if err := ioutil.WriteFile(
filelist,
[]byte(strings.Join(entries, "\n")),
0644,
); err != nil {
return "", errors.Wrap(err, "creating file list for concatentation")
}
merge := eng.command(
eng.FFmpeg,
"-f", "concat",
"-i", filelist,
"-c", "copy",
merged,
)
if out, err := merge.CombinedOutput(); err != nil {
return "", errors.Wrapf(err, "merging cut files: %s", string(out))
}
return merged, nil
}
// Transcode the target video file into a gif.
// Returns a filepath to the gif image.
func (eng *Engine) Transcode(
video string,
start, end float64,
width, height int,
fps float64,
) (string, error) {
if err := eng.init(); err != nil {
return "", fmt.Errorf("initializing engine: %w", err)
}
var (
duration = end - start
filters string
palettegen string
palette = eng.path("palette.png")
output = eng.path(fmt.Sprintf("%s.gif", strings.Split(filepath.Base(video), ".")[0]))
)
if height < -2 {
height = -2
}
if width < -2 {
width = -2
}
if fps > 0.0 {
filters += fmt.Sprintf("fps=%2f", fps)
}
if width > 0.0 || height > 0.0 {
if filters != "" {
filters += ","
}
filters += fmt.Sprintf("scale=%d:%d:flags=lanczos", width, height)
}
if len(filters) > 0 {
palettegen = fmt.Sprintf("%s,palettegen", filters)
} else {
palettegen = "palettegen"
}
defer func() {
eng.Junk = append(eng.Junk, palette, output)
}()
// TODO(jfm): make these structured, with omission as a field.
genPalette := eng.command(
eng.FFmpeg,
"-ss", fmt.Sprintf("%2f;omitempty", start),
"-t", fmt.Sprintf("%2f;omitempty", duration),
"-i", video,
"-vf", palettegen,
"-y", palette,
)
if out, err := genPalette.CombinedOutput(); err != nil {
return "", errors.Wrapf(err, "generating palette: %s", string(out))
}
makeGif := eng.command(
eng.FFmpeg,
"-ss", fmt.Sprintf("%2f;omitempty", start),
"-t", fmt.Sprintf("%2f;omitempty", duration),
"-i", video, "-i", palette,
"-lavfi", fmt.Sprintf("%s [x]; [x][1:v] paletteuse", filters),
"-y", output,
)
if out, err := makeGif.CombinedOutput(); err != nil {
return "", errors.Wrapf(err, "making gif: %s", string(out))
}
return output, nil
}
// Crush reduces the file size of a gif image.
// Accepts a filepath to the gif image and replaces it with the crushed gif.
// Fuzz is a percentage value between 0 and 100, where 0 is best quality, 100 is
// smallest file size. Optimal is typically 2-5.
func (eng *Engine) Crush(gif string, fuzz int) error {
if eng.Convert == "" {
return nil
}
args := []string{gif}
if fuzz > 0 {
args = append(args, "-fuzz", fmt.Sprintf("%d%%", fuzz))
}
args = append(args, "-layers", "Optimize", gif)
crushGif := eng.command(eng.Convert, args...)
if out, err := crushGif.CombinedOutput(); err != nil {
return errors.Wrap(err, string(out))
}
return nil
}
// Clean the temporary files.
func (eng *Engine) Clean() {
for _, f := range eng.Junk {
if err := os.Remove(f); err != nil {
eng.logf("clean: %v\n", err)
}
}
}
// command creates a new exec.Cmd after removing empty arguments.
// If an argument value contains "<value>;omitempty" and <value> is a zero
// value, the argument value and it's corresponding argument specifier are
// considered "empty" and omitted.
func (eng *Engine) command(cmd string, args ...string) *exec.Cmd {
var a []string
for ii := 0; ii < len(args); ii++ {
arg := args[ii]
if arg[0] == '-' { // This is an argument specifier eg "-h".
if v := args[ii+1]; v == "" {
ii++
continue
} else if strings.Contains(v, ";omitempty") {
// Handle special ;omitempty directive.
v = strings.Split(v, ";omitempty")[0]
if v == "" {
ii++
continue
}
x, _ := strconv.Atoi(v)
if x == 0 {
ii++
continue
}
fl, _ := strconv.ParseFloat(v, 64)
if fl <= 0.0 {
ii++
continue
}
args[ii+1] = v
}
}
a = append(a, arg)
}
if eng.Debug {
eng.logf("%s %s\n", cmd, strings.Join(a, " "))
}
return exec.Command(cmd, a...)
}
func (eng *Engine) logf(f string, v ...interface{}) (int, error) {
if eng.Debug && eng.Out != nil {
return fmt.Fprintf(eng.Out, f, v...)
}
return 0, nil
}
// path resolves the given path segments against the configured directory.
func (eng *Engine) path(s ...string) string {
p := filepath.Join(s...)
eng.logf("dir: %s, p: %s\n", eng.Dir, p)
p = strings.Replace(p, eng.Dir, "", 1)
return filepath.Join(eng.Dir, p)
}
func (eng *Engine) init() (err error) {
eng.once.Do(func() {
if eng.FFmpeg == "" {
eng.FFmpeg = "ffmpeg"
}
if eng.Dir == "" {
return
}
err = os.MkdirAll(eng.Dir, 0755)
if err != nil && !os.IsExist(err) {
err = errors.Wrap(err, "preparing directories")
} else if os.IsExist(err) {
err = nil
}
})
return err
}