// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! What an Apple II actually looked like on a colour television. //! //! `video.zig` colours the dot stream with the rule everybody uses: four dots //! make a colour, and which colour depends on which four and where they start. //! That rule is right about *what* the colours are and says nothing about how //! they got there, so it draws them as flat blocks with hard edges — and a //! composite monitor never did that. What it did was demodulate a signal, and //! demodulation 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. //! //! This does the demodulation instead, which is Marc S. Ressl's NTSC emulation //! from OpenEmulator by way of Zellyn Hunter's explanation of it (Hunter, //! n.d.). The steps are: //! //! 1. Each dot is a sample of the composite signal, one or nought. //! 2. Multiply each sample by `1`, `sin φ` and `cos φ` — quadrature //! demodulation, which separates luminance from the two chrominance axes. //! `φ` advances a quarter turn per dot, because the colour subcarrier is //! exactly a quarter of the sample rate. //! 3. Low-pass each of the three with its own filter, luminance wide and //! chrominance narrow. That is the smearing, and it is the whole point: //! chrominance is band-limited to 600 kHz where luminance gets 2 MHz, so //! colour spreads about three times as far as brightness does. //! 4. Turn the resulting Y, U and V into red, green and blue. //! //! ## Why the subcarrier is exactly a quarter //! //! The sample rate is `NTSC_4FSC`, four times the colour subcarrier, and an //! Apple II's dot clock *is* that: 14.318 MHz, four dots per colour cycle. //! Which is why the four-dots-make-a-colour rule works at all, and why `sin φ` //! and `cos φ` take only four values each here rather than needing a //! trigonometric function per dot. //! //! `doc/NTSC.md` sets the whole thing out at length: how the filters are //! built, what the tap values are and what they mean, and where this //! deliberately differs from the notebook. //! //! ## What is a choice here //! //! Less than in `video.palette`, and that is the point of having this. The //! filter coefficients, the bandwidths, the subcarrier phase and the decoding //! matrix are all Ressl's, and they come from NTSC itself rather than from //! anybody's taste. What remains adjustable — saturation, hue, contrast — is //! adjustable on a real television too, and is left at the neutral setting. const std = @import("std"); const video = @import("video.zig"); /// The colour subcarrier, and the rate the dot stream is sampled at. /// /// "NTSC_FSC = 315 / 88 * 1e6" and "NTSC_4FSC = 4 * NTSC_FSC" (Hunter, n.d.), /// which are 3.579545 MHz and 14.318180 MHz — the second being an Apple II's /// dot clock, which is not a coincidence. pub const subcarrier_hz: f64 = 315.0 / 88.0 * 1.0e6; pub const sample_hz: f64 = 4.0 * subcarrier_hz; /// How much of the spectrum each part of the signal is allowed. /// /// Luminance gets 2 MHz and chrominance 600 kHz, which is why colour smears /// about three times as far as brightness. These are OpenEmulator's defaults. pub const luma_hz: f64 = 2_000_000.0; pub const chroma_hz: f64 = 600_000.0; /// The filter is seventeen taps wide: the sample itself and eight either side. pub const taps = 17; pub const reach = taps / 2; /// Where the subcarrier's phase is at the left of the picture. /// /// The colour burst sits at -33 degrees, and OpenEmulator adds a quarter turn /// for each dot the visible image starts past the start of the raster: /// `colorBurst = 2 * PI * (-33 / 360 + (imageLeft % 4) / 4)`. For an Apple II /// `imageLeft` works out at 92, which divides by four exactly, so that second /// term is nothing and a dot's own index can be used for the phase without /// carrying the raster's offset around. The phase is kept as a turn rather /// than as radians because a quarter of a turn is exact and a quarter of two /// pi is not. pub const burst_turns: f64 = -33.0 / 360.0; /// The two filters, centre tap first, worked out at compile time. /// /// Both are a Dolph-Chebyshev window with 50 dB sidelobes multiplied by a /// Lanczos window at the cutoff, normalised so the taps sum to one; the /// chrominance one is then doubled, because demodulating against a sine /// recovers half the amplitude and the other half is the image at twice the /// subcarrier that the low-pass has just thrown away. pub const luma_taps: [reach + 1]f64 = weights(luma_hz, 1.0); pub const chroma_taps: [reach + 1]f64 = weights(chroma_hz, 2.0); /// Y, U and V for one sample of the signal, before the filter. const Sample = struct { y: f64, u: f64, v: f64 }; /// The quarter-turn table: `sin` and `cos` of the subcarrier at each of the /// four phases a dot can have, sampled half a dot in as OpenEmulator does /// (`subcarrier * (x + 0.5)`). const Quadrature = struct { sin: f64, cos: f64 }; const quadrature: [4]Quadrature = blk: { @setEvalBranchQuota(10_000); var table: [4]Quadrature = undefined; for (&table, 0..) |*at, x| { const turns = 0.25 * (@as(f64, @floatFromInt(x)) + 0.5) + burst_turns; const radians = 2.0 * std.math.pi * turns; at.* = .{ .sin = @sin(radians), .cos = @cos(radians) }; } break :blk table; }; /// Decodes one scan line of dots into colours. /// /// Dots off either end of the line are nothing rather than a repeat of the /// edge: what is beyond the picture is blanking, and a line does not begin by /// smearing its first dot outwards. pub fn decodeLine(dots: *const [video.width]bool, into: *[video.width]video.Rgb) void { for (0..video.width) |x| into[x] = decodeAt(dots, x); } /// One dot's colour, which is seventeen dots' worth of signal. pub fn decodeAt(dots: *const [video.width]bool, x: usize) video.Rgb { const centre = sampleAt(dots, @intCast(x)); var y = centre.y * luma_taps[0]; var u = centre.u * chroma_taps[0]; var v = centre.v * chroma_taps[0]; for (1..reach + 1) |i| { const at: isize = @intCast(x); const step: isize = @intCast(i); const before = sampleAt(dots, at - step); const after = sampleAt(dots, at + step); y += (before.y + after.y) * luma_taps[i]; u += (before.u + after.u) * chroma_taps[i]; v += (before.v + after.v) * chroma_taps[i]; } return toRgb(y, u, v); } /// One sample, demodulated but not yet filtered. fn sampleAt(dots: *const [video.width]bool, x: isize) Sample { if (x < 0 or x >= video.width) return .{ .y = 0, .u = 0, .v = 0 }; const lit: f64 = if (dots[@intCast(x)]) 1.0 else 0.0; const phase = quadrature[@as(usize, @intCast(x)) & 3]; return .{ .y = lit, .u = lit * phase.sin, .v = lit * phase.cos }; } /// Y, U and V to red, green and blue. /// /// The matrix is the one in the notebook — /// `1, 1, 1 / 0, -0.394642, 2.032062 / 1.139883, -0.580622, 0` read down its /// columns — which is the usual YUV to RGB of composite video. Saturation, hue /// and contrast would multiply into it ahead of this; all three are at their /// neutral setting, so there is nothing to multiply. fn toRgb(y: f64, u: f64, v: f64) video.Rgb { return .{ .r = clamp(y + 1.139883 * v), .g = clamp(y - 0.394642 * u - 0.580622 * v), .b = clamp(y + 2.032062 * u), }; } fn clamp(value: f64) u8 { const scaled = @round(value * 255.0); if (scaled <= 0) return 0; if (scaled >= 255) return 255; return @intFromFloat(scaled); } /// One of the two filters, as its centre tap and the eight beside it. fn weights(comptime cutoff_hz: f64, comptime gain: f64) [reach + 1]f64 { @setEvalBranchQuota(200_000); var window = chebyshev(50.0); const pass = lanczos(cutoff_hz / sample_hz); for (&window, pass) |*at, low| at.* *= low; var total: f64 = 0; for (window) |at| total += at; var out: [reach + 1]f64 = undefined; for (&out, 0..) |*at, i| at.* = window[reach + i] / total * gain; return out; } /// A Lanczos window at a cutoff, which is a sinc: the ideal low-pass. fn lanczos(comptime cutoff: f64) [taps]f64 { @setEvalBranchQuota(200_000); const fc = @min(cutoff, 0.5); var out: [taps]f64 = undefined; for (&out, 0..) |*at, i| { const x = 2.0 * std.math.pi * fc * (@as(f64, @floatFromInt(i)) - reach); at.* = if (x == 0.0) 1.0 else @sin(x) / x; } return out; } /// A Dolph-Chebyshev window, which is the one with the flattest sidelobes for /// a given width — the reason the smear has no ringing in it. fn chebyshev(comptime sidelobe_db: f64) [taps]f64 { @setEvalBranchQuota(200_000); const m = taps - 1; var spectrum: [m]f64 = undefined; const alpha = std.math.cosh(std.math.acosh(std.math.pow(f64, 10.0, sidelobe_db / 20.0)) / m); for (&spectrum, 0..) |*at, i| { const a = @abs(alpha * @cos(std.math.pi * @as(f64, @floatFromInt(i)) / m)); const sign: f64 = if (i % 2 == 0) 1.0 else -1.0; at.* = sign * (if (a > 1.0) std.math.cosh(m * std.math.acosh(a)) else @cos(m * std.math.acos(a))); } // Back to the time domain, and then the two ends are the same half tap. var out: [taps]f64 = @splat(0); for (0..m) |i| { const omega = 2.0 * std.math.pi * @as(f64, @floatFromInt(i)) / m; var sum: f64 = 0; for (spectrum, 0..) |value, j| sum += value * @cos(@as(f64, @floatFromInt(j)) * omega); out[i] = sum / m; } out[0] /= 2.0; out[taps - 1] = out[0]; var largest: f64 = 0; for (out) |at| largest = @max(largest, @abs(at)); for (&out) |*at| at.* /= largest; return out; } const testing = std.testing; test "the subcarrier has four phases, and they are the ones doc/NTSC.md prints" { // The dot clock is exactly four times the colour subcarrier, so a dot is a // quarter turn and there are four phases rather than five hundred and // sixty. These numbers are published in doc/NTSC.md; asserting them here // is what stops the document drifting away from the code. const want = [4][2]f64{ .{ 0.207912, 0.978148 }, .{ 0.978148, -0.207912 }, .{ -0.207912, -0.978148 }, .{ -0.978148, 0.207912 }, }; for (quadrature, want) |got, expected| { try testing.expectApproxEqAbs(expected[0], got.sin, 1e-6); try testing.expectApproxEqAbs(expected[1], got.cos, 1e-6); } } test "the filters are the ones the notebook builds" { // Worked out at compile time here and in JavaScript there, so agreeing to // six places says the Chebyshev window, the Lanczos window, the // normalisation and the chrominance doubling are all the same arithmetic. const want_luma = [_]f64{ 0.279408, 0.235926, 0.134616, 0.036655, -0.015383, -0.022104, -0.009993, -0.000718, 0.001297, }; const want_chroma = [_]f64{ 0.260299, 0.247879, 0.213726, 0.166016, 0.115090, 0.070082, 0.036478, 0.015433, 0.005148, }; for (luma_taps, want_luma) |got, want| try testing.expectApproxEqAbs(want, got, 1e-6); for (chroma_taps, want_chroma) |got, want| try testing.expectApproxEqAbs(want, got, 1e-6); // Luminance is a low-pass and so sums to one; chrominance sums to two, // being the same filter doubled to make up for demodulation halving it. var luma_sum: f64 = luma_taps[0]; var chroma_sum: f64 = chroma_taps[0]; for (1..reach + 1) |i| { luma_sum += 2 * luma_taps[i]; chroma_sum += 2 * chroma_taps[i]; } try testing.expectApproxEqAbs(@as(f64, 1.0), luma_sum, 1e-9); try testing.expectApproxEqAbs(@as(f64, 2.0), chroma_sum, 1e-9); } /// A line of dots repeating one pattern, which is what a run of hi-res bytes /// puts on the wire. fn repeating(comptime pattern: []const u8) [video.width]bool { var dots: [video.width]bool = undefined; for (&dots, 0..) |*dot, i| dot.* = pattern[i % pattern.len] != 0; return dots; } test "a filled line is white and an empty one is black" { const on = repeating(&.{1}); const off = repeating(&.{0}); // Every tap of the luminance filter, summing to one, on a signal that is // one everywhere. try testing.expectEqual(video.Rgb{ .r = 255, .g = 255, .b = 255 }, decodeAt(&on, 280)); try testing.expectEqual(video.Rgb{ .r = 0, .g = 0, .b = 0 }, decodeAt(&off, 280)); } test "the hi-res colours come out of the signal rather than out of a table" { // A hi-res dot is two of the five hundred and sixty, so alternating hi-res // dots is `1100` repeating, and the two phases of it are the violet and // green a real machine shows. Nothing here knows that: it is what falls // out of demodulating the dots. const violet = decodeAt(&repeating(&.{ 1, 1, 0, 0 }), 280); const green = decodeAt(&repeating(&.{ 0, 0, 1, 1 }), 280); try testing.expect(violet.r > 200 and violet.b > 200 and violet.g < 80); try testing.expect(green.g > 200 and green.r < 80 and green.b < 80); // And alternating every *single* dot is 7.16 MHz, twice the subcarrier and // far above what chrominance is allowed, so it has no colour in it at all // -- which is exactly why the double-hi-res grey patterns are grey. const grey = decodeAt(&repeating(&.{ 1, 0 }), 280); try testing.expect(grey.r > 100 and grey.r < 160); try testing.expectEqual(grey.r, grey.g); try testing.expectEqual(grey.g, grey.b); } test "colour smears further than brightness does" { // The point of the whole exercise. One hi-res dot on its own is not a // block of colour with hard edges: chrominance is band-limited to 600 kHz // where luminance gets 2 MHz, so the colour reaches about three times as // far as the brightness that carries it. var dots: [video.width]bool = @splat(false); dots[280] = true; dots[281] = true; const centre = decodeAt(&dots, 280); const near = decodeAt(&dots, 286); const far = decodeAt(&dots, 296); const saturation = struct { fn of(c: video.Rgb) i32 { const hi = @max(c.r, @max(c.g, c.b)); const lo = @min(c.r, @min(c.g, c.b)); return @as(i32, hi) - lo; } }; // Six dots away there is still colour, and it is not the flat block a // table lookup would give: it has faded. try testing.expect(saturation.of(near) > 0); try testing.expect(saturation.of(near) < saturation.of(centre)); // Sixteen dots away it has gone. try testing.expect(saturation.of(far) < saturation.of(near)); } test "nothing outside the line bleeds into it" { // Beyond the picture is blanking, not a repeat of the edge dot, so a line // whose first dots are lit does not smear them off the left of the screen // and back again. var dots: [video.width]bool = @splat(false); dots[0] = true; dots[1] = true; const inside = decodeAt(&dots, 0); try testing.expect(inside.r > 0 or inside.g > 0 or inside.b > 0); // Far from the two lit dots it is black, at both ends. try testing.expectEqual(video.Rgb{ .r = 0, .g = 0, .b = 0 }, decodeAt(&dots, 300)); try testing.expectEqual(video.Rgb{ .r = 0, .g = 0, .b = 0 }, decodeAt(&dots, video.width - 1)); }