hwcodec 0.1.0

Realtime AV1 and VP9 video encoding and decoding: hardware encoders (NVENC, Quick Sync, AMF, VA-API) and software codecs (SVT-AV1, libvpx, dav1d) behind one interface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
use std::ffi::{CStr, c_char, c_int, c_void};
use std::ptr;
use std::sync::{Mutex, Once, PoisonError};

use crate::codec::{Codec, VideoEncoder};
use crate::{
    AV1_TEMPORAL_LAYERS, Av1Options, EncodedFrame, EncoderConfig, Error, I420Frame, Result,
    av1_cpu_supported,
};

mod ffi {
    #![allow(
        non_upper_case_globals,
        non_camel_case_types,
        non_snake_case,
        dead_code,
        unsafe_op_in_unsafe_fn,
        clippy::all
    )]

    include!(concat!(env!("OUT_DIR"), "/svt.rs"));
}

/// SVT-AV1 preset (0 slowest … 13 fastest) for realtime coding; a speed self-test decides
/// whether the machine is fast enough at all.
const PRESET: i8 = 10;

/// The fastest preset that still has the screen-content tools: SVT-AV1 turns them off in realtime
/// mode from preset 9 on. They cost about four times the encode time of [`PRESET`] (1080p30: about
/// 70% of the frame budget on a 16-thread desktop CPU, 720p30 about 40%), which is why a caller that
/// turns them on should lower the frame rate first.
const SCREEN_CONTENT_PRESET: i8 = 8;

/// Serialises creating and shutting down encoders: SVT-AV1 sets up process-wide state (CPU
/// feature dispatch, logging) there without locking, and parallel calls crashed.
static LIFECYCLE: Mutex<()> = Mutex::new(());

/// SVT-AV1 logs its version banner and configuration at info level to stdout, and warns about
/// tools the realtime configuration turns off on purpose (every encoder start). The app only
/// wants its errors, on stderr like the rest of its diagnostics.
static LOG_CALLBACK: Once = Once::new();

/// How the platform passes a C `va_list` to a function (a pointer, an array or a struct), taken
/// from the callback type bindgen generated so it matches `vsnprintf` on every target.
type VaList = <ffi::SvtAv1LogCallback as LastArgument>::Type;

trait LastArgument {
    type Type;
}

impl<A, B, C, D, E> LastArgument for Option<unsafe extern "C" fn(A, B, C, D, E)> {
    type Type = E;
}

unsafe extern "C" {
    /// The C library's; declared here because MSVC's header only has an inline definition that
    /// bindgen skips.
    fn vsnprintf(buffer: *mut c_char, size: usize, format: *const c_char, args: VaList) -> c_int;
}

/// Receives every SVT-AV1 log line (on its worker threads too).
unsafe extern "C" fn svt_log(
    _context: *mut c_void,
    level: ffi::SvtAv1LogLevel,
    tag: *const c_char,
    format: *const c_char,
    args: VaList,
) {
    if level > ffi::SVT_AV1_LOG_ERROR {
        return;
    }
    let mut buffer = [0 as c_char; 512];
    // SAFETY: SVT-AV1 passes a printf format with its matching arguments; vsnprintf truncates to
    // the buffer and always terminates it.
    let message = unsafe {
        if vsnprintf(buffer.as_mut_ptr(), buffer.len(), format, args) < 0 {
            return;
        }
        CStr::from_ptr(buffer.as_ptr()).to_string_lossy()
    };
    let tag = if tag.is_null() {
        "SVT-AV1".into()
    } else {
        // SAFETY: a non-null tag is a NUL-terminated string.
        unsafe { CStr::from_ptr(tag) }.to_string_lossy()
    };
    log::error!("{tag}: {}", message.trim_end());
}

/// Realtime AV1 encoder on SVT-AV1 (low delay, CBR) with [`AV1_TEMPORAL_LAYERS`] temporal layers.
pub struct Av1Encoder {
    handle: *mut ffi::EbComponentType,
    config: EncoderConfig,
    options: Av1Options,
    /// Live bitrate or frame-rate changes not yet handed to SVT-AV1; they ride along with the
    /// next frame.
    pending_bitrate: bool,
    pending_fps: bool,
}

// SAFETY: the SVT-AV1 handle is owned exclusively by this value and only used through
// `&mut self`; SVT-AV1 runs its own worker threads and has no affinity to the calling thread.
unsafe impl Send for Av1Encoder {}

