voelin-media: capture into sinks, zero-copy conversion, scaling, pools; libvpx tuning

Screen sharing was slow mostly because every frame was copied and
allocated several times on its way to the encoder: the PipeWire callback
copied the mapped buffer into a new Vec, X11 copied the shared-memory
segment, Windows copied twice, `to_i420` allocated fresh planes on one
thread, and libvpx output was copied into Vec after Vec.

Capture backends now hand each frame to a `FrameSink` on their own
thread, with the pixels still in the capture buffer (`FrameRef`: borrowed
planes with strides). `ScreenCapture::start_sink` is implemented by the
test pattern (renders into one reused buffer), X11 (the MIT-SHM segment,
cursor blended in place, monitor/window geometry looked up once a second
instead of every frame), the portal and Windows Graphics Capture (the
mapped staging texture with its row pitch); other backends get a
forwarding default. `start` keeps working through a queue adapter.
`FramePacer` caps frame rates by timestamps; sinks can change the cap
while capturing (X11 and the test pattern follow, the portal renegotiates
the frame rate).

Portal: LINEAR DMA-BUFs are negotiated in addition to shared memory
(mandatory modifier, fixated by us, `dataType` per buffer kind), mapped
once per buffer and read between DMA_BUF_IOCTL_SYNC start/end. When
reading them is slow (uncached VRAM), the stream renegotiates to shared
memory. Tiled modifiers are not offered (needs a GPU import).

The streaming path:
- `workers::Workers`: a fork-join pool that allocates nothing per job.
- `convert::Converter`: any stride, BGRx/BGRA/RGBx/RGBA (yuv's SIMD
  paths), I420 and NV12 into a caller's I420 frame, in row bands on all
  cores; handles buffers without padding after the last row.
- `scale`: separable area-average downscaling (bilinear up), weights per
  size pair computed once, a 2x2 box fast path, row bands on the pool;
  `Pyramid` converts a capture once and derives every requested size
  from the nearest larger one, sharing equal sizes.
- `pool::FramePool`: recycled `Arc<VideoFrame>`s; `handoff::Handoff`: a
  one-slot latest-wins atomic handoff that counts replaced frames.

