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;
20 deviceListener = new VideoDeviceListener();
21 deviceListener.onVideoDeviceChange(this::onVideoDeviceChange);
25 public void enter(Configuration config) {
27 deviceListener.startListening();
32 grabberThread.interrupt();
33 deviceListener.stopListening();
36 private void startGrabberThread(File videoDevice) {
37 assert frameConsumer != null;
38 grabberThread = new Thread() {
40 try (FrameGrabber grabber = FrameGrabber.from(videoDevice, config)) {
41 while (!isInterrupted()) {
42 Optional<VideoFrame> frame = grabber.grabFrame();
43 if (frameConsumer != null) frame.ifPresent(frameConsumer);
44 frame.ifPresent(VideoMode.this::onVideoFrame);
45 // timeIt("frame", grabber::grabFrame);
47 } catch (IOException e) {
52 grabberThread.start();
55 public void onVideoFrame(Consumer<VideoFrame> consumer) {
56 frameConsumer = consumer;
59 private void onVideoFrame(VideoFrame frame) {
60 updateWithFrame(frame.getLedFrame());
63 public void onVideoDeviceChange(Optional<File> videoDevice) {
64 // Should only happen when this mode is active!
65 if (grabberThread != null) {
66 grabberThread.interrupt();
68 videoDevice.ifPresent(this::startGrabberThread);