impl Av1Encoder {
    /// Opens an encoder for `config` with the software-AV1 `options`.
    pub fn new(config: EncoderConfig, options: Av1Options) -> Result<Self> {
        if !av1_cpu_supported() {
            return Err(codec_error(
                "encoder init",
                "the CPU has no AVX2, and SVT-AV1's code for such CPUs crashes".to_owned(),
            ));
        }
        validate(&config)?;
        let handle = open(&config, options)?;
        Ok(Self {
            handle,
            config,
            options,
            pending_bitrate: false,
            pending_fps: false,
        })
    }

    /// The configuration the encoder currently runs with.
    pub fn config(&self) -> EncoderConfig {
        self.config
    }

    /// The software-AV1 options the encoder currently runs with.
    pub fn options(&self) -> Av1Options {
        self.options
    }

    /// Encodes one frame; see [`VideoEncoder::encode`].
    pub fn encode(
        &mut self,
        frame: &I420Frame,
        pts: i64,
        force_keyframe: bool,
    ) -> Result<Vec<EncodedFrame>> {
        if frame.width() != self.config.width || frame.height() != self.config.height {
            return Err(Error::InvalidFrame(format!(
                "frame is {}x{}, encoder is set to {}x{}",
                frame.width(),
                frame.height(),
                self.config.width,
                self.config.height
            )));
        }
        let (w, h) = (frame.width() as usize, frame.height() as usize);
        let chroma_w = w.div_ceil(2);
        let luma = w * h;
        let chroma = chroma_w * h.div_ceil(2);
        let base = frame.data().as_ptr() as *mut u8;

        let mut rate = ffi::SvtAv1RateInfo {
            seq_qp: 0,
            target_bit_rate: bits_per_second(self.config.bitrate_kbps),
        };
        let mut frame_rate = ffi::SvtAv1FrameRateInfo {
            frame_rate_numerator: self.config.fps,
            frame_rate_denominator: 1,
        };
        let mut events = Vec::with_capacity(2);
        if self.pending_bitrate {
            events.push(event(ffi::RATE_CHANGE_EVENT, &mut rate));
        }
        if self.pending_fps {
            events.push(event(ffi::FRAME_RATE_CHANGE_EVENT, &mut frame_rate));
        }
        // SVT-AV1 walks the events as a linked list.
        for index in 1..events.len() {
            let next: *mut ffi::EbPrivDataNode = &mut events[index];
            events[index - 1].next = next;
        }

        // SAFETY: the input descriptors point into `frame`, which outlives the send call; SVT-AV1
        // copies the picture and the event list during svt_av1_enc_send_picture and never writes
        // to the input planes. Output buffers are copied out before they are released.
        unsafe {
            let mut planes = ffi::EbSvtIOFormat {
                luma: base,
                cb: base.add(luma),
                cr: base.add(luma + chroma),
                y_stride: w as u32,
                cr_stride: chroma_w as u32,
                cb_stride: chroma_w as u32,
            };
            let mut input = std::mem::zeroed::<ffi::EbBufferHeaderType>();
            input.size = std::mem::size_of::<ffi::EbBufferHeaderType>() as u32;
            input.p_buffer = (&mut planes as *mut ffi::EbSvtIOFormat).cast();
            input.n_filled_len = (luma + 2 * chroma) as u32;
            input.n_alloc_len = input.n_filled_len;
            input.pts = pts;
            input.pic_type = if force_keyframe {
                ffi::EB_AV1_KEY_PICTURE
            } else {
                ffi::EB_AV1_INVALID_PICTURE
            };
            input.p_app_private = events.first_mut().map_or(ptr::null_mut(), |first| {
                (first as *mut ffi::EbPrivDataNode).cast()
            });
            check(
                ffi::svt_av1_enc_send_picture(self.handle, &mut input),
                "encode",
            )?;
            self.pending_bitrate = false;
            self.pending_fps = false;

            // Low delay: one packet per picture, and this call blocks until it is ready.
            let mut packet: *mut ffi::EbBufferHeaderType = ptr::null_mut();
            check(
                ffi::svt_av1_enc_get_packet(self.handle, &mut packet, 0),
                "get packet",
            )?;
            if packet.is_null() {
                return Err(codec_error("get packet", "no packet".into()));
            }
            let out = &*packet;
            let result = if out.flags & ffi::EB_BUFFERFLAG_ERROR_MASK != 0 {
                Err(codec_error(
                    "encode",
                    format!("error flags {:#x}", out.flags),
                ))
            } else {
                Ok(EncodedFrame {
                    data: std::slice::from_raw_parts(out.p_buffer, out.n_filled_len as usize)
                        .to_vec(),
                    keyframe: out.pic_type == ffi::EB_AV1_KEY_PICTURE,
                    temporal_layer: out.temporal_layer_index,
                    pts: out.pts,
                })
            };
            ffi::svt_av1_enc_release_out_buffer(&mut packet);
            let frame = result?;
            if frame.temporal_layer >= layers(&self.config) {
                return Err(codec_error(
                    "read temporal layer id",
                    format!("unexpected layer id {}", frame.temporal_layer),
                ));
            }
            Ok(vec![frame])
        }
    }

