1 package kaka.cakelight.mode;
3 import kaka.cakelight.Configuration;
4 import kaka.cakelight.FrameGrabber;
5 import kaka.cakelight.VideoDeviceListener;
6 import kaka.cakelight.VideoFrame;
9 import java.io.IOException;
10 import java.util.Optional;
11 import java.util.function.Consumer;
13 public class VideoMode extends Mode {
14 private Configuration config;
15 private Thread grabberThread;
16 private Consumer<VideoFrame> frameConsumer;
17 private VideoDeviceListener deviceListener;
18 private boolean isPaused = false;
21 deviceListener = new VideoDeviceListener();
22 deviceListener.onVideoDeviceChange(this::onVideoDeviceChange);
26 public void enter(Configuration config) {
28 deviceListener.startListening();
37 public void resume() {
39 grabberThread.notify();
44 grabberThread.interrupt();
45 deviceListener.stopListening();
48 private void startGrabberThread(File videoDevice) {
49 assert frameConsumer != null;
50 grabberThread = new Thread() {
52 try (FrameGrabber grabber = FrameGrabber.from(videoDevice, config)) {
53 while (!isInterrupted()) {
54 Optional<VideoFrame> frame = grabber.grabFrame();
58 if (frameConsumer != null) frame.ifPresent(frameConsumer);
59 frame.ifPresent(VideoMode.this::onVideoFrame);
60 // timeIt("frame", grabber::grabFrame);
62 } catch (IOException | InterruptedException e) {
67 grabberThread.start();
70 public void onVideoFrame(Consumer<VideoFrame> consumer) {
71 frameConsumer = consumer;
74 private void onVideoFrame(VideoFrame frame) {
75 updateWithFrame(frame.getLedFrame());
78 public void onVideoDeviceChange(Optional<File> videoDevice) {
79 // Should only happen when this mode is active!
80 if (grabberThread != null) {
81 grabberThread.interrupt();
83 videoDevice.ifPresent(this::startGrabberThread);