|
| 1 | +//go:build with_libav && linux |
| 2 | +// +build with_libav,linux |
| 3 | + |
| 4 | +package screenshoter |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + "image" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/asticode/go-astiav" |
| 13 | + "github.com/facebookincubator/go-belt/tool/logger" |
| 14 | + "github.com/xaionaro-go/avpipeline/frame" |
| 15 | + "github.com/xaionaro-go/avpipeline/node" |
| 16 | + "github.com/xaionaro-go/avpipeline/preset/screencapturer" |
| 17 | + "github.com/xaionaro-go/observability" |
| 18 | + "github.com/xaionaro-go/streamctl/pkg/screenshot" |
| 19 | +) |
| 20 | + |
| 21 | +type Screenshoter struct{} |
| 22 | + |
| 23 | +func New() *Screenshoter { |
| 24 | + return &Screenshoter{} |
| 25 | +} |
| 26 | + |
| 27 | +func (s *Screenshoter) Loop( |
| 28 | + ctx context.Context, |
| 29 | + interval time.Duration, |
| 30 | + config screenshot.Config, |
| 31 | + callback func(context.Context, image.Image), |
| 32 | +) error { |
| 33 | + fpsFloat := 1 / interval.Seconds() |
| 34 | + fps := astiav.Rational{} |
| 35 | + fps.SetNum(int(fpsFloat * 1000)) |
| 36 | + fps.SetDen(1000) |
| 37 | + |
| 38 | + logger.Debugf(ctx, "FPS == %f", fps.Float64()) |
| 39 | + screenCapturer, err := screencapturer.New(ctx, screencapturer.Params{ |
| 40 | + Area: config.Bounds, |
| 41 | + FPS: fps, |
| 42 | + }) |
| 43 | + if err != nil { |
| 44 | + return fmt.Errorf("unable to initialize a screen capturer: %w", err) |
| 45 | + } |
| 46 | + |
| 47 | + errCh := make(chan node.Error, 100) |
| 48 | + observability.Go(ctx, func(ctx context.Context) { |
| 49 | + screenCapturer.Serve(ctx, node.ServeConfig{}, errCh) |
| 50 | + }) |
| 51 | + defer screenCapturer.Close(ctx) |
| 52 | + |
| 53 | + var img image.Image |
| 54 | + for { |
| 55 | + var frame frame.Output |
| 56 | + select { |
| 57 | + case <-ctx.Done(): |
| 58 | + return ctx.Err() |
| 59 | + case err := <-errCh: |
| 60 | + return fmt.Errorf("unable to serve the screenshoter node: %w", err) |
| 61 | + case pkt := <-screenCapturer.OutputPacketChan(): |
| 62 | + return fmt.Errorf("receive a packet (of size %d), while expected a decoded frame", pkt.GetSize()) |
| 63 | + case frame = <-screenCapturer.OutputFrameChan(): |
| 64 | + } |
| 65 | + |
| 66 | + if img == nil { |
| 67 | + img, err = frame.Data().GuessImageFormat() |
| 68 | + if err != nil { |
| 69 | + return fmt.Errorf("unable to guess the image format: %w", err) |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + err := frame.Data().ToImage(img) |
| 74 | + if err != nil { |
| 75 | + return fmt.Errorf("unable to obtain the image: %w", err) |
| 76 | + } |
| 77 | + |
| 78 | + callback(ctx, img) |
| 79 | + } |
| 80 | +} |
0 commit comments