A cycle-accurate Apple II and Apple IIgs emulator written in Zig, usable as both a program and a library.
zig65 doc NTSC.md
9.1 kB · 229 lines
Markdown
at main

How --monitor ntsc works #

src/ntsc.zig draws an Apple II's picture the way a colour television did: by demodulating the composite signal rather than by looking each colour up in a table. This is what it does and why each step is there.

It is Marc S. Ressl's NTSC emulation from OpenEmulator, taken from Zellyn Hunter's Observable notebook explaining it. Nearly every constant below comes from there, and the ones that do not are marked.

The problem #

src/video.zig colours the dot stream with the rule everybody knows: four dots make a colour, and which colour depends on which four and where they start. That rule is correct about what the colours are. What it says nothing about is how they got there, so it paints them as flat blocks with hard edges.

A composite monitor never did that. Colour reaches an Apple II's screen as a 3.58 MHz subcarrier riding on the brightness signal, and getting it back out means filtering — which smears. Colours bleed into their neighbours, a white line picks up fringes, and a single dot on its own is not a colour at all but a coloured smudge a couple of dots wide.

Both renderings are in the program because both are true of something. The table is what the colours are; this is what they looked like.

The one coincidence everything rests on #

An Apple II's dot clock is 14.318 MHz, and the NTSC colour subcarrier is

NTSC_FSC = 315 / 88 × 10⁶ = 3.579545 MHz

so the dot clock is exactly 4 × NTSC_FSC. One dot is a quarter turn of the subcarrier's phase and four dots are one full cycle.

That is why the four-dots rule works at all. It is also what makes this cheap: the sample rate and the subcarrier are in an exact 4:1 ratio, so sin φ and cos φ take four values each rather than needing a trigonometric function per dot.

The algorithm #

Four steps, for each dot of each scan line.

1. The dot is a sample #

Each dot is one sample of the composite signal: 1.0 if lit, 0.0 if not. Nothing more is needed, because on an Apple II the video signal really is a one-bit stream at the dot clock.

2. Quadrature demodulation #

Multiply the sample by three things to split it into a luminance and two chrominance axes:

Y = v
U = v × sin φ
V = v × cos φ

where the phase advances a quarter turn per dot, sampled half a dot in:

φ = 2π × (0.25 × (x + 0.5) + burst)

burst is where the subcarrier's phase sits at the left of the picture. The colour burst is at −33°, and OpenEmulator adds a quarter turn per dot that the visible image starts past the start of the raster:

colorBurst = 2π × (−33/360 + (imageLeft mod 4) / 4)

For an Apple II imageLeft works out at 92, which divides by four exactly, so that second term vanishes and a dot's own index can be used for the phase without carrying the raster offset around. That leaves

burst = −33/360 = −0.091666… turns

and, because the ratio is exactly 4:1, only four distinct phases:

x mod 4 sin φ cos φ
0 +0.207912 +0.978148
1 +0.978148 −0.207912
2 −0.207912 −0.978148
3 −0.978148 +0.207912

ntsc.zig computes this table at compile time and indexes it with x & 3.

3. Low-pass each of the three #

This is the step that makes the picture look right, and the only one with any real arithmetic in it. Each of Y, U and V is convolved with a 17-tap symmetric filter — the dot itself and eight either side, about 1.19 µs of signal.

The two filters differ only in their cutoff:

bandwidth as a fraction of the sample rate
luminance 2 MHz 0.139683
chrominance 600 kHz 0.041905

Chrominance gets a third of the bandwidth luminance does. That single fact is most of what the mode is for: colour spreads about three times as far as the brightness carrying it, which is why a lone dot is a smudge and why a block of colour is solid in the middle and fringed at the edges.

