Skip to main content

CompressedEncoder

Struct CompressedEncoder 

Source
pub struct CompressedEncoder { /* private fields */ }
Expand description

A compressed intra HEVC encoder. Transform-codes intra frames to a decodable Annex-B stream far smaller than raw.

Two modes:

  • prediction-only (default, residual(false)): every cbf = 0, so the reconstruction is the intra prediction (DC/planar/angular with the boundary-smoothing filters). Lossy, tiny, and conformant — ffmpeg decodes it bit-for-bit (see tests/hevc_compress.rs).
  • residual (residual(true), the default): also codes quantized transform coefficients (crate::hevc::residual), which is what makes the output actually resemble the input. Externally conformant — ffmpeg decodes it bit-for-bit to the returned reconstruction, on detailed content and at every QP (tests/hevc_residual_conformance.rs).

Prediction-only is kept because it is a useful bisection tool: it exercises the CU/mode/reference-sample path with no transform or coefficient coding, so when a stream misdecodes, whether it also misdecodes here says which half to look in.

Implementations§

Source§

impl CompressedEncoder

Source

pub fn new(width: u32, height: u32, qp: i32) -> Self

New encoder for width × height at quantization qp.

Examples found in repository?
examples/codec_bench.rs (line 109)
106fn encode_hevc_mp4(args: &Args, frames: &[Yuv420Frame]) -> Vec<u8> {
107    use threers_codec::hevc::compress::CompressedEncoder;
108    let enc =
109        CompressedEncoder::new(args.width, args.height, args.qp).tiles(args.tiles.0, args.tiles.1);
110    let level = enc.config().level_idc;
111    let (vps, sps, pps) = enc.parameter_sets();
112    let mut stream = vec![[
113        vec![0, 0, 0, 1],
114        vps,
115        vec![0, 0, 0, 1],
116        sps,
117        vec![0, 0, 0, 1],
118        pps,
119    ]
120    .concat()];
121    stream.extend(threers_codec::map_frames_pub(frames, |f| {
122        enc.encode_slice_au(f)
123    }));
124    mux_annexb(args, &stream, level)
125}
126
127fn encode_hevc_intra(args: &Args, frames: &[Yuv420Frame], residual: bool) -> Vec<u8> {
128    let mut enc = CompressedEncoder::new(args.width, args.height, args.qp).residual(residual);
129    let level = enc.config().level_idc;
130    let mut recon_out = Vec::new();
131    let stream: Vec<Vec<u8>> = frames
132        .iter()
133        .map(|f| {
134            let (au, recon) = enc.encode_frame(f);
135            if !args.recon.is_empty() {
136                // Crop the CTB-aligned reconstruction back to display size, the
137                // way the conformance window makes a decoder do.
138                let (cw, cwc) = (recon.coded_width as usize, (recon.coded_width / 2) as usize);
139                let (w, h) = (args.width as usize, args.height as usize);
140                for row in 0..h {
141                    recon_out.extend_from_slice(&recon.y[row * cw..row * cw + w]);
142                }
143                for plane in [&recon.u, &recon.v] {
144                    for row in 0..h / 2 {
145                        recon_out.extend_from_slice(&plane[row * cwc..row * cwc + w / 2]);
146                    }
147                }
148            }
149            au
150        })
151        .collect();
152    if !args.recon.is_empty() {
153        std::fs::write(&args.recon, &recon_out).expect("write reconstruction");
154    }
155    mux_annexb(args, &stream, level)
156}
Source

pub fn deblock(self, on: bool) -> Self

Turn the in-loop deblocking filter on or off. On by default.

Source

pub fn aq(self, strength: f32) -> Self

Set the adaptive-quantization strength, in QP steps per octave of coding-tree-block variance. Off by default — measured on photographic content it costs perceptual quality at matched size, the same as on the H.264 side (see docs/codec-benchmark.md). Negative values invert the assignment, which is the control that measurement needs.

Source

pub fn residual(self, on: bool) -> Self

Enable transform-coefficient residual coding. On by default; pass false for the prediction-only path (see the type docs).

