Finally, the signals must be clipped or normalized to [0, 1] to avoid values outside of the valid range.
C_raw = R, G, or B channel
C_clip = clipped or normalized R, G, or B channel
C_clip = max(0, min(1, C_raw))
=== Converting signal RGB to display RGB ===
The final step is to convert signal RGB into the output colorspace, typically sRGB for most monitors.
==== Signal RGB into sRGB ====
Assuming no colorimetry involved, the resulting R, G and B values can directly be quantized into 8 bits per channel:
C' = R, G or B signal
C8bpc = quantized R, G, or B channel
C8bpc = (int)(C' * 255)
However, if the signal RGB is assumed to be fed a reference display with different color primaries, then a correction matrix must be applied to the signal before quantization.
==Emulating in C++ code==
For efficient, ready to use implementations, see [[#Libraries|Libraries]] below. The following is an illustrative example.
Calculating the momentary NTSC signal level can be done as follows in C++:
// pixel = Pixel color (9-bit) given as input. Bitmask format: "eeellcccc".
// phase = Signal phase (0..11). It is a variable that increases by 8 each pixel.
float NTSCsignal(int pixel, int phase)
{
// Terminated voltage levels
static const float levels[16] = {
0.228f, 0.312f, 0.552f, 0.880f, // Signal low
0.616f, 0.840f, 1.100f, 1.100f, // Signal high
0.192f, 0.256f, 0.448f, 0.712f, // Signal low, attenuated
0.500f, 0.676f, 0.896f, 0.896f // Signal high, attenuated
};
// Decode the NES color.
int color = (pixel & 0b000001111); // 0..15 "cccc"
int level = (pixel & 0b000110000) >> 4; // 0..3 "ll"
int emphasis = (pixel & 0b111000000) >> 6; // 0..7 "eee"
if(color > 13) { level = 1; } // For colors 14..15, level 1 is forced.
auto InColorPhase = [=](int color) { return (color + phase) % 12 < 6; }; // Inline function
// When de-emphasis bits are set, some parts of the signal are attenuated:
// colors 14 .. 15 are not affected by de-emphasis
int attenuation = (
(((emphasis & 1) && InColorPhase(0xC))
|| ((emphasis & 2) && InColorPhase(0x4))
|| ((emphasis & 4) && InColorPhase(0x8))) && (color < 0xE)) ? 8 : 0;
// The square wave for this color alternates between these two voltages:
float low = levels[0 + level + attenuation];
float high = levels[4 + level + attenuation];
if(color == 0) { low = high; } // For color 0, only high level is emitted
if(color > 12) { high = low; } // For colors 13..15, only low level is emitted
// Generate the square wave
float signal = InColorPhase(color) ? high : low;
return signal;
}
The process of generating NTSC signal for a single pixel can be simulated with the following C++ code:
void RenderNTSCpixel(unsigned x, int pixel, int PPU_cycle_counter)
{
int phase = PPU_cycle_counter * 8;
for(int p=0; p<8; ++p) // Each pixel produces distinct 8 samples of NTSC signal.
{
float signal = NTSCsignal(pixel, phase + p); // Calculated as above
// Optionally apply some lowpass-filtering to the signal here.
// This emulates the differential phase distortion due to varying DAC impedance.
// Normalize the signal to 0..1 range.
// Since the signal will accumulate by 12 samples, we may put the division by 12 here too.
static const float black=0.312f, white=1.100f;
signal = (signal-black) / (white-black);
// Save the signal for this pixel.
signal_levels[ x*8 + p ] = signal;
}
}
It is important to note that while the NES only generates eight (8) samples of NTSC signal per pixel, the wavelength for chroma is 12 samples long. This means that the colors of adjacent pixels get mandatorily mixed up to some degree. For the same reason, narrow grayscale details can be interpreted as colors.
Because the scanline length is uneven (341*8 is not an even multiple of 12), the color mixing shifts a little each scanline. This appears visually as a sawtooth effect at the edges of colors at high resolution. The sawtooth cycles every 3 scanlines.
Because also the frame length is uneven (neither 262*341*8 nor (262*341-1)*8 is an even multiple of 12), the color mixing also changes a little every frame. When rendering is normally enabled, the screen is alternatingly 89342 and 89341 cycles long. The combination of these (89342+89341)*8 is an even multiple of 12, which means that the artifact pattern cycles every 2 frames. The pattern of cycling can be changed by disabling rendering during the end of the pre-render scanline; it forces the screen length to 89342 cycles, even if would be 89341 otherwise.
The process of decoding NTSC signal (convert it into RGB) is subject to a lot of study, and there are many patents and different techniques for it. A simple method suitable for emulation is covered below. It is not accurate, because in reality the chroma is blurred much more than is done here (the region of signal sampled for U and V is wider than 12 samples), and the filter used here is a simple box FIR filter rather than an IIR filter, but it already produces a quite authentic looking picture. In addition, the border region (total of 26 pixels of background color around the 256-pixel scanline) is not sampled.
float signal_levels[256*8] = {...}; // Eight signal levels for each pixel, normalized to 0..1 range.
Calculated as above.
unsigned Width; // Input: Screen width. Can be not only 256, but anything up to 2048.
float phase; // Input: This should the value that was PPU_cycle_counter * 8 + 3.9
// at the BEGINNING of this scanline. It should be modulo 12.
// It can additionally include a floating-point hue offset.
for(unsigned x = 0; x < Width; ++x)
{
// Determine the region of scanline signal to sample. Take 12 samples.
int center = x * (256*8) / Width + 0;
int begin = center - 6; if(begin < 0) begin = 0;
int end = center + 6; if(end > 256*8) end = 256*8;
float y = 0.f, u = 0.f, v = 0.f; // Calculate the color in YUV.
for(int p = begin; p < end; ++p) // Collect and accumulate samples
{
float level = signal_levels[p] / 12.f; // This division by the amount of samples
// can also be done at the voltage normalization step.
y += level;
// Magic constants explanation:
// * 2.f: Saturation correction for integral of sin(2*PI*x)^2
// + 3.f: Carrier reference phase is off by 90 degrees
// - 0.5f: Carrier phase is additionally off by 15 degrees
u += level * sin( M_PI * (phase + p + 3.f - 0.5f) / 6 ) * 2.f;
v += level * cos( M_PI * (phase + p + 3.f - 0.5f) / 6 ) * 2.f;
}
render_pixel(y,u,v); // Send the YUV color for rendering.
}
The NTSC decoder here produces pixels in YUV color space.
If you want more saturated colors, just multiply u and v with a factor of your choosing, such as 1.7.
If you want brighter colors, just multiply y, u and v with a factor of your choosing, such as 1.1.
If you want to adjust the hue, just add or subtract a value from/to phase.
If you want to see so called chroma dots, change the begin and end in such manner that you collect a number of samples that is not divisible with 12.
If you want to blur the video horizontally, change the begin and end in such manner that the samples are collected from a wider region.
The YUV colors can be converted into sRGB colors with the following formula, using the YUV-to-RGB conversion matrix mentioned previously. This produces a value that can be saved to e.g. framebuffer:
void render_pixel(float y, float u, float v) {
unsigned r = std::round(255.f * (y + 1.139883f * v));
unsigned g = std::round(255.f * (y - 0.394642f * u - 0.580622f * v));
unsigned b = std::round(255.f * (y + 2.032062f * u));
// The decoded signal may produce values beyond the gamut of RGB.
// Clip the signal within 0..255:
if (r>255) r = 255; else if (r<0) r = 0;
if (g>255) g = 255; else if (g<0) g = 0;
if (b>255) b = 255; else if (b<0) b = 0;
// RGB value ready to be written to a framebuffer.
unsigned rgb = r * 0x10000
+ g * 0x00100
+ b * 0x00001;
}
The two images below illustrate the NTSC artifacts.
In the first image, 12 samples of NTSC signal were generated for each NES pixel,
and each display pixel was separately rendered by decoding that 12-sample signal.
In the second image, 8 samples of NTSC signal were generated for each NES pixel,
and each display pixel was rendered by decoding 12 samples of NTSC signal from the
corresponding location within the scanline.
[[File:nes_ntsc_perpixel.png|left|frame|Per-pixel rendering: 12 samples of NTSC signal per input pixel; the same 12 samples are decoded for each output pixel]]
[[File:nes_ntsc_perscanline.gif|left|frame|Per-scanline rendering: 8 samples of NTSC signal per input pixel; 12 samples are decoded for each output pixel]]
[[File:nes_ntsc_perpixel_small.png|left|frame|Same as above, but rendered at 256x240 without upscaling]]
[[File:nes_ntsc_perpixel_small_bw.png|left|frame|Same in grayscale (zero saturation). This illustrates well how the different color values have exactly the same luminosity; only the chroma phase differs.]]
[[File:nes_ntsc_perscanline_small.gif|left|frame|Same as above, but rendered at 256x240 rather than at 2048x240 and then downscaled]]
[[File:nes_ntsc_perscanline_small_bw.gif|left|frame|Same in grayscale]]
The source code of the program that generated these images can be read here: [https://github.com/Gumball2415/bisqwit-example-nes-ntsc bisqwit-example-nes-ntsc].
That code is modified from the original program: [https://bisqwit.iki.fi/jutut/kuvat/programming_examples/nesemu1/ntsc-small.cc ntsc-small.cc].
Both sources are licensed under Creative Commons Attribution-ShareAlike 4.0 International.
Note that even though the image resembles the well-known Philips circle test card, it is not the same; the exact same
colors could not be reproduced with NES colors. In addition, some parts were changed to better test NES features. For example, the backgrounds for the "station ID" regions (the black rectangles at the top and at the bottom inside the circle) are generated using the various blacks within the NES palette.
Later, Bisqwit made a generic [http://forums.nesdev.org/viewtopic.php?p=172329#p172329 integer-based decoder in C++]. This takes a signal at 12 times color burst and can be used to emulate other systems that use shortcuts when generating NTSC video, such as Apple II (where ''every'' color in HGR is an artifact color) and Atari 7800 (whose game ''Tower Toppler'' seriously exploits artifact colors).
==Libraries==
* [http://slack.net/~ant/libs/ntsc.html blargg's nes_ntsc library]
* [//forums.nesdev.org/viewtopic.php?f=21&t=11947 blargg's NTSC demo windows executable]
* [//forums.nesdev.org/viewtopic.php?f=2&t=14338 Forum thread]: New NTSC decoder with integer-only math (short C++ code) - by Bisqwit
* [https://github.com/LMP88959/NTSC-CRT/ LMP88959 (EMMIR)'s NTSC decoder]
== See also ==
* [[Cycle reference chart]]
* [[PAL video]]
* [[PPU palettes]]
== References ==