Each filter is built the same way:

  1. A Dolph–Chebyshev window of 17 taps with 50 dB sidelobes. Chebyshev is the window with the flattest sidelobes for a given width, which is why the smear has no ringing in it. It is computed as a frequency-domain expression run through a real inverse DFT, then folded so the two end taps are half the same tap, then normalised by its largest value.
  2. Multiplied by a Lanczos window at the cutoff, which is a sinc — the ideal low-pass — evaluated at 2π · fc · (i − 8).
  3. Normalised so the taps sum to 1.
  4. For chrominance only, doubled. Demodulating against a sine recovers half the amplitude; the other half is an image at twice the subcarrier which the low-pass has just thrown away, so the factor of two puts it back.

What comes out, centre tap first:

offset luminance chrominance
0 0.279408 0.260299
±1 0.235926 0.247879
±2 0.134616 0.213726
±3 0.036655 0.166016
±4 −0.015383 0.115090
±5 −0.022104 0.070082
±6 −0.009993 0.036478
±7 −0.000718 0.015433
±8 0.001297 0.005148

The luminance taps sum to 1 and the chrominance taps to 2. The difference in shape is the whole point, and it is easiest to see as a fraction of the centre tap:

offset luminance chrominance
±1 84.4% 95.2%
±2 48.2% 82.1%
±3 13.1% 63.8%
±4 −5.5% 44.2%

Luminance is all but gone by ±3 and has turned slightly negative by ±4, where chrominance is still at nearly half. That is the three-to-one bandwidth ratio showing up as three-to-one reach.

These are built at compile time. A test checks them against the notebook's JavaScript to six decimal places, which is what says the two windows, the normalisation and the doubling are the same arithmetic in both.

4. YUV to RGB #

R = Y + 1.139883 V
G = Y − 0.394642 U − 0.580622 V
B = Y + 2.032062 U

then clamp to 0–255. Saturation, hue and contrast would multiply into this matrix ahead of the conversion; all three are at their neutral setting, so there is nothing to multiply. They are adjustable on a real television too.

What falls out of it #

None of these is a special case in the code. They are what the arithmetic does.

dot pattern result why
all lit #ffffff luminance taps sum to 1
all dark #000000
11001100 #f00bff hi-res violet
00110011 #0ff400 hi-res green
10101010 #808080 grey — see below

The last is worth its own note. Alternating every single dot is 7.16 MHz, twice the subcarrier and far above what chrominance is allowed, so nothing survives the chrominance filter and the result has no colour in it at all. That is exactly why the double-hi-res grey patterns are grey, and it is not special-cased anywhere.

The violet and green are the other useful check. A hi-res dot is two of the 560, so alternating hi-res dots is 1100 repeating, and its two phases are the two colours a real machine shows. If the subcarrier phase were two dots out, green and violet would swap — so getting these right is what says burst is right.

Two deliberate differences from the notebook #

Off the end of a line is blanking, not the edge dot. The notebook's getRawPixel clamps to the source image's bounds, so reading past the edge repeats the edge column. That is an artifact of its setup — a 560-wide image placed inside a wider black raster, where the loop reads outside the image on purpose. For a scan line, what lies beyond the picture is blanking, so ntsc.zig returns nothing there. Otherwise a line whose first dots are lit would smear them off the left of the screen and back again.

No vertical doubling. The notebook writes each line twice to get a 4:3 picture out of a 560×192 buffer. Here the scaling belongs to whatever is drawing — the terminal or the screenshot writer — and ntsc.zig returns one colour per dot.

Cost #

About two milliseconds per frame measured in ReleaseFast: 560 × 192 pixels × 17 taps × 3 components is around 5.5 million multiply-adds. That is comfortably inside a 60 Hz budget, so it runs live rather than being a screenshot mode.

The obvious optimisation — adjacent output pixels share 16 of their 17 input samples, so a rolling sum would do far less work — has not been made, because two milliseconds is already cheap enough and the direct form is the one that reads like the description above.

Where to look #

src/ntsc.zig the whole of it: constants, filters, and the decode
src/video.zig the dot stream this consumes, and the table-driven colour rule it is an alternative to
src/picture.zig Monitor, which picks between the four displays