Added a device listener
[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
03670958 8public class VideoMode implements Mode, Consumer<Optional<File>> {
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();
16 deviceListener.onVideoDeviceChange(this);
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
TW
36 while (!isInterrupted()) {
37// Optional<Frame> frame = grabber.grabFrame();
100b82fe
TW
38 grabber.grabFrame().ifPresent(frameConsumer);
39// timeIt("frame", grabber::grabFrame);
4a2d6056
TW
40 // TODO: process frame
41 // TODO: save where the LedController can access it
42 }
43 } catch (IOException e) {
44 e.printStackTrace();
45 }
46 }
47 };
48 thread.start();
49 }
100b82fe
TW
50
51 public void onFrame(Consumer<Frame> consumer) {
52 frameConsumer = consumer;
53 }
03670958
TW
54
55 @Override
56 public void accept(Optional<File> videoDevice) {
57 // Should only happen when this mode is active!
58 if (thread != null) {
59 thread.interrupt();
60 }
61 videoDevice.ifPresent(this::startGrabberThread);
62 }
4a2d6056 63}