Fix YUV colourspace conversion for weird formats

This commit is contained in:
Moulberry committed 2025-02-21 23:26:45 +08:00
1 parent 1e40a669a1
commit e9d826191d
3 files changed
+20 -8

No files matched your search

+1 -1
View File
@@ -9,7 +9,7 @@ yarn_mappings=1.21.4+build.1
loader_version=0.16.9
# Mod Properties
mod_version=0.17.2
mod_version=0.17.5
maven_group=com.moulberry.flashback
archives_base_name=flashback
@@ -216,6 +216,10 @@ public class AsyncFFmpegVideoWriter implements AutoCloseable, VideoWriter {
PointerPointer<AVFrame> tmp_picture_ptr = new PointerPointer<>(tmp_picture);
PointerPointer<AVFrame> picture_ptr = new PointerPointer<>(picture);
Flashback.LOGGER.info("Rescaling to pixel format: {}", dstPixelFormat);
boolean useItu709Colorspace = PixelFormatHelper.isYuvFormat(dstPixelFormat);
Thread scaleThread = new Thread(() -> {
SwsContext img_convert_ctx = null;
@@ -234,20 +238,17 @@ public class AsyncFFmpegVideoWriter implements AutoCloseable, VideoWriter {
}
img_convert_ctx = swscale.sws_getCachedContext(img_convert_ctx, src.width, src.height, src.pixelFormat,
dstWidth, dstHeight, dstPixelFormat, swscale.SWS_BILINEAR,
dstWidth, dstHeight, dstPixelFormat, swscale.SWS_LANCZOS | swscale.SWS_ACCURATE_RND | swscale.SWS_FULL_CHR_H_INT,
null, null, (DoublePointer) null);
if (img_convert_ctx == null) {
throw new RuntimeException("sws_getCachedContext() error: Cannot initialize the conversion context.");
}
int dstRange = 1; // Full
if (dstPixelFormat == AV_PIX_FMT_YUV420P) { // todo: check more values
dstRange = 0; // Partial
if (useItu709Colorspace) {
IntPointer coefficients = swscale.sws_getCoefficients(swscale.SWS_CS_ITU709);
swscale.sws_setColorspaceDetails(img_convert_ctx, coefficients, 1, coefficients, 0, 0, 1 << 16, 1 << 16);
}
IntPointer coefficients = swscale.sws_getCoefficients(swscale.SWS_CS_ITU709);
swscale.sws_setColorspaceDetails(img_convert_ctx, coefficients, 1, coefficients, dstRange, 0, 1 << 16, 1 << 16);
BytePointer data = new BytePointer() {{
this.address = src.pointer;
this.position = 0;
@@ -7,6 +7,7 @@ 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 it.unimi.dsi.fastutil.ints.IntSet;
import org.bytedeco.ffmpeg.avcodec.AVCodec;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
@@ -122,4 +123,14 @@ public class PixelFormatHelper {
return "UNKNOWN(" + pixelFormat + ")";
}
public static boolean isYuvFormat(int pixelFormat) {
try (var descriptor = avutil.av_pix_fmt_desc_get(pixelFormat)) {
if (descriptor == null || descriptor.isNull()) {
throw new RuntimeException();
}
return (descriptor.flags() & avutil.AV_PIX_FMT_FLAG_RGB) == 0 && descriptor.nb_components() >= 2;
}
}
}