You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

screencap.go 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package screencap
  2. import "github.com/kbinani/screenshot"
  3. import "image/jpeg"
  4. import "sync"
  5. import "time"
  6. import "log"
  7. type Buffer struct {
  8. Data []byte
  9. Length int
  10. }
  11. func (buf *Buffer) Write(data []byte) (int, error) {
  12. if len(buf.Data) == 0 {
  13. l := len(data)
  14. if l < 1024 {
  15. l = 2024
  16. }
  17. buf.Data = make([]byte, l)
  18. } else if buf.Length + len(data) > len(buf.Data) {
  19. newSize := len(buf.Data) * 2
  20. for buf.Length + len(data) > newSize {
  21. newSize *= 2
  22. }
  23. newBuf := make([]byte, newSize)
  24. copy(newBuf, buf.Data[0:buf.Length])
  25. buf.Data = newBuf
  26. }
  27. copy(buf.Data[buf.Length:], data)
  28. buf.Length += len(data)
  29. return len(data), nil
  30. }
  31. var (
  32. mut = sync.Mutex{}
  33. chans = make([]chan *Buffer, 0)
  34. startChan = make(chan struct{}, 1)
  35. buffers = make([]Buffer, 4)
  36. currentBuffer = 0
  37. )
  38. func Capture() chan *Buffer {
  39. ch := make(chan *Buffer)
  40. mut.Lock()
  41. chans = append(chans, ch)
  42. mut.Unlock()
  43. select {
  44. case startChan <- struct{}{}:
  45. default:
  46. }
  47. return ch
  48. }
  49. func Run() {
  50. for {
  51. <-startChan
  52. img, err := screenshot.CaptureDisplay(0)
  53. if err != nil {
  54. log.Printf("Failed to capture screenshot: %v", err)
  55. time.Sleep(2 * time.Second)
  56. continue
  57. }
  58. buf := &buffers[currentBuffer]
  59. currentBuffer = (currentBuffer + 1) % len(buffers)
  60. buf.Length = 0
  61. err = jpeg.Encode(buf, img, &jpeg.Options{Quality: 80})
  62. if err != nil {
  63. log.Printf("Failed to encode jpeg: %v", err)
  64. time.Sleep(2 * time.Second)
  65. continue
  66. }
  67. mut.Lock()
  68. for _, ch := range chans {
  69. ch <- buf
  70. }
  71. chans = make([]chan *Buffer, 0)
  72. mut.Unlock()
  73. }
  74. }