    /// Changes the output size. SVT-AV1 starts a new stream, so the next frame is a keyframe.
    pub fn set_resolution(&mut self, width: u32, height: u32) -> Result<()> {
        self.reopen(EncoderConfig {
            width,
            height,
            ..self.config
        })
    }

    /// Changes the total bitrate from the next frame on.
    pub fn set_bitrate(&mut self, bitrate_kbps: u32) -> Result<()> {
        validate(&EncoderConfig {
            bitrate_kbps,
            ..self.config
        })?;
        self.config.bitrate_kbps = bitrate_kbps;
        self.pending_bitrate = true;
        Ok(())
    }

    /// Changes the frame rate from the next frame on.
    pub fn set_fps(&mut self, fps: u32) -> Result<()> {
        let config = EncoderConfig { fps, ..self.config };
        validate(&config)?;
        self.config = config;
        self.pending_fps = true;
        Ok(())
    }

    /// Switches the screen-content tools; a new stream starting with a keyframe.
    pub fn set_options(&mut self, options: Av1Options) -> Result<()> {
        if options == self.options {
            return Ok(());
        }
        let handle = open(&self.config, options)?;
        close(self.handle);
        self.handle = handle;
        self.options = options;
        Ok(())
    }

    fn reopen(&mut self, config: EncoderConfig) -> Result<()> {
        validate(&config)?;
        // The new encoder is opened first so a failure leaves the old one working.
        let handle = open(&config, self.options)?;
        close(self.handle);
        self.handle = handle;
        self.config = config;
        self.pending_bitrate = false;
        self.pending_fps = false;
        Ok(())
    }
}

impl VideoEncoder for Av1Encoder {
    fn codec(&self) -> Codec {
        Codec::Av1
    }

    fn config(&self) -> EncoderConfig {
        Av1Encoder::config(self)
    }

    fn temporal_layers(&self) -> u8 {
        layers(&self.config)
    }

    fn encode(
        &mut self,
        frame: &I420Frame,
        pts: i64,
        force_keyframe: bool,
    ) -> Result<Vec<EncodedFrame>> {
        Av1Encoder::encode(self, frame, pts, force_keyframe)
    }

    fn set_resolution(&mut self, width: u32, height: u32) -> Result<()> {
        Av1Encoder::set_resolution(self, width, height)
    }

    fn set_bitrate(&mut self, bitrate_kbps: u32) -> Result<()> {
        Av1Encoder::set_bitrate(self, bitrate_kbps)
    }

    fn set_fps(&mut self, fps: u32) -> Result<()> {
        Av1Encoder::set_fps(self, fps)
    }
}

impl Drop for Av1Encoder {
    fn drop(&mut self) {
        close(self.handle);
    }
}

fn bits_per_second(kbps: u32) -> u32 {
    kbps.saturating_mul(1000)
}

fn event<T>(node_type: ffi::PrivDataType, data: &mut T) -> ffi::EbPrivDataNode {
    ffi::EbPrivDataNode {
        node_type,
        data: (data as *mut T).cast(),
        size: std::mem::size_of::<T>() as u32,
        next: ptr::null_mut(),
    }
}

fn validate(config: &EncoderConfig) -> Result<()> {
    if config.width < 8 || config.height < 8 {
        return Err(Error::InvalidConfig(format!(
            "size {}x{} (AV1 needs even sizes of at least 8x8)",
            config.width, config.height
        )));
    }
    config.validate_common(AV1_TEMPORAL_LAYERS)?;
    if let Some(threads) = config.threads {
        // SVT-AV1 only takes a coarse level of parallelism, not a number of threads.
        return Err(Error::InvalidConfig(format!(
            "{threads} threads (SVT-AV1 chooses its threads itself)"
        )));
    }
    Ok(())
}

