Adventures in assing images

PRERELEASE THINGO (please don’t actually use it; I’ll put up a more polished version in its own repo soon(tm)… but you also shouldn’t be using that either)

(like the script, this blog post is also a work in progress; I’ll finish it in the coming days alongside hacking on the script)

Once upon a time, lyger wrote a script, Image2ASS, that lets you convert a bitmap image into an ASS script, so you can render raster images in the subtitles. Turns out that trying to shoehorn raster graphics into a vector format behaves very badly – the way image2ass works is that it draws one-pixel-tall rectangles for every run of identically-coloured pixels, and this leads to a huge number of drawings being rendered. (lyger’s version also includes a bit of lossy compression, in that sufficiently close colours will also be merged into the same run, but this does not resolve the fundamental problem that there’s a shitload of drawings.)

There are, of course, independent reimplementations of the same idea. There’s at least png2ass (also written in Python) and encodeStraightIntoASS.php (from the “what if we rendered a whole episode in ASS” Pop Team Epic release). For the sake of brevity, let’s just call all of these “img2ass”.

This is yet another script to add to the family.

The motivation for this was some discussion in the fansubbing cave discussion cave about two weeks ago. Someone complained about a fansub release being laggy on playback, and it turned out it’s because the encoder messed up on dehardsubbing a sign, some miscommunication happened, and the typesetter img2ass’d to cover it up. Everyone came to the conclusion that you should just not use img2ass or anything of that sort in softsubs, which is a reasonable conclusion. But naturally, the discussion also turned to this question: is there a way to make it not lag? Or at least, lag less? If the problem with the existing img2ass scripts is that they generate a lot of drawings, what if we quantise the image and use a single drawing per colour? This obviously uses less drawings than the RLE compression used by Image2ASS or png2ass, so it’s good, right?

…

I’ll admit up front that I don’t know; I haven’t figured out what’s a good way to run benchmarks, but beyond that, as I’m not a typesetter, I don’t know what kinds of things people use img2ass on anyway.

Anyway, that’s what my script does. If the input already has a small number of distinct colours, use a single drawing per colour; otherwise, quantise to 4 bits per channel (note: this is going to change) before doing the vectorisation. Unlike earlier img2ass scripts, mine also features robustness to scaling! (Well, some.)

I do want to remark on a few things that I found interesting, though.

Continue reading →

A little range/median problem

A bit more than a year ago, I posed this question on the bird website (slightly reworded):

Take three independent samples X, Y, Z from a uniform distribution over the interval [0, 1], and consider the sample range max(X,Y,Z) − min(X,Y,Z). The sample range follows a beta distribution B(2, 2), which happens to be symmetric around 1/2. Is there a simple or intuitive explanation for the symmetry?

I’d known of this fact for a very long time (probably like ten years at this point), but I hadn’t really put much effort into figuring it out. I can do the computation all right—the sample range for n samples follows a B(n−1, 2) distribution, and that happens to be symmetric around 1/2 exactly when n=3. On one hand, this suggests that n=3 is a special case and it doesn’t generalise, so we should not expect to see a “simple” description beyond just working it out; on the other hand, that seems a bit defeatist. Incidentally, the median of n samples (when n is odd) follows a B((n+1)/2, (n+1)/2) distribution; obviously this is symmetric (the sample median of any symmetric distribution is symmetric), but less obviously, this also coincides with the distribution of the sample range when n=3. Is there something going on here?

I was doodling a bunch of nonsense recently and in the process, I thought of this problem again. We would like to show that, in some sense, the sample median and the sample range are measuring the exact same thing, just interpreted differently, and one useful tool to accomplish that is a coordinate transform. Now, if we start with the uniform distribution over a unit cube, that’s kind of hard to work with. Neither the range nor the median have convenient interpretation here, and that’s where I got stuck in the past. However, we can sort the three samples first! Obviously, this affects neither the range nor the median; the joint distribution is now a uniform distribution over a tetrahedron with vertices at (0,0,0), (0,0,1), (0,1,1) and (1,1,1). (Here’s a fun exercise: make three paper models of this tetrahedron and three more of its mirror image; these fit together to form a cube although gravity will probably fight you along the way.)

This would be a pretty good time to point out that completely arbitrary coordinate transforms can result in a uniform distribution (as in, uniform over its support) being transformed into something that is not uniform, but as long as we stick to affine transforms (with nonzero Jacobian determinant in a finite-dimensional Euclidean space), uniform distributions stay uniform. Furthermore, taking convex hull commutes with affine transforms: T ( convex hull (S) ) = convex hull ( T (S) ) where T is any affine transform and S is any collection of points. A convex polyhedron (in particular, a tetrahedron) may be treated as the convex hull of its vertices, and this greatly simplifies the task of trying to show that two polyhedra are equal, since we only have to check the vertices and not the shape as a whole.

(Technicality: we’re working with only closed polyhedra here, i.e. the boundary is included. An open polyhedron need not even contain its vertices. Also, convexity is important here; it’s possible for different nonconvex polyhedra to have the same vertices without being congruent. Analogously, in two dimensions, knowing the vertices doesn’t necessarily uniquely define the order in which you draw the edges through them to form a polygon—you have uniqueness when the vertices lie on the boundary of the convex hull but otherwise, uniqueness is not guaranteed. This is not a problem here because tetrahedra are always convex.)

(Also, this is a completely encoding-unrelated blog post, but convex hulls should also show up in the next blog post which is sort of encoding-related and hopefully I’ll finish that before I die by tomorrow.)

As before, we’ll let the sorted coordinates be X ≤ Y ≤ Z, so Y is the median and Z − X is the range. We can also write the inequality as 0 ≤ X ≤ Y ≤ Z ≤ 1 to make the bounds more clear. Instead of choosing the three points independently and then sorting them, we could equivalently choose the median Y first, then pick X ∈ [0, Y] and Z ∈ [Y, 1]. This suggests that we can “take complements” within the intervals [0, Y] and [Y, 1], i.e. 𝒳 := Y − X and 𝒵 := 1 − Z + Y.

(𝒳, Y, 𝒵) is an affine transform of (X, Y, Z), and it would be easy to check that the vertices of our tetrahedron get mapped from (0,0,0), (0,0,1), (0,1,1), (1,1,1) to (0,0,1), (0,0,0), (1,1,1), (0,1,1) by this affine transform. As (unordered) sets, these are equal, so the supports of the joint distributions are identical, and consequently, (X, Y, Z) and (𝒳, Y, 𝒵) are equal in distribution. This also means that the ranges are equal in distribution, i.e. Z − X has the same distribution as 𝒵 − 𝒳 = (1 − Z + Y) − (Y − X) = 1 − (Z − X). But what this is really saying is just that the distribution of the range is symmetric around 1/2, which is exactly what we set out to show.

It turns out that we can also use an affine transform to demonstrate that the median and the range have the same distribution as well, although this connection is harder to motivate. Instead of starting with the median Y and then choosing the minimum X and the maximum Z, we choose the range first, then the location of the median within [min, max], and finally the location of max (which is enough to determine where the interval [min, max] is within [0, 1]). To wit, take 𝔜 := Z − X, 𝔛 := Y − X, ℨ := Z. Again, we have that (𝔛, 𝔜, ℨ) is an affine transform of (X, Y, Z), mapping (0,0,0), (0,0,1), (0,1,1), (1,1,1) to (0,0,0), (0,1,1), (1,1,1), (0,0,1); this is a rearrangement of the vertices, blah blah, (X, Y, Z) and (𝔛, 𝔜, ℨ) are equal in distribution and hence the median Y and the range 𝔜 have equal distributions.

THIS IS NOW A RIICHI BLOG / Some rambling about Tenhou’s ranking systems

(no, not actually, but I guess I wanted some place to blog about stuff)

(Also, disclaimer: I think I’m good, but not very good, at riichi mahjong, so don’t take any of what I write as actual advice. Actually, this also applies to everything else written on this blog!! (This specific post doesn’t have any strategy-related blogging, but I might write some of those in the future. Probably not. Writing is effort.))

Mahjong Soul (aka Majsoul, Jantama) is the new hotness, but I’m old-school and still play on Tenhou. I recently decided I wanted to gitgud at this game, so I made a new Tenhou account about two months ago and then started grinding. Also read Daina Chiba’s first (and currently only) book on basic strategies, which was partially things I already knew (e.g. suji) and partially things that I somehow never picked up after hundreds of games (e.g. riichi/dama judgment).

