-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathminicap.go
379 lines (357 loc) · 8.34 KB
/
minicap.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
377
378
379
package minicap
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"image"
"image/jpeg"
"io"
"math/rand"
"net"
"strings"
"sync"
"time"
// _ "github.com/pixiv/go-libjpeg/jpeg" // not work on windows
)
var (
ErrAlreadyClosed = errors.New("already closed")
)
type Options struct {
Serial string
Adb string
}
type Service struct {
AdbPort int
AdbHost string
lforwardPort int // local forward port
d AdbDevice
r Rotation
dispInfo DisplayInfo
maxReDialCnt int
closed bool
imageC chan image.Image
mu sync.Mutex
lastImage image.Image
}
func NewService(opt Options) (s *Service, err error) {
s = &Service{
AdbPort: 5037,
AdbHost: "localhost",
closed: true,
maxReDialCnt: 10,
}
s.d, err = newAdbDevice(opt.Serial, opt.Adb)
if err != nil {
return
}
s.r, err = newRotationService(opt)
if err != nil {
return
}
return
}
// Install minicap and minicap.so to /data/local/tmp
// files downloaded from github.com/openstf/minicap
func (s *Service) Install() (err error) {
err = s.r.install()
if err != nil {
return
}
abi, err := s.d.getProp("ro.product.cpu.abi")
if err != nil {
return
}
sdk, err := s.d.getProp("ro.build.version.sdk")
if err != nil {
return
}
for _, filename := range []string{"minicap.so", "minicap"} {
isExists := s.d.isFileExists("/data/local/tmp/" + filename)
if isExists {
continue
}
// download file from github
var url string
if filename == "minicap.so" {
url = "https://github.com/openstf/stf/raw/master/vendor/minicap/shared/android-" + sdk + "/" + abi + "/minicap.so"
} else {
url = "https://github.com/openstf/stf/raw/master/vendor/minicap/bin/" + abi + "/minicap"
}
fName := "/data/local/tmp/" + filename
err = s.r.download(fName, url)
if err != nil {
return
}
}
return
}
/*
Check whether minicap is supported on the device
For more information, see: https://github.com/openstf/minicap
*/
func (s *Service) IsSupported() bool {
fileExists := s.d.isFileExists("/data/local/tmp/minicap")
if !fileExists {
err := s.Install()
if err != nil {
return false
}
}
out, err := s.d.shell("LD_LIBRARY_PATH=/data/local/tmp /data/local/tmp/minicap -i")
if err != nil {
return false
}
supported := strings.Contains(out, "height") && strings.Contains(out, "width")
return supported
}
// Remove minicap and minicap.so from device
func (s *Service) Uninstall() (err error) {
for _, filename := range []string{"minicap.so", "minicap"} {
if _, err := s.d.shell("rm", "-f", "/data/local/tmp/"+filename); err != nil {
return err
}
}
return nil
}
// Take screenshot
// If minicap in on, the return the last recent image
func (s *Service) Screenshot() (im image.Image, err error) {
if !s.IsSupported() {
err = errors.New("minicap not supported") // FIXME(ssx): maybe need to fallback to screencap
return
}
dispInfo, err := s.d.getDisplayInfo()
if err != nil {
return
}
if dispInfo.Width > dispInfo.Height {
dispInfo.Width, dispInfo.Height = dispInfo.Height, dispInfo.Width
}
params := fmt.Sprintf("%dx%d@%dx%d/%d", dispInfo.Width, dispInfo.Height,
dispInfo.Width, dispInfo.Height, dispInfo.Orientation*90)
fName := randSeq(10)
fName = fmt.Sprintf("go_%v.jpg", fName)
cmd := fmt.Sprintf("LD_LIBRARY_PATH=/data/local/tmp /data/local/tmp/minicap -n minicap -P %v -s > /data/local/tmp/%v", params, fName)
_, err = s.d.shell(cmd)
if err != nil {
return
}
fout, err := s.d.Device.OpenRead("/data/local/tmp/" + fName)
if err != nil {
return
}
im, _, err = image.Decode(fout)
fout.Close()
return
}
// Capture screen stream based on minicap
func (s *Service) Capture() (imageC <-chan image.Image, err error) {
err = s.r.start()
if err != nil {
return
}
orienC, err := s.r.watch()
if err != nil {
return
}
s.dispInfo, err = s.d.getDisplayInfo()
if err != nil {
return
}
// log.Println(s.dispInfo)
if err = s.runMinicap(s.dispInfo.Orientation); err != nil {
return
}
if err = s.startReadFromSocket(); err != nil {
return
}
// TODO(ssx): too slow here
select {
case orientation := <-orienC:
if orientation != s.dispInfo.Orientation {
s.dispInfo.Orientation = orientation
if err := s.runMinicap(orientation); err != nil {
break
}
time.Sleep(time.Duration(10+rand.Intn(100)) * time.Millisecond)
}
case <-time.After(time.Second):
return nil, errors.New("cannot fetch rotation")
}
go func() {
for {
orientation := <-orienC
if orientation != s.dispInfo.Orientation {
s.dispInfo.Orientation = orientation
if err := s.runMinicap(orientation); err != nil {
break
}
time.Sleep(time.Duration(10+rand.Intn(100)) * time.Millisecond)
}
}
}()
return s.imageC, nil
}
//Sampling minicap with fixed sampling rate
func (s *Service) FixedSampling(imC <-chan image.Image, freq int) <-chan image.Image {
imgFxdC := make(chan image.Image, 1)
go func() {
interval := int64(1e9 / freq)
for {
start := time.Now()
select {
case im := <-imC:
imgFxdC <- im
case <-time.After(time.Millisecond):
im, err := s.LastScreenshot()
if err != nil {
imgFxdC <- im
}
}
duration := time.Since(start).Nanoseconds()
time.Sleep(time.Duration(interval-duration) * time.Nanosecond)
}
}()
return imgFxdC
}
// Start Minicap until the minicap started
func (s *Service) runMinicap(orientation int) (err error) {
if !s.IsSupported() {
err = errors.New("minicap not supported")
return
}
if s.dispInfo.Height == 0 {
s.dispInfo, err = s.d.getDisplayInfo()
if err != nil {
return
}
}
if s.dispInfo.Width > s.dispInfo.Height {
s.dispInfo.Width, s.dispInfo.Height = s.dispInfo.Height, s.dispInfo.Width
}
s.close()
params := fmt.Sprintf("%dx%d@%dx%d/%d", s.dispInfo.Width, s.dispInfo.Height,
s.dispInfo.Width, s.dispInfo.Height, orientation)
cmd := s.d.buildCommand("LD_LIBRARY_PATH=/data/local/tmp", "/data/local/tmp/minicap", "-P", params, "-S")
if err = cmd.Start(); err != nil {
return
}
time.Sleep(time.Millisecond) // ?
if s.lforwardPort == 0 {
s.lforwardPort, err = freePort()
if err != nil {
return
}
}
if _, err = s.d.run("forward", fmt.Sprintf("tcp:%d", s.lforwardPort), "localabstract:minicap"); err != nil {
return
}
s.closed = false
return
}
// Close Minicap Service
func (s *Service) Close() (err error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return ErrAlreadyClosed
}
s.closed = true
close(s.imageC)
s.close()
s.d.run("forward", "--remove", fmt.Sprintf("tcp:%d", s.lforwardPort))
return
}
func (s *Service) close() (err error) {
return s.d.killProc("minicap")
}
// Check whether the minicap stream is closed.
func (s *Service) IsClosed() (Closed bool) {
return s.closed
}
// read image from socket
func (s *Service) startReadFromSocket() (err error) {
var conn net.Conn
s.dispInfo, err = s.d.getDisplayInfo()
if err != nil {
return
}
/*err = s.runMinicap(s.dispInfo.Orientation)
if err != nil {
return
}*/
s.imageC = make(chan image.Image, 1)
go func() {
idxReDialCnt := 0
for {
conn, err = net.Dial("tcp", fmt.Sprintf("%s:%d", s.AdbHost, s.lforwardPort))
if err != nil {
if idxReDialCnt < s.maxReDialCnt {
idxReDialCnt += 1
continue
} else {
break
}
}
var pid, rw, rh, vw, vh uint32
var version uint8
var unused uint8
var orientation uint8
binRead := func(data interface{}) error {
if err != nil {
return err
}
err = binary.Read(conn, binary.LittleEndian, data)
return err
}
binRead(&version)
binRead(&unused)
binRead(&pid)
binRead(&rw)
binRead(&rh)
binRead(&vw)
binRead(&vh)
binRead(&orientation)
binRead(&unused)
if err != nil {
continue
}
bufrd := bufio.NewReader(conn) // Do not put it into for loop
for {
var size uint32
if err = binRead(&size); err != nil {
break
}
lr := &io.LimitedReader{bufrd, int64(size)}
var im image.Image
im, err = jpeg.Decode(lr)
// im, _, err = image.Decode(lr)
if err != nil {
break
}
s.mu.Lock()
if s.closed {
break
}
s.lastImage = im
select {
case s.imageC <- im:
default:
}
s.mu.Unlock()
}
conn.Close()
}
}()
return nil
}
// Return last screenshot from minicap
// if minicap is closed, use Screenshot() instead
func (s *Service) LastScreenshot() (im image.Image, err error) {
if s.lastImage == nil || s.IsClosed() {
im, err = s.Screenshot()
return
}
return s.lastImage, nil
}