Added a custom Color class
[kaka/cakelight.git] / src / kaka / cakelight / VideoMode.java
CommitLineData
4a2d6056
TW
1package kaka.cakelight;
2
03670958 3import java.io.File;
4a2d6056
TW
4import java.io.IOException;
5import java.util.Optional;
100b82fe 6import java.util.function.Consumer;
4a2d6056 7
d182b8cc 8public class VideoMode extends Mode {
4a2d6056
TW
9 private Configuration config;
10 private Thread thread;
100b82fe 11 private Consumer<Frame> frameConsumer;
03670958
TW
12 private VideoDeviceListener deviceListener;
13
14 public VideoMode() {
15 deviceListener = new VideoDeviceListener();
d182b8cc 16 deviceListener.onVideoDeviceChange(this::onVideoDeviceChange);
03670958 17 }
4a2d6056
TW
18
19 @Override
20 public void enter(Configuration config) {
21 this.config = config;
03670958 22 deviceListener.startListening();
4a2d6056
TW
23 }
24
25 @Override
26 public void exit() {
27 thread.interrupt();
03670958 28 deviceListener.stopListening();
4a2d6056
TW
29 }
30
03670958 31 private void startGrabberThread(File videoDevice) {
100b82fe 32 assert frameConsumer != null;
4a2d6056
TW
33 thread = new Thread() {
34 public void run() {
03670958 35 try (FrameGrabber grabber = FrameGrabber.from(videoDevice, config)) {
4a2d6056 36 while (!isInterrupted()) {
03b67a73
TW
37 Optional<Frame> frame = grabber.grabFrame();
38 if (frameConsumer != null) frame.ifPresent(frameConsumer);
39 frame.ifPresent(VideoMode.this::onFrame);
100b82fe 40// timeIt("frame", grabber::grabFrame);
4a2d6056
TW
41 // TODO: process frame
42 // TODO: save where the LedController can access it
43 }
44 } catch (IOException e) {
45 e.printStackTrace();
46 }
47 }
48 };
49 thread.start();
50 }
100b82fe 51
03b67a73 52 public void onVideoFrame(Consumer<Frame> consumer) {
100b82fe
TW
53 frameConsumer = consumer;
54 }
03670958 55
03b67a73
TW
56 private void onFrame(Frame frame) {
57 assert frameListener != null;
58 frameListener.accept(frame.getLedFrame());
59 }
60
d182b8cc 61 public void onVideoDeviceChange(Optional<File> videoDevice) {
03670958
TW
62 // Should only happen when this mode is active!
63 if (thread != null) {
64 thread.interrupt();
65 }
66 videoDevice.ifPresent(this::startGrabberThread);
67 }
4a2d6056 68}