-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
527 lines (456 loc) · 16.4 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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"os"
"os/signal"
"strconv"
"strings"
"time"
"github.com/danielpaulus/quicktime_video_hack/screencapture"
"github.com/google/gousb"
"go.nanomsg.org/mangos/v3"
"go.nanomsg.org/mangos/v3/protocol/push"
// register transports
_ "github.com/nanomsg/mangos/transport/all"
log "github.com/sirupsen/logrus"
)
func main() {
var udid = flag.String( "udid" , "" , "Device UDID" )
var devicesCmd = flag.Bool( "devices" , false , "List devices then exit" )
var decimalFlag= flag.Bool( "decimal" , false , "Show product ID / vendor ID in decimal" )
var jsonFlag = flag.Bool( "json" , false , "Use JSON output when listing devices" )
var pullCmd = flag.Bool( "pull" , false , "Pull video" )
var pushSpec = flag.String( "pushSpec" , "tcp://127.0.0.1:7878", "NanoMsg spec to push h264 nalus to" )
var file = flag.String( "file", "" , "File to save h264 nalus into" )
var verbose = flag.Bool( "v" , false , "Verbose Debugging" )
var enableCmd = flag.Bool( "enable", false, "Enable device" )
var disableCmd = flag.Bool( "disable", false, "Disable device" )
flag.Parse()
log.SetFormatter(&log.JSONFormatter{})
if *verbose {
log.Info("Set Debug mode")
log.SetLevel(log.DebugLevel)
}
if *devicesCmd {
devices( *jsonFlag, *udid, *decimalFlag ); return
} else if *pullCmd {
gopull( *pushSpec, *file, *udid )
} else if *enableCmd {
enable( *udid )
} else if *disableCmd {
disable( *udid )
} else {
flag.Usage()
}
}
func devices( useJson bool, udid string, useDecimal bool ) {
ctx := gousb.NewContext()
devs, err := findIosDevices(ctx)
if err != nil { log.Errorf("Error finding iOS Devices - %s",err) }
if useJson && udid == "" { fmt.Printf("[\n") }
for _,dev := range devs {
serial, _ := dev.SerialNumber()
if udid != "" && serial != udid { continue }
product, _ := dev.Product()
subcs := getVendorSubclasses( dev.Desc )
activated := 0
for _,subc := range subcs {
if int(subc)==42 { activated=1 }
}
pidHex := dev.Desc.Product.String()
vidHex := dev.Desc.Vendor.String()
pid := ""
vid := ""
if useDecimal {
pid64, _ := strconv.ParseInt( pidHex, 16, 16 )
vid64, _ := strconv.ParseInt( vidHex, 16, 16 )
pid = strconv.Itoa( int( pid64 ) )
vid = strconv.Itoa( int( vid64 ) )
} else {
pid = pidHex
vid = vidHex
}
if useJson {
name := strings.Replace( product, `"`,`\"`, -1 )
fmt.Printf(`{"bus":%d,"addr":%d,"port":%d,"udid":"%s","name":"%s","vid":"%s","pid":"%s","activated":%d}`,
dev.Desc.Bus, dev.Desc.Address, dev.Desc.Port, serial, name, vid, pid, activated )
if udid == "" { fmt.Printf(",") }
fmt.Printf("\n")
} else {
fmt.Printf( "Bus: %d, Address: %d, Port: %d, UDID:%s, Name:%s, VID=%s, PID=%s, Activated=%d\n", dev.Desc.Bus, dev.Desc.Address, dev.Desc.Port, serial, product, vid, pid, activated )
}
dev.Close()
}
if useJson && udid == "" { fmt.Printf("]\n") }
ctx.Close()
}
func openDevice( ctx *gousb.Context, uuid string ) ( *gousb.Device, bool ) {
devs, err := findIosDevices(ctx)
if err != nil { log.Errorf("Error finding iOS Devices - %s",err) }
var foundDevice *gousb.Device = nil
activated := false
for _,dev := range devs {
serial, _ := dev.SerialNumber()
if serial == uuid {
foundDevice = dev
subcs := getVendorSubclasses( dev.Desc )
for _,subc := range subcs {
if int(subc)==42 { activated=true }
}
} else {
dev.Close()
}
}
return foundDevice, activated
}
func findIosDevices( ctx *gousb.Context ) ( [] *gousb.Device, error ) {
return ctx.OpenDevices( func(dev *gousb.DeviceDesc) bool {
for _, subc := range getVendorSubclasses( dev ) {
if subc == gousb.ClassApplication { return true }
}
return false
} )
}
func getVendorSubclasses( desc *gousb.DeviceDesc ) ([]gousb.Class) {
subClasses := []gousb.Class{}
for _, conf := range desc.Configs {
for _, iface := range conf.Interfaces {
if iface.AltSettings[0].Class == gousb.ClassVendorSpec {
subClass := iface.AltSettings[0].SubClass
subClasses = append( subClasses, subClass )
}
}
}
return subClasses
}
func gopull( pushSpec string, filename string, udid string ) {
stopChannel := make( chan interface {} )
stopChannel2 := make( chan interface {} )
stopChannel3 := make( chan bool )
waitForSigInt( stopChannel, stopChannel2, stopChannel3 )
var fh *os.File
var err error
var writer screencapture.CmSampleBufConsumer
if filename == "" {
pushSock := setup_nanomsg_sockets( pushSpec )
writer = NewNanoWriter( pushSock )
} else {
fh, err = os.Create( filename )
if err != nil {
log.Errorf("Error creating file %s:%s", filename, err)
}
writer = NewFileWriter( bufio.NewWriter( fh ) )
}
attempt := 1
for {
success := startWithConsumer( writer, udid, stopChannel, stopChannel2 )
if success {
break
}
fmt.Printf("Attempt %i to start streaming\n", attempt)
if attempt >= 4 {
log.WithFields( log.Fields{
"type": "stream_start_failed",
} ).Fatal("Socket new error")
}
attempt++
time.Sleep( time.Second * 1 )
}
<- stopChannel3
writer.Stop()
}
func setup_nanomsg_sockets( pushSpec string ) ( pushSock mangos.Socket ) {
var err error
if pushSock, err = push.NewSocket(); err != nil {
log.WithFields( log.Fields{
"type": "err_socket_new",
"spec": pushSpec,
"err": err,
} ).Fatal("Socket new error")
}
if err = pushSock.Dial(pushSpec); err != nil {
log.WithFields( log.Fields{
"type": "err_socket_connect",
"spec": pushSpec,
"err": err,
} ).Fatal("Socket connect error")
}
return pushSock
}
func enable( udid string ) {
ctx := gousb.NewContext()
var usbDevice *gousb.Device = nil
var activated bool
if udid == "" {
devs, err := findIosDevices(ctx)
if err != nil { log.Errorf("Error finding iOS Devices - %s",err) }
for _,dev := range devs {
oneActivated := false
oneUdid := ""
if usbDevice == nil {
oneUdid, _ = dev.SerialNumber()
subcs := getVendorSubclasses( dev.Desc )
for _,subc := range subcs {
if int(subc)==42 { oneActivated=true }
}
if oneActivated == false {
usbDevice = dev; udid = oneUdid; activated = oneActivated
} else {
dev.Close()
}
} else {
dev.Close()
}
}
if udid != "" { log.Infof("Using first disabled device; uuid=%s", udid ) }
} else {
usbDevice, activated = openDevice( ctx, udid )
log.Info("Opened device")
}
if usbDevice == nil {
log.Info("Could not find a disabled device to activate")
ctx.Close()
return
}
if activated == true {
log.Info("Device already enabled")
usbDevice.Close()
ctx.Close()
return
}
sendQTEnable( usbDevice )
usbDevice.Close()
ctx.Close()
}
func disable( udid string ) {
ctx := gousb.NewContext()
var usbDevice *gousb.Device = nil
var activated bool
if udid == "" {
devs, err := findIosDevices(ctx)
if err != nil { log.Errorf("Error finding iOS Devices - %s",err) }
for _,dev := range devs {
oneActivated := true
oneUdid := ""
if usbDevice == nil {
oneUdid, _ = dev.SerialNumber()
subcs := getVendorSubclasses( dev.Desc )
for _,subc := range subcs {
if int(subc)==42 { oneActivated=true }
}
if oneActivated == true {
usbDevice = dev; udid = oneUdid; activated = oneActivated
} else {
dev.Close()
}
} else {
dev.Close()
}
}
if udid != "" { log.Infof("Using first enabled device; uuid=%s", udid ) }
} else {
usbDevice, activated = openDevice( ctx, udid )
log.Info("Opened device")
}
if usbDevice == nil {
log.Info("Could not find a enabled device to disabled")
ctx.Close()
return
}
if activated == false {
log.Info("Device already disabled")
usbDevice.Close()
ctx.Close()
return
}
usbDevice.Reset()
//sendQTDisable( usbDevice )
usbDevice.Close()
ctx.Close()
}
func startWithConsumer( consumer screencapture.CmSampleBufConsumer, udid string, stopChannel chan interface{}, stopChannel2 chan interface{} ) bool {
ctx := gousb.NewContext()
var usbDevice *gousb.Device = nil
var activated bool = false
if udid == "" {
devs, err := findIosDevices(ctx)
if err != nil { log.Errorf("Error finding iOS Devices - %s",err) }
for _,dev := range devs {
if usbDevice == nil {
udid, _ = dev.SerialNumber()
subcs := getVendorSubclasses( dev.Desc )
for _,subc := range subcs {
if int(subc)==42 { activated=true }
}
usbDevice = dev
} else {
dev.Close()
}
}
} else {
usbDevice, activated = openDevice( ctx, udid )
log.Info("Opened device")
}
if !activated {
log.Info("Not activated; attempting to activate")
sendQTEnable( usbDevice )
var i int = 0
for {
time.Sleep(500 * time.Millisecond)
usbDevice.Close()
var activated bool
usbDevice, activated = openDevice( ctx, udid )
if activated { break }
i++
if i > 5 {
log.Debug("Failed activating config")
return false
}
}
}
adapter := UsbAdapter{}
mp := screencapture.NewMessageProcessor( &adapter, stopChannel, consumer )
err := startReading( &adapter, usbDevice, &mp, stopChannel2 )
if err != nil {
log.Errorf("startReading failure - %s",err)
log.Info("Closing device")
usbDevice.Close()
ctx.Close()
return false
}
log.Info("Closing device")
usbDevice.Close()
ctx.Close()
return true
}
func sendQTEnable( device *gousb.Device ) {
val, err := device.Control(0x40, 0x52, 0x00, 0x02, []byte{})
if err != nil {
log.Warnf("Failed sending control transfer for enabling hidden QT config. Seems like this happens sometimes but it still works usually: %d, %s", val, err)
}
log.Debugf("Enabling QT config RC:%d", val)
}
func sendQTDisable( device *gousb.Device ) {
val, err := device.Control(0x40, 0x52, 0x00, 0x00, []byte{})
if err != nil {
log.Warnf("Failed sending control transfer for enabling hidden QT config. Seems like this happens sometimes but it still works usually: $d, %s", val, err)
}
log.Debugf("Dsiabling QT config RC:%d", val)
}
func waitForSigInt( stopChannel chan interface{}, stopChannel2 chan interface{}, stopChannel3 chan bool ) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for sig := range c {
fmt.Printf("Got signal %s\n", sig)
go func() { stopChannel3 <- true }()
go func() {
stopChannel2 <- true
stopChannel2 <- true
}()
go func() {
stopChannel <- true
stopChannel <- true
}()
}
}()
}
// Stuff below more or less copied from quicktime_video_hack/screencapture/usbadapter.go and other files in that directory
// All of these stuff has to be copied in order to alter startReading due to non-exposed functions and variables
type UsbAdapter struct {
outEndpoint *gousb.OutEndpoint
}
func (usa UsbAdapter) WriteDataToUsb(bytes []byte) {
_, err := usa.outEndpoint.Write(bytes)
if err != nil { log.Error("failed sending to usb", err) }
}
func startReading(usa *UsbAdapter, usbDevice *gousb.Device, receiver screencapture.UsbDataReceiver, stopSignal chan interface{}) error {
var confignum int = 6
config, err := usbDevice.Config(confignum)
if err != nil { return errors.New("Could not retrieve config") }
log.Debugf("QT Config is active: %s", config.String())
/*val, err := usbDevice.Control(0x02, 0x01, 0, 0x86, make([]byte, 0))
if err != nil {
log.Debug("failed control", err)
}
log.Debugf("Clear Feature RC: %d", val)
val, err = usbDevice.Control(0x02, 0x01, 0, 0x05, make([]byte, 0))
if err != nil {
log.Debug("failed control", err)
}
log.Debugf("Clear Feature RC: %d", val)*/
success, iface := findInterfaceForSubclass( config, 0x2a )
if !success || iface == nil { log.Debug("could not get Quicktime Interface"); return err }
log.Debugf("Got QT iface:%s", iface.String())
inboundBulkEndpointIndex, err := grabInBulk(iface.Setting)
if err != nil { return err }
inEndpoint, err := iface.InEndpoint(inboundBulkEndpointIndex)
if err != nil { log.Error("couldnt get InEndpoint"); return err }
log.Debugf("Inbound Bulk: %s", inEndpoint.String())
outboundBulkEndpointIndex, err := grabOutBulk(iface.Setting)
if err != nil { return err }
outEndpoint, err := iface.OutEndpoint(outboundBulkEndpointIndex)
if err != nil { log.Error("couldnt get OutEndpoint"); return err }
log.Debugf("Outbound Bulk: %s", outEndpoint.String())
usa.outEndpoint = outEndpoint
stream, err := inEndpoint.NewStream(4096, 5)
if err != nil { log.Fatal("couldnt create stream"); return err }
log.Debug("Endpoint claimed")
udid, _ := usbDevice.SerialNumber()
log.Infof("Device '%s' ready to stream ( click 'Settings-Developer-Reset Media Services' if nothing happens )", udid )
go func() {
frameExtractor := screencapture.NewLengthFieldBasedFrameExtractor()
for {
buffer := make([]byte, 65536)
n, err := stream.Read(buffer)
if err != nil {
log.Error("couldn't read bytes", err)
return
}
frame, isCompleteFrame := frameExtractor.ExtractFrame(buffer[:n])
if isCompleteFrame {
receiver.ReceiveData(frame)
}
}
}()
<-stopSignal
receiver.CloseSession()
log.Info("Closing usb stream")
err = stream.Close()
if err != nil { log.Error("Error closing stream", err) }
log.Info("Closing usb interface")
iface.Close()
log.Info("Closing config")
config.Close()
sendQTDisable(usbDevice)
return nil
}
func grabOutBulk(setting gousb.InterfaceSetting) (int, error) {
for _, v := range setting.Endpoints {
if v.Direction == gousb.EndpointDirectionOut {
return v.Number, nil
}
}
return 0, errors.New("Outbound Bulkendpoint not found")
}
func grabInBulk(setting gousb.InterfaceSetting) (int, error) {
for _, v := range setting.Endpoints {
if v.Direction == gousb.EndpointDirectionIn {
return v.Number, nil
}
}
return 0, errors.New("Inbound Bulkendpoint not found")
}
func findInterfaceForSubclass(config *gousb.Config, subClass gousb.Class) (bool, *gousb.Interface) {
for _, ifaced := range config.Desc.Interfaces {
if ifaced.AltSettings[0].Class == gousb.ClassVendorSpec &&
ifaced.AltSettings[0].SubClass == subClass {
iface, _ := config.Interface( ifaced.Number, 0 )
return true, iface
}
}
return false, nil
}