1 package kaka.cakelight;
4 import java.io.IOException;
5 import java.util.Optional;
6 import java.util.function.Consumer;
8 public class VideoMode extends Mode {
9 private Configuration config;
10 private Thread thread;
11 private Consumer<Frame> frameConsumer;
12 private VideoDeviceListener deviceListener;
15 deviceListener = new VideoDeviceListener();
16 deviceListener.onVideoDeviceChange(this::onVideoDeviceChange);
20 public void enter(Configuration config) {
22 deviceListener.startListening();
28 deviceListener.stopListening();
31 private void startGrabberThread(File videoDevice) {
32 assert frameConsumer != null;
33 thread = new Thread() {
35 try (FrameGrabber grabber = FrameGrabber.from(videoDevice, config)) {
36 while (!isInterrupted()) {
37 Optional<Frame> frame = grabber.grabFrame();
38 if (frameConsumer != null) frame.ifPresent(frameConsumer);
39 frame.ifPresent(VideoMode.this::onFrame);
40 // timeIt("frame", grabber::grabFrame);
41 // TODO: process frame
42 // TODO: save where the LedController can access it
44 } catch (IOException e) {
52 public void onVideoFrame(Consumer<Frame> consumer) {
53 frameConsumer = consumer;
56 private void onFrame(Frame frame) {
57 assert frameListener != null;
58 frameListener.accept(frame.getLedFrame());
61 public void onVideoDeviceChange(Optional<File> videoDevice) {
62 // Should only happen when this mode is active!
66 videoDevice.ifPresent(this::startGrabberThread);