Created
March 31, 2018 23:45
-
-
Save DBC-Works/8b7f9071f99a9da503037ee7a10161d1 to your computer and use it in GitHub Desktop.
Processing frame recorder classes for creating movie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Future; | |
import java.util.concurrent.TimeUnit; | |
interface FrameRecorder | |
{ | |
abstract void recordFrame(); | |
abstract void finish(); | |
} | |
final class SyncFrameRecorder implements FrameRecorder | |
{ | |
SyncFrameRecorder() | |
{ | |
} | |
void recordFrame() | |
{ | |
saveFrame("img/########.tga"); | |
} | |
void finish() | |
{ | |
} | |
} | |
final class AsyncFrameRecorder implements FrameRecorder | |
{ | |
private final ExecutorService executor = Executors.newCachedThreadPool(); | |
private final List<Future> futures = new ArrayList<Future>(); | |
AsyncFrameRecorder() | |
{ | |
} | |
void recordFrame() | |
{ | |
if (executor.isShutdown()) { | |
return; | |
} | |
loadPixels(); | |
final int[] savePixels = Arrays.copyOf(pixels, pixels.length); | |
final long saveFrameCount = frameCount; | |
Runnable saveTask = new Runnable() { | |
public void run() { | |
final PImage frameImage = createImage(width, height, HSB); | |
frameImage.pixels = savePixels; | |
frameImage.save(String.format("img/%08d.jpg", saveFrameCount)); | |
} | |
}; | |
Iterator<Future> it = futures.iterator(); | |
while (it.hasNext()) { | |
Future f = it.next(); | |
if (f.isDone()) { | |
it.remove(); | |
} | |
} | |
futures.add(executor.submit(saveTask)); | |
} | |
void finish() | |
{ | |
try { | |
Thread.sleep(1000); | |
} | |
catch (InterruptedException e) { | |
} | |
for (Future f : futures) { | |
if (f.isDone() == false && f.isCancelled() == false) { | |
try { | |
f.get(); | |
} | |
catch (InterruptedException e) { | |
} | |
catch (ExecutionException e) { | |
} | |
} | |
} | |
if (executor.isShutdown() == false) { | |
executor.shutdown(); | |
try { | |
if (executor.awaitTermination(5, TimeUnit.SECONDS) == false) { | |
executor.shutdownNow(); | |
executor.awaitTermination(5, TimeUnit.SECONDS); | |
} | |
} | |
catch (InterruptedException e) { | |
executor.shutdownNow(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment