The H.264 encoders on phones take 8-bit input. Feed one the samples of an HDR10 film as they are and it encodes them as if they were SDR, so the colours come out wrong: the 10-bit values were never meant to be read that way. When Yonto Player on Android has to re-encode a picture for a cast, an HDR frame is therefore brought to SDR BT.709 first, and that step is a small routine in plain C.
When a phone re-encodes at all
A cast does not always touch the picture. A file the receiver can decode is repackaged as it is, and from a Jellyfin, Emby or Plex server the server is asked to convert. The casting page lists the cases. The one that matters here is on Android: a picture the receiver cannot decode, or one larger than it takes, is converted on the phone as it plays. The target is H.264, and for HDR10 or HLG the page says the picture is tone-mapped to SDR, which is what a Chromecast shows.
The path has three parts. libVLC decodes the title, the routine in this post maps the frame when it is HDR, and the device's own H.264 encoder (a hardware one before a software one, when it has both) takes the result. libVLC only decodes here, and the app ships no video encoder of its own.
Getting raw frames out of a player
The Java MediaPlayer in the libVLC build the app carries does not expose the C API's video callbacks, which are what you want for "give me each picture". core/vlcpipe is a small JNI shim that looks those functions up with dlopen and dlsym in the libvlc.so the app already carries, so libVLC is not rebuilt for it. It sets a lock, a display and a format callback, plays at the pace of the title, and hands Kotlin a direct byte buffer inside the display callback.
The format callback is where HDR matters. For an SDR title the shim asks for I420, 8 bits a sample. For an HDR title it asks for I0AL, 4:2:0 with 10 bits in each sample, stored in two bytes.
Which titles take that path is decided in common Kotlin, from what the file's headers say about its colour:
// Simplified sketch of the rule, not the real file. data class ToneMapping(val hlg: Boolean, val bt2020: Boolean) fun toneMappingFor(colour: VideoColour): ToneMapping? { if (colour.transfer == Transfer.SDR) return null // left as it is return ToneMapping( hlg = colour.transfer == Transfer.HLG, // else PQ bt2020 = colour.primaries != Primaries.BT709, // unspecified counts as BT.2020 ) } Null means "do not touch it", and the shim is asked for the 8-bit picture.
What the mapping does to a pixel
tonemap.c turns a 10-bit, limited-range picture in BT.2020 (PQ or HLG) into an 8-bit, limited-range BT.709 one. It assumes a 1000-nit master, since it does not read mastering metadata. For each pixel it does this, in order:
- Undo the transfer function. Y'CbCr becomes R'G'B' codes, and each code becomes linear light through the PQ curve or the HLG one.
- For HLG, apply its system gain. HLG describes scene light, so a display adjustment for a 1000-nit screen (a system gamma of 1.2) comes first.
- Compress the brightness. One gain is worked out from the pixel's brightest channel with the BT.2390 roll-off, and all three channels are multiplied by it. The roll-off targets a peak of 203 nits, the SDR white level of BT.2408.
- Change primaries. For a BT.2020 source, a 3x3 matrix from BT.2087 takes the linear colour to BT.709 primaries. Colours outside the BT.709 gamut are clipped; there is no gamut compression.
- Code the result. Each linear value is encoded with a 2.4 power curve, a display-referred choice, and the stream is tagged BT.709. The R'G'B' values are then converted to limited-range BT.709 Y'CbCr, with the chroma averaged over each 2x2 block.
A simplified sketch of one pixel:
/* Simplified sketch, not the real file. */ static void pixel(int y, float cb, float cr, int hlg, int bt2020, float out[3]) { int code[3]; float lin[3]; ycbcr_to_codes(y, cb, cr, code); /* BT.2020 matrix */ for (int c = 0; c < 3; c++) lin[c] = hlg ? hlg_to_scene[code[c]] : pq_to_linear[code[c]]; if (hlg) scale(lin, hlg_system_gain(luma_of(lin))); /* scene -> display light */ scale(lin, tone_gain[brightest(lin)]); /* one gain keeps hue */ if (bt2020) bt2020_to_bt709(lin); /* 3x3, linear light */ for (int c = 0; c < 3; c++) out[c] = sdr_code(lin[c]); /* 2.4 power curve */ /* the caller turns out[] into BT.709 Y'CbCr, chroma averaged per 2x2 block */ } Two choices in it are worth explaining.
One gain per pixel, from its brightest channel. The routine's own comment says this is so hues hold. That applies to this gain step only; the clipping in step 4 is separate. If each channel were compressed on its own, the ratio between them would change as the brightest one runs into the limit, and a saturated colour would drift towards grey. One gain applied to all three keeps the ratio.
The curve. The BT.2390 roll-off leaves everything below a knee untouched and bends the part above it along a cubic Hermite spline until it lands on the SDR maximum:
/* Simplified sketch of the roll-off, in PQ-encoded, normalised units. */ float rolloff(float e1, float max_lum) { /* e1 in [0, 1] */ float ks = 1.5f * max_lum - 0.5f; /* the knee */ if (e1 <= ks) return e1; /* below it: unchanged */ float t = (e1 - ks) / (1 - ks), t2 = t * t, t3 = t2 * t; return (2*t3 - 3*t2 + 1) * ks + (t3 - 2*t2 + t) * (1 - ks) + (-2*t3 + 3*t2) * max_lum; } Keeping it cheap
pow and exp per pixel would be a lot of work for every pixel of every frame, so none runs in the pixel loop.
- Lookup tables, built once. Two linearisation tables (PQ and HLG) and three gain tables are 4,096 entries each, filled the first time the routine runs (
pthread_once). The PQ tone gain is indexed by the PQ code; the HLG system gain and the HLG tone gain are indexed by the square root of the light, which gives the shadows more entries. - An output table indexed by a float's bits. The SDR coding table is indexed by the float's exponent and its top ten mantissa bits. That spaces entries by ratio rather than by step, across sixteen octaves of light, with no
logand no division. - Chroma once per 2x2 block. The picture is 4:2:0, so one chroma sample covers a 2x2 block. The routine computes the four R'G'B' values, writes four luma bytes, and averages the four for the one Cb and Cr.
- Bands across cores. The picture is cut into horizontal bands of whole pairs of rows, up to eight, one per online core, with the calling thread taking the first.
On the Kotlin side the mapped picture is written into a buffer the app owns, and only then copied into the encoder's input image. A comment in the code notes that writing the encoder's own memory a byte at a time is many times slower.
Checking it
The JNI function accepts only direct buffers, checks that both are as large as the width, height and pitch it was given say, requires an even size of at least 2, and returns false otherwise. The Kotlin side treats false as a failed encode.
The rule that decides which titles are mapped is plain Kotlin with unit tests: PQ in BT.2020, HLG with its own curve, unspecified primaries taken as BT.2020, PQ already in BT.709 not converted again, and SDR of any bit depth left alone.
What I would take from it
- Convert once, at the boundary, to the format the next stage understands, and tell that stage what it is getting. Here the encoder is told BT.709, SDR, limited range.
- Tables beat math in an inner loop, and a float's bit pattern makes a good index.
- Keep native code small and checked at its entrance.