/// The temporal layers an encoder for `config` produces.
fn layers(config: &EncoderConfig) -> u8 {
    config.temporal_layers.unwrap_or(AV1_TEMPORAL_LAYERS)
}

/// Creates and starts an SVT-AV1 encoder for `config`.
fn open(config: &EncoderConfig, options: Av1Options) -> Result<*mut ffi::EbComponentType> {
    let _lifecycle = LIFECYCLE.lock().unwrap_or_else(PoisonError::into_inner);
    // SAFETY: the callback must be registered before the first handle, which fixes the logging
    // setup; the lifecycle lock keeps it apart from other encoders being created.
    LOG_CALLBACK
        .call_once(|| unsafe { ffi::svt_av1_set_log_callback(Some(svt_log), ptr::null_mut()) });
    // SAFETY: svt_av1_enc_init_handle fills the configuration with defaults before it is changed;
    // the handle is released again on every error path.
    unsafe {
        let mut handle = ptr::null_mut();
        let mut cfg = std::mem::zeroed::<ffi::EbSvtAv1EncConfiguration>();
        check(
            ffi::svt_av1_enc_init_handle(&mut handle, &mut cfg),
            "encoder init",
        )?;
        configure(&mut cfg, config, options);
        let started = check(
            ffi::svt_av1_enc_set_parameter(handle, &mut cfg),
            "configure encoder",
        )
        .and_then(|()| check(ffi::svt_av1_enc_init(handle), "start encoder"));
        if let Err(err) = started {
            ffi::svt_av1_enc_deinit_handle(handle);
            return Err(err);
        }
        Ok(handle)
    }
}

fn configure(cfg: &mut ffi::EbSvtAv1EncConfiguration, config: &EncoderConfig, options: Av1Options) {
    cfg.enc_mode = if options.screen_content {
        SCREEN_CONTENT_PRESET
    } else {
        PRESET
    };
    cfg.source_width = config.width;
    cfg.source_height = config.height;
    cfg.frame_rate_numerator = config.fps;
    cfg.frame_rate_denominator = 1;
    cfg.encoder_bit_depth = 8;

    // Real-time low delay: every frame only references earlier ones, no lookahead, so each frame
    // comes out of the encode call that took it in.
    cfg.rtc = true;
    cfg.pred_structure = ffi::LOW_DELAY;
    // 2^levels frames per mini-GOP, layers 0..=levels.
    cfg.hierarchical_levels = u32::from(layers(config)) - 1;
    cfg.look_ahead_distance = 0;
    cfg.enable_tf = 0;
    cfg.scene_change_detection = 0;

    // Keyframes only on request (new viewer, packet loss) or a new stream. Low delay honours a
    // per-picture key request without `force_key_frames`.
    cfg.intra_period_length = -1;
    cfg.intra_refresh_type = ffi::SVT_AV1_KF_REFRESH;

    cfg.rate_control_mode = ffi::SVT_AV1_RC_MODE_CBR as u8;
    cfg.target_bit_rate = bits_per_second(config.bitrate_kbps);
    // The same tight buffer as the VP9 encoder: a throttled viewer's upload has little room for
    // bursts after a step down.
    cfg.starting_buffer_level_ms = 500;
    cfg.optimal_buffer_level_ms = 600;
    cfg.maximum_buffer_size_ms = 700;
    cfg.under_shoot_pct = 50;
    cfg.over_shoot_pct = 50;

    cfg.screen_content_mode = u32::from(options.screen_content);
    cfg.level_of_parallelism = parallelism();
}

