From 665f69899e26dd08d163385718ac34aa5b3588f3 Mon Sep 17 00:00:00 2001 From: Oneric Date: Fri, 8 Dec 2023 20:13:19 +0100 Subject: [PATCH] Gracefully handle negative Encoding values Back in 2012 libass added a custom Encoding=-1 extension to enable automatic BiDi base direction instead of the usual LTR default. The assumption/hope presumably was that since all valid font encodings are positive VSFilter would just gracefully ignore them. However, this is unfortuantely not the case. When passed to GDI the charSet is cast to a byte and will wrap around to a valid value, severely restricting which fonts can be used. Searching through a large pile of subtitles the only hits for negative values in the Encoding field were from generally corrupted files. It thus appears so far fortunately nobody used the extension in released fiels (only transient conversion from other formats during playback) and also nobody is relying on the wraparound in VSFilter. To minimise future problems treat all negative Encodings as the default charset. This matches how libass does fontselection for -1 albeit it doesn't reproduce the BiDi base direction. It also conveniently carves out the [-2, INT_MIN] range for potential future extensions common to VSFilters and libass, e.g. Encoding=-2 for a RTL base direction (which should be easier to implement in VSFilter than auto base direction) --- src/subtitles/RTS.cpp | 1 + src/subtitles/STS.cpp | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/subtitles/RTS.cpp b/src/subtitles/RTS.cpp index bd309a7f..ab109fa0 100644 --- a/src/subtitles/RTS.cpp +++ b/src/subtitles/RTS.cpp @@ -2524,6 +2524,7 @@ bool CRenderedTextSubtitle::ParseSSATag( CSubtitle* sub, const AssTagList& assTa case CMD_fe: { int n = wcstol(p, NULL, 10); + if (n < 0) n = DEFAULT_CHARSET; style.charSet = !p.IsEmpty() ? n : org.charSet; diff --git a/src/subtitles/STS.cpp b/src/subtitles/STS.cpp index ea0c46e7..47ddc8c0 100644 --- a/src/subtitles/STS.cpp +++ b/src/subtitles/STS.cpp @@ -1554,6 +1554,7 @@ static bool OpenSubStationAlpha(CTextFile* file, CSimpleTextSubtitle& ret, int C { CString StyleName; int alpha; + int encoding; CRect tmp_rect; StyleName = WToT(GetStr(buff)); @@ -1578,9 +1579,11 @@ if(sver >= 4) style->borderStyle = GetInt(buff); if(sver >= 6) tmp_rect.bottom = GetInt(buff); style->marginRect = tmp_rect; if(sver <= 4) alpha = GetInt(buff); - style->charSet = GetInt(buff); + encoding = GetInt(buff); if(sver >= 6) style->relativeTo = GetInt(buff); + // Map unsupported extension to the most permissive charSet + style->charSet = encoding < 0 ? DEFAULT_CHARSET : encoding; if(sver <= 4) style->colors[2] = style->colors[3]; // style->colors[2] is used for drawing the outline if(sver <= 4) alpha = max(min(alpha, 0xff), 0); if(sver <= 4) {for(int i = 0; i < 3; i++) style->alpha[i] = alpha; style->alpha[3] = 0x80;}