Tenhou uses two different ranking systems. The main one is the kyuu/dan rank: you gain some points for placing first and second, you lose (a lot of) points for placing fourth, and you get to “level up” every time you hit a point threshold. Conversely, if you lose too many games in a row, you can also drop in rank. The amount of points earned for placing first/second depends on the room you play in (ippan is 30/15, joukyuu is 60/15, tokujou is 75/30, houou is 90/45) and is independent of the current rank; on the other hand, the amount of points lost for placing fourth depends on your current rank (0 up to 3-kyuu, 15 for 2-kyuu, increasing progressively thereafter) and is independent of the room. If you somehow manage to rank up all the way, there’s a special “tenhoui” rank beyond 10-dan, at which point you’ll never derank for losing games, but of course you also can’t progress any further.

If you assume that an average player has placement stats of 25%/25%/25%/25% (this does not reflect reality, but bear with me), we can look at the “steady-state” rank if someone plays a gazillion games in the same room: the steady-state rank for playing in the ippan room is 1-dan, for joukyuu it’s 3-dan, for tokujou it’s 5-dan, and for houou it’s 7-dan. If you actually look at Tenhou’s per-rank placement stats, you’ll probably find something very strange: above 1-dan, the placement stats are more like 26% / 25.5% / 24.5% / 24%. It’s a small difference, but given how large the sample size is, it’s certainly statistically significant.