Examples found in repository?
examples/codec_bench.rs (line 128)
127fn encode_hevc_intra(args: &Args, frames: &[Yuv420Frame], residual: bool) -> Vec<u8> {
128    let mut enc = CompressedEncoder::new(args.width, args.height, args.qp).residual(residual);
129    let level = enc.config().level_idc;
130    let mut recon_out = Vec::new();
131    let stream: Vec<Vec<u8>> = frames
132        .iter()
133        .map(|f| {
134            let (au, recon) = enc.encode_frame(f);
135            if !args.recon.is_empty() {
136                // Crop the CTB-aligned reconstruction back to display size, the
137                // way the conformance window makes a decoder do.
138                let (cw, cwc) = (recon.coded_width as usize, (recon.coded_width / 2) as usize);
139                let (w, h) = (args.width as usize, args.height as usize);
140                for row in 0..h {
141                    recon_out.extend_from_slice(&recon.y[row * cw..row * cw + w]);
142                }
143                for plane in [&recon.u, &recon.v] {
144                    for row in 0..h / 2 {
145                        recon_out.extend_from_slice(&plane[row * cwc..row * cwc + w / 2]);
146                    }
147                }
148            }
149            au
150        })
151        .collect();
152    if !args.recon.is_empty() {
153        std::fs::write(&args.recon, &recon_out).expect("write reconstruction");
154    }
155    mux_annexb(args, &stream, level)
156}
Source

pub fn config(&self) -> &HevcConfig

The active configuration.

Examples found in repository?
examples/codec_bench.rs (line 110)
106fn encode_hevc_mp4(args: &Args, frames: &[Yuv420Frame]) -> Vec<u8> {
107    use threers_codec::hevc::compress::CompressedEncoder;
108    let enc =
109        CompressedEncoder::new(args.width, args.height, args.qp).tiles(args.tiles.0, args.tiles.1);
110    let level = enc.config().level_idc;
111    let (vps, sps, pps) = enc.parameter_sets();
112    let mut stream = vec![[
113        vec![0, 0, 0, 1],
114        vps,
115        vec![0, 0, 0, 1],
116        sps,
117        vec![0, 0, 0, 1],
118        pps,
119    ]
120    .concat()];
121    stream.extend(threers_codec::map_frames_pub(frames, |f| {
122        enc.encode_slice_au(f)
123    }));
124    mux_annexb(args, &stream, level)
125}
126
127fn encode_hevc_intra(args: &Args, frames: &[Yuv420Frame], residual: bool) -> Vec<u8> {
128    let mut enc = CompressedEncoder::new(args.width, args.height, args.qp).residual(residual);
129    let level = enc.config().level_idc;
130    let mut recon_out = Vec::new();
131    let stream: Vec<Vec<u8>> = frames
132        .iter()
133        .map(|f| {
134            let (au, recon) = enc.encode_frame(f);
135            if !args.recon.is_empty() {
136                // Crop the CTB-aligned reconstruction back to display size, the
137                // way the conformance window makes a decoder do.
138                let (cw, cwc) = (recon.coded_width as usize, (recon.coded_width / 2) as usize);
139                let (w, h) = (args.width as usize, args.height as usize);
140                for row in 0..h {
141                    recon_out.extend_from_slice(&recon.y[row * cw..row * cw + w]);
142                }
143                for plane in [&recon.u, &recon.v] {
144                    for row in 0..h / 2 {
145                        recon_out.extend_from_slice(&plane[row * cwc..row * cwc + w / 2]);
146                    }
147                }
148            }
149            au
150        })
151        .collect();
152    if !args.recon.is_empty() {
153        std::fs::write(&args.recon, &recon_out).expect("write reconstruction");
154    }
155    mux_annexb(args, &stream, level)
156}
Source

pub fn encode_frame(&mut self, frame: &Yuv420Frame) -> (Vec<u8>, Reconstruction)

Encode one 4:2:0 frame → Annex-B access unit, plus the reconstruction a conformant decoder reproduces. The first call prepends VPS/SPS/PPS.

Examples found in repository?
examples/codec_bench.rs (line 134)
127fn encode_hevc_intra(args: &Args, frames: &[Yuv420Frame], residual: bool) -> Vec<u8> {
128    let mut enc = CompressedEncoder::new(args.width, args.height, args.qp).residual(residual);
129    let level = enc.config().level_idc;
130    let mut recon_out = Vec::new();
131    let stream: Vec<Vec<u8>> = frames
132        .iter()
133        .map(|f| {
134            let (au, recon) = enc.encode_frame(f);
135            if !args.recon.is_empty() {
136                // Crop the CTB-aligned reconstruction back to display size, the
137                // way the conformance window makes a decoder do.
138                let (cw, cwc) = (recon.coded_width as usize, (recon.coded_width / 2) as usize);
139                let (w, h) = (args.width as usize, args.height as usize);
140                for row in 0..h {
141                    recon_out.extend_from_slice(&recon.y[row * cw..row * cw + w]);
142                }
143                for plane in [&recon.u, &recon.v] {
144                    for row in 0..h / 2 {
145                        recon_out.extend_from_slice(&plane[row * cwc..row * cwc + w / 2]);
146                    }
147                }
148            }
149            au
150        })
151        .collect();
152    if !args.recon.is_empty() {
153        std::fs::write(&args.recon, &recon_out).expect("write reconstruction");
154    }
155    mux_annexb(args, &stream, level)
156}
Source

