-
Notifications
You must be signed in to change notification settings - Fork 240
/
vhs.go
224 lines (194 loc) · 6.08 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
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"sync"
"time"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/input"
"github.com/go-rod/rod/lib/launcher"
)
// VHS is the object that controls the setup.
type VHS struct {
Options *Options
Page *rod.Page
browser *rod.Browser
TextCanvas *rod.Element
CursorCanvas *rod.Element
mutex *sync.Mutex
recording bool
tty *exec.Cmd
close func() error
}
// Options is the set of options for the setup.
type Options struct {
FontFamily string
FontSize int
LetterSpacing float64
LineHeight float64
Prompt string
TypingSpeed time.Duration
Theme Theme
Test TestOptions
Video VideoOptions
}
const (
defaultFontSize = 22
typingSpeed = 50 * time.Millisecond
)
// DefaultVHSOptions returns the default set of options to use for the setup function.
func DefaultVHSOptions() Options {
return Options{
Prompt: "\\[\\e[38;2;90;86;224m\\]> \\[\\e[0m\\]",
FontFamily: "JetBrains Mono,DejaVu Sans Mono,Menlo,Bitstream Vera Sans Mono,Inconsolata,Roboto Mono,Hack,Consolas,ui-monospace,monospace",
FontSize: defaultFontSize,
LetterSpacing: 0,
LineHeight: 1.0,
TypingSpeed: typingSpeed,
Theme: DefaultTheme,
Video: DefaultVideoOptions(),
}
}
// New sets up ttyd and go-rod for recording frames.
func New() VHS {
port := randomPort()
tty := StartTTY(port)
go tty.Run() //nolint:errcheck
opts := DefaultVHSOptions()
path, _ := launcher.LookPath()
u := launcher.New().Leakless(false).Bin(path).MustLaunch()
browser := rod.New().ControlURL(u).MustConnect().SlowMotion(opts.TypingSpeed)
page := browser.MustPage(fmt.Sprintf("http://localhost:%d", port))
mu := &sync.Mutex{}
return VHS{
Options: &opts,
Page: page,
browser: browser,
tty: tty,
recording: true,
mutex: mu,
close: browser.Close,
}
}
// 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
width := vhs.Options.Video.Width - padding - padding
height := vhs.Options.Video.Height - padding - padding
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")
// Set Prompt
vhs.Page.MustElement("textarea").
MustInput(fmt.Sprintf(` set +o history; unset PROMPT_COMMAND; export PS1="%s"; clear;`, vhs.Options.Prompt)).
MustType(input.Enter)
// 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 } }",
vhs.Options.FontSize, vhs.Options.FontFamily, vhs.Options.LetterSpacing,
vhs.Options.LineHeight, vhs.Options.Theme.String()))
// 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
// Cleanup cleans up a VHS instance and terminates the go-rod browser and ttyd
// processes.
//
// It also begins the rendering process of the frames into videos.
func (vhs *VHS) Cleanup() {
vhs.PauseRecording()
// 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()
_ = vhs.tty.Process.Kill()
// 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 {
fmt.Println(string(out))
}
}
// Cleanup frames if we successfully made the GIF.
if vhs.Options.Video.CleanupFrames {
_ = os.RemoveAll(vhs.Options.Video.Input)
}
}
const quality = 0.92
// Record begins the goroutine which captures images from the xterm.js canvases.
func (vhs *VHS) Record() {
interval := time.Second / time.Duration(vhs.Options.Video.Framerate)
time.Sleep(interval)
go func() {
counter := 0
for {
if !vhs.recording {
time.Sleep(interval + interval)
continue
}
if vhs.Page != nil {
counter++
start := time.Now()
cursor, cursorErr := vhs.CursorCanvas.CanvasToImage("image/png", quality)
text, textErr := vhs.TextCanvas.CanvasToImage("image/png", quality)
if textErr == nil && cursorErr == nil {
if err := os.WriteFile(
filepath.Join(vhs.Options.Video.Input, fmt.Sprintf(cursorFrameFormat, counter)),
cursor,
os.ModePerm,
); err != nil {
log.Printf("error writing cursor frame: %v", err)
}
if err := os.WriteFile(
filepath.Join(vhs.Options.Video.Input, fmt.Sprintf(textFrameFormat, counter)),
text,
os.ModePerm,
); err != nil {
log.Printf("error writing text frame: %v", err)
}
} else {
log.Printf("error: %v, %v", textErr, cursorErr)
}
elapsed := time.Since(start)
if elapsed >= interval {
continue
} else {
time.Sleep(interval - elapsed)
}
}
}
}()
}
// 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
}