- Blog
- Engineering
- Picking a good video poster without machine learning
Picking a good video poster without machine learning
How Chunkify chooses a sharp, representative poster frame with FFmpeg and a few image measurements, and what it costs on large files.
By the Chunkify team
A poster is the image people see before they press play. It sits in your video list, in link previews, and in the player before the first frame loads. A good one makes a video look worth watching. A bad one, such as a blurred transition or a black frame, makes it look broken.
Until recently, Chunkify took the poster from about 10 seconds into the video and only checked that the frame was not black. That works for many videos, but it often lands on an intro, a logo, or a camera move. Here is one of ours:
The first frame was taken during a zoom, so everything is smeared. The second comes from the same video six seconds later. This article explains how we now pick the right one automatically, without a trained model, and what it costs on large files.
How others approach it
Large consumer platforms have invested heavily in this. In 2015, YouTube described a thumbnailer that samples about one frame per second and scores each frame with a neural network trained on creators' custom thumbnails. Netflix built AVA, which annotates frames with brightness, contrast, blur, faces, and composition to help its designers find artwork.
You don't always need a model, though. In 2016, Yahoo Research published a study of 1,118 videos comparing the frames professional editors chose as thumbnails with the frames they didn't. Good thumbnails correlated strongly with objective quality measures such as texture and sharpness. Their system ranks frames with visual quality metrics and uses clustering to keep the choice representative, and its code is open source as Hecate.
We wanted something in that spirit: better than a fixed position, cheap enough to run on every upload, and simple enough to explain. Most of what makes a frame a bad poster can be measured directly. Is it blurred? Is it empty? Is it too dark or washed out?
Where to look
We pick 8 positions spread evenly between 10% and 60% of the duration.
The start of a video is often an intro, a logo, or a fade from black. The end often shows a result, a conclusion, or credits, which can spoil the video or simply say little about it. The middle stretch is where the subject usually is.
If every candidate in that range is black, which happens with dark or slow-starting videos, we try 4 more positions between 60% and 90%. If we don't know the duration, we use the first keyframe.
Reading one frame cheaply
Decoding a frame at an exact time can be expensive. Video is compressed in groups of pictures: one keyframe that can be decoded on its own, followed by frames that only store differences. To show the frame at 16.6 seconds, a decoder normally starts at the previous keyframe and decodes every frame up to the target. With a keyframe every 10 seconds on a high-bitrate file, that can mean reading tens of megabytes for one image.
A poster doesn't need the exact frame, so we take the keyframe at or before each position and decode only that:
ffmpeg -copyts -start_at_zero \
-skip_frame nokey -noaccurate_seek -ss 16.6 \
-i "https://example.com/video.mp4" \
-map 0:v:0 -vf "scale='min(1920,iw)':-2" \
-frames:v 1 -q:v 2 -update 1 candidate.jpg
-ssbefore-iseeks in the input using the container's index, so FFmpeg requests only the bytes around that position. Over HTTP, that's a range request rather than a download.-noaccurate_seekkeeps the keyframe FFmpeg lands on, instead of decoding forward to the exact time.-skip_frame nokeytells the decoder to ignore every frame that isn't a keyframe.-frames:v 1stops after one image.
-copyts -start_at_zero matters more than it looks. Without it, FFmpeg shifts timestamps so that the seek position becomes zero, and the keyframe before that position gets a negative timestamp. The output then discards it and waits for the next keyframe, which can be a whole group of pictures later. On our test file, which has a keyframe every 10 seconds, removing those two flags increased the data read for one candidate from about 3 MB to 28 MB.
In production, we also add FFmpeg's showinfo filter to the chain to read the frame's actual timestamp, so the poster reports the time it really came from.
Scoring a frame
We compute five measurements, each between 0 and 1: sharpness, detail, contrast, exposure, and colorfulness. Each one is a short Go function, using only the standard library and golang.org/x/image/draw. In production, we compute them in two passes over the pixels; here they are split so each one reads on its own.
Each candidate is resized to 480 pixels wide, so a sharp 4K frame and a sharp 720p frame score about the same, and most measurements then work on its brightness (luma):
// brightness returns each pixel's luma, from 0 to 255, row by row.
func brightness(img *image.RGBA) []float64 {
b := img.Bounds()
lum := make([]float64, 0, b.Dx()*b.Dy())
for y := 0; y < b.Dy(); y++ {
for x := 0; x < b.Dx(); x++ {
i := img.PixOffset(x, y)
r, g, bl := float64(img.Pix[i]), float64(img.Pix[i+1]), float64(img.Pix[i+2])
lum = append(lum, 0.299*r+0.587*g+0.114*bl)
}
}
return lum
}
Sharpness
Sharpness does most of the work. The Laplacian measures how much each pixel differs from its four neighbors. Sharp edges give large values in both directions, and blur smooths them away, so their variance is a long-standing, simple blur measure:
// sharpness is the variance of the Laplacian, mapped to 0-1.
func sharpness(lum []float64, width, height int) float64 {
var sum, squares float64
n := 0
for y := 1; y < height-1; y++ {
for x := 1; x < width-1; x++ {
v := lum[(y-1)*width+x] + lum[(y+1)*width+x] +
lum[y*width+x-1] + lum[y*width+x+1] - 4*lum[y*width+x]
sum += v
squares += v * v
n++
}
}
if n == 0 {
return 0
}
mean := sum / float64(n)
variance := squares/float64(n) - mean*mean
return variance / (variance + 100)
}
variance / (variance + 100) turns an unbounded number into a value between 0 and 1. On test frames, a sharp image scores 0.86, a slight blur 0.15, and a heavy blur 0.02.
Detail
Title cards and flat color have almost no edges. Detail counts the pixels where brightness changes sharply, and treats 8% of the frame or more as full detail:
// detail is the share of pixels on a clear edge, mapped to 0-1.
func detail(lum []float64, width, height int) float64 {
edges, n := 0, 0
for y := 1; y < height-1; y++ {
for x := 1; x < width-1; x++ {
dx := lum[y*width+x+1] - lum[y*width+x-1]
dy := lum[(y+1)*width+x] - lum[(y-1)*width+x]
if math.Hypot(dx, dy) > 24 {
edges++
}
n++
}
}
if n == 0 {
return 0
}
return min(1, float64(edges)/float64(n)/0.08)
}
Contrast, exposure, and black pixels
Contrast compares the darkest and brightest 5% of pixels. Using percentiles rather than the minimum and maximum ignores a few stray pixels. Exposure is 1 at mid-gray and falls to 0 for pure black or pure white:
// contrast is the spread between the 5th and 95th brightness
// percentiles; half the range or more counts as full contrast.
func contrast(lum []float64) float64 {
var histogram [256]int
for _, l := range lum {
histogram[int(l)]++
}
spread := percentile(histogram, len(lum), 0.95) -
percentile(histogram, len(lum), 0.05)
return min(1, spread/128)
}
// percentile walks the histogram until it has seen fraction of the pixels.
func percentile(histogram [256]int, pixels int, fraction float64) float64 {
seen := 0
for value, count := range histogram {
seen += count
if float64(seen) >= fraction*float64(pixels) {
return float64(value)
}
}
return 255
}
// exposure is 1 at mid-gray (120) and 0 at pure black or white.
func exposure(lum []float64) float64 {
sum := 0.0
for _, l := range lum {
sum += l
}
mean := sum / float64(len(lum))
return max(0, 1-math.Abs(mean-120)/120)
}
// blackPercent counts pixels at or below FFmpeg's blackframe threshold.
func blackPercent(lum []float64) float64 {
black := 0
for _, l := range lum {
if l <= 32 {
black++
}
}
return 100 * float64(black) / float64(len(lum))
}
Colorfulness
Colorfulness averages each pixel's saturation, and treats an average of 0.35 or more as fully colorful:
// colorfulness is the average saturation, mapped to 0-1.
func colorfulness(img *image.RGBA) float64 {
b := img.Bounds()
sum := 0.0
for y := 0; y < b.Dy(); y++ {
for x := 0; x < b.Dx(); x++ {
i := img.PixOffset(x, y)
r, g, bl := float64(img.Pix[i]), float64(img.Pix[i+1]), float64(img.Pix[i+2])
if high := max(r, g, bl); high > 0 {
sum += (high - min(r, g, bl)) / high
}
}
}
return min(1, sum/float64(b.Dx()*b.Dy())/0.35)
}
Combining them
The score weights the measurements, favoring sharpness and detail, then applies two adjustments:
// score rates a frame taken at the given time, in seconds,
// from a video of the given duration.
func score(frame image.Image, at, duration float64) float64 {
// Resize to 480 pixels wide, keeping the aspect ratio.
b := frame.Bounds()
w := min(480, b.Dx())
h := max(1, int(math.Round(float64(b.Dy())*float64(w)/float64(b.Dx()))))
img := image.NewRGBA(image.Rect(0, 0, w, h))
draw.ApproxBiLinear.Scale(img, img.Bounds(), frame, b, draw.Src, nil)
lum := brightness(img)
s := 0.35*sharpness(lum, w, h) + 0.20*detail(lum, w, h) +
0.15*contrast(lum) + 0.15*exposure(lum) + 0.15*colorfulness(img)
// Fade out frames that are almost entirely black.
s *= min(1, max(0, (99.5-blackPercent(lum))/9.5))
// Prefer earlier frames when two candidates are otherwise similar.
if duration > 0 {
s -= 0.05 * at / duration
}
return s
}
The black adjustment has no effect up to 90% black pixels and removes the whole score at 99.5%. Dark interfaces and night scenes keep their score as long as they show something; fades and empty frames don't.
Every constant here was chosen by hand on test frames and real recordings, so treat them as a starting point for your own videos.
Putting it together
With the FFmpeg command and the score, picking a poster is a short loop: compute the 8 positions, read the keyframe at each one, score it, and keep the best.
// bestPoster returns the highest-scoring keyframe between 10% and
// 60% of the video, as a JPEG.
func bestPoster(input string, duration float64) ([]byte, error) {
var best []byte
bestScore := math.Inf(-1)
for i := range 8 {
at := duration * (0.10 + 0.50*(float64(i)+0.5)/8)
frame, err := keyframe(input, at)
if err != nil {
continue
}
img, err := jpeg.Decode(bytes.NewReader(frame))
if err != nil {
continue
}
if s := score(img, at, duration); s > bestScore {
best, bestScore = frame, s
}
}
if best == nil {
return nil, errors.New("no usable frame")
}
return best, nil
}
// keyframe returns the keyframe at or before the given time as a JPEG.
func keyframe(input string, at float64) ([]byte, error) {
return exec.Command("ffmpeg", "-v", "error",
"-copyts", "-start_at_zero",
"-skip_frame", "nokey", "-noaccurate_seek",
"-ss", strconv.FormatFloat(at, 'f', 3, 64),
"-i", input, "-map", "0:v:0",
"-vf", "scale='min(1920,iw)':-2",
"-frames:v", "1", "-q:v", "2",
"-c:v", "mjpeg", "-f", "image2pipe", "-",
).Output()
}
Together with the functions above, this is a complete poster picker. Production adds a few things around it: two candidates read in parallel, a time limit for each candidate, the extra positions for dark videos, the keyframe's exact timestamp instead of the target time, and a fallback for streams that don't mark their keyframes.
Here are the 8 candidates from the recording above, with their scores:
The coastline frame wins clearly. The terminal and chart frames are sharp but dark and mostly empty, so they rank lower. The nearly empty frames score close to zero. The blurred poster we used to pick scores 0.01.
What didn't work
Penalizing dark pixels. Our first version multiplied the score by the share of non-black pixels. That ruined dark interfaces: a sharp terminal window on a black background is 95% black and dropped to a score of about zero, the same as an empty frame. A video made entirely of dark UI would then have been ranked almost at random. Penalizing only frames that are nearly empty fixed this while still rejecting fades.
FFmpeg's entropy filter as a detail measure. It measures how spread out the brightness histogram is, not how much detail the image has. Blurring a frame spreads the histogram, so entropy increased with blur. Edge density measures detail directly.
Benchmarking over localhost. Our first measurements counted the bytes the test server wrote. Over localhost, the server fills socket buffers at about a gigabyte per second until FFmpeg closes the connection, so the count reflected time, not what FFmpeg needed. Throttling the test server to 50 MB/s, close to a single cloud storage stream, gave realistic numbers.
Cost on large files
Picking from 8 candidates costs more than reading one frame. Each read spends most of its time waiting on the network, so we read two candidates in parallel, each with its own single-threaded FFmpeg process. That halves the time without reading any more data.
To check the cost stays reasonable, we used a 2.25 GB, 15-minute 1080p file at 20 Mbps with a keyframe every 10 seconds. We served it over HTTP at 50 MB/s per connection, with 30 ms before the first byte, close to a single cloud storage stream:
| File layout | 8 candidates, 2 in parallel | 1 frame (previous method) |
|---|---|---|
| MP4, index at the start | 26 MB, 0.85 s | 3.5 MB, 0.23 s |
| MP4, index at the end | 32 MB, 1.1 s | 4.3 MB, 0.31 s |
| MPEG-TS | 227 MB, 4.8 s | 15 MB, 0.82 s |
For MP4, each candidate reads about 3–4 MB, the index plus one keyframe, wherever it is in the file. A 10 GB file costs about the same as a 1 GB file. MPEG-TS has no index, so FFmpeg searches for each position by timestamp, which takes more requests and more data, but still finishes in seconds.
Two safeguards keep worst cases bounded. Each candidate has its own time limit; if one runs out, usually because the input can't seek efficiently, sampling stops and keeps the best frame already read. And if a stream doesn't mark its keyframes, we fall back to decoding one frame normally.
Limits
This is a heuristic, not a model of what people find appealing:
- The weights were tuned by hand on synthetic test frames and real recordings, not on a large labeled set.
- Film grain and heavy noise look like sharp detail to the Laplacian.
- There is no face or subject detection, which is what learned systems rely on most.
- The 10%–60% range is a default that suits most videos, not a rule about every one.
For most uploads, avoiding blurred, empty, and badly exposed frames is enough to make the poster look intentional, and it costs a few megabytes and about a second per video.

