Commit | Line | Data |
---|---|---|
4a2d6056 TW |
1 | package kaka.cakelight; |
2 | ||
03670958 | 3 | import java.io.File; |
4a2d6056 TW |
4 | import java.io.IOException; |
5 | import java.util.Optional; | |
100b82fe | 6 | import java.util.function.Consumer; |
4a2d6056 | 7 | |
d182b8cc | 8 | public 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 | } |
42 | } catch (IOException e) { | |
43 | e.printStackTrace(); | |
44 | } | |
45 | } | |
46 | }; | |
47 | thread.start(); | |
48 | } | |
100b82fe | 49 | |
03b67a73 | 50 | public void onVideoFrame(Consumer<Frame> consumer) { |
100b82fe TW |
51 | frameConsumer = consumer; |
52 | } | |
03670958 | 53 | |
03b67a73 | 54 | private void onFrame(Frame frame) { |
6b569670 | 55 | updateWithFrame(frame.getLedFrame()); |
03b67a73 TW |
56 | } |
57 | ||
d182b8cc | 58 | public void onVideoDeviceChange(Optional<File> videoDevice) { |
03670958 TW |
59 | // Should only happen when this mode is active! |
60 | if (thread != null) { | |
61 | thread.interrupt(); | |
62 | } | |
63 | videoDevice.ifPresent(this::startGrabberThread); | |
64 | } | |
4a2d6056 | 65 | } |