use anyhow::{anyhow, Result};
use videocall_codecs::encoder::{Encodable, EncodedFrame, EncoderConfig};
const KEYFRAME_INTERVAL: u32 = 150;
#[cfg(feature = "libvpx")]
use videocall_codecs::encoder::Vp9Encoder as Inner;
#[cfg(not(feature = "libvpx"))]
use videocall_codecs::vp9::Vp9Encoder as Inner;
pub struct VideoEncoderBuilder {
pub min_quantizer: u32,
pub max_quantizer: u32,
pub bitrate_kbps: u32,
pub fps: u32,
pub resolution: (u32, u32),
pub cpu_used: u32,
pub profile: u32,
}
impl VideoEncoderBuilder {
pub fn new(fps: u32, cpu_used: u8) -> Self {
Self {
bitrate_kbps: 500,
max_quantizer: 60,
min_quantizer: 40,
resolution: (640, 480),
fps,
cpu_used: cpu_used as u32,
profile: 0,
}
}
}
impl VideoEncoderBuilder {
pub fn set_resolution(mut self, width: u32, height: u32) -> Self {
self.resolution = (width, height);
self
}
pub fn build(&self) -> Result<VideoEncoder> {
let (width, height) = self.resolution;
if width % 2 != 0 || width == 0 {
return Err(anyhow!("Width must be divisible by 2"));
}
if height % 2 != 0 || height == 0 {
return Err(anyhow!("Height must be divisible by 2"));
}
if self.profile != 0 {
return Err(anyhow!(
"Unsupported VP9 profile {}: only profile 0 (8-bit 4:2:0) is supported",
self.profile
));
}
let config = EncoderConfig {
width,
height,
framerate: self.fps,
bitrate_kbps: self.bitrate_kbps,
keyframe_interval: KEYFRAME_INTERVAL,
min_quantizer: self.min_quantizer,
max_quantizer: self.max_quantizer,
cpu_used: self.cpu_used as u8,
};
let inner = <Inner as Encodable>::new(config)?;
Ok(VideoEncoder {
inner,
pending: None,
})
}
}
pub struct VideoEncoder {
inner: Inner,
pending: Option<EncodedFrame>,
}
impl VideoEncoder {
pub fn update_bitrate_kbps(&mut self, bitrate: u32) -> anyhow::Result<()> {
Encodable::update_bitrate_kbps(&mut self.inner, bitrate)
}
pub fn encode(&mut self, pts: i64, data: &[u8]) -> anyhow::Result<Frames<'_>> {
self.pending = Encodable::encode(&mut self.inner, pts, data)?;
Ok(Frames {
frame: self.pending.as_ref().map(|f| Frame {
data: &f.data,
key: f.is_keyframe,
pts: f.pts,
}),
})
}
}
#[derive(Clone, Copy, Debug)]
pub struct Frame<'a> {
pub data: &'a [u8],
pub key: bool,
pub pts: i64,
}
pub struct Frames<'a> {
frame: Option<Frame<'a>>,
}
impl<'a> Iterator for Frames<'a> {
type Item = Frame<'a>;
fn next(&mut self) -> Option<Self::Item> {
self.frame.take()
}
}