Encoder

Struct Encoder 

Source
pub struct Encoder<T: YUVPixelType> { /* private fields */ }
Expand description

The main VP8/VP9 video encoder.

§Example

The example below expects the input image in YUV 4:2:0 planar format. While the encoder supports a number of YUV format variants (see crate::image::ImageFormat), if you are working non-YUV formats (e.g. RGB), you will first have to convert your data to one of the YUV formats supported by the encoder. The yuv crate contains many highly optimized pixel format conversion functions. See crate::ImageFormat for an example.

Note that the encoder below has most of its settings set to their default values for the codec. The EncoderConfig struct gives you a lot more more tuning options.

use std::num::NonZero;
use vpx_rs::{
    Encoder, EncoderConfig, EncoderFrameFlags, Error, Packet,
    RateControl, Timebase,
};

// Initializes a VP8 encoder instance.
fn new_vp8_encoder(width: u32, height: u32) -> Result<Encoder<u8>, Error> {
    // Start by preparing the encoder configuration.
    let mut config = EncoderConfig::<u8>::new(
        vpx_rs::enc::CodecId::VP8,
        width,
        height,
        // assume a framerate of 30 fps, implying a 1/30 timebase
        Timebase {
            num: NonZero::new(1).unwrap(),
            den: NonZero::new(30).unwrap(),
        },
        RateControl::ConstantBitRate(8000),
    )?;
    // Construct the actual encoder and return the result.
    Encoder::new(config)
}

// Encodes a single frame in YUV 4:2:0 planar format and sends the
// compressed bitstream to a writer.
fn encode_yuv420_frame<W: std::io::Write>(
    encoder: &mut Encoder<u8>,
    frame_counter: i64,
    width: u32,
    height: u32,
    yuv420_pixels: &[u8],
    output_stream: &mut W,
) -> Result<(), Box<dyn std::error::Error>> {
    // Wrap the input buffer in an ImageData structure, together
    // with information about the data format and dimensions.
    let image = vpx_rs::YUVImageData::<u8>::from_raw_data(
        vpx_rs::ImageFormat::I420,
        width as usize,
        height as usize,
        yuv420_pixels,
    )?;
    // Send the image to the encoder for compression.
    let packets = encoder.encode(
        frame_counter,
        1,
        image,
        vpx_rs::EncodingDeadline::default(),
        EncoderFrameFlags::empty(),
    )?;
    // The encoder can spit out a series of various data packets.
    for packet in packets {
        match packet {
            // CompressedFrame packets contain the actual compressed
            // video bitstream, which we need to send to the output.
            Packet::CompressedFrame(frame) => {
                println!(
                    "Encoder produced frame with {} bytes, pts: {}",
                    frame.data.len(),
                    frame.pts,
                );
                // send the compressed video data to the output
                output_stream.write(&frame.data)?;
            },
            // Remaining packet types contain various metainformation.
            // Most of these need to be enabled manually by calling
            // Encoder::codec_control_set() and setting various
            // advanced encoder options.
            _ => {
                println!(
                    "Encoder also produced something else: {packet:?}",
                );
            }
        }
    }
    Ok(())
}

Implementations§

Source§

impl<T: YUVPixelType> Encoder<T>

Source

pub fn new(config: EncoderConfig<T>) -> Result<Self>

Constructs a new encoder.

Source

pub fn encode( &mut self, pts: i64, duration: u64, image: YUVImageData<'_, T>, deadline: EncodingDeadline, flags: EncoderFrameFlags, ) -> Result<PacketIterator<'_>>

Encodes a frame of image data.

  • pts: The presentation timestamp of this frame. This should be specified in the timebase units set up in the encoder config.
  • duration: Duration to show frame, in timebase units.
  • image: The image to be encoded.
  • deadline: The encoding deadline to pass to the encoder.

Returns an interator of stream packets which were generated from this frame. Please note that the encoder need not generate new packets for every frame passed in. It can buffer multiple frames and then emit multiple stream packets at once. The deadline argument hints the encoder how much it should trade off reduced latency for better compression.

Source

pub fn stream_info(&mut self) -> Option<StreamInfo>

Returns information about the stream being produced.

Source

pub fn codec_control_set( &mut self, control: EncoderControlSet<'_>, ) -> Result<()>

Provides fine-grained codec control after initialization.

Trait Implementations§

Source§

impl<T: Debug + YUVPixelType> Debug for Encoder<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: YUVPixelType> Drop for Encoder<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<T: YUVPixelType> Send for Encoder<T>

Source§

impl<T: YUVPixelType> Sync for Encoder<T>

Auto Trait Implementations§

§

impl<T> Freeze for Encoder<T>

§

impl<T> RefUnwindSafe for Encoder<T>
where T: RefUnwindSafe,

§

impl<T> Unpin for Encoder<T>
where T: Unpin,

§

impl<T> UnwindSafe for Encoder<T>
where T: UnwindSafe,

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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.