pub fn encode_slice_au(&self, frame: &Yuv420Frame) -> Vec<u8> ⓘ

One frame’s slice NAL, in Annex-B form, without parameter sets.

Takes &self. That is the whole point: an all-intra stream carries nothing between frames — compressed_slice_rbsp reads the config and the pixels and nothing else — so frames can be encoded on separate threads and the result is byte-identical to encoding them in order.

Examples found in repository?
examples/codec_bench.rs (line 122)
106fn encode_hevc_mp4(args: &Args, frames: &[Yuv420Frame]) -> Vec<u8> {
107    use threers_codec::hevc::compress::CompressedEncoder;
108    let enc =
109        CompressedEncoder::new(args.width, args.height, args.qp).tiles(args.tiles.0, args.tiles.1);
110    let level = enc.config().level_idc;
111    let (vps, sps, pps) = enc.parameter_sets();
112    let mut stream = vec![[
113        vec![0, 0, 0, 1],
114        vps,
115        vec![0, 0, 0, 1],
116        sps,
117        vec![0, 0, 0, 1],
118        pps,
119    ]
120    .concat()];
121    stream.extend(threers_codec::map_frames_pub(frames, |f| {
122        enc.encode_slice_au(f)
123    }));
124    mux_annexb(args, &stream, level)
125}
Source

pub fn encode_slice_au_at(&self, frame: &Yuv420Frame, qp: i32) -> Vec<u8> ⓘ

encode_slice_au at a quantizer chosen per frame, which is what rate control needs.

Only the slice header moves: init_qp_minus26 stays zero in the PPS and the frame’s quantizer rides in slice_qp_delta, so the parameter sets are the same ones for every frame however the rate controller steers.

Source

pub fn tiles(self, cols: u32, rows: u32) -> Self

Split the picture into cols x rows tiles, which can then be encoded concurrently. See HevcConfig::tile_grid for what it costs.

Examples found in repository?
examples/codec_bench.rs (line 109)
106fn encode_hevc_mp4(args: &Args, frames: &[Yuv420Frame]) -> Vec<u8> {
107    use threers_codec::hevc::compress::CompressedEncoder;
108    let enc =
109        CompressedEncoder::new(args.width, args.height, args.qp).tiles(args.tiles.0, args.tiles.1);
110    let level = enc.config().level_idc;
111    let (vps, sps, pps) = enc.parameter_sets();
112    let mut stream = vec![[
113        vec![0, 0, 0, 1],
114        vps,
115        vec![0, 0, 0, 1],
116        sps,
117        vec![0, 0, 0, 1],
118        pps,
119    ]
120    .concat()];
121    stream.extend(threers_codec::map_frames_pub(frames, |f| {
122        enc.encode_slice_au(f)
123    }));
124    mux_annexb(args, &stream, level)
125}
Source

pub fn parameter_sets(&self) -> (Vec<u8>, Vec<u8>, Vec<u8>)

The parameter sets, as they go into hvcC.

Examples found in repository?
examples/codec_bench.rs (line 111)
106fn encode_hevc_mp4(args: &Args, frames: &[Yuv420Frame]) -> Vec<u8> {
107    use threers_codec::hevc::compress::CompressedEncoder;
108    let enc =
109        CompressedEncoder::new(args.width, args.height, args.qp).tiles(args.tiles.0, args.tiles.1);
110    let level = enc.config().level_idc;
111    let (vps, sps, pps) = enc.parameter_sets();
112    let mut stream = vec![[
113        vec![0, 0, 0, 1],
114        vps,
115        vec![0, 0, 0, 1],
116        sps,
117        vec![0, 0, 0, 1],
118        pps,
119    ]
120    .concat()];
121    stream.extend(threers_codec::map_frames_pub(frames, |f| {
122        enc.encode_slice_au(f)
123    }));
124    mux_annexb(args, &stream, level)
125}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.