FFmpeg Rejects an Odd Frame Size: Pad the Canvas Before H.264 Encoding
Reproduce the libx264 odd-width error, pad a 161 by 91 frame before yuv420p conversion, and inspect the resulting H.264 video.

FFmpeg printed `width not divisible by 2 (161×91)` while opening libx264. The command had asked for H.264 video with the `yuv420p` pixel format. It returned a nonzero status, and the file it left at the output path was empty. The odd-sized source was a one-second test pattern. We had no real footage, bitrate target, audio stream, or delivery service to account for while reproducing the failure.
We kept the source and encoding options the same and inserted a filter that made the canvas 162 by 92. That export succeeded. The probe reported H.264, `yuv420p`, and 12 video frames at the new dimensions. Padding is useful here because it can allocate the additional column and row without first shrinking or stretching the pattern. The encoding that follows has its own effect on pixels, so this experiment checks the geometry and the frame count separately from image fidelity.
Find the error that identifies the failing stage
Read the first diagnostic that describes what failed. In the retained run, the message names libx264 and the width, then gives both dimensions. Later lines say that the encoder could not open and that the output did not receive packets. Those are consequences you would expect from the initialization failure. The width message supplies the more specific question. What size arrived at the encoder under this preset?
The experiment records the nonzero exit status and checks for the substring `not divisible by 2`. It does not hard-code the number returned on Windows. If the executable were missing, the script would not have the required tool. If the encoder were unavailable in a different FFmpeg build, the command could fail for that reason instead. The nonzero status alone would not reproduce this example. Matching a useful diagnostic makes the reproduction about the error you actually want to investigate.
Look for dimensions after upstream edits as well as in the original file. A source file with even dimensions might be cropped to an odd rectangle before encoding. The original dimensions in a media inventory would then give you the wrong target for diagnosis. Write down what the filter chain receives and what it sends to the encoder. A synthetic test can start directly at the size that fails. When working on an application, a second test can go through the crop, resize, or other feature that produced that size.
The pad filter allocates an output canvas and places the input at selected coordinates. FFmpeg filter documentation
The selected format is relevant because the encoder is dealing with a subsampled chroma representation. In `yuv420p`, neighboring luma positions share chroma samples across two dimensions. The tested libx264 setup imposes an even-dimension rule for this input. An odd-sized RGB pattern is still valid source material. Its failure here is specific to the encoding path we selected. Do not infer from the message that every possible H.264 encoder, pixel format, or container must reject every odd frame.
Reproduce the failure without substituting a new input
The script uses FFmpeg's `lavfi` input and a `testsrc` description with size `161×91`, rate `12`, and duration `1`. A local generator supplies the input for both runs. The command does not first export or resize a file, so there is no additional operation to explain how the input became odd. If you substitute an existing asset, retain a copy of it and inspect the stream before comparing the result. The evidence in this article comes from the generated pattern.
Run the script with a fresh output directory. It finds `ffmpeg` and `ffprobe` on the path, captures their output, and checks the return status. The command uses `-n` so an existing output file is not overwritten. The script also creates the directory itself and expects it to be new. Give a repeat run a different directory. That way a probe cannot accidentally read the successful output from an earlier attempt, and you can compare the receipts after changing a parameter.
The first command uses `-c:v libx264` and `-pix_fmt yuv420p` with the odd source and writes to `odd.mp4`. Do not use the existence of that path as proof the experiment succeeded. A zero-byte file is one possible consequence of this particular failed run. A production wrapper should decide what counts as an accepted export and publish a file only after checking those conditions. For this diagnostic, leave the baseline file and error log in the experiment directory so the failure is inspectable.
The second command keeps the same generator, codec, and requested output pixel format. It adds `-vf` with the exact filter string shown in the code and uses `padded.mp4` as the output name. Holding the encoder options fixed is useful because you could also get a different outcome by changing the output format. That would answer a different question. Here the target remained `yuv420p`, and the deliberate change was the input presented to the encoding stage.
Choose where the extra column and row will go
The filter expression is `format=rgb24,pad=162:92:0:0:black`. Read it as two operations. First select an RGB representation for the padding operation. Then allocate the target canvas and put the source at the given horizontal and vertical offsets. The final command still asks the encoder for a `yuv420p` stream. The RGB selection describes the intermediate filter step, while the pixel format reported by ffprobe describes the encoded result.
In this case the placement is at x = 0 and y = 0. The original image occupies the top-left 161 by 91 rectangle of the padded canvas. There is one additional column at the right and one additional row at the bottom, including the new bottom-right corner. Black is the fill value specified to the filter. This describes the geometry before encoding. The test does not compare RGB values at the border after lossy H.264 encoding.
Keeping the origin fixed matters if another part of the project records positions against the source image. A point labeled at coordinate x = 20, y = 30 has the same coordinate in the padded layout before encoding. If you put the extra column on the left instead, the point would move horizontally by one pixel. For a drawing over a video or a crop record tied to pixels, that difference can matter. Decide the anchor before deriving or reusing the coordinates.
A one-pixel addition cannot be split evenly across opposing edges on an integer pixel grid. If the surrounding project asks for symmetric margins, consider whether it can accept a larger even canvas or has a defined rounding convention. For example, an export template might reserve a border on both sides that is wider than the minimum needed for encoding. That choice should come from the layout requirement. The fixture only tests the minimum extension of these two odd dimensions with a fixed top-left origin.
Some export specifications describe an exact display proportion rather than just even storage dimensions. Padding changes the width and height of the stored frame. A crop, scaling rule, or display metadata can change what a viewer sees. If a delivery rule names exact dimensions or display aspect ratio, verify that rule separately. The 162 by 92 fixture proves acceptance of the even canvas by the selected encoder. It is not a claim about an approved broadcast or platform preset.
odd_frame.py
"""Reproduce and repair odd frame dimensions in one local libx264 export."""
import json
from pathlib import Path
import shutil
import subprocess
import sys
def run(tool, args, root):
return subprocess.run([tool, *args], cwd=root, capture_output=True, text=True,
encoding='utf-8', timeout=40)
def checked(result):
result.check_returncode()
return result.stdout
def experiment(root):
root = Path(root).resolve()
ffmpeg, ffprobe = (shutil.which(name) for name in ('ffmpeg', 'ffprobe'))
if not ffmpeg or not ffprobe:
raise RuntimeError('Install ffmpeg and ffprobe first')
root.mkdir()
options = ['-nostdin', '-hide_banner', '-v', 'error', '-n']
source = ['-f', 'lavfi', '-i', 'testsrc=size=161x91:rate=12:duration=1']
encoding = ['-c:v', 'libx264', '-pix_fmt', 'yuv420p']
failed = run(ffmpeg, [*options, *source, *encoding, 'odd.mp4'], root)
assert failed.returncode != 0 and 'not divisible by 2' in failed.stderr, failed.stderr
checked(run(ffmpeg, [*options, *source, '-vf', 'format=rgb24,pad=162:92:0:0:black',
*encoding, 'padded.mp4'], root))
data = json.loads(checked(run(ffprobe, ['-v', 'error', '-select_streams', 'v:0', '-count_frames',
'-show_entries', 'stream=codec_name,width,height,pix_fmt,nb_read_frames',
'-of', 'json', 'padded.mp4'], root)))['streams'][0]
assert data == {'codec_name': 'h264', 'width': 162, 'height': 92, 'pix_fmt': 'yuv420p', 'nb_read_frames': '12'}, data
report = {'failed_returncode': failed.returncode, 'failed_stderr': failed.stderr,
'fixed': data, 'ffmpeg': checked(run(ffmpeg, ['-version'], root)).splitlines()[0]}
(root / 'probe.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
return report
if __name__ == '__main__':
print(json.dumps(experiment(sys.argv[1]), indent=2))
Recorded local check: Two explicit compound assertion checks in the original script. On FFmpeg build 2026-01-26-git-fe0813d6e2 Windows, lavfi testsrc is 161×91 at12fps for1s; libx264 with yuv420p fails nonzero, stderr specifically width not divisible by2; odd.mp4 is zero bytes in this run. Corrected filter format=rgb24,pad=162:92:0:0:black, same libx264/yuv420p yields H.264 162×92 and ffprobe counts12. The 0:0 placement extends right and bottom before encoding; no decoded pixel equality, audio, quality, viewing, codec generalization or height-only error test. RGB first is a chosen filter order, not a universal requirement. Report actual error text, not a universal return code.; environment: Python 3.12.3 Windows; ffmpeg version 2026-01-26-git-fe0813d6e2-full_build-www.gyan.dev
Verify what the exported file contains
The probe reads the first video stream from `padded.mp4` using `-select_streams v:0`. The script asks for the codec name, width, height, pixel format, and counted frames. Those fields have concrete expected values. The codec name is `h264`, the width and height are 162 and 92, the pixel format is `yuv420p`, and `nb_read_frames` is reported as the string `"12"`. The assertion compares the complete dictionary so a different pixel format would fail even if the dimensions matched.
Counting frames serves a different purpose from reading the canvas dimensions. An output with the correct width and height can still contain fewer frames than you expect. Here the test pattern asks for 12 frames per second for one second, and the successful output yields 12 counted frames. The small test checks count, rather than comparing timestamps or decoding each frame to a reference pixel array. If timing or frame identity matters in an adapted project, use an additional measurement that addresses that requirement directly.
The separate guide to checking what actually made it into an FFmpeg export deals with audio duration. The useful connection is to measure the output rather than treating an exit status as a complete delivery check. This experiment creates a picture source without an audio stream. To adapt the check to a clip with sound, identify which streams should be present and what needs to be preserved about each. A successful geometry fix should not be credited with preserving audio that was never present in the test.
The JSON report retains the exact encoder version line. The fixture ran in Python 3.12.3 on Windows with FFmpeg build `2026-01-26-git-fe0813d6e2`. The test date was November 10, 2026. Record the build separately from the test date. A package name alone does not establish which encoders or filters it exposes, and a build date does not tell a reviewer when you ran the experiment. When repeating it elsewhere, retain both facts and describe any differences in the observed result.
Compare padding with a change to the picture
Padding leaves the source rectangle inside a larger frame at the filter step. It is a useful choice when the edge of the original contains information that should remain in the picture and a narrow border is allowed. A screenshot or a diagram might have a label flush with the right edge. Cropping a column to make the width even could touch that label. Choosing the pad deliberately keeps the rectangle available before the encoder applies its own representation.
Cropping would move in the other direction. With the same 161 by 91 input, an application could choose a 160 by 90 rectangle if it has permission to discard one column and one row. That is a design option, not an output produced by this experiment. A crop can be appropriate when the removed edge is already an unwanted border. To adopt it, specify which rectangle is retained and test a source with meaningful content near the boundary. A width check alone cannot tell you whether the chosen crop preserved the intended details.
Scaling defines another output contract. Resampling to a target size can make sense when the project already needs a resized picture. In that case choose the size and aspect policy together rather than stretching the width and height independently to any convenient even numbers. A proposal could test a pattern with known geometry to check what happened to its proportions. The pad fixture does not compare interpolation methods or claim that scaling would look worse. It simply makes a chosen allocation without first resizing the pattern.
If your caller handles several input sizes, calculate the target dimensions from the policy once. The next even integer for a positive dimension is the dimension itself if it is even and one greater if it is odd. The supplied code uses explicit 162 and 92 to keep the reproduction narrow. A generalized helper could calculate both values and then select padding coordinates consistent with the anchor. Test an already even input, an odd width, an odd height, and two odd dimensions before adopting that helper. The original run covers only the last combination and reports the width error.
Preserve the boundary when integrating the fix
An application that receives sizes from several sources can log three values during a controlled run. Record the source frame dimensions, the geometry immediately before encoding, and the encoded stream dimensions. The source tells you what came in, the filter report tells you what the command tried to hand off, and the stream tells you what was produced. They can legitimately differ. The goal is to make each difference traceable to an operation whose behavior the project has chosen.
If a pipeline creates several variants from the same asset, put the padding rule where the export preset can actually use it. A preview might accept the unpadded RGB dimensions while the H.264 path requires the geometry adjustment. Applying the rule to a single unrelated preview function would not fix the failing export. Add a project-level test through the normal export entry point when you can. The small fixture demonstrates a working command. It does not verify the behavior of another application that wraps it.
Keep output acceptance distinct from successful process creation. A wrapper can first require a zero exit code, then inspect the expected stream and any relevant artifact properties. If an export fails, preserve the useful diagnostic and keep the incomplete result out of the path used by later consumers. The experiment keeps its empty baseline under a clearly separate name. A real project can decide whether to retain failed artifacts for debugging and where they may be stored. This distinction is especially useful when automatic upload or handoff jobs watch a directory.
If you need to investigate a project that pads unexpectedly, check whether the preset applies the same rule to already even inputs. A helper that always adds one changes an even dimension into an odd one and recreates the problem. A helper that rounds to a multiple other than two may be serving a different format or layout. Write the requirement in terms of the target and use input cases that distinguish it from simpler-looking formulas. In this fixture the expected output is explicit, so the probe can catch a wrong dimension without guessing which rule produced it.
Build a regression that explains its own result
The original script contains two compound assertions. The first expects a failure with the specific divisibility diagnostic. The second expects the exact stream facts from the repaired file. The pair helps separate a missing or broken encoder from a working geometry fix. If the baseline begins to succeed after a tool change, inspect the actual stream and the changed preset before treating that as a regression in your application. It may mean that a different output format was selected or that the build behaves differently.
Run both commands with the same input description. Record the full filter string rather than a paraphrase such as “make even.” This allows someone else to see that the source starts at 0,0, that the selected intermediate format is RGB, and that the fill was set to black. If a project later adds centering, scaling, or a larger target, update the expected stream result and test the placement using an appropriate visual or pixel measurement. Keep a copy of the earlier evidence so reviewers know which command produced which result.
Inspect an output using the tool that can answer the question you have. The probe can verify encoded dimensions and counted frames. A visual review of a real project export could examine whether the edge is visible and whether the desired crop is still recognizable. A separate comparison could check recorded timestamps if audio and video have to align. Each measurement belongs to its own check. The current evidence gives a narrow reproducible answer about one encoder error and the resulting even-sized stream.
Before shipping an adapted preset, compare the exact requirement with the accepted output. A destination that requires a particular frame size may reject a file that is merely even. A project using annotations may also require the source origin to remain fixed. Treat those as conditions alongside the codec and pixel format rather than assuming that all requirements follow from a successful process exit. The local command and report give you a starting point for testing those choices with a fixture that fails in a recognizable way.
Check a change in geometry before comparing playback
Suppose you receive an export request for a slide with a chart against the right border. A useful placement test would put a known marker at the edge of a small pattern, perform the padding operation, and inspect the marker in a representation chosen for geometry checking. That can distinguish padding at the right from a crop or from padding at the left. Comparing an encoded pixel exactly to its source is a different test, particularly when the encoder is lossy. Choose the representation and matching tolerance before stating which pixel property the regression protects. The original fixture uses probe fields, so it establishes the canvas change rather than the survival of a particular pixel value.
If an export will be opened in two applications, verify the delivery requirement in the one that matters before describing a playback result. The same 162 by 92 frame could be displayed in a scaled preview or placed into a larger viewer rectangle. A report about width and height from ffprobe does not determine the appearance of either viewer. If the intended destination shows a border that the project must conceal, you can evaluate a different pad color or a different geometry operation. Keep that work separate from the initial diagnosis so a display adjustment does not obscure whether libx264 accepted the corrected dimensions.
There is also a difference between a frame that is even at the beginning of a pipeline and a frame that is even after all output filters. If a later step trims a border, the final width can become odd again. If a later step introduces a precise display size, the minimally padded size may cease to be the delivery size. Trace the sequence in the order it is evaluated. In the fixture, the padding is the last geometry operation before encoding, so the dimensions measured on the output can be tied directly to the fixed canvas.
For an operator-facing check, keep the diagnostic connected to the original command. A log might say that the expected stream was H.264 at a specified width, height, and format but that the process ended before the probe could inspect any video. That message gives the next person somewhere to look. A bare “invalid export” loses the distinction between a missing frame, an incompatible format, and an encoder initialization error. The retained baseline and corrected report show how to keep both sides of that comparison with a repeatable source.
Prepared with AI assistance and automated review. The original fixture was run locally. The lead photograph illustrates the subject.



