mirror of
https://github.com/darksaid98/Flashback.git
synced 2026-12-01 22:16:01 +00:00
Stuff
This commit is contained in:
1 parent
9c4a30d224
commit
666398e480
174 files changed
+8694
-2942
No files matched your search
@@ -0,0 +1,205 @@
|
||||
package com.moulberry.flashback.exporting;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import org.lwjgl.PointerBuffer;
|
||||
import org.lwjgl.system.MemoryStack;
|
||||
import org.lwjgl.util.nfd.NFDFilterItem;
|
||||
import org.lwjgl.util.nfd.NativeFileDialog;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public class AsyncFileDialogs {
|
||||
|
||||
private static CompletableFuture<String> currentSaveOrOpenFileDialog = null;
|
||||
private static final ExecutorService dialogThread = Executors.newSingleThreadExecutor();
|
||||
private static boolean initializedNfd = false;
|
||||
|
||||
public static boolean hasDialog() {
|
||||
return currentSaveOrOpenFileDialog != null;
|
||||
}
|
||||
|
||||
public static CompletableFuture<String> saveFileDialog(String defaultPath, String defaultName, String filterDescription, String... filters) {
|
||||
if (hasDialog()) return CompletableFuture.completedFuture(null);
|
||||
|
||||
currentSaveOrOpenFileDialog = new CompletableFuture<>();
|
||||
CompletableFuture<String> future = currentSaveOrOpenFileDialog;
|
||||
|
||||
boolean initializedNfd = AsyncFileDialogs.initializedNfd;
|
||||
AsyncFileDialogs.initializedNfd = true;
|
||||
|
||||
Runnable runnable = () -> {
|
||||
if (!initializedNfd) {
|
||||
NativeFileDialog.NFD_Init();
|
||||
}
|
||||
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
PointerBuffer out = stack.callocPointer(1);
|
||||
|
||||
StringBuilder filterBuilder = new StringBuilder();
|
||||
|
||||
for (String filter : filters) {
|
||||
if (!filterBuilder.isEmpty()) filterBuilder.append(",");
|
||||
filterBuilder.append(filter(filter));
|
||||
}
|
||||
|
||||
NFDFilterItem.Buffer filtersBuffer = NFDFilterItem.malloc(1);
|
||||
filtersBuffer.get(0)
|
||||
.name(stack.UTF8(filter(filterDescription)))
|
||||
.spec(stack.UTF8(filterBuilder.toString()));
|
||||
|
||||
int result = NativeFileDialog.NFD_SaveDialog(out, filtersBuffer, filter(defaultPath), filter(defaultName));
|
||||
|
||||
if (result != NativeFileDialog.NFD_OKAY) {
|
||||
currentSaveOrOpenFileDialog.complete(null);
|
||||
currentSaveOrOpenFileDialog = null;
|
||||
} else {
|
||||
currentSaveOrOpenFileDialog.complete(out.getStringUTF8(0));
|
||||
currentSaveOrOpenFileDialog = null;
|
||||
NativeFileDialog.NFD_FreePath(out.get(0));
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
t.printStackTrace();
|
||||
} finally {
|
||||
if (currentSaveOrOpenFileDialog != null) {
|
||||
currentSaveOrOpenFileDialog.complete(null);
|
||||
currentSaveOrOpenFileDialog = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (Minecraft.ON_OSX) {
|
||||
// MacOS needs dialogs to be run from the main thread
|
||||
Minecraft.getInstance().submit(runnable);
|
||||
} else {
|
||||
dialogThread.submit(runnable);
|
||||
}
|
||||
|
||||
return future;
|
||||
}
|
||||
|
||||
public static CompletableFuture<String> openFileDialog(String defaultPath, String filterDescription, String... filters) {
|
||||
if (hasDialog()) return CompletableFuture.completedFuture(null);
|
||||
|
||||
currentSaveOrOpenFileDialog = new CompletableFuture<>();
|
||||
CompletableFuture<String> future = currentSaveOrOpenFileDialog;
|
||||
|
||||
boolean initializedNfd = AsyncFileDialogs.initializedNfd;
|
||||
AsyncFileDialogs.initializedNfd = true;
|
||||
|
||||
Runnable runnable = () -> {
|
||||
if (!initializedNfd) {
|
||||
NativeFileDialog.NFD_Init();
|
||||
}
|
||||
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
PointerBuffer out = stack.callocPointer(1);
|
||||
|
||||
StringBuilder filterBuilder = new StringBuilder();
|
||||
|
||||
for (String filter : filters) {
|
||||
if (!filterBuilder.isEmpty()) filterBuilder.append(",");
|
||||
filterBuilder.append(filter(filter));
|
||||
}
|
||||
|
||||
NFDFilterItem.Buffer filtersBuffer = NFDFilterItem.malloc(1);
|
||||
filtersBuffer.get(0)
|
||||
.name(stack.UTF8(filter(filterDescription)))
|
||||
.spec(stack.UTF8(filterBuilder.toString()));
|
||||
|
||||
int result = NativeFileDialog.NFD_OpenDialog(out, filtersBuffer, filter(defaultPath));
|
||||
|
||||
if (result != NativeFileDialog.NFD_OKAY) {
|
||||
currentSaveOrOpenFileDialog.complete(null);
|
||||
currentSaveOrOpenFileDialog = null;
|
||||
} else {
|
||||
currentSaveOrOpenFileDialog.complete(out.getStringUTF8(0));
|
||||
currentSaveOrOpenFileDialog = null;
|
||||
NativeFileDialog.NFD_FreePath(out.get(0));
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
t.printStackTrace();
|
||||
} finally {
|
||||
if (currentSaveOrOpenFileDialog != null) {
|
||||
currentSaveOrOpenFileDialog.complete(null);
|
||||
currentSaveOrOpenFileDialog = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (Minecraft.ON_OSX) {
|
||||
// MacOS needs dialogs to be run from the main thread
|
||||
Minecraft.getInstance().submit(runnable);
|
||||
} else {
|
||||
dialogThread.submit(runnable);
|
||||
}
|
||||
|
||||
return future;
|
||||
}
|
||||
|
||||
public static CompletableFuture<String> openFolderDialog(String defaultPath) {
|
||||
if (hasDialog()) return CompletableFuture.completedFuture(null);
|
||||
|
||||
currentSaveOrOpenFileDialog = new CompletableFuture<>();
|
||||
CompletableFuture<String> future = currentSaveOrOpenFileDialog;
|
||||
|
||||
boolean initializedNfd = AsyncFileDialogs.initializedNfd;
|
||||
AsyncFileDialogs.initializedNfd = true;
|
||||
|
||||
Runnable runnable = () -> {
|
||||
if (!initializedNfd) {
|
||||
NativeFileDialog.NFD_Init();
|
||||
}
|
||||
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
PointerBuffer out = stack.callocPointer(1);
|
||||
|
||||
int result = NativeFileDialog.NFD_PickFolder(out, filter(defaultPath));
|
||||
|
||||
if (result != NativeFileDialog.NFD_OKAY) {
|
||||
currentSaveOrOpenFileDialog.complete(null);
|
||||
currentSaveOrOpenFileDialog = null;
|
||||
} else {
|
||||
currentSaveOrOpenFileDialog.complete(out.getStringUTF8(0));
|
||||
currentSaveOrOpenFileDialog = null;
|
||||
NativeFileDialog.NFD_FreePath(out.get(0));
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
t.printStackTrace();
|
||||
} finally {
|
||||
if (currentSaveOrOpenFileDialog != null) {
|
||||
currentSaveOrOpenFileDialog.complete(null);
|
||||
currentSaveOrOpenFileDialog = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (Minecraft.ON_OSX) {
|
||||
// MacOS needs dialogs to be run from the main thread
|
||||
Minecraft.getInstance().submit(runnable);
|
||||
} else {
|
||||
dialogThread.submit(runnable);
|
||||
}
|
||||
|
||||
return future;
|
||||
}
|
||||
|
||||
public static String filter(CharSequence in) {
|
||||
return filterLT20(in.toString()
|
||||
.replace("'", "")
|
||||
.replace("\"", "")
|
||||
.replace("$", "")
|
||||
.replace("`", ""));
|
||||
}
|
||||
|
||||
public static String filterLT20(CharSequence in) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (int i = 0; i < in.length(); i++) {
|
||||
char c = in.charAt(i);
|
||||
if (c >= 32 || c == '\n') builder.append(c);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package com.moulberry.flashback.exporting;
|
||||
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import com.moulberry.flashback.Flashback;
|
||||
import com.moulberry.flashback.SneakyThrow;
|
||||
import com.moulberry.flashback.mixin.record.MixinFFmpegFrameRecorder;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import org.bytedeco.ffmpeg.avutil.AVComponentDescriptor;
|
||||
import org.bytedeco.ffmpeg.avutil.AVFrame;
|
||||
import org.bytedeco.ffmpeg.avutil.AVPixFmtDescriptor;
|
||||
import org.bytedeco.ffmpeg.global.avutil;
|
||||
import org.bytedeco.ffmpeg.global.swscale;
|
||||
import org.bytedeco.ffmpeg.swscale.SwsContext;
|
||||
import org.bytedeco.javacpp.BytePointer;
|
||||
import org.bytedeco.javacpp.DoublePointer;
|
||||
import org.bytedeco.javacpp.Pointer;
|
||||
import org.bytedeco.javacpp.PointerPointer;
|
||||
import org.bytedeco.javacv.FFmpegFrameRecorder;
|
||||
import org.bytedeco.javacv.FFmpegLogCallback;
|
||||
import org.bytedeco.javacv.Frame;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
import static org.bytedeco.ffmpeg.global.avutil.*;
|
||||
import static org.bytedeco.ffmpeg.global.swscale.SWS_BILINEAR;
|
||||
import static org.bytedeco.ffmpeg.global.swscale.sws_freeContext;
|
||||
|
||||
public class AsyncVideoEncoder implements AutoCloseable {
|
||||
|
||||
@Nullable
|
||||
private final ArrayBlockingQueue<ImageFrame> rescaleQueue;
|
||||
private final ArrayBlockingQueue<ImageFrame> encodeQueue;
|
||||
|
||||
@Nullable
|
||||
private final ArrayBlockingQueue<Long> reusePictureData;
|
||||
|
||||
private final AtomicBoolean finishRescaleThread = new AtomicBoolean(false);
|
||||
private final AtomicBoolean finishEncodeThread = new AtomicBoolean(false);
|
||||
private final AtomicBoolean finishedWriting = new AtomicBoolean(false);
|
||||
|
||||
private final AtomicReference<Throwable> threadedError = new AtomicReference<>(null);
|
||||
|
||||
private static final int SRC_PIXEL_FORMAT = avutil.AV_PIX_FMT_RGBA;
|
||||
|
||||
private record ImageFrame(long pointer, int size, int width, int height, int channels, int imageDepth, int stride, int pixelFormat) implements AutoCloseable {
|
||||
public void close() {
|
||||
MemoryUtil.nmemFree(this.pointer);
|
||||
}
|
||||
}
|
||||
|
||||
public AsyncVideoEncoder(ExportSettings settings, String filename) {
|
||||
int width = settings.resolutionX();
|
||||
int height = settings.resolutionY();
|
||||
|
||||
final int maxResolutionArea = 3840 * 2160;
|
||||
if (width*height > maxResolutionArea) {
|
||||
double factor = (width*height) / (double) maxResolutionArea;
|
||||
factor = Math.sqrt(factor);
|
||||
width = (int) Math.floor(width / factor);
|
||||
height = (int) Math.floor(height / factor);
|
||||
}
|
||||
|
||||
int maxBitrate = Math.min(288_000_000, 5000 + (int) Math.ceil(width * height * settings.framerate()));
|
||||
int bitrate;
|
||||
if (settings.bitrate() <= 0) {
|
||||
bitrate = maxBitrate;
|
||||
} else {
|
||||
bitrate = Math.min(settings.bitrate(), maxBitrate);
|
||||
}
|
||||
double fps = settings.framerate();
|
||||
|
||||
String extension = settings.container().extension();
|
||||
|
||||
try {
|
||||
if (FabricLoader.getInstance().isDevelopmentEnvironment() || true) {
|
||||
FFmpegLogCallback.set();
|
||||
}
|
||||
|
||||
int dstPixelFormat = PixelFormatHelper.getBestPixelFormat(settings.encoder());
|
||||
boolean needsRescale = SRC_PIXEL_FORMAT != dstPixelFormat;
|
||||
|
||||
final FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
|
||||
filename, width, height, 0);
|
||||
|
||||
recorder.setVideoBitrate(bitrate);
|
||||
recorder.setVideoCodec(settings.codec().codecId());
|
||||
recorder.setVideoCodecName(settings.encoder());
|
||||
recorder.setFormat(extension);
|
||||
recorder.setFrameRate(fps);
|
||||
recorder.setPixelFormat(dstPixelFormat);
|
||||
recorder.setGopSize((int) Math.ceil(fps * 2));
|
||||
|
||||
recorder.start();
|
||||
|
||||
this.encodeQueue = new ArrayBlockingQueue<>(needsRescale ? 24 : 32);
|
||||
this.rescaleQueue = needsRescale ? new ArrayBlockingQueue<>(8) : null;
|
||||
this.reusePictureData = needsRescale ? new ArrayBlockingQueue<>(32) : null;
|
||||
|
||||
Thread encodeThread = createEncodeThread(recorder);
|
||||
if (needsRescale) {
|
||||
Thread rescaleThread = createRescaleThread(width, height, dstPixelFormat);
|
||||
rescaleThread.start();
|
||||
}
|
||||
encodeThread.start();
|
||||
} catch (IOException e) {
|
||||
throw SneakyThrow.sneakyThrow(e);
|
||||
}
|
||||
}
|
||||
|
||||
private @NotNull Thread createEncodeThread(FFmpegFrameRecorder recorder) {
|
||||
Thread encodeThread = new Thread(() -> {
|
||||
while (true) {
|
||||
ImageFrame src;
|
||||
|
||||
try {
|
||||
src = this.encodeQueue.poll(10, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
throw SneakyThrow.sneakyThrow(e);
|
||||
}
|
||||
|
||||
try {
|
||||
if (src == null) {
|
||||
if (this.finishEncodeThread.get()) {
|
||||
recorder.stop();
|
||||
recorder.close();
|
||||
this.finishedWriting.set(true);
|
||||
return;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
int size = src.height * src.stride * Frame.pixelSize(src.imageDepth);
|
||||
ByteBuffer buffer = MemoryUtil.memByteBuffer(src.pointer, size);
|
||||
|
||||
recorder.recordImage(src.width, src.height, src.imageDepth, src.channels,
|
||||
src.stride, src.pixelFormat, buffer);
|
||||
|
||||
if (this.reusePictureData != null) {
|
||||
if (this.reusePictureData.offer(src.pointer)) { // try adding to the reuse queue, ignore if full
|
||||
src = null; // don't deallocate
|
||||
}
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
try {
|
||||
recorder.release();
|
||||
} catch (FFmpegFrameRecorder.Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
this.threadedError.set(t);
|
||||
this.finishRescaleThread.set(true);
|
||||
this.finishEncodeThread.set(true);
|
||||
this.finishedWriting.set(true);
|
||||
return;
|
||||
} finally {
|
||||
if (src != null) {
|
||||
src.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
encodeThread.setName("Video Encode Thread");
|
||||
return encodeThread;
|
||||
}
|
||||
|
||||
private Thread createRescaleThread(int dstWidth, int dstHeight, int dstPixelFormat) {
|
||||
int dstSize = av_image_get_buffer_size(dstPixelFormat, dstWidth, dstHeight, 1);
|
||||
int dstDepth = dstSize * 8 / dstWidth / dstHeight;
|
||||
int dstChannels;
|
||||
|
||||
try (AVPixFmtDescriptor descriptor = av_pix_fmt_desc_get(dstPixelFormat)) {
|
||||
dstChannels = descriptor.nb_components();
|
||||
}
|
||||
|
||||
AVFrame picture = avutil.av_frame_alloc();
|
||||
if (picture == null) {
|
||||
throw new RuntimeException("av_frame_alloc() error: Could not allocate picture.");
|
||||
}
|
||||
|
||||
AVFrame tmp_picture = avutil.av_frame_alloc();
|
||||
if (tmp_picture == null) {
|
||||
throw new RuntimeException("av_frame_alloc() error: Could not allocate tmp_picture.");
|
||||
}
|
||||
|
||||
PointerPointer<AVFrame> tmp_picture_ptr = new PointerPointer<>(tmp_picture);
|
||||
PointerPointer<AVFrame> picture_ptr = new PointerPointer<>(picture);
|
||||
|
||||
Thread scaleThread = new Thread(() -> {
|
||||
SwsContext img_convert_ctx = null;
|
||||
|
||||
while (true) {
|
||||
try (ImageFrame src = this.rescaleQueue.poll(10, TimeUnit.MILLISECONDS)) {
|
||||
if (src == null) {
|
||||
if (this.finishRescaleThread.get()) {
|
||||
av_frame_free(picture);
|
||||
av_frame_free(tmp_picture);
|
||||
sws_freeContext(img_convert_ctx);
|
||||
this.finishEncodeThread.set(true);
|
||||
return;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
img_convert_ctx = swscale.sws_getCachedContext(img_convert_ctx, src.width, src.height, src.pixelFormat,
|
||||
dstWidth, dstHeight, dstPixelFormat, swscale.SWS_BILINEAR,
|
||||
null, null, (DoublePointer) null);
|
||||
if (img_convert_ctx == null) {
|
||||
throw new RuntimeException("sws_getCachedContext() error: Cannot initialize the conversion context.");
|
||||
}
|
||||
|
||||
BytePointer data = new BytePointer() {{
|
||||
this.address = src.pointer;
|
||||
this.position = 0;
|
||||
this.limit = src.size;
|
||||
this.capacity = src.size;
|
||||
}};
|
||||
|
||||
Long tempPointerAddressLong = this.reusePictureData.poll();
|
||||
if (tempPointerAddressLong == null) {
|
||||
tempPointerAddressLong = MemoryUtil.nmemAlloc(dstSize);
|
||||
if (tempPointerAddressLong == 0) {
|
||||
throw new OutOfMemoryError();
|
||||
}
|
||||
}
|
||||
|
||||
// Bit of a hack to create a BytePointer for this library
|
||||
long tempPointerAddress = tempPointerAddressLong;
|
||||
BytePointer tempPointer = new BytePointer() {{
|
||||
this.address = tempPointerAddress;
|
||||
this.position = 0;
|
||||
this.limit = dstSize;
|
||||
this.capacity = dstSize;
|
||||
}};
|
||||
|
||||
av_image_fill_arrays(tmp_picture_ptr, tmp_picture.linesize(), data, src.pixelFormat, src.width, src.height, 1);
|
||||
av_image_fill_arrays(picture_ptr, picture.linesize(), tempPointer, dstPixelFormat, dstWidth, dstHeight, 1);
|
||||
|
||||
int step = src.stride * Math.abs(src.imageDepth) / 8;
|
||||
tmp_picture.linesize(0, step);
|
||||
tmp_picture.format(src.pixelFormat);
|
||||
tmp_picture.width(src.width);
|
||||
tmp_picture.height(src.height);
|
||||
|
||||
picture.format(dstPixelFormat);
|
||||
picture.width(dstWidth);
|
||||
picture.height(dstHeight);
|
||||
|
||||
swscale.sws_scale(img_convert_ctx, tmp_picture_ptr, tmp_picture.linesize(),
|
||||
0, src.height, picture_ptr, picture.linesize());
|
||||
|
||||
this.encodeQueue.put(new ImageFrame(tempPointerAddress, dstSize, dstWidth, dstHeight, dstChannels, dstDepth,
|
||||
dstWidth, dstPixelFormat));
|
||||
} catch (Throwable t) {
|
||||
try {
|
||||
av_frame_free(picture);
|
||||
av_frame_free(tmp_picture);
|
||||
sws_freeContext(img_convert_ctx);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
this.threadedError.set(t);
|
||||
this.finishRescaleThread.set(true);
|
||||
this.finishEncodeThread.set(true);
|
||||
this.finishedWriting.set(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
scaleThread.setName("Image Rescale Thread");
|
||||
return scaleThread;
|
||||
}
|
||||
|
||||
private void checkEncodeError(@Nullable AutoCloseable closeable) {
|
||||
Throwable t = this.threadedError.get();
|
||||
if (t != null) {
|
||||
this.finishRescaleThread.set(true);
|
||||
this.finishEncodeThread.set(true);
|
||||
this.finishedWriting.set(true);
|
||||
|
||||
if (closeable != null) {
|
||||
try {
|
||||
closeable.close();
|
||||
} catch (Exception e) {
|
||||
Flashback.LOGGER.error("Error while trying to close passed AutoClosable", e);
|
||||
}
|
||||
}
|
||||
SneakyThrow.sneakyThrow(t);
|
||||
}
|
||||
}
|
||||
|
||||
public void encode(NativeImage src) {
|
||||
checkEncodeError(src);
|
||||
|
||||
if (this.finishRescaleThread.get() || this.finishEncodeThread.get() || this.finishedWriting.get()) {
|
||||
src.close();
|
||||
throw new IllegalStateException("Cannot encode after finish()");
|
||||
}
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
ImageFrame imageFrame = new ImageFrame(src.pixels, (int) src.size, src.getWidth(), src.getHeight(),
|
||||
4, Frame.DEPTH_INT, src.getWidth(), SRC_PIXEL_FORMAT);
|
||||
if (this.rescaleQueue != null) {
|
||||
this.rescaleQueue.put(imageFrame);
|
||||
} else {
|
||||
this.encodeQueue.put(imageFrame);
|
||||
}
|
||||
break;
|
||||
} catch (InterruptedException ignored) {}
|
||||
checkEncodeError(src);
|
||||
}
|
||||
}
|
||||
|
||||
public void finish() {
|
||||
checkEncodeError(null);
|
||||
|
||||
if (this.rescaleQueue != null) {
|
||||
while (!this.rescaleQueue.isEmpty()) {
|
||||
checkEncodeError(null);
|
||||
LockSupport.parkNanos("waiting for rescale queue to empty", 100000L);
|
||||
}
|
||||
}
|
||||
while (!this.encodeQueue.isEmpty()) {
|
||||
checkEncodeError(null);
|
||||
LockSupport.parkNanos("waiting for encode queue to empty", 100000L);
|
||||
}
|
||||
|
||||
this.finishRescaleThread.set(true);
|
||||
if (this.rescaleQueue == null) {
|
||||
this.finishEncodeThread.set(true);
|
||||
}
|
||||
|
||||
while (!this.finishedWriting.get()) {
|
||||
LockSupport.parkNanos("waiting for encoder thread to finish", 100000L);
|
||||
}
|
||||
|
||||
checkEncodeError(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (this.rescaleQueue != null) {
|
||||
for (ImageFrame src : this.rescaleQueue) {
|
||||
src.close();
|
||||
}
|
||||
}
|
||||
for (ImageFrame src : this.encodeQueue) {
|
||||
src.close();
|
||||
}
|
||||
|
||||
this.finishRescaleThread.set(true);
|
||||
this.finishEncodeThread.set(true);
|
||||
|
||||
while (!this.finishedWriting.get()) {
|
||||
LockSupport.parkNanos("waiting for encoder thread to finish", 100000L);
|
||||
}
|
||||
|
||||
if (this.reusePictureData != null) {
|
||||
for (Long address : this.reusePictureData) {
|
||||
if (address != 0) {
|
||||
MemoryUtil.nmemFree(address);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.moulberry.flashback.exporting;
|
||||
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import io.humble.ferry.Buffer;
|
||||
import io.humble.ferry.JNIReference;
|
||||
import io.humble.video.Codec;
|
||||
import io.humble.video.Encoder;
|
||||
import io.humble.video.MediaPacket;
|
||||
import io.humble.video.MediaPicture;
|
||||
import io.humble.video.MediaPictureResampler;
|
||||
import io.humble.video.Muxer;
|
||||
import io.humble.video.MuxerFormat;
|
||||
import io.humble.video.PixelFormat;
|
||||
import io.humble.video.Rational;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
public class AsyncVideoEncoder {
|
||||
|
||||
private final Muxer muxer;
|
||||
private final Encoder encoder;
|
||||
private final MediaPictureResampler resampler;
|
||||
private final MediaPacket packet;
|
||||
private final ArrayBlockingQueue<NativeImage> inputQueue;
|
||||
private final AtomicBoolean shouldEnd = new AtomicBoolean(false);
|
||||
private final AtomicBoolean finishedWriting = new AtomicBoolean(false);
|
||||
|
||||
public AsyncVideoEncoder(int fps) {
|
||||
this.inputQueue = new ArrayBlockingQueue<>(32);
|
||||
final Rational framerate = Rational.make(1, fps);
|
||||
this.muxer = Muxer.make("new_output.mp4", null, "mp4");
|
||||
final MuxerFormat format = this.muxer.getFormat();
|
||||
Codec codec = Codec.findEncodingCodec(format.getDefaultVideoCodecId());
|
||||
this.encoder = Encoder.make(codec);
|
||||
|
||||
this.encoder.setWidth(1920);
|
||||
this.encoder.setHeight(1060);
|
||||
final PixelFormat.Type pixelformat = PixelFormat.Type.PIX_FMT_YUV420P;
|
||||
this.encoder.setPixelFormat(pixelformat);
|
||||
this.encoder.setTimeBase(framerate);
|
||||
|
||||
if (format.getFlag(MuxerFormat.Flag.GLOBAL_HEADER)) {
|
||||
this.encoder.setFlag(Encoder.Flag.FLAG_GLOBAL_HEADER, true);
|
||||
}
|
||||
|
||||
this.encoder.open(null, null);
|
||||
this.muxer.addNewStream(this.encoder);
|
||||
try {
|
||||
this.muxer.open(null, null);
|
||||
} catch (InterruptedException | IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
this.resampler = MediaPictureResampler.make(
|
||||
this.encoder.getWidth(), this.encoder.getHeight(), pixelformat,
|
||||
this.encoder.getWidth(), this.encoder.getHeight(), PixelFormat.Type.PIX_FMT_RGBA, 0);
|
||||
this.resampler.open();
|
||||
|
||||
this.packet = MediaPacket.make();
|
||||
|
||||
record Pictures(MediaPicture picture, MediaPicture pictureRgba) {}
|
||||
|
||||
ArrayBlockingQueue<Pictures> pictureInputQueue = new ArrayBlockingQueue<>(32);
|
||||
ArrayBlockingQueue<Pictures> pictureOutputQueue = new ArrayBlockingQueue<>(32);
|
||||
|
||||
for (int i = 0; i < 32; i++) {
|
||||
MediaPicture picture = MediaPicture.make(
|
||||
this.encoder.getWidth(),
|
||||
this.encoder.getHeight(),
|
||||
pixelformat
|
||||
);
|
||||
picture.setTimeBase(framerate);
|
||||
|
||||
MediaPicture pictureRgba = MediaPicture.make(
|
||||
this.encoder.getWidth(),
|
||||
this.encoder.getHeight(),
|
||||
PixelFormat.Type.PIX_FMT_RGBA
|
||||
);
|
||||
|
||||
pictureInputQueue.add(new Pictures(picture, pictureRgba));
|
||||
}
|
||||
|
||||
AtomicBoolean shouldEndEncoderThread = new AtomicBoolean(false);
|
||||
|
||||
new Thread(() -> {
|
||||
int currentFrame = 0;
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
Pictures pictures = pictureInputQueue.poll(10, TimeUnit.MILLISECONDS);
|
||||
if (pictures == null) {
|
||||
if (this.shouldEnd.get()) {
|
||||
shouldEndEncoderThread.set(true);
|
||||
return;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
NativeImage src = this.inputQueue.poll(10, TimeUnit.MILLISECONDS);
|
||||
if (src == null) {
|
||||
if (this.shouldEnd.get()) {
|
||||
shouldEndEncoderThread.set(true);
|
||||
return;
|
||||
} else {
|
||||
pictureInputQueue.put(pictures);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
final AtomicReference<JNIReference> ref = new AtomicReference<JNIReference>(
|
||||
null);
|
||||
Buffer buffer = pictures.pictureRgba.getData(0);
|
||||
int size = pictures.pictureRgba.getDataPlaneSize(0);
|
||||
ByteBuffer pictureByteBuffer = buffer.getByteBuffer(0,
|
||||
size, ref);
|
||||
buffer.delete();
|
||||
|
||||
pictureByteBuffer.order(ByteOrder.nativeOrder());
|
||||
for (int pixel : src.getPixelsRGBA()) {
|
||||
pictureByteBuffer.putInt(pixel);
|
||||
}
|
||||
src.close();
|
||||
|
||||
pictures.pictureRgba.setTimeStamp(currentFrame++);
|
||||
pictures.pictureRgba.setComplete(true);
|
||||
|
||||
this.resampler.resample(pictures.picture, pictures.pictureRgba);
|
||||
|
||||
if (ref.get() != null) {
|
||||
ref.get().delete();
|
||||
}
|
||||
|
||||
pictureOutputQueue.put(pictures);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
|
||||
new Thread(() -> {
|
||||
while (true) {
|
||||
try {
|
||||
Pictures pictures = pictureOutputQueue.poll(10, TimeUnit.MILLISECONDS);
|
||||
if (pictures == null) {
|
||||
if (shouldEndEncoderThread.get()) {
|
||||
do {
|
||||
this.encoder.encode(this.packet, null);
|
||||
if (this.packet.isComplete()) {
|
||||
this.muxer.write(this.packet, false);
|
||||
}
|
||||
} while (this.packet.isComplete());
|
||||
|
||||
this.muxer.close();
|
||||
|
||||
this.muxer.delete();
|
||||
this.encoder.delete();
|
||||
this.resampler.delete();
|
||||
this.packet.delete();
|
||||
this.finishedWriting.set(true);
|
||||
|
||||
pictures = pictureInputQueue.poll();
|
||||
while (pictures != null) {
|
||||
pictures.picture.delete();
|
||||
pictures.pictureRgba.delete();
|
||||
pictures = pictureInputQueue.poll();
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
this.encoder.encode(this.packet, pictures.picture);
|
||||
if (this.packet.isComplete()) {
|
||||
this.muxer.write(this.packet, false);
|
||||
}
|
||||
} while (this.packet.isComplete());
|
||||
|
||||
if (shouldEndEncoderThread.get()) {
|
||||
pictures.picture.delete();
|
||||
pictures.pictureRgba.delete();
|
||||
} else {
|
||||
pictureInputQueue.put(pictures);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
public void encode(NativeImage src) {
|
||||
while (true) {
|
||||
try {
|
||||
this.inputQueue.put(src);
|
||||
return;
|
||||
} catch (InterruptedException ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
public void finish() {
|
||||
while (!this.inputQueue.isEmpty()) {
|
||||
LockSupport.parkNanos("waiting for image queue to empty", 100000L);
|
||||
}
|
||||
|
||||
this.shouldEnd.set(true);
|
||||
|
||||
while (!this.finishedWriting.get()) {
|
||||
LockSupport.parkNanos("waiting for encoder thread to finish", 100000L);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
package com.moulberry.flashback.exporting;
|
||||
|
||||
import com.mojang.blaze3d.pipeline.RenderTarget;
|
||||
import com.mojang.blaze3d.pipeline.TextureTarget;
|
||||
import com.mojang.blaze3d.platform.GlStateManager;
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import com.mojang.blaze3d.platform.Window;
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
import com.mojang.blaze3d.vertex.*;
|
||||
import com.moulberry.flashback.FixedDeltaTracker;
|
||||
import com.moulberry.flashback.Flashback;
|
||||
import com.moulberry.flashback.state.EditorState;
|
||||
import com.moulberry.flashback.state.EditorStateCache;
|
||||
import com.moulberry.flashback.playback.ReplayServer;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.renderer.FogRenderer;
|
||||
import net.minecraft.client.renderer.ShaderInstance;
|
||||
import net.minecraft.client.sounds.SoundEngine;
|
||||
import org.joml.Matrix4f;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
public class ExportJob {
|
||||
|
||||
private final ExportSettings settings;
|
||||
|
||||
private boolean running = false;
|
||||
private boolean shouldChangeFramebufferSize = false;
|
||||
private long lastRenderMillis;
|
||||
private long escapeCancelStartMillis = -1;
|
||||
private long renderStartTime;
|
||||
|
||||
private boolean showingDebug = false;
|
||||
private boolean pressedDebugKey = false;
|
||||
private long serverTickTimeNanos = 0;
|
||||
private long clientTickTimeNanos = 0;
|
||||
private long renderTimeNanos = 0;
|
||||
private long encodeTimeNanos = 0;
|
||||
private long downloadTimeNanos = 0;
|
||||
|
||||
private final AtomicBoolean finishedServerTick = new AtomicBoolean(false);
|
||||
|
||||
public ExportJob(ExportSettings settings) {
|
||||
this.settings = settings;
|
||||
}
|
||||
|
||||
public boolean isRunning() {
|
||||
return this.running;
|
||||
}
|
||||
|
||||
public void onFinishedServerTick() {
|
||||
this.finishedServerTick.set(true);
|
||||
}
|
||||
|
||||
public boolean shouldChangeFramebufferSize() {
|
||||
return this.running && this.shouldChangeFramebufferSize;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return this.settings.resolutionX();
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return this.settings.resolutionY();
|
||||
}
|
||||
|
||||
public void run() {
|
||||
ReplayServer replayServer = Flashback.getReplayServer();
|
||||
if (this.running || replayServer == null) {
|
||||
throw new IllegalStateException("run() called twice");
|
||||
}
|
||||
this.running = true;
|
||||
|
||||
UUID uuid = UUID.randomUUID();
|
||||
|
||||
String tempFileName = "replay_export_temp/" + uuid + "." + this.settings.container().extension();
|
||||
Path exportTempFile = Path.of(tempFileName);
|
||||
Path exportTempFolder = exportTempFile.getParent();
|
||||
|
||||
TextureTarget infoRenderTarget = null;
|
||||
|
||||
try {
|
||||
Files.createDirectories(exportTempFolder);
|
||||
|
||||
RenderTarget mainTarget = Minecraft.getInstance().mainRenderTarget;
|
||||
infoRenderTarget = new TextureTarget(mainTarget.width, mainTarget.height, false, Minecraft.ON_OSX);
|
||||
|
||||
try (AsyncVideoEncoder encoder = new AsyncVideoEncoder(this.settings, tempFileName);
|
||||
SaveableFramebufferQueue downloader = new SaveableFramebufferQueue(this.settings.resolutionX(), this.settings.resolutionY())) {
|
||||
doExport(encoder, downloader, infoRenderTarget);
|
||||
}
|
||||
|
||||
Files.move(exportTempFile, this.settings.output(), StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
this.running = false;
|
||||
this.shouldChangeFramebufferSize = false;
|
||||
Minecraft.getInstance().resizeDisplay();
|
||||
|
||||
try {
|
||||
Files.deleteIfExists(exportTempFile);
|
||||
} catch (IOException ignored) {}
|
||||
|
||||
try {
|
||||
boolean empty;
|
||||
try (var stream = Files.newDirectoryStream(exportTempFolder)) {
|
||||
empty = !stream.iterator().hasNext();
|
||||
}
|
||||
if (empty) {
|
||||
Files.deleteIfExists(exportTempFolder);
|
||||
}
|
||||
} catch (IOException ignored) {}
|
||||
|
||||
if (infoRenderTarget != null) {
|
||||
infoRenderTarget.destroyBuffers();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void doExport(AsyncVideoEncoder encoder, SaveableFramebufferQueue downloader, TextureTarget infoRenderTarget) {
|
||||
ReplayServer replayServer = Flashback.getReplayServer();
|
||||
if (replayServer == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.setup(replayServer);
|
||||
|
||||
shouldChangeFramebufferSize = true;
|
||||
Minecraft.getInstance().resizeDisplay();
|
||||
|
||||
double framesPerTick = this.settings.framerate() / 20.0;
|
||||
|
||||
int currentFrame = 0;
|
||||
int totalFrames = (int) Math.ceil((this.settings.endTick() - this.settings.startTick() + 1) * framesPerTick);
|
||||
int clientTickCount = 0;
|
||||
|
||||
this.renderStartTime = System.currentTimeMillis();
|
||||
|
||||
EditorState editorState = EditorStateCache.get(replayServer.getMetadata().replayIdentifier);
|
||||
|
||||
while (currentFrame <= totalFrames) {
|
||||
double currentTickDouble = currentFrame / framesPerTick;
|
||||
int currentTick = (int) currentTickDouble;
|
||||
double partialTick = currentTickDouble - currentTick;
|
||||
int targetServerTick = this.settings.startTick() + currentTick;
|
||||
|
||||
// Wait until server is on correct replay tick
|
||||
long start = System.nanoTime();
|
||||
this.setServerTickAndWait(replayServer, targetServerTick, false);
|
||||
serverTickTimeNanos += System.nanoTime() - start;
|
||||
|
||||
// Tick client
|
||||
while (clientTickCount < currentTick) {
|
||||
start = System.nanoTime();
|
||||
this.runClientTick();
|
||||
clientTickTimeNanos += System.nanoTime() - start;
|
||||
|
||||
clientTickCount += 1;
|
||||
}
|
||||
|
||||
long pauseScreenStart = System.currentTimeMillis();
|
||||
while (Minecraft.getInstance().getOverlay() != null || Minecraft.getInstance().screen != null) {
|
||||
this.runClientTick();
|
||||
|
||||
Window window = Minecraft.getInstance().getWindow();
|
||||
RenderTarget renderTarget = Minecraft.getInstance().mainRenderTarget;
|
||||
renderTarget.bindWrite(true);
|
||||
RenderSystem.clear(16640, Minecraft.ON_OSX);
|
||||
Minecraft.getInstance().gameRenderer.render(new FixedDeltaTracker(0.0f, 0.0f), true);
|
||||
renderTarget.unbindWrite();
|
||||
|
||||
this.shouldChangeFramebufferSize = false;
|
||||
renderTarget.blitToScreen(window.getWidth(), window.getHeight(), false);
|
||||
window.updateDisplay();
|
||||
this.shouldChangeFramebufferSize = true;
|
||||
|
||||
LockSupport.parkNanos("waiting for pause overlay to disappear", 50_000_000L);
|
||||
|
||||
// Force remove screens/overlays after 5s/15s respectively
|
||||
long currentTime = System.currentTimeMillis();
|
||||
if (pauseScreenStart > currentTime) {
|
||||
pauseScreenStart = currentTime;
|
||||
}
|
||||
if (currentTime - pauseScreenStart > 5000) {
|
||||
Minecraft.getInstance().setScreen(null);
|
||||
}
|
||||
if (currentTime - pauseScreenStart > 15000) {
|
||||
Minecraft.getInstance().setOverlay(null);
|
||||
}
|
||||
}
|
||||
|
||||
this.tryUnfreezeClient();
|
||||
|
||||
editorState.applyKeyframes(Minecraft.getInstance(), (float)(this.settings.startTick() + currentTickDouble));
|
||||
|
||||
RenderTarget oldTarget = Minecraft.getInstance().getMainRenderTarget();
|
||||
SaveableFramebuffer saveable = downloader.take();
|
||||
RenderTarget renderTarget = saveable.getFramebuffer(this.settings.resolutionX(), this.settings.resolutionY());
|
||||
|
||||
Minecraft.getInstance().mainRenderTarget = renderTarget;
|
||||
|
||||
renderTarget.bindWrite(true);
|
||||
|
||||
RenderSystem.clear(16640, Minecraft.ON_OSX);
|
||||
|
||||
// Perform rendering
|
||||
PerfectFrames.waitUntilFrameReady();
|
||||
FogRenderer.setupNoFog();
|
||||
RenderSystem.enableCull();
|
||||
Minecraft.getInstance().timer.deltaTicks = 1 / (float) framesPerTick;
|
||||
Minecraft.getInstance().timer.realtimeDeltaTicks = 1 / (float) framesPerTick;
|
||||
Minecraft.getInstance().timer.deltaTickResidual = (float) partialTick;
|
||||
Minecraft.getInstance().timer.pausedDeltaTickResidual = (float) partialTick;
|
||||
|
||||
start = System.nanoTime();
|
||||
Minecraft.getInstance().gameRenderer.render(new FixedDeltaTracker(1 / (float) framesPerTick, (float) partialTick), true);
|
||||
renderTimeNanos += System.nanoTime() - start;
|
||||
|
||||
renderTarget.unbindWrite();
|
||||
|
||||
Minecraft.getInstance().mainRenderTarget = oldTarget;
|
||||
|
||||
this.shouldChangeFramebufferSize = false;
|
||||
boolean cancel = finishFrame(renderTarget, infoRenderTarget, currentFrame, totalFrames);
|
||||
this.shouldChangeFramebufferSize = true;
|
||||
|
||||
submitDownloadedFrames(encoder, downloader, false);
|
||||
|
||||
downloader.startDownload(saveable);
|
||||
|
||||
if (cancel) {
|
||||
break;
|
||||
}
|
||||
|
||||
currentFrame += 1;
|
||||
}
|
||||
|
||||
submitDownloadedFrames(encoder, downloader, true);
|
||||
encoder.finish();
|
||||
}
|
||||
|
||||
private void setup(ReplayServer replayServer) {
|
||||
Minecraft minecraft = Minecraft.getInstance();
|
||||
|
||||
// Clear particles
|
||||
minecraft.particleEngine.clearParticles();
|
||||
|
||||
// Apply keyframes at start tick
|
||||
EditorState editorState = EditorStateCache.get(replayServer.getMetadata().replayIdentifier);
|
||||
editorState.applyKeyframes(Minecraft.getInstance(), this.settings.startTick());
|
||||
|
||||
// Ensure position is updated before doing anything else
|
||||
this.runClientTick();
|
||||
this.setServerTickAndWait(replayServer, replayServer.getReplayTick(), true);
|
||||
|
||||
int currentTick = Math.max(0, this.settings.startTick() - 20);
|
||||
|
||||
// Ensure replay server is paused at currentTick
|
||||
this.setServerTickAndWait(replayServer, currentTick, true);
|
||||
this.runClientTick();
|
||||
|
||||
// Advance until tick is at start
|
||||
while (currentTick < this.settings.startTick()) {
|
||||
this.setServerTickAndWait(replayServer, currentTick, true);
|
||||
this.runClientTick();
|
||||
currentTick += 1;
|
||||
}
|
||||
|
||||
// Ensured replay server is paused at startTick
|
||||
this.setServerTickAndWait(replayServer, this.settings.startTick(), true);
|
||||
this.runClientTick();
|
||||
|
||||
// Remove screen
|
||||
minecraft.setScreen(null);
|
||||
}
|
||||
|
||||
private void setServerTickAndWait(ReplayServer replayServer, int targetTick, boolean force) {
|
||||
if (force || replayServer.getReplayTick() != targetTick) {
|
||||
this.finishedServerTick.set(false);
|
||||
|
||||
replayServer.jumpToTick = targetTick;
|
||||
replayServer.replayPaused = true;
|
||||
replayServer.sendFinishedServerTick.set(true);
|
||||
|
||||
while (!this.finishedServerTick.compareAndExchange(true, false)) {
|
||||
LockSupport.parkNanos("waiting for server thread", 100000L);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void runClientTick() {
|
||||
this.tryUnfreezeClient();
|
||||
|
||||
while (Minecraft.getInstance().pollTask()) {}
|
||||
Minecraft.getInstance().tick();
|
||||
this.tryUnfreezeClient();
|
||||
}
|
||||
|
||||
private void tryUnfreezeClient() {
|
||||
ClientLevel level = Minecraft.getInstance().level;
|
||||
if (level != null) {
|
||||
level.tickRateManager().setFrozen(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void submitDownloadedFrames(AsyncVideoEncoder encoder, SaveableFramebufferQueue downloader, boolean drain) {
|
||||
NativeImage image;
|
||||
while (true) {
|
||||
long start = System.nanoTime();
|
||||
image = downloader.finishDownload(drain);
|
||||
downloadTimeNanos += System.nanoTime() - start;
|
||||
|
||||
if (image == null) {
|
||||
break;
|
||||
}
|
||||
|
||||
start = System.nanoTime();
|
||||
encoder.encode(image);
|
||||
encodeTimeNanos += System.nanoTime() - start;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean finishFrame(RenderTarget framebuffer, RenderTarget infoRenderTarget, int currentFrame, int totalFrames) {
|
||||
boolean cancel = false;
|
||||
|
||||
long currentTime = System.currentTimeMillis();
|
||||
if (currentTime - this.lastRenderMillis > 1000/60 || currentFrame == totalFrames) {
|
||||
Window window = Minecraft.getInstance().getWindow();
|
||||
|
||||
{
|
||||
GlStateManager._colorMask(true, true, true, false);
|
||||
GlStateManager._disableDepthTest();
|
||||
GlStateManager._depthMask(false);
|
||||
GlStateManager._viewport(0, 0, window.getWidth(), window.getHeight());
|
||||
GlStateManager._disableBlend();
|
||||
|
||||
Minecraft minecraft = Minecraft.getInstance();
|
||||
ShaderInstance shaderInstance = Objects.requireNonNull(minecraft.gameRenderer.blitShader, "Blit shader not loaded");
|
||||
shaderInstance.setSampler("DiffuseSampler", framebuffer.colorTextureId);
|
||||
shaderInstance.apply();
|
||||
BufferBuilder bufferBuilder = RenderSystem.renderThreadTesselator().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.BLIT_SCREEN);
|
||||
bufferBuilder.addVertex(0.0F, 0.0F, 0.0F);
|
||||
bufferBuilder.addVertex(1.0F, 0.0F, 0.0F);
|
||||
bufferBuilder.addVertex(1.0F, 1.0F, 0.0F);
|
||||
bufferBuilder.addVertex(0.0F, 1.0F, 0.0F);
|
||||
BufferUploader.draw(bufferBuilder.buildOrThrow());
|
||||
shaderInstance.clear();
|
||||
GlStateManager._depthMask(true);
|
||||
GlStateManager._colorMask(true, true, true, true);
|
||||
}
|
||||
|
||||
this.lastRenderMillis = currentTime;
|
||||
|
||||
Font font = Minecraft.getInstance().font;
|
||||
var bufferSource = Minecraft.getInstance().renderBuffers().bufferSource();
|
||||
bufferSource.endBatch();
|
||||
infoRenderTarget.bindWrite(true);
|
||||
|
||||
RenderSystem.clearColor(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
|
||||
RenderSystem.clear(16640, Minecraft.ON_OSX);
|
||||
|
||||
int guiScale = 4;
|
||||
int scaledWidth = (int) Math.ceil(infoRenderTarget.width / guiScale);
|
||||
int scaledHeight = (int) Math.ceil(infoRenderTarget.height / guiScale);
|
||||
|
||||
Matrix4f matrix4f = new Matrix4f().setOrtho(0.0f, scaledWidth, scaledHeight, 0.0f, 1000.0f, 21000.0f);
|
||||
RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.ORTHOGRAPHIC_Z);
|
||||
|
||||
Matrix4f matrix = new Matrix4f();
|
||||
matrix.translate(0.0f, 0.0f, -11000.0f);
|
||||
|
||||
RenderSystem.disableDepthTest();
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
|
||||
lines.add("Exported Frames: " + currentFrame + "/" + totalFrames);
|
||||
|
||||
long elapsed = currentTime - this.renderStartTime;
|
||||
lines.add("Time elapsed: " + formatTime(elapsed));
|
||||
|
||||
if (currentFrame >= this.settings.framerate()) {
|
||||
long estimatedRemaining = (currentTime - this.renderStartTime) * (totalFrames - currentFrame) / currentFrame;
|
||||
lines.add("Estimated time remaining: " + formatTime(estimatedRemaining));
|
||||
}
|
||||
|
||||
lines.add("");
|
||||
|
||||
boolean debugPressed = GLFW.glfwGetKey(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_F3) != GLFW.GLFW_RELEASE;
|
||||
if (pressedDebugKey != debugPressed) {
|
||||
pressedDebugKey = debugPressed;
|
||||
if (pressedDebugKey) {
|
||||
showingDebug = !showingDebug;
|
||||
}
|
||||
}
|
||||
|
||||
if (showingDebug) {
|
||||
lines.add("ST: " + serverTickTimeNanos/1000000 + ", CT: " + clientTickTimeNanos/1000000);
|
||||
lines.add("RT: " + renderTimeNanos/1000000 + ", ET: " + encodeTimeNanos/1000000);
|
||||
lines.add("DT: " + downloadTimeNanos/1000000);
|
||||
} else {
|
||||
lines.add("Press [F3] to show debug info");
|
||||
}
|
||||
|
||||
lines.add("");
|
||||
|
||||
if (currentFrame == totalFrames) {
|
||||
lines.add("Saving...");
|
||||
} else if (GLFW.glfwGetKey(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_ESCAPE) != GLFW.GLFW_RELEASE) {
|
||||
long current = System.currentTimeMillis();
|
||||
if (this.escapeCancelStartMillis <= 0 || current < this.escapeCancelStartMillis) {
|
||||
this.escapeCancelStartMillis = current;
|
||||
}
|
||||
if (current - this.escapeCancelStartMillis > 3000) {
|
||||
cancel = true;
|
||||
lines.add("Saving...");
|
||||
} else {
|
||||
long remainingSeconds = 3 - (current - this.escapeCancelStartMillis) / 1000;
|
||||
lines.add("Hold [ESC] to cancel (" + remainingSeconds + "s)");
|
||||
}
|
||||
} else {
|
||||
lines.add("Hold [ESC] to cancel");
|
||||
this.escapeCancelStartMillis = -1;
|
||||
}
|
||||
|
||||
int x = scaledWidth / 2;
|
||||
int y = scaledHeight / 2 - font.lineHeight * (lines.size() + 1)/2;
|
||||
for (String line : lines) {
|
||||
if (line.isEmpty()) {
|
||||
y += font.lineHeight / 2 + 1;
|
||||
} else {
|
||||
font.drawInBatch(line, x - font.width(line)/2f, y,
|
||||
-1, true, matrix, bufferSource, Font.DisplayMode.NORMAL, 0, 0xF000F0);
|
||||
y += font.lineHeight;
|
||||
}
|
||||
}
|
||||
|
||||
bufferSource.endBatch();
|
||||
RenderSystem.enableDepthTest();
|
||||
|
||||
infoRenderTarget.unbindWrite();
|
||||
|
||||
RenderSystem.defaultBlendFunc();
|
||||
RenderSystem.enableBlend();
|
||||
infoRenderTarget.blitToScreen(window.getWidth(), window.getHeight(), false);
|
||||
Minecraft.getInstance().getWindow().updateDisplay();
|
||||
}
|
||||
|
||||
return cancel;
|
||||
}
|
||||
|
||||
private String formatTime(long millis) {
|
||||
long seconds = (millis / 1000) % 60;
|
||||
long minutes = (millis / 1000 / 60) % 60;
|
||||
long hours = millis / 1000 / 60 / 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return hours + "h " + minutes + "m " + seconds + "s";
|
||||
} else if (minutes > 0) {
|
||||
return minutes + "m " + seconds + "s";
|
||||
} else {
|
||||
return seconds + "s";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.moulberry.flashback.exporting;
|
||||
|
||||
import com.moulberry.flashback.combo_options.VideoCodec;
|
||||
import com.moulberry.flashback.combo_options.VideoContainer;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public record ExportSettings(int resolutionX, int resolutionY, int startTick, int endTick, double framerate, VideoContainer container,
|
||||
VideoCodec codec, String encoder, int bitrate, Path output) {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.moulberry.flashback.exporting;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class FrexFlawlessFramesIntegration implements Consumer<Function<String, Consumer<Boolean>>> {
|
||||
|
||||
@Override
|
||||
public void accept(Function<String, Consumer<Boolean>> flawlessFrames) {
|
||||
PerfectFrames.frexFlawlessFrames.add(flawlessFrames.apply("flashback"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.moulberry.flashback.exporting;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.multiplayer.PlayerInfo;
|
||||
import net.minecraft.client.player.AbstractClientPlayer;
|
||||
import net.minecraft.client.resources.SkinManager;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class PerfectFrames {
|
||||
|
||||
private static boolean isEnabled = false;
|
||||
static List<Consumer<Boolean>> frexFlawlessFrames = new ArrayList<>();
|
||||
|
||||
private static final Set<UUID> ignoreSkinLoading = new HashSet<>();
|
||||
|
||||
public static void enable() {
|
||||
isEnabled = true;
|
||||
ignoreSkinLoading.clear();
|
||||
for (Consumer<Boolean> frexFlawlessFramesConsumer : frexFlawlessFrames) {
|
||||
frexFlawlessFramesConsumer.accept(true);
|
||||
}
|
||||
}
|
||||
|
||||
public static void disable() {
|
||||
isEnabled = false;
|
||||
ignoreSkinLoading.clear();
|
||||
for (Consumer<Boolean> frexFlawlessFramesConsumer : frexFlawlessFrames) {
|
||||
frexFlawlessFramesConsumer.accept(false);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return isEnabled;
|
||||
}
|
||||
|
||||
public static void waitUntilFrameReady() {
|
||||
long start = System.currentTimeMillis();
|
||||
while (!isFrameReady(start)) {
|
||||
LockSupport.parkNanos("waiting for frame to be ready", 100000L);
|
||||
while (Minecraft.getInstance().pollTask()) {}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isFrameReady(long start) {
|
||||
long current = System.currentTimeMillis();
|
||||
boolean forceFrameReady = current - start > 15000;
|
||||
|
||||
ClientLevel level = Minecraft.getInstance().level;
|
||||
SkinManager skinManager = Minecraft.getInstance().getSkinManager();
|
||||
|
||||
if (level != null) {
|
||||
if (forceFrameReady) {
|
||||
System.err.println("Waiting for skin loading took too long, ignoring...");
|
||||
for (AbstractClientPlayer player : level.players()) {
|
||||
if (player == Minecraft.getInstance().player) {
|
||||
continue;
|
||||
}
|
||||
PlayerInfo playerInfo = player.getPlayerInfo();
|
||||
if (playerInfo != null && !skinManager.getOrLoad(playerInfo.getProfile()).isDone()) {
|
||||
System.err.println("Took too long to load skin for " + player.getUUID());
|
||||
ignoreSkinLoading.add(player.getUUID());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (AbstractClientPlayer player : level.players()) {
|
||||
if (player == Minecraft.getInstance().player) {
|
||||
continue;
|
||||
}
|
||||
if (ignoreSkinLoading.contains(player.getUUID())) {
|
||||
continue;
|
||||
}
|
||||
PlayerInfo playerInfo = player.getPlayerInfo();
|
||||
if (playerInfo != null && !skinManager.getOrLoad(playerInfo.getProfile()).isDone()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.moulberry.flashback.exporting;
|
||||
|
||||
import com.moulberry.flashback.Flashback;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import org.bytedeco.ffmpeg.avcodec.AVCodec;
|
||||
import org.bytedeco.ffmpeg.global.avcodec;
|
||||
import org.bytedeco.ffmpeg.global.avutil;
|
||||
import org.bytedeco.javacpp.BytePointer;
|
||||
import org.bytedeco.javacpp.IntPointer;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class PixelFormatHelper {
|
||||
|
||||
private static final Map<String, Integer> bestPixelFormats = new HashMap<>();
|
||||
|
||||
public static int getBestPixelFormat(String codecName) {
|
||||
if (bestPixelFormats.containsKey(codecName)) {
|
||||
return bestPixelFormats.get(codecName);
|
||||
}
|
||||
|
||||
int bestPixelFormat = calculateBestPixelFormat(codecName);
|
||||
|
||||
if (bestPixelFormat == avutil.AV_PIX_FMT_NONE) {
|
||||
throw new RuntimeException("Unable to determine best alternate pixel format for " + codecName);
|
||||
}
|
||||
if (bestPixelFormat != avutil.AV_PIX_FMT_YUV420P) {
|
||||
Flashback.LOGGER.info("Chose to use alternate pixel format {} for codec {}", pixelFormatToString(bestPixelFormat), codecName);
|
||||
}
|
||||
|
||||
bestPixelFormats.put(codecName, bestPixelFormat);
|
||||
return bestPixelFormat;
|
||||
}
|
||||
|
||||
private static int calculateBestPixelFormat(String codecName) {
|
||||
try (AVCodec codec = avcodec.avcodec_find_encoder_by_name(codecName)) {
|
||||
IntList supportedFormats = new IntArrayList();
|
||||
|
||||
IntPointer pixFmts = codec.pix_fmts();
|
||||
|
||||
int index = 0;
|
||||
while (true) {
|
||||
int pixFmt = pixFmts.get(index);
|
||||
if (pixFmt == -1) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (pixFmt == avutil.AV_PIX_FMT_YUV420P) {
|
||||
return avutil.AV_PIX_FMT_YUV420P;
|
||||
}
|
||||
|
||||
supportedFormats.add(pixFmt);
|
||||
index += 1;
|
||||
}
|
||||
|
||||
supportedFormats.add(avutil.AV_PIX_FMT_NONE);
|
||||
|
||||
return avcodec.avcodec_find_best_pix_fmt_of_list(supportedFormats.toIntArray(), avutil.AV_PIX_FMT_BGRA, 0, new int[1]);
|
||||
}
|
||||
}
|
||||
|
||||
private static String pixelFormatToString(int pixelFormat) {
|
||||
try (BytePointer name = avutil.av_get_pix_fmt_name(pixelFormat)) {
|
||||
return name.getString();
|
||||
} catch (Throwable ignored) {}
|
||||
return "UNKNOWN(" + pixelFormat + ")";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.moulberry.flashback.exporting;
|
||||
|
||||
import com.mojang.blaze3d.pipeline.MainTarget;
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import org.lwjgl.opengl.GL30C;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
public class SaveableFramebuffer implements AutoCloseable {
|
||||
|
||||
private MainTarget framebuffer;
|
||||
private int pboId;
|
||||
|
||||
private boolean isDownloading = false;
|
||||
|
||||
public SaveableFramebuffer() {
|
||||
this.framebuffer = null;
|
||||
this.pboId = -1;
|
||||
}
|
||||
|
||||
public boolean isDownloading() {
|
||||
return isDownloading;
|
||||
}
|
||||
|
||||
public MainTarget getFramebuffer(int width, int height) {
|
||||
if (this.isDownloading) {
|
||||
throw new IllegalStateException("Can't get the framebuffer for rendering while still downloading");
|
||||
}
|
||||
|
||||
if (this.framebuffer == null) {
|
||||
this.framebuffer = new MainTarget(width, height);
|
||||
}
|
||||
|
||||
return this.framebuffer;
|
||||
}
|
||||
|
||||
public void startDownload(int width, int height) {
|
||||
if (this.isDownloading) {
|
||||
throw new IllegalStateException("Can't start downloading while already downloading");
|
||||
}
|
||||
this.isDownloading = true;
|
||||
|
||||
if (this.pboId == -1) {
|
||||
this.pboId = GL30C.glGenBuffers();
|
||||
|
||||
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, this.pboId);
|
||||
GL30C.glBufferData(GL30C.GL_PIXEL_PACK_BUFFER, (long) width * height * 4, GL30C.GL_STREAM_READ);
|
||||
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, 0);
|
||||
}
|
||||
|
||||
this.framebuffer.bindWrite(true);
|
||||
|
||||
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, this.pboId);
|
||||
GL30C.glReadPixels(0, 0, width, height, GL30C.GL_RGBA, GL30C.GL_UNSIGNED_BYTE, 0);
|
||||
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, 0);
|
||||
|
||||
this.framebuffer.unbindWrite();
|
||||
}
|
||||
|
||||
public NativeImage finishDownload(int width, int height) {
|
||||
if (!this.isDownloading) {
|
||||
throw new IllegalStateException("Can't finish downloading before download has started");
|
||||
}
|
||||
this.isDownloading = false;
|
||||
|
||||
NativeImage nativeImage = new NativeImage(NativeImage.Format.RGBA, width, height, false);
|
||||
|
||||
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, this.pboId);
|
||||
ByteBuffer buffer = GL30C.glMapBuffer(GL30C.GL_PIXEL_PACK_BUFFER, GL30C.GL_READ_ONLY);
|
||||
|
||||
if (buffer == null) {
|
||||
throw new IllegalStateException("OpenGL error occurred while mapping buffer");
|
||||
}
|
||||
|
||||
// Copy bytes
|
||||
MemoryUtil.memCopy(MemoryUtil.memAddress(buffer), nativeImage.pixels, nativeImage.size);
|
||||
|
||||
// for (int y = 0; y < nativeImage.getHeight(); ++y) {
|
||||
// for (int x = 0; x < nativeImage.getWidth(); ++x) {
|
||||
// int rgba = nativeImage.getPixelRGBA(x, y);
|
||||
// nativeImage.setPixelRGBA(x, y, (rgba & 0xFFFFFF) | (80 << NativeImage.Format.RGBA.alphaOffset()));
|
||||
// }
|
||||
// }
|
||||
|
||||
nativeImage.flipY();
|
||||
|
||||
GL30C.glUnmapBuffer(GL30C.GL_PIXEL_PACK_BUFFER);
|
||||
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, 0);
|
||||
|
||||
return nativeImage;
|
||||
}
|
||||
|
||||
public void close() {
|
||||
if (this.framebuffer != null) {
|
||||
this.framebuffer.destroyBuffers();
|
||||
this.framebuffer = null;
|
||||
}
|
||||
if (this.pboId != -1) {
|
||||
GL30C.glDeleteBuffers(this.pboId);
|
||||
this.pboId = -1;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.moulberry.flashback.exporting;
|
||||
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class SaveableFramebufferQueue implements AutoCloseable {
|
||||
|
||||
private final int width;
|
||||
private final int height;
|
||||
|
||||
private static final int CAPACITY = 3;
|
||||
|
||||
private final List<SaveableFramebuffer> available = new ArrayList<>();
|
||||
private final List<SaveableFramebuffer> waiting = new ArrayList<>();
|
||||
|
||||
public SaveableFramebufferQueue(int width, int height) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
for (int i = 0; i < CAPACITY; i++) {
|
||||
this.available.add(new SaveableFramebuffer());
|
||||
}
|
||||
}
|
||||
|
||||
public SaveableFramebuffer take() {
|
||||
if (this.available.isEmpty()) {
|
||||
throw new IllegalStateException("No textures available!");
|
||||
}
|
||||
return this.available.removeFirst();
|
||||
}
|
||||
|
||||
public void startDownload(SaveableFramebuffer texture) {
|
||||
texture.startDownload(this.width, this.height);
|
||||
this.waiting.add(texture);
|
||||
}
|
||||
|
||||
public @Nullable NativeImage finishDownload(boolean drain) {
|
||||
if (this.waiting.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!drain && !this.available.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
SaveableFramebuffer texture = this.waiting.removeFirst();
|
||||
NativeImage nativeImage = texture.finishDownload(this.width, this.height);
|
||||
this.available.add(texture);
|
||||
return nativeImage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
for (SaveableFramebuffer texture : this.waiting) {
|
||||
texture.close();
|
||||
}
|
||||
for (SaveableFramebuffer texture : this.available) {
|
||||
texture.close();
|
||||
}
|
||||
this.waiting.clear();
|
||||
this.available.clear();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user