forked from charmbracelet/vhs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
vhs.go
376 lines (321 loc) · 9.7 KB
/
vhs.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package main
import (
"context"
"errors"
"fmt"
"log"
"math"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/launcher"
"github.com/go-rod/rod/lib/proto"
)
// VHS is the object that controls the setup.
type VHS struct {
Options *Options
Errors []error
Page *rod.Page
browser *rod.Browser
TextCanvas *rod.Element
CursorCanvas *rod.Element
mutex *sync.Mutex
started bool
recording bool
tty *exec.Cmd
totalFrames int
close func() error
}
// Options is the set of options for the setup.
type Options struct {
Shell Shell
FontFamily string
FontSize int
LetterSpacing float64
LineHeight float64
TypingSpeed time.Duration
Theme Theme
Test TestOptions
Video VideoOptions
LoopOffset float64
CursorBlink bool
}
const (
defaultFontSize = 22
defaultTypingSpeed = 50 * time.Millisecond
defaultLineHeight = 1.0
defaultLetterSpacing = 1.0
fontsSeparator = ","
defaultCursorBlink = true
)
var defaultFontFamily = withSymbolsFallback(strings.Join([]string{
"JetBrains Mono",
"DejaVu Sans Mono",
"Menlo",
"Bitstream Vera Sans Mono",
"Inconsolata",
"Roboto Mono",
"Hack",
"Consolas",
"ui-monospace",
"monospace",
}, fontsSeparator))
var symbolsFallback = []string{
"Apple Symbols",
}
func withSymbolsFallback(font string) string {
return font + fontsSeparator + strings.Join(symbolsFallback, fontsSeparator)
}
// DefaultVHSOptions returns the default set of options to use for the setup function.
func DefaultVHSOptions() Options {
return Options{
FontFamily: defaultFontFamily,
FontSize: defaultFontSize,
LetterSpacing: defaultLetterSpacing,
LineHeight: defaultLineHeight,
TypingSpeed: defaultTypingSpeed,
Shell: Shells[defaultShell],
Theme: DefaultTheme,
Video: DefaultVideoOptions(),
CursorBlink: defaultCursorBlink,
}
}
// New sets up ttyd and go-rod for recording frames.
func New() VHS {
mu := &sync.Mutex{}
opts := DefaultVHSOptions()
return VHS{
Options: &opts,
recording: true,
mutex: mu,
}
}
// Start starts ttyd, browser and everything else needed to create the gif.
func (vhs *VHS) Start() error {
vhs.mutex.Lock()
defer vhs.mutex.Unlock()
if vhs.started {
return fmt.Errorf("vhs is already started")
}
port := randomPort()
vhs.tty = buildTtyCmd(port, vhs.Options.Shell)
if err := vhs.tty.Start(); err != nil {
return fmt.Errorf("could not start tty: %w", err)
}
path, _ := launcher.LookPath()
enableNoSandbox := os.Getenv("VHS_NO_SANDBOX") != ""
u, err := launcher.New().Leakless(false).Bin(path).NoSandbox(enableNoSandbox).Launch()
if err != nil {
return fmt.Errorf("could not launch browser: %w", err)
}
browser := rod.New().ControlURL(u).MustConnect()
page, err := browser.Page(proto.TargetCreateTarget{URL: fmt.Sprintf("http://localhost:%d", port)})
if err != nil {
return fmt.Errorf("could not open ttyd: %w", err)
}
vhs.browser = browser
vhs.Page = page
vhs.close = vhs.browser.Close
vhs.started = true
return nil
}
// Setup sets up the VHS instance and performs the necessary actions to reflect
// the options that are default and set by the user.
func (vhs *VHS) Setup() {
// Set Viewport to the correct size, accounting for the padding that will be
// added during the render.
padding := vhs.Options.Video.Padding
margin := 0
if vhs.Options.Video.MarginFill != "" {
margin = vhs.Options.Video.Margin
}
bar := 0
if vhs.Options.Video.WindowBar != "" {
bar = vhs.Options.Video.WindowBarSize
}
width := vhs.Options.Video.Width - double(padding) - double(margin)
height := vhs.Options.Video.Height - double(padding) - double(margin) - bar
vhs.Page = vhs.Page.MustSetViewport(width, height, 0, false)
// Let's wait until we can access the window.term variable.
vhs.Page = vhs.Page.MustWait("() => window.term != undefined")
// Find xterm.js canvases for the text and cursor layer for recording.
vhs.TextCanvas, _ = vhs.Page.Element("canvas.xterm-text-layer")
vhs.CursorCanvas, _ = vhs.Page.Element("canvas.xterm-cursor-layer")
// Apply options to the terminal
// By this point the setting commands have been executed, so the `opts` struct is up to date.
vhs.Page.MustEval(fmt.Sprintf("() => { term.options = { fontSize: %d, fontFamily: '%s', letterSpacing: %f, lineHeight: %f, theme: %s, cursorBlink: %t } }",
vhs.Options.FontSize, vhs.Options.FontFamily, vhs.Options.LetterSpacing,
vhs.Options.LineHeight, vhs.Options.Theme.String(), vhs.Options.CursorBlink))
// Fit the terminal into the window
vhs.Page.MustEval("term.fit")
_ = os.RemoveAll(vhs.Options.Video.Input)
_ = os.MkdirAll(vhs.Options.Video.Input, os.ModePerm)
}
const cleanupWaitTime = 100 * time.Millisecond
// Terminate cleans up a VHS instance and terminates the go-rod browser and ttyd
// processes.
func (vhs *VHS) terminate() error {
// Give some time for any commands executed (such as `rm`) to finish.
//
// If a user runs a long running command, they must sleep for the required time
// to finish.
time.Sleep(cleanupWaitTime)
// Tear down the processes we started.
vhs.browser.MustClose()
return vhs.tty.Process.Kill()
}
// Cleanup individual frames.
func (vhs *VHS) Cleanup() error {
return os.RemoveAll(vhs.Options.Video.Input)
}
// Render starts rendering the individual frames into a video.
func (vhs *VHS) Render() error {
// Apply Loop Offset by modifying frame sequence
if err := vhs.ApplyLoopOffset(); err != nil {
return err
}
// Generate the video(s) with the frames.
var cmds []*exec.Cmd
cmds = append(cmds, MakeGIF(vhs.Options.Video))
cmds = append(cmds, MakeMP4(vhs.Options.Video))
cmds = append(cmds, MakeWebM(vhs.Options.Video))
for _, cmd := range cmds {
if cmd == nil {
continue
}
out, err := cmd.CombinedOutput()
if err != nil {
log.Println(string(out))
}
}
return nil
}
// ApplyLoopOffset by modifying frame sequence
func (vhs *VHS) ApplyLoopOffset() error {
if vhs.totalFrames <= 0 {
return errors.New("no frames")
}
loopOffsetPercentage := vhs.Options.LoopOffset
// Calculate # of frames to offset from LoopOffset percentage
loopOffsetFrames := int(math.Ceil(loopOffsetPercentage / 100.0 * float64(vhs.totalFrames)))
// Take care of overflow and keep track of exact offsetPercentage
loopOffsetFrames = loopOffsetFrames % vhs.totalFrames
// No operation if nothing to offset
if loopOffsetFrames <= 0 {
return nil
}
// Move all frames in [offsetStart, offsetEnd] to end of frame sequence
offsetStart := vhs.Options.Video.StartingFrame
offsetEnd := loopOffsetFrames
// New starting frame will be the next frame after offsetEnd
vhs.Options.Video.StartingFrame = offsetEnd + 1
// Rename all text and cursor frame files in the range concurrently
errCh := make(chan error)
doneCh := make(chan bool)
var wg sync.WaitGroup
for counter := offsetStart; counter <= offsetEnd; counter++ {
wg.Add(1)
go func(frameNum int) {
defer wg.Done()
offsetFrameNum := frameNum + vhs.totalFrames
if err := os.Rename(
filepath.Join(vhs.Options.Video.Input, fmt.Sprintf(cursorFrameFormat, frameNum)),
filepath.Join(vhs.Options.Video.Input, fmt.Sprintf(cursorFrameFormat, offsetFrameNum)),
); err != nil {
errCh <- fmt.Errorf("error applying offset to cursor frame: %w", err)
}
}(counter)
wg.Add(1)
go func(frameNum int) {
defer wg.Done()
offsetFrameNum := frameNum + vhs.totalFrames
if err := os.Rename(
filepath.Join(vhs.Options.Video.Input, fmt.Sprintf(textFrameFormat, frameNum)),
filepath.Join(vhs.Options.Video.Input, fmt.Sprintf(textFrameFormat, offsetFrameNum)),
); err != nil {
errCh <- fmt.Errorf("error applying offset to text frame: %w", err)
}
}(counter)
}
go func() {
wg.Wait()
close(doneCh)
}()
select {
case <-doneCh:
return nil
case err := <-errCh:
// Bail out in case of an error while renaming
return err
}
}
const quality = 1.0
// Record begins the goroutine which captures images from the xterm.js canvases.
func (vhs *VHS) Record(ctx context.Context) <-chan error {
ch := make(chan error)
interval := time.Second / time.Duration(vhs.Options.Video.Framerate)
go func() {
counter := 0
start := time.Now()
for {
select {
case <-ctx.Done():
_ = vhs.terminate()
// Save total # of frames for offset calculation
vhs.totalFrames = counter
// Signal caller that we're done recording.
close(ch)
return
case <-time.After(interval - time.Since(start)):
// record last attempt
start = time.Now()
if !vhs.recording {
continue
}
if vhs.Page == nil {
continue
}
cursor, cursorErr := vhs.CursorCanvas.CanvasToImage("image/png", quality)
text, textErr := vhs.TextCanvas.CanvasToImage("image/png", quality)
if textErr != nil || cursorErr != nil {
ch <- fmt.Errorf("error: %v, %v", textErr, cursorErr)
continue
}
counter++
if err := os.WriteFile(
filepath.Join(vhs.Options.Video.Input, fmt.Sprintf(cursorFrameFormat, counter)),
cursor,
os.ModePerm,
); err != nil {
ch <- fmt.Errorf("error writing cursor frame: %w", err)
continue
}
if err := os.WriteFile(
filepath.Join(vhs.Options.Video.Input, fmt.Sprintf(textFrameFormat, counter)),
text,
os.ModePerm,
); err != nil {
ch <- fmt.Errorf("error writing text frame: %w", err)
continue
}
}
}
}()
return ch
}
// ResumeRecording indicates to VHS that the recording should be resumed.
func (vhs *VHS) ResumeRecording() {
vhs.mutex.Lock()
defer vhs.mutex.Unlock()
vhs.recording = true
}
// PauseRecording indicates to VHS that the recording should be paused.
func (vhs *VHS) PauseRecording() {
vhs.mutex.Lock()
defer vhs.mutex.Unlock()
vhs.recording = false
}