| 1 | package kaka.cakelight; |
| 2 | |
| 3 | import java.io.*; |
| 4 | import java.util.Optional; |
| 5 | |
| 6 | import static kaka.cakelight.Main.log; |
| 7 | |
| 8 | public class FrameGrabber implements Closeable { |
| 9 | private Configuration config; |
| 10 | private File file; |
| 11 | private int bytesPerFrame; |
| 12 | private InputStream fileStream; |
| 13 | |
| 14 | private FrameGrabber() { |
| 15 | } |
| 16 | |
| 17 | public static FrameGrabber from(File videoDevice, Configuration config) { |
| 18 | FrameGrabber fg = new FrameGrabber(); |
| 19 | fg.config = config; |
| 20 | fg.file = videoDevice; |
| 21 | fg.bytesPerFrame = config.video.width * config.video.height * config.video.bpp; |
| 22 | fg.prepare(); |
| 23 | return fg; |
| 24 | } |
| 25 | |
| 26 | private boolean prepare() { |
| 27 | try { |
| 28 | fileStream = new FileInputStream(file); |
| 29 | return true; |
| 30 | } catch (FileNotFoundException e) { |
| 31 | e.printStackTrace(); |
| 32 | return false; |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Must be run in the same thread as {@link #prepare}. |
| 38 | */ |
| 39 | public Optional<Frame> grabFrame() { |
| 40 | try { |
| 41 | byte[] data = new byte[bytesPerFrame]; |
| 42 | int count = fileStream.read(data); |
| 43 | log("# of bytes read = " + count); |
| 44 | return Optional.of(Frame.of(data, config)); |
| 45 | } catch (IOException e) { |
| 46 | e.printStackTrace(); |
| 47 | } |
| 48 | |
| 49 | return Optional.empty(); |
| 50 | } |
| 51 | |
| 52 | @Override |
| 53 | public void close() throws IOException { |
| 54 | fileStream.close(); |
| 55 | } |
| 56 | } |