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 synchronized (grabberThread) {
40 grabberThread.notify();
46 grabberThread.interrupt();
47 deviceListener.stopListening();
50 private void startGrabberThread(File videoDevice) {
51 assert frameConsumer != null;
52 grabberThread = new Thread() {
54 try (FrameGrabber grabber = FrameGrabber.from(videoDevice, config)) {
55 while (!isInterrupted()) {
56 Optional<VideoFrame> frame = grabber.grabFrame();
58 synchronized (grabberThread) {
62 if (frameConsumer != null) frame.ifPresent(frameConsumer);
63 frame.ifPresent(VideoMode.this::onVideoFrame);
64 // timeIt("frame", grabber::grabFrame);
66 } catch (IOException | InterruptedException e) {
71 grabberThread.start();
74 public void onVideoFrame(Consumer<VideoFrame> consumer) {
75 frameConsumer = consumer;
78 private void onVideoFrame(VideoFrame frame) {
79 updateWithFrame(frame.getLedFrame());
82 public void onVideoDeviceChange(Optional<File> videoDevice) {
83 // Should only happen when this mode is active!
84 if (grabberThread != null) {
85 grabberThread.interrupt();
87 videoDevice.ifPresent(this::startGrabberThread);