Codecs: `VideoEncoder::encode_with` hands out encoded frames borrowed
from the encoder (libvpx's own buffer; OpenH264 into a reused buffer).
libvpx: `cpu-used` adapts to the measured encode time against the frame
interval (VP8 levels -10..-4, VP9 starting at 8 within 5..9), threads from
all CPUs the frame size can use, VP8 token partitions and VP9 tile
columns from the thread count and width, keyframes only on request,
frame durations from timestamps (variable frame rate), `set_fps`, and
`speed` for stats. A probe on the desktop test pattern showed VP8 speeds
beyond -10 are no faster on screen content, only worse (about 3 dB PSNR).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-27 08:35:57 +00:00
1 parent 31b138adf1
commit bbfd9aba47
18 files changed
+2780 -271

No files matched your search

+37 -6
View File
@@ -21,7 +21,8 @@ use openh264::encoder::{
use openh264::formats::{YUVSlices, YUVSource};
use crate::codec::{
Codec, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder,
Codec, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder,
VideoEncoder,
};
use crate::convert;
use crate::frame::{FrameData, Plane, VideoFrame};
@@ -187,11 +188,19 @@ pub struct OpenH264Encoder {
config: EncoderConfig,
profile: H264Profile,
encoder: Option<Encoder>,
/// The last frame's bitstream (reused).
output: Vec<u8>,
}
impl OpenH264Encoder {
fn new(library: OpenH264, config: EncoderConfig) -> Result<Self> {
let mut encoder = Self { library, config, profile: H264Profile::default(), encoder: None };
let mut encoder = Self {
library,
config,
profile: H264Profile::default(),
encoder: None,
output: Vec::new(),
};
encoder.encoder = Some(encoder.create()?);
Ok(encoder)
}
@@ -244,6 +253,24 @@ impl VideoEncoder for OpenH264Encoder {
}
fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result<Vec<EncodedFrame>> {
let mut frames = Vec::new();
self.encode_with(frame, force_keyframe, &mut |f| {
frames.push(EncodedFrame {
data: f.data.to_vec(),
keyframe: f.keyframe,
pts_90khz: f.pts_90khz,
});
})?;
Ok(frames)
}
/// Writes the NAL units into a buffer kept across frames.
fn encode_with(
&mut self,
frame: &VideoFrame,
force_keyframe: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
let i420 = convert::to_i420(frame)?;
let FrameData::I420 { y, u, v } = &i420.data else {
unreachable!("to_i420 returns I420");
@@ -263,11 +290,15 @@ impl VideoEncoder for OpenH264Encoder {
Err(e) => return Err(Error::Encoder { codec: Codec::H264, message: e.to_string() }),
};
let keyframe = matches!(bitstream.frame_type(), FrameType::IDR | FrameType::I);
let data = bitstream.to_vec();
if data.is_empty() || matches!(bitstream.frame_type(), FrameType::Skip) {
return Ok(Vec::new());
if matches!(bitstream.frame_type(), FrameType::Skip) {
return Ok(());
}
Ok(vec![EncodedFrame { data, keyframe, pts_90khz: i420.pts_90khz() }])
self.output.clear();
bitstream.write_vec(&mut self.output);
if !self.output.is_empty() {
out(EncodedChunk { data: &self.output, keyframe, pts_90khz: i420.pts_90khz() });
}
Ok(())
}
/// The `openh264` crate has no safe way to change the bitrate of a
+46 -11
View File
@@ -128,6 +128,10 @@ pub struct EncoderConfig {
pub content: ContentHint,
/// Encoder threads; 0 picks a number from the resolution and CPU count.
pub threads: u32,
/// A fixed speed / quality trade-off in the backend's own terms (libvpx
/// `cpu-used`); `None` lets the encoder adapt it to how long frames take
/// to encode compared to the frame interval.
pub speed: Option<i32>,
}
impl Default for EncoderConfig {
@@ -138,30 +142,34 @@ impl Default for EncoderConfig {
keyframe_interval: None,
content: ContentHint::Screen,
threads: 0,
speed: None,
}
}
}
impl EncoderConfig {
/// Threads for a `width` x `height` encode (libwebrtc's heuristic).
/// Threads for a `width` x `height` encode: all CPUs, but no more than
/// one per 320x240 pixels (more would idle on small frames).
pub fn threads_for(&self, width: u32, height: u32) -> u32 {
if self.threads > 0 {
return self.threads;
}
let cpus = std::thread::available_parallelism().map_or(1, |n| n.get() as u32);
let pixels = width * height;
if pixels >= 1920 * 1080 && cpus > 8 {
8
} else if pixels >= 1280 * 720 && cpus > 3 {
4
} else if pixels >= 640 * 480 && cpus > 2 {
2
} else {
1
}
let useful = (u64::from(width) * u64::from(height) / (320 * 240)).clamp(1, 64) as u32;
cpus.min(useful)
}
}
/// An encoded frame borrowed from the encoder (see
/// [`VideoEncoder::encode_with`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EncodedChunk<'a> {
pub data: &'a [u8],
pub keyframe: bool,
/// Presentation time on the 90 kHz RTP clock.
pub pts_90khz: u64,
}
/// One encoded frame, ready for `voelin_stream::Peer::write`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncodedFrame {
@@ -183,8 +191,35 @@ pub trait VideoEncoder: Send {
/// encoder skipped it (rate control), usually one.
fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result<Vec<EncodedFrame>>;
/// Like [`encode`](Self::encode), but hands each encoded frame to `out`
/// borrowed from the encoder's own buffer, so nothing is allocated or
/// copied here (libvpx does this; the default goes through `encode`).
fn encode_with(
&mut self,
frame: &VideoFrame,
force_keyframe: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
for f in self.encode(frame, force_keyframe)? {
out(EncodedChunk { data: &f.data, keyframe: f.keyframe, pts_90khz: f.pts_90khz });
}
Ok(())
}
/// Change the target bitrate (bits per second).
fn set_bitrate(&mut self, bps: u32) -> Result<()>;
/// Change the expected frame rate (rate control and speed decisions);
/// ignored by encoders that follow the frame timestamps anyway.
fn set_fps(&mut self, fps: u32) -> Result<()> {
let _ = fps;
Ok(())
}
/// The current speed setting, for statistics (libvpx `cpu-used`).
fn speed(&self) -> Option<i32> {
None
}
}
/// A video decoder.
+202 -20
View File
@@ -1,13 +1,20 @@
//! VP8 and VP9 through the system libvpx.
//!
//! Encoder settings follow libwebrtc's realtime configuration: one pass CBR,
//! no lag, error resilient, fixed high speed (`cpu-used` 8), keyframes on
//! request, and screen-content tuning for [`ContentHint::Screen`].
//! no lag (`VPX_DL_REALTIME`), error resilient, keyframes only on request,
//! and screen-content tuning for [`ContentHint::Screen`]
//! (`VP8E_SET_SCREEN_CONTENT_MODE`, `VP9E_SET_TUNE_CONTENT`, static
//! threshold). Threads default to the CPUs the frame size can use; VP8 gets
//! as many token partitions, VP9 row multithreading and tile columns by
//! width. `cpu-used` adapts to the measured encode time (see
//! [`SpeedControl`]) unless [`EncoderConfig::speed`] fixes it. Bitrate
//! changes apply to the running encoder, without a keyframe.
use std::time::Duration;
use std::time::{Duration, Instant};
use crate::codec::{
Codec, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder,
Codec, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder,
VideoEncoder,
};
use crate::convert;
use crate::frame::{FrameData, Plane, VIDEO_CLOCK_RATE, VideoFrame};
@@ -38,18 +45,99 @@ pub fn libvpx_version() -> String {
raw::version()
}
/// Speed levels (bigger is faster): VP8 `cpu-used` is minus the level (a
/// fixed speed), VP9's is the level (realtime mode).
struct Levels {
slowest: i32,
fastest: i32,
/// Where adapting starts: fast, so the first seconds do not fall behind.
start: i32,
}
// VP8 levels above 10 are no faster on screen content, only worse.
const VP8_LEVELS: Levels = Levels { slowest: 4, fastest: 10, start: 10 };
const VP9_LEVELS: Levels = Levels { slowest: 5, fastest: 9, start: 8 };
/// Adapts the speed level to how long frames take to encode compared to
/// the frame interval: faster above 75 % of it, slower (better quality)
/// below 35 %, deciding every 15 frames on a running mean of the encode
/// time (keyframes excluded: they are always slow).
pub struct SpeedControl {
level: i32,
slowest: i32,
fastest: i32,
/// Mean encode time in seconds.
mean: f64,
frames: u32,
}
impl SpeedControl {
const WINDOW: u32 = 15;
const TOO_SLOW: f64 = 0.75;
const TOO_FAST: f64 = 0.35;
fn new(levels: &Levels) -> Self {
Self {
level: levels.start,
slowest: levels.slowest,
fastest: levels.fastest,
mean: 0.0,
frames: 0,
}
}
pub fn level(&self) -> i32 {
self.level
}
/// Account one encode; returns the new level if it changed.
pub fn update(&mut self, took: Duration, interval: Duration) -> Option<i32> {
let took = took.as_secs_f64();
self.mean = if self.frames == 0 { took } else { self.mean * 0.8 + took * 0.2 };
self.frames += 1;
if self.frames < Self::WINDOW || interval.is_zero() {
return None;
}
let load = self.mean / interval.as_secs_f64();
let level = if load > Self::TOO_SLOW {
(self.level + 1).min(self.fastest)
} else if load < Self::TOO_FAST {
(self.level - 1).max(self.slowest)
} else {
self.level
};
if level == self.level {
return None;
}
self.level = level;
self.frames = 0;
Some(level)
}
}
/// libvpx VP8 / VP9 encoder.
pub struct VpxEncoder {
codec: Codec,
config: EncoderConfig,
encoder: Option<raw::Encoder>,
last_pts: Option<i64>,
speed: SpeedControl,
}
impl VpxEncoder {
pub fn new(codec: Codec, config: EncoderConfig) -> Result<Self> {
check(codec, true)?;
Ok(Self { codec, config, encoder: None, last_pts: None })
let levels = if codec == Codec::Vp9 { &VP9_LEVELS } else { &VP8_LEVELS };
Ok(Self { codec, config, encoder: None, last_pts: None, speed: SpeedControl::new(levels) })
}
/// The libvpx `cpu-used` value in use.
pub fn cpu_used(&self) -> i32 {
match (self.config.speed, self.codec) {
(Some(speed), _) => speed,
(None, Codec::Vp9) => self.speed.level(),
(None, _) => -self.speed.level(),
}
}
fn error(&self, message: String) -> Error {
@@ -69,6 +157,7 @@ impl VpxEncoder {
keyframe_interval: self.config.keyframe_interval,
screen: self.config.content == ContentHint::Screen,
threads: self.config.threads_for(width, height),
speed: self.cpu_used(),
};
let encoder = raw::Encoder::new(&params).map_err(|e| self.error(e))?;
self.encoder = Some(encoder);
@@ -87,19 +176,43 @@ impl VideoEncoder for VpxEncoder {
}
fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result<Vec<EncodedFrame>> {
let mut frames = Vec::new();
self.encode_with(frame, force_keyframe, &mut |f| {
frames.push(EncodedFrame {
data: f.data.to_vec(),
keyframe: f.keyframe,
pts_90khz: f.pts_90khz,
});
})?;
Ok(frames)
}
/// Encodes straight from the frame's planes (I420 frames are not
/// copied) and hands out libvpx's own output buffer.
fn encode_with(
&mut self,
frame: &VideoFrame,
force_keyframe: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
let i420 = convert::to_i420(frame)?;
let FrameData::I420 { y, u, v } = &i420.data else {
unreachable!("to_i420 returns I420");
};
// libvpx needs strictly increasing timestamps.
// libvpx needs strictly increasing timestamps; the duration of a
// frame is the time since the previous one (rate control follows a
// variable frame rate).
let interval = VIDEO_CLOCK_RATE / u64::from(self.config.fps.max(1));
let mut pts = i420.pts_90khz() as i64;
if let Some(last) = self.last_pts
&& pts <= last
{
pts = last + 1;
}
let duration = match self.last_pts {
Some(last) if pts <= last => {
pts = last + 1;
1
}
Some(last) => ((pts - last) as u64).min(VIDEO_CLOCK_RATE),
None => interval,
};
self.last_pts = Some(pts);
let duration = VIDEO_CLOCK_RATE / u64::from(self.config.fps.max(1));
let image = raw::I420 {
width: i420.width,
height: i420.height,
@@ -110,15 +223,40 @@ impl VideoEncoder for VpxEncoder {
uv_stride: u.stride,
};
let codec = self.codec;
let encoder = self.ensure_encoder(i420.width, i420.height)?;
let packets = encoder
.encode(&image, pts, duration, force_keyframe)
self.ensure_encoder(i420.width, i420.height)?;
let encoder = self.encoder.as_mut().expect("created above");
let started = Instant::now();
let mut keyframe = force_keyframe;
encoder
.encode(&image, pts, duration, force_keyframe, &mut |p| {
keyframe |= p.keyframe;
if !p.data.is_empty() {
out(EncodedChunk {
data: p.data,
keyframe: p.keyframe,
pts_90khz: p.pts as u64,
});
}
})
.map_err(|message| Error::Encoder { codec, message })?;
Ok(packets
.into_iter()
.filter(|p| !p.data.is_empty())
.map(|p| EncodedFrame { data: p.data, keyframe: p.keyframe, pts_90khz: p.pts as u64 })
.collect())
if self.config.speed.is_none() && !keyframe {
let budget = Duration::from_secs(1) / self.config.fps.max(1);
if let Some(level) = self.speed.update(started.elapsed(), budget) {
let cpu_used = if codec == Codec::Vp9 { level } else { -level };
tracing::debug!(%codec, cpu_used, "encoder speed");
encoder.set_speed(cpu_used).map_err(|message| Error::Encoder { codec, message })?;
}
}
Ok(())
}
fn set_fps(&mut self, fps: u32) -> Result<()> {
self.config.fps = fps.max(1);
Ok(())
}
fn speed(&self) -> Option<i32> {
Some(self.cpu_used())
}
fn set_bitrate(&mut self, bps: u32) -> Result<()> {
@@ -243,6 +381,50 @@ mod tests {
assert!(!encoder.encode(&frame(3, 97, 55), false).unwrap()[0].keyframe);
}
#[test]
fn speed_follows_the_encode_time() {
let mut control = SpeedControl::new(&VP8_LEVELS);
let interval = Duration::from_millis(33);
// Fast encodes: slower levels (better quality) down to the slowest.
let mut changes = Vec::new();
for _ in 0..500 {
changes.extend(control.update(Duration::from_millis(2), interval));
}
assert_eq!(control.level(), VP8_LEVELS.slowest);
assert!(changes.windows(2).all(|w| w[1] == w[0] - 1), "{changes:?}");
// Slow encodes: faster again.
for _ in 0..500 {
control.update(Duration::from_millis(30), interval);
}
assert_eq!(control.level(), VP8_LEVELS.fastest);
// In between: stays.
let level = control.level();
for _ in 0..100 {
assert!(
control.update(Duration::from_millis(18), interval).is_none()
|| level != control.level()
);
}
}
#[test]
fn borrowed_output_and_fixed_speed() {
let config = EncoderConfig { speed: Some(-6), ..EncoderConfig::default() };
let mut encoder = VpxEncoder::new(Codec::Vp8, config).unwrap();
assert_eq!(encoder.speed(), Some(-6));
let mut sizes = Vec::new();
for n in 0..3 {
encoder
.encode_with(&frame(n, 64, 48), false, &mut |f| {
sizes.push((f.data.len(), f.keyframe))
})
.unwrap();
}
assert_eq!(sizes.len(), 3);
assert!(sizes[0].1 && !sizes[1].1);
assert_eq!(VpxEncoder::new(Codec::Vp9, EncoderConfig::default()).unwrap().speed(), Some(8));
}
#[test]
fn garbage_is_an_error() {
let mut decoder = VpxDecoder::new(Codec::Vp8).unwrap();
+40 -22
View File
@@ -15,11 +15,6 @@ use vpx_sys as ffi;
pub(super) type RawResult<T> = std::result::Result<T, String>;
/// Speed for realtime encoding. VP8: negative means a fixed speed (a
/// positive value would let libvpx pick one from a CPU budget).
const VP8_CPU_USED: c_int = -8;
const VP9_CPU_USED: c_int = 8;
fn iface(vp9: bool, encoder: bool) -> *const ffi::vpx_codec_iface {
// SAFETY: these return pointers to static interface tables (or NULL if
// libvpx was built without that codec); no arguments.
@@ -109,14 +104,21 @@ pub(super) struct EncoderParams {
pub keyframe_interval: Option<u32>,
pub screen: bool,
pub threads: u32,
/// `cpu-used`: VP8 -16 (fastest) to -4 as a fixed speed (negative), VP9
/// 5 to 9 in realtime mode.
pub speed: i32,
}
pub(super) struct Packet {
pub data: Vec<u8>,
/// An encoded frame, borrowed from libvpx until the next call.
pub(super) struct Packet<'a> {
pub data: &'a [u8],
pub keyframe: bool,
pub pts: i64,
}
/// Longest keyframe distance libvpx is given with keyframes on request only.
const NO_KEYFRAMES: u32 = 1 << 30;
/// An initialised encoder context.
pub(super) struct Encoder {
// Boxed: libvpx keeps pointers to the context and the configuration.
@@ -164,7 +166,11 @@ impl Encoder {
cfg.kf_min_dist = 0;
cfg.kf_max_dist = n.max(1);
}
None => cfg.kf_mode = ffi::vpx_kf_mode::VPX_KF_DISABLED,
None => {
// Keyframes only when forced (a viewer asks for one).
cfg.kf_mode = ffi::vpx_kf_mode::VPX_KF_DISABLED;
cfg.kf_max_dist = NO_KEYFRAMES;
}
}
// SAFETY: zeroed context as libvpx expects before init.
@@ -184,10 +190,14 @@ impl Encoder {
})?;
let mut encoder = Self { ctx, cfg };
encoder.set_speed(p.speed)?;
// log2 of the thread count, for splitting the frame.
let log2_threads = 31 - p.threads.max(1).leading_zeros();
if p.vp9 {
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_CPUUSED, VP9_CPU_USED)?;
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_ROW_MT, 1)?;
let tiles = (31 - p.threads.max(1).leading_zeros()) as c_int;
// Tiles are at least 256 pixels wide.
let max_tiles = 31 - (p.width / 256).max(1).leading_zeros();
let tiles = log2_threads.min(max_tiles) as c_int;
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_TILE_COLUMNS, tiles)?;
// Cyclic refresh: realtime adaptive quantisation.
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_AQ_MODE, 3)?;
@@ -197,7 +207,9 @@ impl Encoder {
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_TUNE_CONTENT, screen)?;
}
} else {
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_CPUUSED, VP8_CPU_USED)?;
// Token partitions (1, 2, 4 or 8) let decoders use threads too.
let partitions = log2_threads.min(3) as c_int;
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_TOKEN_PARTITIONS, partitions)?;
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_NOISE_SENSITIVITY, 0)?;
if p.screen {
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_SCREEN_CONTENT_MODE, 1)?;
@@ -220,6 +232,11 @@ impl Encoder {
check(Some(&self.ctx), err).map_err(|e| format!("control {id:?}: {e}"))
}
/// Change `cpu-used` of the running encoder (see [`EncoderParams::speed`]).
pub fn set_speed(&mut self, speed: i32) -> RawResult<()> {
self.control(ffi::vp8e_enc_control_id::VP8E_SET_CPUUSED, speed as c_int)
}
/// Change the target bitrate of the running encoder.
pub fn set_bitrate(&mut self, kbps: u32) -> RawResult<()> {
self.cfg.rc_target_bitrate = kbps.max(1);
@@ -233,14 +250,16 @@ impl Encoder {
(self.cfg.g_w, self.cfg.g_h)
}
/// Encode one frame (pts and duration in 1/90000 s).
/// Encode one frame (pts and duration in 1/90000 s); `out` gets the
/// encoded frames, borrowed from libvpx.
pub fn encode(
&mut self,
img: &I420<'_>,
pts: i64,
duration: u64,
keyframe: bool,
) -> RawResult<Vec<Packet>> {
out: &mut dyn FnMut(Packet<'_>),
) -> RawResult<()> {
img.check()?;
if (img.width, img.height) != self.size() {
return Err("frame size differs from the encoder size".into());
@@ -287,16 +306,16 @@ impl Encoder {
)
};
check(Some(&self.ctx), err)?;
Ok(self.drain())
self.drain(out);
Ok(())
}
fn drain(&mut self) -> Vec<Packet> {
let mut packets = Vec::new();
fn drain(&mut self, out: &mut dyn FnMut(Packet<'_>)) {
let mut iter: ffi::vpx_codec_iter_t = ptr::null();
loop {
// SAFETY: iterates the packets of the last encode call; each
// packet and its buffer stay valid until the next libvpx call on
// this context, and are copied before that.
// this context, which `out` cannot make (it has no access to it).
let pkt = unsafe { ffi::vpx_codec_get_cx_data(&mut *self.ctx, &mut iter) };
if pkt.is_null() {
break;
@@ -307,18 +326,17 @@ impl Encoder {
}
// SAFETY: `frame` is the active union member for frame packets.
let frame = unsafe { pkt.data.frame };
let data = if frame.buf.is_null() || frame.sz == 0 {
Vec::new()
let data: &[u8] = if frame.buf.is_null() || frame.sz == 0 {
&[]
} else {
unsafe { std::slice::from_raw_parts(frame.buf.cast::<u8>(), frame.sz) }.to_vec()
unsafe { std::slice::from_raw_parts(frame.buf.cast::<u8>(), frame.sz) }
};
packets.push(Packet {
out(Packet {
data,
keyframe: frame.flags & ffi::VPX_FRAME_IS_KEY != 0,
pts: frame.pts,
});
}
packets
}
}