This commit is contained in:
Moulberry committed 2024-08-29 10:34:49 +08:00
1 parent d2a217509f
commit 4d8f896cdf
90 files changed
+2345 -720

No files matched your search

@@ -21,6 +21,7 @@ import org.bytedeco.javacv.FFmpegLogCallback;
import org.bytedeco.javacv.Frame;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import org.lwjgl.system.MemoryUtil;
import java.io.IOException;
@@ -51,7 +52,7 @@ public class AsyncVideoEncoder implements AutoCloseable {
private final AtomicReference<Throwable> threadedError = new AtomicReference<>(null);
private static final int SRC_PIXEL_FORMAT = avutil.AV_PIX_FMT_RGBA;
public 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,
@Nullable FloatBuffer audioBuffer) implements AutoCloseable {
@@ -89,11 +90,12 @@ public class AsyncVideoEncoder implements AutoCloseable {
String extension = settings.container().extension();
try {
if (FabricLoader.getInstance().isDevelopmentEnvironment() || true) {
FFmpegLogCallback.set();
}
FFmpegLogCallback.set();
int dstPixelFormat = PixelFormatHelper.getBestPixelFormat(settings.encoder());
boolean wantTransparency = settings.transparent();
int dstPixelFormat = PixelFormatHelper.getBestPixelFormat(settings.encoder(), wantTransparency);
Flashback.LOGGER.info("Encoding video with pixel format {}", PixelFormatHelper.pixelFormatToString(dstPixelFormat));
boolean needsRescale = SRC_PIXEL_FORMAT != dstPixelFormat;
final FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
@@ -14,14 +14,13 @@ import com.moulberry.flashback.compat.IrisApiWrapper;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler;
import com.moulberry.flashback.keyframe.types.SpeedKeyframeType;
import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.state.KeyframeTrack;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import it.unimi.dsi.fastutil.doubles.DoubleList;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import it.unimi.dsi.fastutil.floats.FloatList;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Screenshot;
@@ -48,6 +47,7 @@ import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;
@@ -94,11 +94,11 @@ public class ExportJob {
}
public int getWidth() {
return this.settings.resolutionX();
return this.settings.resolutionX() * (this.settings.ssaa() ? 2 : 1);
}
public int getHeight() {
return this.settings.resolutionY();
return this.settings.resolutionY() * (this.settings.ssaa() ? 2 : 1);
}
public Random getParticleRandom() {
@@ -248,11 +248,8 @@ public class ExportJob {
this.settings.editorState().applyKeyframes(keyframeHandler, (float)(this.settings.startTick() + currentTickDouble));
SaveableFramebuffer saveable;
RenderTarget renderTarget;
saveable = downloader.take();
renderTarget = Minecraft.getInstance().mainRenderTarget;
SaveableFramebuffer saveable = downloader.take();
RenderTarget renderTarget = Minecraft.getInstance().mainRenderTarget;
renderTarget.bindWrite(true);
RenderSystem.clear(16640, Minecraft.ON_OSX);
@@ -294,7 +291,7 @@ public class ExportJob {
submitDownloadedFrames(encoder, downloader, false);
saveable.audioBuffer = audioBuffer;
downloader.startDownload(renderTarget, saveable);
downloader.startDownload(renderTarget, saveable, this.settings.ssaa());
if (cancel) {
ExportJobQueue.drainingQueue = false;
@@ -594,8 +591,8 @@ public class ExportJob {
private float tickrate = 20.0f;
@Override
public EnumSet<KeyframeType> supportedKeyframes() {
return EnumSet.of(KeyframeType.SPEED, KeyframeType.TIMELAPSE);
public Set<KeyframeType<?>> supportedKeyframes() {
return Set.of(SpeedKeyframeType.INSTANCE, TimelapseKeyframeType.INSTANCE);
}
@Override
@@ -16,7 +16,7 @@ public record ExportSettings(@Nullable String name, EditorState editorState,
int resolutionX, int resolutionY, int startTick, int endTick, double framerate,
boolean resetRng,
// Video
VideoContainer container, VideoCodec codec, String encoder, int bitrate,
VideoContainer container, VideoCodec codec, String encoder, int bitrate, boolean transparent, boolean ssaa,
// Audio
boolean recordAudio,
// Output
@@ -1,6 +1,10 @@
package com.moulberry.flashback.exporting;
import com.moulberry.flashback.Flashback;
import it.unimi.dsi.fastutil.ints.Int2BooleanMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import org.bytedeco.ffmpeg.avcodec.AVCodec;
@@ -15,26 +19,29 @@ import java.util.Map;
public class PixelFormatHelper {
private static final Map<String, Integer> bestPixelFormats = new HashMap<>();
private static final Map<String, Integer> bestPixelFormatsTransparent = new HashMap<>();
public static int getBestPixelFormat(String codecName) {
if (bestPixelFormats.containsKey(codecName)) {
return bestPixelFormats.get(codecName);
public static int getBestPixelFormat(String codecName, boolean transparent) {
Map<String, Integer> best = transparent ? bestPixelFormatsTransparent : bestPixelFormats;
if (best.containsKey(codecName)) {
return best.get(codecName);
}
int bestPixelFormat = calculateBestPixelFormat(codecName);
int bestPixelFormat = calculateBestPixelFormat(codecName, transparent);
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);
Flashback.LOGGER.info("Chose to use alternate pixel format {} for codec {} with transparent={}", pixelFormatToString(bestPixelFormat), codecName, transparent);
}
bestPixelFormats.put(codecName, bestPixelFormat);
best.put(codecName, bestPixelFormat);
return bestPixelFormat;
}
private static int calculateBestPixelFormat(String codecName) {
private static int calculateBestPixelFormat(String codecName, boolean transparent) {
try (AVCodec codec = avcodec.avcodec_find_encoder_by_name(codecName)) {
IntList supportedFormats = new IntArrayList();
@@ -51,7 +58,7 @@ public class PixelFormatHelper {
break;
}
if (pixFmt == avutil.AV_PIX_FMT_YUV420P) {
if (!transparent && pixFmt == avutil.AV_PIX_FMT_YUV420P) {
return avutil.AV_PIX_FMT_YUV420P;
}
@@ -61,11 +68,54 @@ public class PixelFormatHelper {
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]);
if (transparent) {
int format = avcodec.avcodec_find_best_pix_fmt_of_list(supportedFormats.toIntArray(), AsyncVideoEncoder.SRC_PIXEL_FORMAT, 1, new int[1]);
if (format != avutil.AV_PIX_FMT_NONE) {
return format;
}
}
return avcodec.avcodec_find_best_pix_fmt_of_list(supportedFormats.toIntArray(), AsyncVideoEncoder.SRC_PIXEL_FORMAT, 0, new int[1]);
}
}
private static String pixelFormatToString(int pixelFormat) {
// Pixel format supports transparency
private static final Int2BooleanMap pixelFormatSupportsTransparency = new Int2BooleanOpenHashMap();
public static boolean doesPixelFormatSupportTransparency(int pixelFormat) {
if (pixelFormatSupportsTransparency.containsKey(pixelFormat)) {
return pixelFormatSupportsTransparency.get(pixelFormat);
}
boolean supports = calculateDoesPixelFormatSupportTransparency(pixelFormat);
pixelFormatSupportsTransparency.put(pixelFormat, supports);
return supports;
}
private static boolean calculateDoesPixelFormatSupportTransparency(int pixelFormat) {
try (var descriptor = avutil.av_pix_fmt_desc_get(pixelFormat)) {
if (descriptor == null || descriptor.isNull()) {
return false;
}
return (descriptor.flags() & avutil.AV_PIX_FMT_FLAG_ALPHA) != 0;
}
}
// Pixel format names
private static final Int2ObjectMap<String> pixelFormatNames = new Int2ObjectOpenHashMap<>();
public static String pixelFormatToString(int pixelFormat) {
if (pixelFormatNames.containsKey(pixelFormat)) {
return pixelFormatNames.get(pixelFormat);
}
String name = pixelFormatToStringInner(pixelFormat);
pixelFormatNames.put(pixelFormat, name);
return name;
}
private static String pixelFormatToStringInner(int pixelFormat) {
try (BytePointer name = avutil.av_get_pix_fmt_name(pixelFormat)) {
return name.getString();
} catch (Throwable ignored) {}
@@ -3,6 +3,8 @@ package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.pipeline.MainTarget;
import com.mojang.blaze3d.pipeline.RenderTarget;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL30C;
import org.lwjgl.system.MemoryUtil;
@@ -20,7 +22,6 @@ public class SaveableFramebuffer implements AutoCloseable {
this.pboId = -1;
}
public void startDownload(RenderTarget framebuffer, int width, int height) {
if (this.isDownloading) {
throw new IllegalStateException("Can't start downloading while already downloading");
@@ -4,17 +4,21 @@ 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.TextureUtil;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.BufferUploader;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.VertexFormat;
import com.moulberry.flashback.visuals.ShaderManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ShaderInstance;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30C;
import org.lwjgl.opengl.GL32C;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
@@ -29,23 +33,16 @@ public class SaveableFramebufferQueue implements AutoCloseable {
private final List<SaveableFramebuffer> available = new ArrayList<>();
private final List<SaveableFramebuffer> waiting = new ArrayList<>();
private final RenderTarget flipbuffer;
private final ShaderInstance flipShader;
private final RenderTarget flipBuffer;
public SaveableFramebufferQueue(int width, int height) {
this.width = width;
this.height = height;
this.flipbuffer = new TextureTarget(width, height, false, false);
this.flipBuffer = new TextureTarget(width, height, false, false);
for (int i = 0; i < CAPACITY; i++) {
this.available.add(new SaveableFramebuffer());
}
try {
this.flipShader = new ShaderInstance(Minecraft.getInstance().getResourceManager(), "blit_screen_flip", DefaultVertexFormat.BLIT_SCREEN);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public SaveableFramebuffer take() {
@@ -55,7 +52,12 @@ public class SaveableFramebufferQueue implements AutoCloseable {
return this.available.removeFirst();
}
private void blitFlip(RenderTarget src) {
private void blitFlip(RenderTarget src, boolean supersampling) {
int oldFilterMode = src.filterMode;
if (supersampling) {
src.setFilterMode(GL11.GL_LINEAR);
}
GlStateManager._colorMask(true, true, true, true);
GlStateManager._disableDepthTest();
GlStateManager._depthMask(false);
@@ -63,27 +65,32 @@ public class SaveableFramebufferQueue implements AutoCloseable {
GlStateManager._disableBlend();
RenderSystem.disableCull();
this.flipbuffer.bindWrite(true);
this.flipShader.setSampler("DiffuseSampler", src.colorTextureId);
this.flipShader.apply();
this.flipBuffer.bindWrite(true);
ShaderInstance flipShader = ShaderManager.blitScreenFlip;
flipShader.setSampler("DiffuseSampler", src.colorTextureId);
flipShader.apply();
BufferBuilder bufferBuilder = RenderSystem.renderThreadTesselator().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.BLIT_SCREEN);
bufferBuilder.addVertex(0.0F, 1.0F, 0.0F);
bufferBuilder.addVertex(1.0F, 1.0F, 0.0F);
bufferBuilder.addVertex(1.0F, 0.0F, 0.0F);
bufferBuilder.addVertex(0.0F, 0.0F, 0.0F);
BufferUploader.draw(bufferBuilder.buildOrThrow());
this.flipShader.clear();
flipShader.clear();
GlStateManager._depthMask(true);
GlStateManager._colorMask(true, true, true, true);
RenderSystem.enableCull();
if (supersampling) {
src.setFilterMode(oldFilterMode);
}
}
public void startDownload(RenderTarget target, SaveableFramebuffer texture) {
//Do an inline flip
this.blitFlip(target);
public void startDownload(RenderTarget target, SaveableFramebuffer texture, boolean supersampling) {
// Do an inline flip
this.blitFlip(target, supersampling);
texture.startDownload(this.flipbuffer, this.width, this.height);
texture.startDownload(this.flipBuffer, this.width, this.height);
this.waiting.add(texture);
}
@@ -118,8 +125,7 @@ public class SaveableFramebufferQueue implements AutoCloseable {
}
this.waiting.clear();
this.available.clear();
this.flipbuffer.destroyBuffers();
this.flipShader.close();
this.flipBuffer.destroyBuffers();
}