fn close(handle: *mut ffi::EbComponentType) {
    // SAFETY: `handle` was started by `open` and is closed exactly once by its owner. SVT-AV1
    // wants the end of the stream signalled and its last packet collected before shutdown.
    unsafe {
        let mut eos = std::mem::zeroed::<ffi::EbBufferHeaderType>();
        eos.size = std::mem::size_of::<ffi::EbBufferHeaderType>() as u32;
        eos.flags = ffi::EB_BUFFERFLAG_EOS;
        eos.pic_type = ffi::EB_AV1_INVALID_PICTURE;
        if ffi::svt_av1_enc_send_picture(handle, &mut eos) == ffi::EB_ErrorNone {
            loop {
                let mut packet: *mut ffi::EbBufferHeaderType = ptr::null_mut();
                let status = ffi::svt_av1_enc_get_packet(handle, &mut packet, 1);
                if status != ffi::EB_ErrorNone || packet.is_null() {
                    break;
                }
                let last = (*packet).flags & ffi::EB_BUFFERFLAG_EOS != 0;
                ffi::svt_av1_enc_release_out_buffer(&mut packet);
                if last {
                    break;
                }
            }
        }
        let _lifecycle = LIFECYCLE.lock().unwrap_or_else(PoisonError::into_inner);
        let status = ffi::svt_av1_enc_deinit(handle);
        if status != ffi::EB_ErrorNone {
            log::error!("SVT-AV1 encoder shutdown failed: {status:#x}");
        }
        ffi::svt_av1_enc_deinit_handle(handle);
    }
}

fn parallelism() -> u32 {
    // SVT-AV1's low levels of parallelism: level 1 is about two and a half times slower at
    // 1080p30, and above level 3 the gain is a few percent while the game or app being shared
    // loses cores (measured with the `encode_speed` example).
    if std::thread::available_parallelism().map_or(1, |n| n.get()) > 8 {
        3
    } else {
        2
    }
}

fn check(status: ffi::EbErrorType, operation: &'static str) -> Result<()> {
    if status == ffi::EB_ErrorNone {
        return Ok(());
    }
    Err(codec_error(operation, format!("error {status:#x}")))
}

fn codec_error(operation: &'static str, message: String) -> Error {
    Error::Codec {
        library: "SVT-AV1",
        operation,
        message,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn config() -> EncoderConfig {
        EncoderConfig::new(320, 240, 30, 500)
    }

    /// The layer of each of the first `count` frames.
    fn layers_of(encoder: &mut Av1Encoder, count: i64) -> Vec<u8> {
        let frame =
            I420Frame::new(320, 240, vec![128; I420Frame::buffer_len(320, 240)]).expect("frame");
        (0..count)
            .map(|index| {
                let out = encoder.encode(&frame, index * 33, false).expect("encode");
                out[0].temporal_layer
            })
            .collect()
    }

    #[test]
    fn validates_the_settings() {
        validate(&config()).expect("defaults");
        validate(&EncoderConfig {
            fps: 120,
            ..config()
        })
        .expect("120 fps");
        for layers in 1..=AV1_TEMPORAL_LAYERS {
            validate(&config().with_temporal_layers(layers)).expect("layers");
        }
        for invalid in [
            EncoderConfig { fps: 0, ..config() },
            EncoderConfig {
                fps: 121,
                ..config()
            },
            config().with_temporal_layers(0),
            config().with_temporal_layers(4),
            config().with_threads(2),
            config().with_max_size(320, 239),
        ] {
            assert!(matches!(validate(&invalid), Err(Error::InvalidConfig(_))));
        }
    }

    #[test]
    fn produces_the_default_and_the_requested_layers() {
        if !av1_cpu_supported() {
            return;
        }
        let mut encoder = Av1Encoder::new(config(), Av1Options::default()).expect("encoder");
        assert_eq!(encoder.temporal_layers(), AV1_TEMPORAL_LAYERS);
        assert_eq!(layers_of(&mut encoder, 5), [0, 2, 1, 2, 0]);

        let one = config().with_temporal_layers(1);
        let mut encoder = Av1Encoder::new(one, Av1Options::default()).expect("encoder");
        assert_eq!(encoder.temporal_layers(), 1);
        assert_eq!(layers_of(&mut encoder, 4), [0, 0, 0, 0]);

        let two = config().with_temporal_layers(2);
        let mut encoder = Av1Encoder::new(two, Av1Options::default()).expect("encoder");
        assert_eq!(layers_of(&mut encoder, 4), [0, 1, 0, 1]);
        // The settings survive a new stream at another size.
        encoder.set_resolution(640, 480).expect("resize");
        assert_eq!(encoder.temporal_layers(), 2);
        assert!(matches!(
            encoder.set_resolution(7682, 480),
            Err(Error::InvalidConfig(_))
        ));
    }

    #[test]
    fn rejects_a_thread_count_when_opened() {
        if !av1_cpu_supported() {
            return;
        }
        assert!(matches!(
            Av1Encoder::new(config().with_threads(2), Av1Options::default()),
            Err(Error::InvalidConfig(_))
        ));
    }
}