[screenshot of Tenhou's stats by rank; link leads to the source]

(The columns read, from left to right: ranking points; rate; total points (this is irrelevant); first rate; second rate; third rate; fourth rate; bankruptcy/negative rate; per-hand win rate; per-hand deal-in rate; per-hand riichi rate; total games played; number of players at the given rank. The rows read, from top to bottom: newcomer/unranked; 9-kyuu through 1-kyuu; 1-dan/shodan; 2-dan through 10-dan; tenhoui.)

In every game, there has to be exactly one person placing first, exactly one placing second, exactly one placing third, and exactly one placing fourth. How is it possible for the distribution to not be even? One thing to note is that Tenhou prunes accounts for inactivity, and it’s plausible that people who lose a lot don’t play anymore, so the average placement of the accounts that remain is improved. Another possible explanation is that once we look at the mid/higher dan ranks, there are more people at lower ranks than there are people at higher ranks (the player count peaks at 2-dan), so on average you’re usually playing with players with a (slightly) lower rank than yourself. Rank correlates with skill level, so naturally you’d do better when playing against lower-rank players.

(The rooms are sorta gated by ranks, but it’s not a “strict” gate: there are usually two rooms that players can choose to play in. Up to 1-kyuu it’s only ippan; up to 4-dan R1800 it’s ippan+joukyuu; up to 7-dan R2000 it’s joukyuu+tokujou; beyond that it’s tokujou+houou. Access to the houou room also requires a paid subscription, which further weeds out casuals.)

Taking the slightly uneven placement stats into account, the steady-state ranks also change slightly, but not to an extent that my not-very-quantitative analysis will reveal. (More precisely, we can determine the stationary distribution of the rank and then take the time-average of that, but that requires doing a bunch of ~calculations~ and I can’t be arsed.) We also need to consider that players are somewhat incentivised to play in the better room that they can play in (if they have two rooms to choose from), since the last-place penalty is the same for either room but the better room has better first/second-place bonuses; but if they’re playing in a room filled with players of much better skill level (e.g. a new 1-kyuu player playing in joukyuu) they’ll also lose more. tl;dr it’s complicated


The second ranking system is the “rate”/”rating”, the R value you see next to your kyuu/dan rank. This is somewhat like the Elo rating system used in chess and other multiplayer games, but adjusted for the fact that mahjong is a four-player game and Tenhou’s version also uses a simpler formula.

[screenshot: 4-dan R2008]

(totally not flexing here, nope (actually my rate has since gone down since I started writing this post, rip (actually it has gone down even more since I wrote this parenthetical note, very rip)))

The rate starts at 1500, and there’s a bonus for placing first/second and a penalty for placing third/fourth, as well as a bonus for playing against better players and a penalty for playing against worse players (as measured by their rates).

The change in rate (the… rate of change of rate (sorry)) decreases as the number of games played increases: the Δrate has a multiplier that starts at 1.0 for new accounts, reducing gradually and linearly to 0.2 after 400 games, staying at 0.2 thereafter. Accounts that have many games logged will thus rarely experience large rate fluctuations, while newer accounts (with less than 300 games) can have relatively large rate fluctuations in the short term. The actual formula (which is included in Tenhou’s manual, which is in Japanese) is:

\displaystyle  \text{multiplier}=\max(1-0.002\times(\text{number of games}),0.2)\\  \text{bonus}=20\times(2.5-\text{placement})\\  =\begin{cases}+30&\text{for first}\\+10&\text{for second}\\-10&\text{for third}\\-30&\text{for fourth}\end{cases}\\  \text{adjustment}=(\max(1500,\text{table average rate})-\text{player's rate})/40\\  \Delta\text{rate}=\text{multiplier}\times(\text{bonus}+\text{adjustment})

In the limit, the sum of Δrate across all four players of a game will be zero. (This holds if all players have the same multiplier and the average rate is at least 1500.) Again, while it might seem that this means that it’s impossible to gain rate on average once you’re highly-ranked and playing with other skilled high-rank high-rate players, I’d guess that the actual process by which really good players gain rate is by indirectly siphoning it from weaker players, for similar reasons as mentioned for kyuu/dan rank.

The Flash client used to show the rates of all the players when watching replays; the HTML client shows it only for players who are at least R1800. (I don’t know if the premium client shows rates in replays. I also don’t know if the Flash client still does this, because who the hell uses Flash in 2019?)

We can do a bit of algebra to determine the “expected” placement from the difference in rate. Rather than considering the table average (which is affected by your own rate), it’s more useful to compare your rate against the other players’ average rate; the difference against others’ average will be 4/3 of the difference against the table average. Assuming the rates accurately reflect the players’ skill levels (i.e. they’ve played enough games against comparable players for their rate to stabilise), being r rate better than the others means that your average placement should be 2.5-3r/3200. For example, at R1800 you’re around 150 rating points better than typical joukyuu players at R1650, so your average placement should be 2.36. (I don’t know what the actual average rate is for joukyuu players, but that’s roughly where I used to be.)

There is one major caveat to trying to use the rating system to compare players of very disparate skill levels, however. As mentioned above, the rooms are gated by rank and rate, so it’s uncommon for players to be playing against people with much higher or much lower rates (as in a difference of 300 or more) and we shouldn’t expect the formula to be calibrated for such drastic differences. The rate update formula uses a linear correspondence between rate difference and expected placement, which makes sense for small differences (every differentiable function looks locally linear, which is pretty much what it means for a function to be differentiable anyway), but there may be higher-order nonlinear effects that come into play with larger differences. The obvious thing to do is to look at the limiting behaviour: it’s mathematically impossible to get an average placement better than 1.00 or worse than 4.00, so with a rate difference of at least 1600, the formula no longer makes sense. (Is 1600 difference possible? I think I’ve seen people with R9xx, and the best players are around R2200, which makes for a difference of “only” 1200-1300. But even a gap of 1200 is unrealistically large.)

For example, Elo for chess makes use of a logistic curve. (Note that chess is a two-player game and is scored by points: a win is +1, a draw is +1/2, and a loss is +0.) A difference in r of Elo rating corresponds to an expected score of \frac1{1+1.00577^{-r}}=\frac12+\frac12\tanh(0.00288r). Ignoring the fact that chess has draws and that draws aren’t uncommon in games by good players, a “perfect” player who always wins can have unbounded Elo growth. For small Elo differences (less than 150, say), the expected score is still approximately linear \approx\frac12+0.00144r, but unlike Tenhou’s rate, this formula doesn’t break down in the limit of large Elo differences—having an infinitely better Elo doesn’t mean that your opponent will lose ∞% of the time (which is good, because that’s impossible).

One important difference between chess and mahjong is that chess is an essentially deterministic game, while mahjong is a game of skill and chance. In riichi mahjong, even good players can get screwed over by bad luck every so often. As long as you’re not playing against complete idiots, roughly one in every ten games will have you end in fourth place for pretty much no reason other than the RNG hating you. (But you don’t get to complain about this, because for the exact same reason, as long as you don’t play like a complete idiot, roughly the same amount of your wins can also be attributed to RNG.) I’m actually not entirely sure whether Elo-like rating systems should be more vs. less applicable for games involving chance; Elo was originally designed for chess, but that shouldn’t automatically mean that it’s more suited for deterministic games than luck-based games. After all, the rating update formula essentially treats match-ups as being probabilistic, which naïvely doesn’t make too much sense in a deterministic game. The variance in a luck-based game functions as dither (ah! something relevant to the rest of the blog!), and while it makes the result of individual matches have little meaning, it also increases the accuracy of average rankings over large numbers of matches. You could imagine a deterministic game boiling down to each player having an inherent “ability” parameter, and the player with a higher ability parameter would always win, making Elo unusable.

But of course while the rules of chess allow for completely deterministic play with a completely deterministic outcome, this isn’t how actual people play. Chess isn’t a solved game, and there are many openings (with their own continuations) that are not clearly advantageous for either player. The number of possible game states grows exponentially (at least until it reaches endgame), so it’s not possible for humans (or even computers) to meaningfully memorise a complete set of responses to what opponents do, and players end up relying on heuristics that can be affected by their current mental state (which isn’t deterministic!). The possibility of blunders also contributes some randomness.

That was kind of a long digression, but what I was trying to lead into was that if we assume Tenhou’s rating system makes sense for larger rate differences, then… I forgot what I was going to write in the rest of this sentence, because I wrote most of this up in July and it’s been two months since. I might write some more ~words~ on the topic of Elo-like rating systems at a later time, but for now I kinda just want to get this post out and forget about it until a few more months later.

Some notes about stable half-pel filters

These two blog posts by Casey Muratori on “stable” half-pel filters showed up on Hacker News recently: [1] [2].

The idea is that in a video format, interpolation can be used to improve motion vector estimation. Without interpolation, it’s impossible to efficiently code objects moving at non-integer numbers of pixels per frame. (And speaking of which, just because the screen is discretised into pixels doesn’t mean that the “position” of an object has to be similarly discretised.) On the other hand, it’s often not useful to have too much precision in specifying the motion vectors, because precision doesn’t come for free. The more precise the MVs are, the more bits we’ll need to convey them. Common video formats usually have half-pel, quarter-pel, and sometimes eighth-pel interpolation filters. (In H.264, the quarter-pel filter is computed from the half-pel filter. HEVC has separately-computed half-pel and quarter-pel filters. Neither H.264 nor HEVC have eighth-pel filters for luma.) I’m not going to go too much into the background here, because (i) you should already know this and (ii) even if you don’t, you can just read the linked blog posts above.

The key thing you need to know is that interpolating very small shifts to high precision is easy (because this is a continuous function (under reasonable assumptions!), epsilon delta blah blah blah), and in the opposite direction, the largest possible shift is exactly half of a sample. (Shifting by, say, 0.9 of a sample is equivalent to shifting by one whole sample (exact; no rounding errors or blurring or whatever), then shifting 0.1 of a sample back. That’s why half of a sample is the maximum possible shift.) So the worst-case behaviour can be expected to come from half-pel filters, while the 1/4 and 3/4 filters are relatively well-behaved.

An interpolation filter can be analysed in the spatial domain, i.e. looking at its coefficients. This normally isn’t very useful, but if we’re designing a video format, we kind of need to know how large the intermediate/output values can grow compared to the inputs. A basic triangle (“linear”, “bilinear”) filter has coefficients (1/2, 1/2). Both positive values, so it’ll never produce any undershoot/overshoot. What happens if it’s applied multiple times? Imagine treating it like a probability distribution; convolve it multiple times and we’ll get a binomial distribution, which is approximately normal. (This is from the central limit theorem.) So that behaves like a Gaussian blur in the limit, eventually blurring everything into a uniform patch.

The central limit theorem applies not just to (1/2, 1/2), but to any finite kernel that’s nonnegative (and hence can be treated as a probability distribution). No matter how we arrange our coefficients, we cannot avoid blurring in the limit if we stick to nonnegative coefficients. (There are infinite-support kernels that don’t tend to a Gaussian in the limit, but those must tend to distributions that are “blurrier” than a Gaussian.) This is about as far as we can get with a purely spatial-domain analysis.

Rather than a spatial-domain analysis, a frequency-domain analysis will be much more useful. This is equivalent to eigenvalue/eigenvector analysis—the eigenvectors of linear shift-invariant filters are just the complex exponentials, and a Fourier transform is just a change of basis to the complex exponentials. In general, we’ll get complex numbers all over the place with a Fourier transform, but if we restrict our focus to symmetric half-pel kernels, the imaginary parts all cancel out and we’re left with a sum of cosine functions.

Blah blah blah, enough with words, let’s draw some graphs. This is the frequency response (discrete-time Fourier transform, DTFT) of a (1/2, 1/2) kernel, which is just cos(πx). (Or, we’ll just write it as (1, 1) and leave the normalisation implicit.) The x axis is a normalised frequency, where 1 is the sampling rate and 0.5 is the Nyquist limit.

[graph: (1, 1) frequency response]

Repeatedly applying this filter (in the spatial domain) corresponds to taking a power of this frequency response. The frequency response has absolute value strictly less than 1 at every frequency other than 0, so it converges to zero at every non-zero frequency. (Zero frequency, or “DC”, is the average value of the samples.) This is the frequency response of (1, 1)10.

[graph: (1, 1)^10 frequency response]

And of (1, 1)100.

[graph: (1, 1)^100 frequency response]

We can also look at (1, 0, 0, 1), and similar kernels with more zeros inserted. The DTFTs of these have formulae cos(nπx) for odd n. These form a basis for the finite symmetric even-length kernels. The below animation cycles through (1,0,0,1), (1,0,0,0,0,1), (1,0,0,0,0,0,0,1), and (1,0,0,0,0,0,0,0,0,1). Note that the vertical axis includes negative values for these plots.

[graphs of (1,0,0,1), … , (1,0,0,0,0,0,0,0,0,1)]

By combining these in varying amounts, we can approximate any desired (symmetric) frequency response arbitrarily closely… as long as it’s continuously differentiable. This is a pretty strong condition, and in practice (in particular, in this very scenario of designing a half-pel filter) we won’t be able to satisfy continuous differentiability over the whole frequency range, but if the function is at least piecewise continuously differentiable, we get uniform convergence away from the (finitely many) discontinuities.

Getting back to trying to design a half-pel filter, what exactly are we looking for in the frequency response? If (the absolute value of) the frequency response exceeds 1 anywhere, it’ll explode to infinity as we apply the filter repeatedly. On the other hand, for the frequencies where the frequency response is less than 1, that goes to zero. For example, consider the filter used in H.264: (1, −5, 20, 20, −5, 1).

The filter itself:

10 applications:

40 applications (note the scale):

The frequency response of the original filter exceeds 1 in the low frequencies, and it does indeed explode to infinity in that region. In the high frequencies, the frequency response is less than one, and indeed that goes to zero.

If we want a filter that preserves the original image, the ideal would be having a completely flat frequency response, equal to 1 over the interval [−1/2, 1/2]. This is not possible, even if we allow for infinite filters. Consider an alternating signal […, 0, 1, 0, 1, 0, 1, …]. Any reasonable notion of a half-sample shift will immediately blur this to a constant signal […, 1/2, 1/2, 1/2, …] in one step, so doing two half-sample shifts will not recover the original signal. Or, if we look at the frequency domain, the cosine functions we’re using as our basis are always zero at ±1/2, so obviously we can’t get anything but 0 at the endpoints.

We can ask for the frequency response to be equal to 1 over the open interval (−1/2, 1/2), and 0 at the endpoints. That gives us the sinc filter, which has infinitely many nonzero coefficients. Let sinc(x) = sin(πx)/(πx).

\displaystyle(\cdots,\mathrm{sinc}(-5/2),\mathrm{sinc}(-3/2),\mathrm{sinc}(-1/2),\mathrm{sinc}(1/2),\mathrm{sinc}(3/2),\mathrm{sinc}(5/2),\cdots)\\  {=\frac2\pi\left(\cdots,+\frac19,-\frac17,+\frac15,-\frac13,+1,+1,-\frac13,+\frac15,-\frac17,+\frac19,\cdots\right)}

This can’t really be used in practice because of the whole “infinitely many coefficients” thing. The next best thing is to multiply this by a window function; the wider the window, the closer this will be to the true sinc filter. There are many different choices of windows, but one of the most common choices is to use a differently scaled sinc function as the window; this is the Lanczos filter. (Note that while the sinc filter by itself is already normalised to unit sum, this is not the case for a windowed sinc.) Here are plots of the frequency responses of 6-tap Lanczos and 8-tap Lanczos, and just for fun, a 20-tap Lanczos. (Technically, these plots aren’t for the frequency response of the Lanczos filter itself, but for the half-pel filter you get by sampling the Lanczos filter and normalising.)



Observe the slight bump right before the frequency response falls off; this is related to the Gibbs phenomenon. As the window is widened, the bumps move towards the endpoints while becoming thinner, but more importantly, the bumps never get shorter. This means that however many taps are used for Lanczos, it will always explode to infinity at the same rate. This is a fundamental property of Lanczos, but it’s not a fundamental property of windowed sincs in general. By choosing another window (specifically, one with nonnegative Fourier transform), this can be avoided. For example, consider the triangular kernel. The following animation shows the frequency response of a triangle-windowed sinc, as the number of taps increases from 2 to 20.

The frequency response never exceeds 1, so this never explodes to infinity. Just as the triangle window may be obtained by convolving two boxes, we can also convolve two parabolas to get a new window function (1-|x|)^3(1+3|x|+|x|^2) (with |x|\le1). (This window doesn’t seem to have a common name.) This is more nicely-behaved than the triangle window, since it’s twice continuously differentiable everywhere (whereas the triangle window is merely continuous); the graphs also look less “wavy”.


Now, getting back to the blog posts linked right at the top of this post. What would being a “stable” filter mean? In the crudest sense, the frequency response should never blow up no matter how many times the filter is applied. (There are other notions of “stability” used in signal processing and other areas of applied mathematics, but we’ll stick to this specific one for this blog post.) This is equivalent to requiring (the absolute value of) the frequency response to be at most 1 everywhere, as mentioned above. But is it possible to have a (finite) filter that preserves some some semblance of the input image as the number of filter applications tends to infinity? No, if (i) we stick to symmetric even-length kernels and (ii) we’re working with infinite precision (i.e. the mathematical reals, rather than fixed-point or floating-point numbers).

One way to look at this is to consider what it means to “preserve” the input image. We already know we can’t ask for the whole range of frequencies [−1/2, 1/2] to be exactly preserved; we can’t even have (−1/2, 1/2) with a finite filter either. But can we preserve some smaller section of frequencies, e.g. [−1/4, 1/4]? The answer to that is still no; if there were some finite filter with a completely flat frequency response around any frequency (not necessarily the zero frequency), then since the frequency response is a (complex-)analytic function, we can apply analytic continuation to conclude that it’s flat everywhere. But since the frequency response is 0 at the half-integers, that means that the filter is the zero filter, and hence preserves no frequency, a contradiction.

There are two ways around this. We can drop the first condition and start using asymmetric kernels, but even then the only finite filters that have completely flat frequency responses are the translations (by an integer number of samples), for the same reason as above. Alternatively, we can drop the second condition, and allow for approximately preserved frequencies. This is much easier to satisfy; if we know in advance how much precision we’re working with, we can just design our filters accordingly so that the deviation from a flat response (over a specified frequency range) is small enough to be hidden by rounding error.

Here’s the frequency response of the 6-tap filter from the second blog post, (0.027617, −0.130815, 0.603198, 0.603198, −0.130815, 0.027617):

The frequency-domain overshoot here is much smaller than with the original 6-tap Lanczos, and it’s approximately flat (to less than 1% error) over [−0.27, 0.27]. It wouldn’t be stable with infinite precision, but if we’re working with only 8-bit images, that’s good enough.


But is stability even an important criterion for choosing an interpolation filter in a video format? Apparently not—H.264 and HEVC both use filters with significant frequency-domain overshoot.

If we place stability as our top priority, that forces the filters to have a very specific shape; the frequency response must look something like the no-overshoot windowed sinc filters above. It’s strictly less than 1 over the whole range of frequencies, so it loses energy. Losing energy leads to blur, and blur is bad from a psychovisual point of view.

Also, the interpolation filters in video formats aren’t applied successively with nothing else in between; after motion compensation is done, the residual still needs to be sent. Taking the residual coded on each frame into account, this prevents the error from exploding exponentially. And since multiple reference frames can be used, it doesn’t necessarily have to always predict a 1/2-pixel shift from the previous frame; the encoder could just as well use a 1-pixel shift (no interpolation) from two frames ago.


Bonus side note: If you look carefully at all the graphs in this post, you might notice that the near-horizontal and near-vertical sections all look like they’re drawn with a dashed style. That’s because the graphing software I used (FooPlot) uses HTML5 canvas, and Firefox doesn’t apply gamma correction. I could have fixed the images separately, but :effort:.

PLEASE ASK FOR ADVICE IF YOU’RE NEW TO ENCODING

Hi.

Guess who just watched a video that was badly encoded?

That’s right; it’s me.

This blog has like zero readership these days (did you know that WordPress.com tells you site stats? revolutionary, I know) so I don’t know who exactly I’m trying to reach out to with this post. I guess I’m just venting on a more public platform than my locked Twitter account? (Well, “public” in the literal sense, but clearly my Twitter account has an order of magnitude more visibility despite being locked. On the other hand, I’m already venting very frequently on Twitter and for the most part I think I’m preaching to the choir.)

BUT ANYWAY MY POINT IS: I want to watch properly encoded videos. I’ve always maintained that learning the basics of encoding is not hard. You just need to spend time to actually learn it and then care about producing a good result. I’m not going to complain about relatively obscure shit like rainbowing in analogue transfers or rainbow banding in just about any White Fox series; those are genuinely difficult to fix and if people choose to leave those alone, fine. That’s what I’d do too. I absolutely am going to complain if you don’t properly deinterlace sources that should be deinterlaced, or if you completely munge IVTC and end up blending frames, or if you somehow resize frames to the wrong aspect ratio, or if you make other mistakes along those lines. Ask experienced encoders for help if you need it. If you aren’t sure whether you need help, you do.

(Gigantic caveat: “experience” doesn’t necessarily correlate with having encoded a lot. This post may or may not have been spurred by a raw encoder who has been around for years and yet still makes rookie mistakes. Basically, ask encoders in established fansub groups. For the same reason that random raw encoders can’t be trusted, you can’t trust a fansub group that consists of the same two people doing all of the shows they’ve done with no fresh blood ever. Maybe those two people are very selective with who they work with, or maybe (and this is more likely) those two people are so bad at fansubbing that no one else wants to associate with them and learning from them is perhaps not the best idea. I kinda just want to say “use your own judgment” here, but a failure to use personal judgment is the whole point of this post, so lol.)

some shitty antialiasing filter idk

function progressivefix(clip c, clip "deint")
{
c
deint = default(deint, nnedi3(field=3))
sep = separaterows(2)
top = sep.selecteven()
bot = sep.selectodd()
topb = deint.separaterows(2).selectevery(4, 2)
botb = deint.separaterows(2).selectevery(4, 1)
topa = bot.mt_convolution("1", "1 1 0", u=3, v=3)
bota = top.mt_convolution("1", "0 1 1", u=3, v=3)
topc = raveragew(top, 1, topa, -1, topb, 1)
botc = raveragew(bot, 1, bota, -1, botb, 1)
topfixed = median3(top, topb, topc)
botfixed = median3(bot, botb, botc)
interleave(topfixed, botfixed).weaverows(2)
}

(The median3 filter is included in mpeg2stinx.)

I stole some filter someone posted on Doom9 a couple of years ago, and made it more general (and thus also more prone to breaking if you don’t know what you’re doing). Sometimes you have badly deinterlaced footage and the footage has undergone some additional processing; for example, in the sample on the linked Doom9 thread, said additional processing would be adding hardsubs.

Being “badly deinterlaced” is, of course, not very well defined, because there are very many ways to deinterlace and most of them are bad. For instance, you could linear-resize the top fields to full height, so the top field in an output frame would look nice and sharp, while the bottom field would look like garbage. Or you could do that to the bottom fields. The Doom9 version of the filter only covers the case where the top fields are good, but essentially the same idea can be applied to content where it is not determined ahead of time which fields are good and which fields are bad. That’s this filter.

Note that while you can use pretty much any deinterlacer in place of the default nnedi3, it probably isn’t worth it. Using something like QTGMC ironically gave me more aliasing in the final output while being much slower, although this can vary between sources. (The ansatz in the filter is that each row in the bad field is the average of the rows above and below, but if the footage was originally deinterlaced with another filter, this assumption breaks down. This usually doesn’t have much of a visible impact because nnedi3 still has some residual aliasing, but if you used a “perfect” deinterlacer, the inaccuracy would reintroduce aliasing.)

Errata

Quick round-up of stuff I said on this blog (and maybe elsewhere) that I later found to be wrong.

Four years ago, I wrote about some weird discrete Gaussian coefficients that kept showing up in all sorts of code/papers/etc. Those coefficients showed up again in a paper I was reading (or maybe re-reading; I don’t remember), so I did a little bit of digging around to see how they might’ve been derived.

These are the common coefficients:
\displaystyle\frac1{273}\begin{pmatrix}1&4&7&4&1\\4&16&26&16&4\\7&26&41&26&7\\4&16&26&16&4\\1&4&7&4&1\end{pmatrix}

This is what you get if you multiply each entry of the sampled Gaussian kernel (decimal values are printed in the linked blog post) by 273:
\displaystyle\begin{pmatrix}1&4&6&4&1\\4&16&27&16&4\\6&27&44&27&6\\4&16&27&16&4\\1&4&6&4&1\end{pmatrix}

The central coefficient is different, and this has 6 and 27 instead of 7 and 26. Also, note that the accumulated rounding error causes this kernel to actually sum up to 276 rather than 273. Since the sampled Gaussian has a lower variance (0.92) than we want (1), we can increase the variance by reducing the weight of the central coefficient to compensate. So we subtract 3 from the central value, and we get this:
\displaystyle\begin{pmatrix}1&4&6&4&1\\4&16&27&16&4\\6&27&41&27&6\\4&16&27&16&4\\1&4&6&4&1\end{pmatrix}

The variance of this kernel is 262/273, which is much closer to 1 than the 125/91 value of the weird kernel… or is it? I was kinda thinking out loud on that blue bird website, suggesting that this was a stupid digit transposition error (6, 27 to 7, 26), but after a while I realised that there must’ve been a calculation error somewhere. Turns out I mis-calculated the variance of the weird kernel four years ago, and its variance is actually 268/273, which is actually better than the kernel we got by rounding and adjusting the central coefficient.

But, you know, point still holds about the kernel being weird and I don’t know why people still use it. You could just use binomial coefficients, which (i) are dyadic and (ii) give a kernel with variance exactly 1 as opposed to merely being close to 1. Also, why just shift the weights to (7, 26) to make the variance 268/273, when you can shift them to (8, 25) to get the variance to be 274/273, which is even closer to 1? Weird kernel is still weird, but a bit less weird than I’d initially thought it was.

(The possibility of the kernel being a result of digit transposition still stands, and the digit transposition causing the variance to be closer to 1 could’ve been purely accidental.)


In 2015, I mentioned using a Lehmer mean to merge different video sources. (Not directly using the Lehmer mean, but using the Lehmer mean on high-passed copies of the sources and then adding that back to a low-passed copy of one of the sources.)

The erroneous part there was the claim that the Lehmer mean \frac{x^p+y^p}{x^{p-1}+y^{p-1}} is infinitely differentiable everywhere, which is not true. With p=3, it is continuous but not differentiable at (0, 0), although it is indeed infinitely differentiable everywhere else. The power mean, in contrast, fails to be differentiable on infinitely many points.

Why don’t people sub old series?

This is a point I briefly covered in a post I wrote a year and a half ago.

A lot of people seem to think it has something to do with e-peen. That’s not technically wrong—some of us do fansub for the e-peen—but it also misses the really important fact I brought up before that finding staff to do old shows is pretty difficult.

Every time an /a/non asks for old shows to be subbed, my instinctive responses would be: If you think it’s so easy, why don’t you sub it? If you don’t think it’s so easy, why do you expect us to do it for free?

Since this is an encoding blog (wait, is it supposed to be one? I’m not sure), I’d also like to point out that most old anime releases had encoding issues that are nontrivial to fix. Good luck finding someone willing to spend hours per episode fixing something that will be watched by maybe twenty people?

Adventures in deconvolution

Note (2017-03-20): the majority of this post was written on 19-21 February 2014. I no longer remember where I was going with this, and obviously that means I don’t remember what else I was going to write for this post. Have fun.

Sharpening filters are usually nonlinear, but blurring filters are usually linear. So deconvolution shall be used in the context of resharpening a blurred image. The term “filter” should also be assumed to refer exclusively to discrete filters.

Tl;dr: more of me writing about technical stuff I don’t know very well. Things may be hilariously inaccurate.

If you look at deconvolution in the frequency domain, it amounts to taking the reciprocal of the DTFT. Then doing an inverse transform provides a means to deconvolve using another convolution. Of course if you look at the Wikipedia article on deconvolution it’s not as simple as that. In addition, if we had the appropriate tools, an IIR filter would be more suitable. For instance, exact deconvolution of an (a,b,a) kernel (like Avisynth’s Blur, assuming that 2a+b=1) can be done with a causal/anticausal pair of filters with one pole each, provided that b>1/2. (Presumably this can be done with hqdn3d with negative values because it uses one-pole IIR filters, but I’ve never tried this. I don’t know of other Avisynth filters that intentionally provide IIR filters.)

On the other hand, with b≤1/2, the DTFT has zeros, so if you try to take the reciprocal of that you end up dividing by zero. You’re not allowed to do that, so don’t. (A similar caveat is that even if b is greater than but close to 1/2, you’re still dividing by a small number, which is also numerically unstable. Likewise for inverting Gaussian blurs.) What we can do is to try to approximate the reciprocal of the DTFT away from those zeros/small values.

Wiener deconvolution is one such approach (through minimising mean square error). It’s linear if you already have estimates on the source/noise power spectrum, but if you need to estimate those values from your input, it’s nonlinear. More importantly, this is inconvenient to implement within Avisynth because we can’t just take DFTs of our source.

An alternative approach is regularisation, which is actually a term encompassing a broad range of techniques, and in the context of deconvolution includes the aforementioned Wiener deconvolution. This is also easier to deal with in Avisynth (as long as we don’t insist on any particular method of regularisation) and since this is an encoding blog and not a DSP blog, we’re going to focus on that.

Regularisation is not so important if the convolution kernel of interest is exactly known and its inverse converges to zero quickly enough, but in practice the convolution isn’t exact (due to rounding errors), we don’t usually know the convolution kernel exactly either and sometimes the convolution kernel doesn’t have a convergent inverse (for example, if it has zeros in its DTFT). Regularisation, broadly defined, is any method by which we can mitigate the effects of these sources of inexactness in deconvolution.

A few months ago mirkosp posted a sample with some random vertical blurring in the middle of a scene. (The first link points to a reupload on MediaFire because posting links to others’ Dropbox accounts is probably not a good idea.)

<mirkosp> https://dl.dropboxusercontent.com/u/[redacted]/vshift.ts prunedtree think there could be a way to fix the weird vertical shift that starts at around halfway through this sample?
<mirkosp> i solved it with freezeframe in this case
<mirkosp> but i’ve seen it happen elsewhere and I had to just sort of live with it
<mirkosp> this is a helpful sample because the same exact frames are fine before the shift kicks in
<mirkosp> frame 125 is fine, 126 fucks up

My gut feel told me the vertical blurring was probably done with something like a (1/2,0,…,0,1/2) kernel, but neither (1/2,0,1/2) nor (1/2,0,0,0,1/2) looked quite right. The former blurred too much, the latter blurred too little, and while convolving with (1/2,0,0,1/2) seems to do the trick, it also introduces a half-pixel shift. However, this half-pixel shift is not really all that big of a deal since we can always use a resampler to get rid of it later on.

Side note: alternatively, we can adjust shift the kernel itself by half a pixel. Using sinc interpolation with binomial coefficients as a window, I got (27,-440,5940,16632,-11550,16632,5940,-440,27)/32768. (One nice thing about using binomial coefficients as a window is that the normalisation factors tend to end up as powers of two. Another nice thing is that it’s closely related to polynomial interpolation and Taylor series, but I don’t have a formal proof of this.) These shifted coefficients are fairly useless though, since there’s a simpler approach that also avoids dealing with the two distinct zeros in the DTFT. I plotted the frequency responses of both (1/2,0,0,1/2) and the aforementioned approximate shifted version (blue and green resp.; the frequencies are normalised so that ±0.5 is Nyquist frequency). Although they match up pretty closely for the lower frequencies, the difference gets progressively larger close to Nyquist. The two distinct zeros are at Nyquist and one-third Nyquist. (Note also that that the DTFT of a discrete signal is real iff it’s symmetric around zero, which is true in our case. The graphing program I use doesn’t support complex numbers so thank goodness I don’t have to hack up support using loads of trigonometric functions.)

The first insight I had was that this kernel only affected rows that were the same modulo 3, so we can just SeparateRows(3), do our deconvolution magic, WeaveRows(3), then fix the 1.5-pixel shift. (This is probably not ideal, but it’s simpler.) By looking at rows in groups of three, our convolution kernel is now just (1/2,1/2), which happens to be something I’ve previously covered in this blog, albeit in the context of temporal filtering rather than spatial filtering. As I was previously concerned with convolution in the time dimension, where ghosting from future frames is much more jarring than ghosting from past frames, that post focused on asymmetric filters. There’s no such limitation to bother with here.

Side note: we could also factor (1/2,0,0,1/2) as (1/2,1/2)∗(1,-1,1) then deconvolve those separately, but now instead of having one filter with real zeros in its DTFT, we have to deal with two filters with real zeros in their DTFTs. This doesn’t exactly help. If we try to use a Maclaurin series expansion on the reciprocal of the DTFT of (1,-1,1) or (1/2,0,0,1/2), our radius of convergence would be guaranteed to be less than one-third Nyquist because of the poles there. (I’m fudging a few things here. We should really be looking at the Laplace transform rather than DTFT, and also we can’t quite directly use Maclaurin series unless we perform a change of variables first. Maclaurin/Taylor series approaches generally also tend to be suboptimal in numerical analysis.)

Consider a doubly infinite sequence (…,1,-1,1,-1,1,1,-1,1,-1,1,…) which is symmetric around the (1,1) subsequence and alternates in sign everywhere else. Convolving this with (1/2,1/2) gives exactly a unit impulse (and zero everywhere else), so this can be considered to be an inverse of (1/2,1/2). It is in fact the only symmetric inverse; all other inverses are asymmetric. This inverse kernel doesn’t converge, but what we can do is to window it (which is also mentioned in the earlier post). I don’t have much signal processing knowledge so we’ll just have to resort to experimentation.

A rectangular window is extremely badly behaved; convolving it with (1/2,1/2) leads to a kernel of the form (±1/2,0,0,…,1,…,0,0,±1/2), the DTFT of which is just a (co)sine-squared curve, which has loads of distinct zeros. A triangular window is better, but still has plenty of oscillation in the frequency domain and the actual filtered image ends up with a lot of ringing. Gaussian and Gaussian-like windows (including higher-order B-spline windows and the aforementioned binomial coefficient windows) don’t have as much frequency-domain oscillation, but do have pretty significant overshoot.

What I suggested to mirkosp was a (1,-2,3,-4,5,-6,7,7,-6,5,-4,3,-2,1) kernel, which worked sorta fine, but could’ve been better yet—one simple improvement is to decrease the absolute value of every coefficient by 0.5. Because I like procrastinating actually important things I should be doing (like encoding Symphogear), I continued experimenting with the source.

One of the random thoughts that came to mind was to multiply a triangular window with an exponential window; I’ve previously tried this in deblending, which worked better than a pure exponential window or triangular window (though still terrible in general), so maybe it works better here? And it does: reduced frequency-domain oscillation, no overshoot, and reduced ringing too.

Our “regularisation” here could be as simple as making an edge mask to combine the deconvolved parts with the original, and then we’re done. Or actually, and I left this out earlier, the source has some annoying borders so getting rid of them (using BalanceBorders or the like) first is important. The logo is also affected by the deconvolution (since it’s not blurred like the rest of the frame), so delogoing should also be done prior.

Now, with all the above :blogging: written, a new approach to this deconvolution came to mind. If instead of using one symmetric kernel, we use two asymmetric kernels, and then combine the two together? I’m retard tier at filter design and the ad hoc windowing process above is rather questionable so let’s try looking for kernels that satisfy specific properties. For example, for an n-term kernel, after convolving it with (1/2,1/2), we can insist that it has unit sum and that its first, second, …, (n-1)th moments are zero. n variables, n equations.

For two terms these requirements give (3,-1)/2, for three terms (7,-4,1)/4, for four terms (15,-11,5,-1)/8, and these just so happen to be closely related to binomial coefficients. In fact, these coefficients turn up in A110814, although the signs are different every other row.

The idea is that with our asymmetric filter, we have ringing artifacts that only go upwards, so by applying the same filter upside down, we’d have artifacts going downwards. If we take the median of the upwards-filtered image, downwards-filtered image and the unfiltered image, we should end up with something pretty decent, without even explicitly resorting to using an edge mask! (Though an edge mask applied afterwards cleans up more residual ringing.) Another method of merging the up and down images is to choose the pixel that minimises the difference with the original, sort of like in MinBlur. (That said, if you do implement exactly like in MinBlur, this ends up being identical to using a median. In other words, I just unintentionally stumbled upon an optimisation for MinBlur.)

As symmetric even-length filters must have a zero in the DTFT at Nyquist frequency, there’s the dilemma of trying to approximate the reciprocal of small numbers (at frequencies near Nyquist) with other small numbers (because the DTFT of the “inverse” kernel also has a zero at Nyquist); using asymmetric filters would avoid this. The downside is that we lack obvious guarantees on the phase, which we’ve conveniently ignored up until now. Symmetric filters are necessarily either exactly in phase or antiphase, but with asymmetric filters the DTFT is not a real function and in general the phase is nonlinear, which results in phase distortion.

Side note: for odd-length symmetric filters, I’m taking the centre sample to be sampled at t=0 (and the rest of the samples are at integers), while for even-length symmetric filters, the two centre samples are at t=±1/2 (and the rest of the samples are at half-integers). Symmetric filters under alternative conventions (such as setting the first nonzero sample to t=0) are not necessarily in phase/antiphase. For the asymmetric filters, I’m taking the first sample to be at t=0.

I needed to get some other graphing program that supported complex numbers so these are made with one different from the previous graph. Again, x-axis is frequency in cycles per pixel (i.e. 2π radians/pixel), but this time the y-axis is in radians. Why different units? Idklol. I plotted the phase responses of the triangle-windowed asymmetric filter as well as the filter derived above. The jump of π radians at Nyquist frequency is due to the simple zero of the (1/2,1/2) kernel. There’s a fifty percent chance that I got the sign convention wrong, but don’t mind that.

Enough :words:, time for pictures. The pictures have been preprocessed by BalanceBorders and a delogoing filter I originally hacked up for the Animelo encodes. Other than these two filters, chroma is untouched.

Bonus feature (logs from 2017-02-24):

<mirkosp> who wrote unshift? i’m pretty sure it was somebody here
<mirkosp> maybe torchlight but dunno
<torchlight> no idea what that is
<torchlight> wait
<CoffeeFlux> lol
<torchlight> I may or may not have written something like that
<mirkosp> a script that takes 1080p crossconverted from 480
<CoffeeFlux> fucking torch
<mirkosp> or 486 perhaps, but same deal
<torchlight> oh, that’s definitely not mine
<CoffeeFlux> inb4 it was our resident corpse
<mirkosp> it does some magic number convolution to make a sharp shift with lotsa artifacts
<mirkosp> and then combines the two shifted clips in some way to restore a sharp clip with less artefacts
<torchlight> er
<torchlight> now that does sound familiar
<torchlight> ????
<mirkosp> i slightly modded it for a safer median that has no ringing leftovers at the cost of some very slight sharpness loss in very specific details
<mirkosp> i wanted to share the script online because this is definitely useful stuff, but I realized I can’t find the script around
<mirkosp> not on doom9 nor on avs wiki
<torchlight> dither_resize16(width(),height()/2,src_top=4,kernelv=”impulse 255 -247 219 -163 93 -37 9 -1 0″,fv=-1) < are these the magic coefficients
<mirkosp> YES
<torchlight> yeah that’s mine lol

Saki live action series

This is a thing.

We’re subbing it.

Releases can be found at the usual place, but I’d honestly recommend waiting for the batch version because I bullshitted the translation for the first two episodes and now we have an actual translator to go over the scripts. While I’m at it, if someone wants to typeset this, contact me on Rizon or wherever. (Stallers need not apply.)

Episode 4 and the special will hopefully both be released within the week. (For real this time! Ep 4 just needs editing and QC.)

Staff:
Translation: Crunchyroll (1), me (1, 2), lae (3), bitmap (4, special)
Editing: lae (2-4, special)
Timing: me
Typesetting: \an8
Encoding: gradfun3
Batch TLC: bitmap (1-3)

LiSA TV

Over the past few months, I’ve been doing solo releases of the LiSA TV series, based on the Crunchyroll streams. Basically, some crew follow LiSA (the J-pop artist behind SAO OP, Fate/Zero OP1, etc.) around various places in Japan and sometimes elsewhere, and they do fun things.

I wanted to try out youtube-dl’s ripping functionality and CR had 1080p streams available even for free users; nobody had uploaded rips to NT, so I thought I would. (As of roughly last month, HD streams have been restricted to premium accounts, so I begged someone to lend me their premium account to rip ep 11.)

One thing led to another and I ended up editing/TLCing and timing the scripts. I didn’t bother conning a typesetter into doing this because there were a shitload of signs and the video was of quality too horrid to meaningfully typeset to. By “horrid” I mean that every single episode has been interlaced at some point, where ep 1 has residual combing and every later episode has been low-passed vertically with chroma ghosting.

Far as I can tell, it streams only on Crunchyroll and Wakanim. I checked Wakanim’s video quality when someone ripped the stream for me, but it was also too bad to meaningfully decide whether this or CR was less offensively awful. (In Wakanim’s stream, both luma and chroma have ghosting, which I’m not sure is an improvement, and it’s more annoying to rip too. And just to rub salt into the wound, it has French hardsubs.) I googled for a bit, but, given the show’s title, it is as difficult to look up as you’d expect. I did find an ANN article announcing that it was being streamed on CR, but we already knew that.

Also, man, are the Crunchyroll scripts for this series shoddy as heck. The translation is often very stilted, and there are bizarre mishearings where it’s clear that the translator is either lacking common sense, not trying very hard, or not even looking at the video. Almost none of the dialogue is scripted (I think?), so having a few mishearings is understandable, but the complete disregard for context in translation is baffling. Just in the last episode (#11) there was a mishearing of “甘えた” as “甘いな”, and TL-kun clearly never thought about whether “naïve” was a sensible translation in context.

The timing’s pretty iffy too. The translator leaves out parts of a sentence that can’t be heard clearly quite often (excusable since there’s no script), but the timer just goes full retard and times the next line into the untranslated bits. This happens a lot, and I think the timers just aren’t very experienced at timing partial translations. (I’m going to go ahead and assume there’s more than one timer because there’s no way a single timer can fail to learn how to time such scripts properly after ten episodes. CR can’t possibly be hiring timers that shitty, right?)

I’ve done some very conservative editing on the scripts and left some awkward translations untouched, but the lines I did change were definitely for the better. Apart from cosmetic changes like fixing typos, I also fixed every mistranslation I spotted (in both dialogue and typesetting) and rewrote all the probably-correct-but-gibberish-sounding lines. The timing has also been completely fixed.

Basically, if you’ve been watching it on CR, you should watch my release instead! It’s still terrible, but 50% less so! You can grab it on NT—just search for “LiSA TV”.

PS: While this show is listed as being published by Aniplex on CR’s website, I’ve been told that the translation is actually done on CR’s end rather than by Aniplex or Bang Zoom. Given the lazy translation and timing, though, I’m not sure if the difference matters!

Supersampling without upscaling

Public draft; post to be finished at a later date. Update (2017-03-20): This post is essentially abandoned, but given that I’ve already spent a fair amount of time writing it, I might as well just publish it.

(Note: actually an idea I messed with about four months ago but never bothered disclosing. Also, some of the terminology may differ from the standard usage a little.)

Loads of sharpening filters operate on a 3×3 window of pixels, because filters with small windows can usually be made very fast if you can use RemoveGrain for the heavy lifting. The drawback is that you have only eight neighbour pixels to work with, so strong nonlinear sharpening tends to introduce aliasing very quickly.

The classical solution to this problem is to upscale somewhere between 1.5× and 4×, apply the filter (possibly with a tweaked strength), and downscale back to the original resolution (or to some other user-specified res). This trick is so commonly used that you could look into just about any sharpening or dehaloing script and find a construct like this. It does work reasonably well if used properly, and scripts generally have sane defaults for supersampling.

However, large supersampling factors (say, 3× and above) are potentially undesirable for a couple of reasons. Firstly, it gets slower quadratically in the supersampling ratio. To put this in perspective, 3× supersampling is less than half the speed of 2× supersampling, which is a quarter the speed of not supersampling at all!

Secondly, the supersampling effectively puts a cap on the filtering strength (for some vague ill-defined notion of filter strength). Consider the extreme case of, say, 1000× supersampling. At this scale, every 3×3 window will look like a flat patch, and the filtering just can’t possibly do much of anything. (Technically, it’s possible to construct artificial inputs where applying a sinc filter will leave patches with arbitrarily large variation, but we don’t use sinc filters for resampling and we usually don’t deal with such pathological inputs anyway.)

Thirdly, some filters just don’t make much sense to be used with large supersampling factors. Say, if you have a filter that removes certain kinds of pixel-wide defects, then supersampling would make those defects much larger and possibly be missed by the original filter.

The first thing I tried was to apply different subpixel offsets to nine copies of the image, apply the original filter, weave the nine copies into a single (3w)×(3h) image, and then downscale back to w×h. The subpixel offsets used here are multiples of thirds of a pixel, so that the weaving itself doesn’t introduce aliasing. Another way of looking at this is that this is equivalent to upscaling 3×, applying a widened version of the original filter, then downscaling. Works, sort of, but has the same terrible speed as before.

We can modify the above procedure slightly; we apply different offsets to multiple copies, apply filtering, undo those offsets, then average all of the copies. In the case where the resampling kernel used for applying the subpixel offsets has the constant preservation property, then this is equivalent to the previous idea if the offsets form a regular grid. It is, however, somewhat less efficient and less accurate, since the pixels of the copies are blended together in two steps (undoing offsets then averaging) rather than just one (downscale).

A side note on “constant preservation”: roughly speaking, what we want from a resampling filter is that if you resample a solid colour, you get back a solid colour. This is the fifth point in the classic article on how to write a resampler by Avery Lee. Most of the commonly used resampling kernels do not preserve constant values exactly. Indeed, among the kernels used in AviSynth’s resizers, only three possess this property when upscaling by an integer factor: box, bilinear and bicubic. For kernels that do not satisfy this constraint, downscaling by an integer factor n will give different weights to samples depending on their coordinates modulo n. That said, these kernels do generally approximate constant preservation well enough for this to not be a significant concern; 6-tap Lanczos has error at most 3.5%, for example.

Getting back to the topic, with this modified procedure, we do not have to constrain ourselves to sampling on a grid at all! Supersampling on an axis-aligned grid comes with the drawback that many aliasing artifacts are related to the pixel boundaries being axis-aligned, and many of the offset copies have the same horizontal offset or the same vertical offset, which doesn’t help with the antialiasing. We do still want to sample on a grid, though, because the symmetry makes thinking about them much easier. So what do we do? We use a rotated grid!

Using rotated grids essentially gives us the benefit of sampling at n different horizontal offsets and n different vertical offsets with only n samples, rather than having to use n2 samples. Note that not every value of n corresponds to a meaningful rotated grid. Specifically, n must be greater than 1 and also the sum of two coprime squares for this to make sense. (If the squares have common divisor d2, then the number of distinct horizontal/vertical offsets is only n/d, rather than n.) The smallest examples are given in A008784: 2, 5, 10, 13, and so on.

For example, if we take n = 13 = 22 + 32, then we should sample with offsets (2i/13 mod 1, 3i/13 mod 1), which looks roughly like this:

[insert fancy graphics here]

It’s sort of possible to adapt this to values of n not satisfying the sum-of-two-coprime-squares criterion by adopting an n-queens-like layout. SmoothD2 uses something like this by default, controllable with a speed-quality tradeoff parameter.

As with (non-rotated) grid supersampling, we do quickly enter diminishing returns territory with rotated grid supersampling as the supersampling factor increases. It’s probably not meaningful to use n ≥ 10 because of the huge speed hit for what are likely to be negligible improvements over, say, 3× or 4× grid supersampling. This leaves n = 2 or 5, and n = 2 is also probably too small to be useful, so n = 5 is the only real choice.

Another side note: The sampling scheme given by n = 2 is also known as quincunx supersampling. The name stems from how, if you divide the image into pixel-sized cells, the five samples in the rotated grid contributing to each output sample form a quincunx. Note that the type of supersampling introduced in this post differs from the convention in graphics rendering; that convention skips the “undo offset” step and goes straight to taking a weighted average of the image at specified offsets. Not undoing the offset causes this type of supersampling AA to induce a small amount of blur, with the blurriness depending on the offsets and the weights used for the weighted average.

Another way of thinking of rotated grid supersampling is that it actually is equivalent to rotating and upsampling by a factor of √n, though we also have to rotate/scale how our filter samples to compensate. This allows us to compute the offset copies of the source image somewhat more efficiently. While the usual fast way of rotating an image uses three shears, here we also need to scale; it turns out that that (most) 2D transformations can be represented as a shear-scale-shear-scale chain, which saves one shearing over scaling and rotating-by-three-shears separately. (More precisely, this decomposition exists iff the transformation matrix is nonsingular and at least one of the two diagonal entries is nonzero.)

We adopt the convention that the transformation matrix T is given such that T(\mathbf{dst})=\mathbf{src}, as well as taking the positive y direction to be downwards. For a rotation by \theta\in[-\pi/4,\pi/4] clockwise and scaling by a factor of k, assuming that k\ge\cos\theta (necessarily true for our purposes, since we’re taking k=\sqrt n>1), we have the matrix decomposition as follows.

\displaystyle\frac1k\begin{pmatrix}\cos\theta&\sin\theta\\-\sin\theta&\cos\theta\end{pmatrix}=\begin{pmatrix}1&0\\-\tan\theta&\tfrac1k\sec\theta\end{pmatrix}\begin{pmatrix}\tfrac1k\cos\theta&\tfrac1k\sin\theta\\0&1\end{pmatrix}=\begin{pmatrix}1&\\&\tfrac1k\sec\theta\end{pmatrix}\begin{pmatrix}1&\\-k\sin\theta&1\end{pmatrix}\begin{pmatrix}\tfrac1k\cos\theta&\\&1\end{pmatrix}\begin{pmatrix}1&\tan\theta\\&1\end{pmatrix}

Without any optimisation, the per-sample complexity of computing n offset copies directly is proportional to 2(n−1) (note that the zero-offset copy is just the input and so we get it for free), whereas with the aforementioned shear-scale-shear-scale filter chain, this “drops” to (1+2√n(sec θ)+n). This actually fails to be an optimisation unless n≥10, but we’ve already established that using n≥10 is not so useful. The algorithm also becomes tremendously more complicated, having a whole bunch of edge cases that need to be properly dealt with, so this rotate-and-upscale algorithm is purely of academic interest.

What if we do away with assuming that our rotated grid must remain as a square grid? In particular, we can use a sampling scheme of the form (i/n mod 1, ki/n mod 1), where k and n are coprime. This would still have translational symmetry, but we lose the four-fold rotational symmetry except in a few special cases. If we look at

(I was going to write about almost-regular-triangular lattices here but then I lost the code I was using to churn out numbers and I can’t be bothered to rewrite it.)

Public draft; post to be finished at a later date.

Why don’t people re-sub old series?

Almost every anime series since about two years ago has had a simulcast, and of those that weren’t simulcast but had fansub releases, it was generally true that the only groups that bothered to pick them were those good enough to handle original translations and were competent overall. (There are some exceptions, like a certain group that still hasn’t managed to get friendly with aers.)

The situation was a bit more bleak before that. We’d have random releases by groups that (i) fail at encoding, (ii) fail at translating, (iii) fail at English, (iv) fail at timing, (v) fail at typesetting, and quite often (vi) all of the above. Timing and typesetting standards only really started to rise circa 2012 when unanimated wrote guides and effectively released them to the public, so bad timing is essentially a given in most releases before then. While I don’t think it’d be fair to judge old typesetting by today’s standards (what with vastly improved tools available, such as the autoupdate feature introduced in Aegisub 3.0), timing hasn’t progressed much technology-wise and poor timing in old releases can only be attributed to incompetence. The same goes for every other aspect of a fansub release.

People often whine about how fansubbers should not oversub shows (where “oversubbing” can sometimes mean working on a show that already has a simulcast) and instead go devote their efforts into subbing old unsubbed shows. I think that’s a ridiculous stance to take, because subbing any single show from scratch is actually a lot of effort, and finding the staff willing to do this is nigh impossible. Not having a weekly release schedule also compels people to be really lazy and stall things; I think it’s safe to say that most translators don’t have the discipline to do their work timely even without a weekly schedule. (Let’s see: I’ve worked with vale, shark, Oosran, Nanu, Futsuu, fnord, bb27, airco… okay, maybe airco and vale are exceptions nobody is an exception!) Beyond that, unsubbed shows tend to be unsubbed either because they suck or because giving them proper releases would involve much larger amounts of effort than the average otaku-bait series. Either way, conning people to work on your pet project of subbing a thousand episodes of Sazae-san is not feasible.

What I want to talk about are old series that already have softsubbed releases. In theory, the main selling point of softsubbing is that fixing imperfections in the scripts should be as simple as loading it up in Aegisub and making the relevant changes. In practice, who the hell does that? Or rather, who the hell does that and is competent enough to do it without making things worse on the whole?

On one hand, we have people like Kristen who actively worsen scripts to fit their incorrect view of Japanese culture. On the other hand, there aren’t really a lot of people who improve mediocre scripts and then release them.

I don’t mean to say that the scripts should receive full TLC and editing passes. This is not realistic to expect for the reasons I mentioned above, unless you’re a translator or editor yourself. Even changes as “trivial” as having reasonable colour choices in the main dialogue can greatly improve the watching experience. (Hi, THORA!) And maybe running the script through Aegisub’s timing postprocessor too. These don’t take much effort, but it’s still a nonzero amount of effort and I guess what I’m hoping for is that other people would do this and release their results, so more than one person benefits from the improved scripts.

I’ve tried fixing up the scripts for a few old series, but I only ever finished two series and released only one of those two. It just kinda sucks to effectively listen through the whole episode once to shift/retime it, and then have a second pass to watch it. Since I’m also doing this with the intent of releasing the scripts eventually, I also go to fix all the tiny errors I spot, and unfortunately this is extremely distracting when all I want to do is to watch the darned show.

And of course, it seems like nobody else ever does this. Maybe I just answered my own question and, for most people, even if they’re offended by the terrible subtitles, they don’t deem that there’s enough utility out of spending time to improve the subtitles when over 90% of the people watching the series won’t notice the existence of improved subs, and 90% of the remainder don’t care about what’s improved anyway.

Being a fansubber and having standards sucks. Ignorance is bliss.

Nonseparable spatial bandpass filters

[screenshot]

w = 1920
h = 1200

blankclip(width=w,height=h,pixel_type="yv12",color_yuv=$808080)
addgrainc(1000,seed=1)
converttoy8()
Dither_convert_8_to_16()
for(i=1,40)
{
	thin = dither_box_filter16(radius=6).dither_box_filter16(radius=5)
	wide = dither_box_filter16(radius=2)
	raveragew(wide,1.5,thin,-0.5,lsb_in=true,lsb_out=true,mode=0)
	#~ dither_lut16("x 32768 - 1.1 * 32768 +")
}
ditherpost(mode=0)
mergergb(last,last,last)

Inspired by some Doom9 posts. :words: to come later.

A precise debicubic

Maybe I should just post this directly to Doom9 but I’d like to believe the people who read this blog are much less intellectually-challenged than certain Doom9 posters.

Something I learnt “recently” was that debicubic’s 16-bit mode actually doesn’t have high precision; the result is good to only ~8 bits, and the low eight bits of the output are somehow clustered around small values, even though you’d expect them to be roughly uniformly distributed. At first I thought this was only a problem with RGB (I mentioned this on Twitter while exploring the use of debicubic as an IIR blurring filter–a story for another time), but _08 mentioned about it in #ANE and I’ve confirmed that it affects YV12 input as well.

First off, the RGB problem is much bigger; rather than just losing some precision, debicubic gives completely wrong results. This seems to depend on whether the LSB is mostly zeros. Just don’t ever use 16-bit debicubic in RGB. Getting back to YV12, we usually don’t want to use debicubic on the chroma anyway, so let’s consider just the luma. (The below function was simplified from a larger script I’m working on and I haven’t tested this simplified version, so usual caveats blah blah blah. Also, 16-bit input/output only.)

function debicubicy_precise(clip src, int dst_width, int dst_height, float "src_left", float "src_top", float "src_width", float "src_height", float "b", float "c")
{
	sw = src.width()
	sh = src.height()/2
	src_left   = default(src_left,   0.0)
	src_top    = default(src_top,    0.0)
	src_width  = default(src_width,  sw)
	src_height = default(src_height, sh)
	if (src_width <= 0.0)  {src_width  = sw + src_width  - src_left}
	if (src_height <= 0.0) {src_height = sh + src_height - src_top}
	inv_left = -src_left * dst_width/src_width
	inv_top = -src_top * dst_height/src_height
	inv_width = (sw-src_left) * dst_width/src_width
	inv_height = (sh-src_top) * dst_height/src_height
	seed = debicubicy(src, dst_width, dst_height, src_left, src_top, src_width+src_left, src_height+src_top, lsb_inout=true, b=b, c=c)
	up = seed.dither_resize16(sw, sh, inv_left, inv_top, inv_width, inv_height, kernel="bicubic", fh=-1.0, fv=-1.0, taps=taps, a1=b, a2=c)
	diff = dither_sub16(src, up, dif=true).dither_lut16("x 32768 - 99 * 32768 +")
	down = diff.debicubicy(dst_width, dst_height, src_left, src_top, src_width+src_left, src_height+src_top, lsb_inout=true, b=a1, c=a2)
	down = down.dither_lut16("x 32768 - 99 / 32768 + round")
	return seed.dither_add16(down, dif=true)
}

By the way, src_width and src_height in debilinear/debicubic don’t have the same semantics as in AviSynth’s internal resizers or Dither_resize16; in debilinear/debicubic those refer to the x and y coordinates of the “cropped” sampling area, not to the width or height. I’ve never seen this documented anywhere. The above script uses the standard semantics, as in the internal resizers and Dither_resize16.

This simple hack of iterative refinement brings up the precision to around 15 bits, so there. Here’s a comparison of the error, amplified by a factor of 128.

Debilinear is not affected by this loss of precision when working in 16-bit mode, so there’s no need for a similar hack in that case.

Update (2017-03-20): Don’t actually use this version. It’s barely tested and I’ve had a bunch of people telling me that it’s broken in weird ways. Use _08’s version.