pub struct H264EncoderWrapper {
pub width: i32,
pub height: i32,
pub is_i444: bool,
pub bit_depth: u32,
/* private fields */
}Expand description
One long-lived libx264 session for a stripe, holding the raw x264_t handle alongside a
mirror of its live parameters so the encoder can be retuned per frame instead of rebuilt.
Rebuilding an x264 encoder is expensive and forces a fresh IDR, so a stripe keeps its instance
across frames and only nudges CRF, bitrate, VBV, and frame rate live; the tracked current_*
fields are that mirror, letting a reconfigure skip the FFI call whenever nothing actually changed.
is_i444 (4:4:4 vs 4:2:0) is baked into the encoder’s color space at open, so a change to it is
one of the few things that forces a full rebuild; is_cbr records which rate-control mode was
chosen at open and gates which of the live reconfigures apply. The manual Send impl exists only
because a raw pointer is not Send by default and the handle must move onto the rayon stripe
workers; Drop closes it under the global open/close lock for the same reason that lock exists.
Fields§
§width: i32§height: i32§is_i444: bool§bit_depth: u32The bits per sample the session was opened at, baked in as the chroma format is.
Implementations§
Source§impl H264EncoderWrapper
impl H264EncoderWrapper
Sourcepub fn new(
width: i32,
height: i32,
crf: i32,
is_i444: bool,
fps: f64,
threads: i32,
cbr_mode: bool,
bitrate_kbps: i32,
vbv_kbit: i32,
min_qp: i32,
max_qp: i32,
) -> Option<Self>
pub fn new( width: i32, height: i32, crf: i32, is_i444: bool, fps: f64, threads: i32, cbr_mode: bool, bitrate_kbps: i32, vbv_kbit: i32, min_qp: i32, max_qp: i32, ) -> Option<Self>
Open an x264 encoder tuned for real-time screen streaming, or None on failure.
Why this configuration. These frames are captured live and must ship immediately, so the
encoder is optimized for latency over compression ratio: the ultrafast preset keeps encode
time under the frame budget, and zerolatency bars the frame reordering and lookahead
buffering that would otherwise add pipeline delay. Everything below then bends x264 toward the
pipeline’s own keyframe and color model instead of its broadcast-oriented defaults.
- Preset/tune: starts from the
ultrafastpreset with thezerolatencytune, then overrides resolution, frame rate (floored to 30 fps when under 1), and thread count. - Infinite GOP:
i_keyint_maxis set to x264’s infinite sentinel and adaptive scene-cut is disabled (i_scenecut_threshold = 0), so the encoder never injects an unrequested IDR on a scene change — keyframes are purely on-demand via the forced-IDR path, matching the strict infinite-GOP model. - Rate control:
- CBR (
cbr_mode): ABR targetingbitrate_kbpswith a VBV cap pinned to the same value (buffervbv_kbit, precomputed by the caller from the frame-time multiplier policy) and filler disabled.max_qpis the legibility floor (caps how ugly a rate-starved frame gets) andmin_qpthe waste ceiling (stops over-spending on easy content); both are clamped to 51, and the ceiling is 51 when unset because x264’s own default admits out-of-spec quantizers above it that exist only to force skips when the VBV underflows, which leaves rows of the picture frozen on old content. A budget the content cannot meet overshoots instead, as NVENC and libvpx do. - CRF (default): constant-quality with
f_rf_constant = crf. A positivevbv_kbitcaps it with a VBV of that buffer at a peak ofbitrate_kbps(x264’s capped CRF): the rate factor still picks the quantizer and the VBV bounds the size of a frame, a key frame above all, under CBR’s ceiling of 51, so content the cap starves overshoots it rather than freezes.vbv_kbit == 0leaves it uncapped.
- CBR (
- Color: I444 at full range or I420 at limited range, a VUI declaring that range
with the BT.709 primaries, transfer, and matrix the sRGB source and the conversion
carry, and the matching
high444/baselineprofile. - Coding tools: CABAC and the 8x8 transform are disabled, matching the low-latency baseline profile — CAVLC entropy coding with no 8x8 DCT — for minimal encode cost.
- Output: repeated headers (SPS/PPS before each keyframe) and Annex-B framing, with x264’s own logging silenced.
- References: a decoded picture buffer of
REFERENCE_FRAMES(i_dpb_size), declaring the lowest level up to 5.2 that holds them (h264_reference_level: 5.0 at 1080p, where 4.2 holds four), soinvalidate_referencecan leave a frame a client lost out of the predictions with earlier frames still there to predict from, for a report up to eight frames late (133 ms at 60 fps). Motion search keeps its single reference. frame_num: x264 counts it in sixteen values for that buffer, and a loss covering the frame where it wraps costs a key frame (ReferenceWindow), so the stream carries it a byte wider (WideFrameNum): 4096 values, one such frame in 68 s at 60 fps.
The x264_encoder_open call is serialized under X264_OPEN_CLOSE_LOCK because it mutates
libx264 global state.
Sourcepub fn with_depth(
width: i32,
height: i32,
crf: i32,
is_i444: bool,
bit_depth: u32,
fps: f64,
threads: i32,
cbr_mode: bool,
bitrate_kbps: i32,
vbv_kbit: i32,
min_qp: i32,
max_qp: i32,
reference_frames: u32,
) -> Option<Self>
pub fn with_depth( width: i32, height: i32, crf: i32, is_i444: bool, bit_depth: u32, fps: f64, threads: i32, cbr_mode: bool, bitrate_kbps: i32, vbv_kbit: i32, min_qp: i32, max_qp: i32, reference_frames: u32, ) -> Option<Self>
new at bit_depth bits per sample: 10 opens a High 10 session, or High 4:4:4
Predictive at 10 bits, which reads its planes as 16-bit samples; its decoded picture
buffer keeps at most reference_frames, 0 for the level’s (video_reference_frames).
Sourcepub fn ten_bit() -> bool
pub fn ten_bit() -> bool
Whether the linked libx264 opens a 10-bit session, which is a property of how the library was built, asked once of a session too small to cost anything.
Sourcepub fn reconfigure_crf(&mut self, new_crf: i32)
pub fn reconfigure_crf(&mut self, new_crf: i32)
Retune the constant-quality CRF on the running encoder, so a quality change costs a parameter push rather than tearing down and rebuilding the session (a rebuild would force an IDR and drop encoder state).
It is a no-op in CBR mode, where rate is bitrate-controlled and CRF simply does not apply, and
a no-op when the value is unchanged — the tracked current_crf is what makes that cheap
early-out possible. Otherwise it reads the encoder’s live parameters, overwrites
f_rf_constant, and pushes the change via x264_encoder_reconfig, advancing the tracked CRF
only once the reconfig has actually succeeded so the mirror never drifts from the encoder.
Sourcepub fn reconfigure_rate(&mut self, bitrate_kbps: i32, vbv_kbit: i32, fps: f64)
pub fn reconfigure_rate(&mut self, bitrate_kbps: i32, vbv_kbit: i32, fps: f64)
Retune bitrate/VBV (CBR, or a capped CRF) and/or frame rate to match the live settings, structured to be called unconditionally every frame so the caller need not track what changed itself.
Because encode_cpu fires it on every frame, it first computes the would-be values and bails
before touching the encoder when neither the bitrate/VBV nor the frame rate differs from
what is live — that self-gating keeps a per-frame call nearly free.
A frame-rate change reopens the encoder rather than reconfiguring it: x264_encoder_reconfig
does not apply i_fps_*, and the CBR/VBV per-frame budget is bitrate / fps, so a session
left at its old rate ships roughly half the configured bitrate once fps halves. The reopen
carries the new bitrate/VBV too, and a fresh session emits an IDR on its first frame; a failed
reopen keeps the working session instead of nulling the handle. Capping a CRF session or
lifting its cap reopens it too, since x264 retunes a VBV in place only while one is on. A
bitrate/VBV-only change otherwise stays a live x264_encoder_reconfig, and the tracked
mirror advances only on success so it cannot drift from the encoder’s real state.
Sourcepub fn last_reference(&self) -> Reference
pub fn last_reference(&self) -> Reference
The frame the last encoded frame predicted from.
Sourcepub fn last_qp(&self) -> Option<u32>
pub fn last_qp(&self) -> Option<u32>
The quantizer the rate control last coded a frame at, held frames aside.
Sourcepub fn hold_quantizer(&mut self, qp: i32)
pub fn hold_quantizer(&mut self, qp: i32)
Encode the next frame at quantizer qp whatever the rate control, leaving the session’s
own for the frame after: x264’s per-picture forced quantizer.
Under a constant rate x264’s row-level VBV control moves a forced quantizer back toward
the rate control’s own for the frame, so a held key frame there, a fresh start for the
decoder anyway, starts a fresh session (open_for_held_key) whose rate control plans that
frame with HELD_KEY_BUDGET_S of the target, which also bounds its size, and takes the
session’s own rate back for the frame after.
Sourcepub fn invalidate_reference(&mut self, frame_id: u16) -> bool
pub fn invalidate_reference(&mut self, frame_id: u16) -> bool
Leave frame frame_id and every frame after it out of the predictions. False when x264
refuses, and the caller codes a key frame instead.
Sourcepub fn encode_with_headers(
&mut self,
y: &[u8],
u: &[u8],
v: &[u8],
y_stride: i32,
u_stride: i32,
v_stride: i32,
frame_id: u16,
y_start: u16,
force_idr: bool,
omit_headers: bool,
output_buf: &mut Vec<u8>,
) -> bool
pub fn encode_with_headers( &mut self, y: &[u8], u: &[u8], v: &[u8], y_stride: i32, u_stride: i32, v_stride: i32, frame_id: u16, y_start: u16, force_idr: bool, omit_headers: bool, output_buf: &mut Vec<u8>, ) -> bool
Encode one YUV frame into H.264 and frame it for the wire, reporting whether the encoder actually emitted a bitstream this call.
The boolean return is load-bearing: x264_encoder_encode can legitimately produce nothing on
a given call, and the caller must forward a stripe only when real bytes exist — never an empty
or header-only packet. Framing is conditional because the transport needs the pipeline’s small
wire header to route the stripe, while omit_headers consumers take the bare Annex-B
elementary stream.
- Picture setup: wraps the borrowed Y/U/V planes and their strides in an
x264_picture_twith the encoder’s CSP, stamps the presentation timestamp with the session’s count of encoded frames (the one an invalidation names), and requests an IDR whenforce_idris set or no reference is left to predict from (otherwiseX264_TYPE_AUTO). - Encode: calls
x264_encoder_encode; a non-positive returned size means no frame was emitted this call, so the function returnsfalsewithout writing output. - Framing:
output_bufis cleared and refilled. Unlessomit_headersis set, the wire header is prepended with a frame kind read from the actual output picture type rather than fromforce_idr, because the encoder may not honor a keyframe request and the client keys its decode-recovery on the kind it truly received. Withomit_headersthe output is bare Annex-B. - Payload: every NAL payload is appended to
output_bufafter the optional header, itsframe_numwidened (WideFrameNum), so the bytes past the wire header are always a contiguous Annex-B access unit.
Trait Implementations§
Source§impl Drop for H264EncoderWrapper
Available on crate feature gpl only.
impl Drop for H264EncoderWrapper
gpl only.impl Send for H264EncoderWrapper
gpl only.Auto Trait Implementations§
impl !Sync for H264EncoderWrapper
impl Freeze for H264EncoderWrapper
impl RefUnwindSafe for H264EncoderWrapper
impl Unpin for H264EncoderWrapper
impl UnsafeUnpin for H264EncoderWrapper
impl UnwindSafe for H264EncoderWrapper
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can
then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be
further downcast into Rc<ConcreteType> where ConcreteType implements Trait.§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more