-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
228 lines (197 loc) · 4.86 KB
/
main.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
package main
import (
"context"
"flag"
"fmt"
"image"
"image/color"
"image/png"
"os"
"os/signal"
"runtime"
"strings"
"syscall"
"time"
"github.com/blackjack/webcam"
"github.com/lucasb-eyer/go-colorful"
"github.com/muesli/termenv"
"github.com/nfnt/resize"
"golang.org/x/term"
)
var (
col = color.Color(color.RGBA{0, 0, 0, 0}) // if alpha is 0, use truecolor
pixels = []rune{' ', '.', ',', ':', ';', 'i', '1', 't', 'f', 'L', 'C', 'G', '0', '8', '@'}
)
func main() {
if runtime.GOOS != "linux" {
fmt.Fprintln(os.Stderr, "asciicam only works on Linux")
os.Exit(1)
}
// graceful shutdown on SIGINT, SIGTERM
ctx, cancel := context.WithCancel(context.Background())
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
fmt.Println("\nShutting down...")
cancel()
}()
if err := run(ctx); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func run(ctx context.Context) error {
dev := flag.String("dev", "/dev/video0", "video device")
sample := flag.String("sample", "bgsample", "Where to find/store the sample data")
gen := flag.Bool("gen", false, "Generate a new background")
screen := flag.Bool("greenscreen", false, "Use greenscreen")
screenDist := flag.Float64("threshold", 0.13, "Greenscreen threshold")
ansi := flag.Bool("ansi", false, "Use ANSI")
usecol := flag.String("color", "", "Use single color")
w := flag.Uint("width", 0, "output width")
h := flag.Uint("height", 0, "output height")
camWidth := flag.Uint("camWidth", 320, "cam input width")
camHeight := flag.Uint("camHeight", 180, "cam input height")
showFPS := flag.Bool("fps", false, "Show FPS")
flag.Parse()
if *usecol != "" {
c, err := colorful.Hex(*usecol)
if err != nil {
return fmt.Errorf("invalid color: %v", err)
}
col = c
}
height := *h // height of the terminal output
width := *w // width of the terminal output
// detect terminal width
isTerminal := term.IsTerminal(int(os.Stdout.Fd()))
if isTerminal {
w, h, err := term.GetSize(int(os.Stdout.Fd()))
if err == nil {
if width == 0 {
width = uint(w)
}
if height == 0 {
height = uint(h)
}
}
}
if width == 0 {
width = 125
}
if height == 0 {
height = 50
}
// ANSI rendering uses half-height blocks
if *ansi {
height *= 2
}
cam, err := webcam.Open(*dev)
if err != nil {
return err
}
defer cam.Close() //nolint:errcheck
// find available yuyv format
formats := cam.GetSupportedFormats()
for k, v := range formats {
fmt.Println(k, v)
if strings.Contains(v, "YUYV") {
f, w, h, err := cam.SetImageFormat(k, uint32(*camWidth), uint32(*camHeight))
if err != nil {
return fmt.Errorf("failed to set image format: %w", err)
}
fmt.Println(f, w, h)
}
}
// start streaming
_ = cam.SetBufferCount(1)
err = cam.StartStreaming()
if err != nil {
return fmt.Errorf("failed to start streaming: %w", err)
}
defer cam.StopStreaming() //nolint:errcheck
var bg image.Image
if !*gen && *screen {
bg, err = loadBgSamples(*sample, width, height)
if err != nil {
return fmt.Errorf("could not load background samples: %w", err)
}
}
p := termenv.EnvColorProfile()
termenv.HideCursor()
defer termenv.ShowCursor()
termenv.AltScreen()
defer termenv.ExitAltScreen()
// seed fps counter
var fps []float64
for i := 0; i < 10; i++ {
fps = append(fps, 0)
}
i := 0
for {
if ctx.Err() != nil {
return nil //nolint:nilerr
}
err = cam.WaitForFrame(1)
switch err.(type) {
case nil:
case *webcam.Timeout:
fmt.Fprintln(os.Stderr, err.Error())
continue
default:
return fmt.Errorf("failed waiting for frame: %w", err)
}
frame, err := cam.ReadFrame()
if err != nil {
return fmt.Errorf("failed to read frame: %w", err)
}
if len(frame) == 0 {
continue
}
img := frameToImage(frame, *camWidth, *camHeight)
// generate background sample data
if *gen {
f, err := os.Create(fmt.Sprintf("%s/%d.png", *sample, i))
if err != nil {
return fmt.Errorf("failed to create sample file: %w", err)
}
if err := png.Encode(f, img); err != nil {
return fmt.Errorf("failed to encode sample frame: %w", err)
}
_ = f.Close()
i++
if i > 100 {
os.Exit(0)
}
}
// resize for further processing
img = resize.Resize(width, height, img, resize.Bilinear).(*image.RGBA)
// virtual green screen
if !*gen && *screen {
greenscreen(img, bg, *screenDist)
}
now := time.Now()
// convert frame to ascii/ansi
var s string
if *ansi {
s = imageToANSI(width, height, p, img)
} else {
s = imageToASCII(width, height, p, img)
}
// render
termenv.MoveCursor(0, 0)
fmt.Fprint(os.Stdout, s)
if *showFPS {
for i := len(fps) - 1; i > 0; i-- {
fps[i] = fps[i-1]
}
fps[0] = float64(time.Second / time.Since(now))
var fpsa float64
for _, f := range fps {
fpsa += f
}
fmt.Printf("FPS: %.0f", fpsa/float64(len(fps)))
}
}
}