Debian Codegraph @

.cargo/vendor/rav1e/src/capi.rs

raw
1 // Copyright (c) 2001-2016, Alliance for Open Media. All rights reserved
2 // Copyright (c) 2017-2023, The rav1e contributors. All rights reserved
3 //
4 // This source code is subject to the terms of the BSD 2 Clause License and
5 // the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6 // was not distributed with this source code in the LICENSE file, you can
7 // obtain it at www.aomedia.org/license/software. If the Alliance for Open
8 // Media Patent License 1.0 was not distributed with this source code in the
9 // PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10
11 //! # C API for rav1e
12 //!
13 //! [rav1e](https://github.com/xiph/rav1e/) is an [AV1](https://aomediacodec.github.io/av1-spec/)
14 //! encoder written in [Rust](https://rust-lang.org)
15 //!
16 //! This is the C-compatible API
17 #![deny(missing_docs)]
18 // Basically everything will be unsafe since this is a FFI
19 #![allow(clippy::undocumented_unsafe_blocks)]
20 // const extern fns are unstable
21 #![allow(clippy::missing_const_for_fn)]
22
23 use std::slice;
24 use std::sync::Arc;
25
26 use std::ffi::CStr;
27 use std::ffi::CString;
28 use std::mem;
29 use std::os::raw::c_char;
30 use std::os::raw::c_int;
31 use std::os::raw::c_void;
32
33 use libc::ptrdiff_t;
34 use libc::size_t;
35
36 use num_derive::*;
37 use num_traits::cast::FromPrimitive;
38
39 use scan_fmt::scan_fmt;
40
41 use crate::api::SceneDetectionSpeed;
42 use crate::prelude as rav1e;
43
44 type PixelRange = rav1e::PixelRange;
45 type ChromaSamplePosition = rav1e::ChromaSamplePosition;
46 type ChromaSampling = rav1e::ChromaSampling;
47 type MatrixCoefficients = rav1e::MatrixCoefficients;
48 type ColorPrimaries = rav1e::ColorPrimaries;
49 type TransferCharacteristics = rav1e::TransferCharacteristics;
50 type Rational = rav1e::Rational;
51 type FrameTypeOverride = rav1e::FrameTypeOverride;
52 type FrameOpaqueCb = Option<extern fn(*mut c_void)>;
53 type T35 = rav1e::T35;
54
55 #[derive(Clone)]
56 enum FrameInternal {
57 U8(Arc<rav1e::Frame<u8>>),
58 U16(Arc<rav1e::Frame<u16>>),
59 }
60
61 impl From<rav1e::Frame<u8>> for FrameInternal {
62 fn from(f: rav1e::Frame<u8>) -> FrameInternal {
63 FrameInternal::U8(Arc::new(f))
64 }
65 }
66
67 impl From<rav1e::Frame<u16>> for FrameInternal {
68 fn from(f: rav1e::Frame<u16>) -> FrameInternal {
69 FrameInternal::U16(Arc::new(f))
70 }
71 }
72
73 impl From<Arc<rav1e::Frame<u8>>> for FrameInternal {
74 fn from(f: Arc<rav1e::Frame<u8>>) -> FrameInternal {
75 FrameInternal::U8(f)
76 }
77 }
78
79 impl From<Arc<rav1e::Frame<u16>>> for FrameInternal {
80 fn from(f: Arc<rav1e::Frame<u16>>) -> FrameInternal {
81 FrameInternal::U16(f)
82 }
83 }
84
85 struct FrameOpaque {
86 opaque: *mut c_void,
87 cb: FrameOpaqueCb,
88 }
89
90 unsafe impl Send for FrameOpaque {}
91 unsafe impl Sync for FrameOpaque {}
92
93 impl Default for FrameOpaque {
94 fn default() -> Self {
95 FrameOpaque { opaque: std::ptr::null_mut(), cb: None }
96 }
97 }
98
99 impl Drop for FrameOpaque {
100 fn drop(&mut self) {
101 let FrameOpaque { opaque, cb } = self;
102 if let Some(cb) = cb {
103 cb(*opaque);
104 }
105 }
106 }
107
108 /// Raw video Frame
109 ///
110 /// It can be allocated through `rav1e_frame_new()`,
111 /// populated using `rav1e_frame_fill_plane()`,
112 /// and freed using `rav1e_frame_unref()`.
113 pub struct Frame {
114 fi: FrameInternal,
115 frame_type: FrameTypeOverride,
116 opaque: Option<FrameOpaque>,
117 t35_metadata: Vec<T35>,
118 }
119
120 /// Status that can be returned by encoder functions.
121 #[repr(C)]
122 #[derive(Copy, Clone, Debug, FromPrimitive, PartialEq)]
123 pub enum EncoderStatus {
124 /// Normal operation.
125 Success = 0,
126 /// The encoder needs more data to produce an output packet.
127 ///
128 /// May be emitted by `rav1e_receive_packet` when frame reordering is
129 /// enabled.
130 NeedMoreData,
131 /// There are enough frames in the queue.
132 ///
133 /// May be emitted by `rav1e_send_frame` when trying to send a frame after
134 /// the encoder has been flushed or the internal queue is full.
135 EnoughData,
136 /// The encoder has already produced the number of frames requested.
137 ///
138 /// May be emitted by `rav1e_receive_packet` after a flush request had been
139 /// processed or the frame limit had been reached.
140 LimitReached,
141 /// A Frame had been encoded but not emitted yet.
142 Encoded,
143 /// Generic fatal error.
144 Failure = -1,
145 /// A frame was encoded in the first pass of a 2-pass encode, but its stats
146 /// data was not retrieved with `rav1e_twopass_out`, or not enough stats data
147 /// was provided in the second pass of a 2-pass encode to encode the next
148 /// frame.
149 NotReady = -2,
150 }
151
152 impl EncoderStatus {
153 const fn to_c(&self) -> *const u8 {
154 use self::EncoderStatus::*;
155 match self {
156 Success => "Normal operation\0".as_ptr(),
157 NeedMoreData => "The encoder needs more data to produce an output packet\0".as_ptr(),
158 EnoughData => "There are enough frames in the queue\0".as_ptr(),
159 LimitReached => "The encoder has already produced the number of frames requested\0".as_ptr(),
160 Encoded => "A Frame had been encoded but not emitted yet\0".as_ptr(),
161 Failure => "Generic fatal error\0".as_ptr(),
162 NotReady => "First-pass stats data not retrieved or not enough second-pass data provided\0".as_ptr(),
163 }
164 }
165 }
166
167 impl From<Option<rav1e::EncoderStatus>> for EncoderStatus {
168 fn from(status: Option<rav1e::EncoderStatus>) -> Self {
169 match status {
170 None => EncoderStatus::Success,
171 Some(s) => match s {
172 rav1e::EncoderStatus::NeedMoreData => EncoderStatus::NeedMoreData,
173 rav1e::EncoderStatus::EnoughData => EncoderStatus::EnoughData,
174 rav1e::EncoderStatus::LimitReached => EncoderStatus::LimitReached,
175 rav1e::EncoderStatus::Encoded => EncoderStatus::Encoded,
176 rav1e::EncoderStatus::Failure => EncoderStatus::Failure,
177 rav1e::EncoderStatus::NotReady => EncoderStatus::NotReady,
178 },
179 }
180 }
181 }
182
183 /// Encoder configuration
184 ///
185 /// Instantiate it using `rav1e_config_default()` and fine-tune it using
186 /// `rav1e_config_parse()`.
187 ///
188 /// Use `rav1e_config_unref()` to free its memory.
189 pub struct Config {
190 cfg: rav1e::Config,
191 }
192
193 enum EncContext {
194 U8(rav1e::Context<u8>),
195 U16(rav1e::Context<u16>),
196 }
197
198 impl EncContext {
199 fn new_frame(&self) -> FrameInternal {
200 match self {
201 EncContext::U8(ctx) => ctx.new_frame().into(),
202 EncContext::U16(ctx) => ctx.new_frame().into(),
203 }
204 }
205 fn send_frame(
206 &mut self, frame: Option<FrameInternal>, frame_type: FrameTypeOverride,
207 opaque: Option<rav1e::Opaque>, t35_metadata: Box<[T35]>,
208 ) -> Result<(), rav1e::EncoderStatus> {
209 let info = rav1e::FrameParameters {
210 frame_type_override: frame_type,
211 opaque,
212 t35_metadata,
213 };
214 if let Some(frame) = frame {
215 match (self, frame) {
216 (EncContext::U8(ctx), FrameInternal::U8(ref f)) => {
217 ctx.send_frame((f.clone(), info))
218 }
219 (EncContext::U16(ctx), FrameInternal::U16(ref f)) => {
220 ctx.send_frame((f.clone(), info))
221 }
222 _ => Err(rav1e::EncoderStatus::Failure),
223 }
224 } else {
225 match self {
226 EncContext::U8(ctx) => ctx.send_frame(None),
227 EncContext::U16(ctx) => ctx.send_frame(None),
228 }
229 }
230 }
231
232 fn receive_packet(&mut self) -> Result<Packet, rav1e::EncoderStatus> {
233 fn receive_packet<T: rav1e::Pixel>(
234 ctx: &mut rav1e::Context<T>,
235 ) -> Result<Packet, rav1e::EncoderStatus>
236 where
237 FrameInternal: From<Arc<v_frame::frame::Frame<T>>>,
238 {
239 ctx.receive_packet().map(|p| {
240 let mut p = std::mem::ManuallyDrop::new(p);
241 let opaque = p.opaque.take().map_or_else(std::ptr::null_mut, |o| {
242 let mut opaque = o.downcast::<FrameOpaque>().unwrap();
243 opaque.cb = None;
244 opaque.opaque
245 });
246 let p = std::mem::ManuallyDrop::into_inner(p);
247 let rav1e::Packet {
248 data, rec, source, input_frameno, frame_type, ..
249 } = p;
250 let len = data.len();
251 let data = Box::into_raw(data.into_boxed_slice()) as *const u8;
252 let rec = if let Some(rec) = rec {
253 let rec = FrameInternal::from(rec);
254 Box::into_raw(Box::new(Frame {
255 fi: rec,
256 frame_type: FrameTypeOverride::No,
257 opaque: None,
258 t35_metadata: Vec::new(),
259 }))
260 } else {
261 std::ptr::null_mut()
262 };
263 let source = if let Some(source) = source {
264 let source = FrameInternal::from(source);
265 Box::into_raw(Box::new(Frame {
266 fi: source,
267 frame_type: FrameTypeOverride::No,
268 opaque: None,
269 t35_metadata: Vec::new(),
270 }))
271 } else {
272 std::ptr::null_mut()
273 };
274 Packet { data, rec, source, len, input_frameno, frame_type, opaque }
275 })
276 }
277 match self {
278 EncContext::U8(ctx) => receive_packet(ctx),
279 EncContext::U16(ctx) => receive_packet(ctx),
280 }
281 }
282
283 fn container_sequence_header(&self) -> Vec<u8> {
284 match self {
285 EncContext::U8(ctx) => ctx.container_sequence_header(),
286 EncContext::U16(ctx) => ctx.container_sequence_header(),
287 }
288 }
289
290 fn twopass_bytes_needed(&mut self) -> usize {
291 match self {
292 EncContext::U8(ctx) => ctx.twopass_bytes_needed(),
293 EncContext::U16(ctx) => ctx.twopass_bytes_needed(),
294 }
295 }
296
297 fn twopass_in(&mut self, buf: &[u8]) -> Result<usize, rav1e::EncoderStatus> {
298 match self {
299 EncContext::U8(ctx) => ctx.twopass_in(buf),
300 EncContext::U16(ctx) => ctx.twopass_in(buf),
301 }
302 }
303
304 fn twopass_out(&mut self) -> Option<&[u8]> {
305 match self {
306 EncContext::U8(ctx) => ctx.twopass_out(),
307 EncContext::U16(ctx) => ctx.twopass_out(),
308 }
309 }
310
311 fn rc_summary_size(&self) -> usize {
312 match self {
313 EncContext::U8(ctx) => ctx.rc_summary_size(),
314 EncContext::U16(ctx) => ctx.rc_summary_size(),
315 }
316 }
317
318 fn rc_receive_pass_data(&mut self) -> Option<rav1e::RcData> {
319 match self {
320 EncContext::U8(ctx) => ctx.rc_receive_pass_data(),
321 EncContext::U16(ctx) => ctx.rc_receive_pass_data(),
322 }
323 }
324
325 fn rc_second_pass_data_required(&self) -> usize {
326 match self {
327 EncContext::U8(ctx) => ctx.rc_second_pass_data_required(),
328 EncContext::U16(ctx) => ctx.rc_second_pass_data_required(),
329 }
330 }
331
332 fn rc_send_pass_data(
333 &mut self, data: &[u8],
334 ) -> Result<(), rav1e::EncoderStatus> {
335 match self {
336 EncContext::U8(ctx) => ctx.rc_send_pass_data(data),
337 EncContext::U16(ctx) => ctx.rc_send_pass_data(data),
338 }
339 }
340
341 fn config(&self) -> rav1e::EncoderConfig {
342 // Ideally this would return a reference instead of cloning,
343 // but that would require a breaking change in the CAPI.
344 match self {
345 EncContext::U8(ctx) => ctx.config.clone(),
346 EncContext::U16(ctx) => ctx.config.clone(),
347 }
348 }
349 }
350
351 /// Encoder context
352 ///
353 /// Contains the encoding state, it is created by `rav1e_context_new()` using an
354 /// Encoder configuration.
355 ///
356 /// Use `rav1e_context_unref()` to free its memory.
357 pub struct Context {
358 ctx: EncContext,
359 last_err: Option<rav1e::EncoderStatus>,
360 }
361
362 type FrameType = rav1e::FrameType;
363
364 /// Encoded Packet
365 ///
366 /// The encoded packets are retrieved using `rav1e_receive_packet()`.
367 ///
368 /// Use `rav1e_packet_unref()` to free its memory.
369 #[repr(C)]
370 pub struct Packet {
371 /// Encoded data buffer
372 pub data: *const u8,
373 /// Encoded data buffer size
374 pub len: size_t,
375 /// Frame sequence number
376 pub input_frameno: u64,
377 /// Frame type
378 pub frame_type: FrameType,
379 /// User provided opaque data
380 pub opaque: *mut c_void,
381 /// The reconstruction of the shown frame.
382 /// This is freed automatically by `rav1e_packet_unref()`.
383 pub rec: *mut Frame,
384 /// The Reference Frame
385 /// This is freed automatically by `rav1e_packet_unref()`.
386 pub source: *mut Frame,
387 }
388
389 /// Version information as presented in `[package]` `version`.
390 ///
391 /// e.g. `0.1.0`
392 ///
393 /// Can be parsed by [semver](https://crates.io/crates/semver).
394 /// This returns the version of the loaded library, regardless
395 /// of which version the library user was built against.
396 #[no_mangle]
397 pub unsafe extern fn rav1e_version_short() -> *const c_char {
398 concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() as *const c_char
399 }
400
401 static FULL_VERSION_C: std::sync::OnceLock<CString> =
402 std::sync::OnceLock::new();
403
404 /// Version information with the information
405 /// provided by `git describe --tags`.
406 ///
407 /// e.g. `0.1.0 (v0.1.0-1-g743d464)`
408 ///
409 /// This returns the version of the loaded library, regardless
410 /// of which version the library user was built against.
411 #[no_mangle]
412 pub unsafe extern fn rav1e_version_full() -> *const c_char {
413 FULL_VERSION_C
414 .get_or_init(|| {
415 CString::new(crate::version::full()).expect("Bogus version data")
416 })
417 .as_ptr() as *const c_char
418 }
419
420 /// Simple Data
421 ///
422 /// Use `rav1e_data_unref()` to free its memory.
423 #[repr(C)]
424 pub struct Data {
425 /// Pointer to the data buffer
426 pub data: *const u8,
427 /// Data buffer size
428 pub len: size_t,
429 }
430
431 /// Free a `RaData` buffer
432 #[no_mangle]
433 pub unsafe extern fn rav1e_data_unref(data: *mut Data) {
434 if !data.is_null() {
435 let data = Box::from_raw(data);
436 let _ = Vec::from_raw_parts(
437 data.data as *mut u8,
438 data.len as usize,
439 data.len as usize,
440 );
441 }
442 }
443
444 /// Create a `RaConfig` filled with default parameters.
445 #[no_mangle]
446 pub unsafe extern fn rav1e_config_default() -> *mut Config {
447 let cfg = rav1e::Config::default();
448
449 let c = Box::new(Config { cfg });
450
451 Box::into_raw(c)
452 }
453
454 unsafe fn decode_slice<'a>(
455 data: *mut *const u8, len: *mut size_t,
456 ) -> (c_int, Option<&'a [u8]>) {
457 if *len < 8 {
458 return (8, None);
459 }
460
461 let buf = slice::from_raw_parts(*data, *len as usize);
462 let (len_bytes, rest) = buf.split_at(std::mem::size_of::<u64>());
463 let buf_len = u64::from_be_bytes(len_bytes.try_into().unwrap()) as usize;
464 let full_len = buf_len + 8;
465 if buf_len > rest.len() {
466 return (full_len as c_int, None);
467 }
468
469 *len -= full_len;
470 *data = (*data).offset(full_len.try_into().unwrap());
471
472 (0, Some(&rest[..buf_len]))
473 }
474
475 /// Setup a second pass rate control using the provided summary
476 ///
477 /// Passing `NULL` data resets the rate control settings.
478 ///
479 /// If additional data is required, pointer and len stay unchanged, otherwise
480 /// they are updated.
481 ///
482 /// Return:
483 /// `0` on success
484 /// `> 0` if the buffer has to be larger
485 /// `< 0` on failure
486 #[no_mangle]
487 // Panic can never occur here
488 #[allow(clippy::missing_panics_doc)]
489 pub unsafe extern fn rav1e_config_set_rc_summary(
490 cfg: *mut Config, data: *mut *const u8, len: *mut size_t,
491 ) -> c_int {
492 if data.is_null() {
493 (*cfg).cfg.rate_control.summary = None;
494
495 return 0;
496 }
497
498 let (needed, maybe_buf) = decode_slice(data, len);
499
500 if maybe_buf.is_none() {
501 return needed;
502 }
503
504 let summary = rav1e::RateControlSummary::from_slice(maybe_buf.unwrap()).ok();
505 if summary.is_none() {
506 -1
507 } else {
508 (*cfg).cfg.rate_control.summary = summary;
509
510 0
511 }
512 }
513
514 /// Request to emit pass data
515 ///
516 /// Set emit to 0 to not emit pass data, non-zero to emit pass data.
517 ///
518 #[no_mangle]
519 pub unsafe extern fn rav1e_config_set_emit_data(
520 cfg: *mut Config, emit: c_int,
521 ) {
522 (*cfg).cfg.rate_control.emit_pass_data = emit != 0;
523 }
524
525 /// Set the display aspect ratio of the stream
526 ///
527 /// Needed for anamorphic video.
528 #[no_mangle]
529 pub unsafe extern fn rav1e_config_set_sample_aspect_ratio(
530 cfg: *mut Config, sample_aspect_ratio: Rational,
531 ) {
532 (*cfg).cfg.enc.sample_aspect_ratio = sample_aspect_ratio
533 }
534
535 /// Set the time base of the stream
536 ///
537 /// Needed for rate control.
538 #[no_mangle]
539 pub unsafe extern fn rav1e_config_set_time_base(
540 cfg: *mut Config, time_base: Rational,
541 ) {
542 (*cfg).cfg.enc.time_base = time_base
543 }
544
545 /// Set pixel format of the stream.
546 ///
547 /// Supported values for `subsampling` and `chroma_pos` are defined by the
548 /// enum types `RaChromaSampling` and `RaChromaSamplePosition` respectively.
549 /// Valid values for `pixel_range` are 0 and 1.
550 ///
551 /// Returns a negative value on error or 0.
552 #[no_mangle]
553 pub unsafe extern fn rav1e_config_set_pixel_format(
554 cfg: *mut Config, bit_depth: u8, subsampling: ChromaSampling,
555 chroma_pos: ChromaSamplePosition, pixel_range: PixelRange,
556 ) -> c_int {
557 if bit_depth != 8 && bit_depth != 10 && bit_depth != 12 {
558 return -1;
559 }
560 (*cfg).cfg.enc.bit_depth = bit_depth as usize;
561
562 let subsampling_val =
563 std::mem::transmute::<ChromaSampling, i32>(subsampling);
564 if ChromaSampling::from_i32(subsampling_val).is_none() {
565 return -1;
566 }
567 (*cfg).cfg.enc.chroma_sampling = subsampling;
568
569 let chroma_pos_val =
570 std::mem::transmute::<ChromaSamplePosition, i32>(chroma_pos);
571 if ChromaSamplePosition::from_i32(chroma_pos_val).is_none() {
572 return -1;
573 }
574 (*cfg).cfg.enc.chroma_sample_position = chroma_pos;
575
576 let pixel_range_val = std::mem::transmute::<PixelRange, i32>(pixel_range);
577 if PixelRange::from_i32(pixel_range_val).is_none() {
578 return -1;
579 }
580 (*cfg).cfg.enc.pixel_range = pixel_range;
581
582 0
583 }
584
585 /// Set color properties of the stream.
586 ///
587 /// Supported values are defined by the enum types
588 /// `RaMatrixCoefficients`, `RaColorPrimaries`, and `RaTransferCharacteristics`
589 /// respectively.
590 ///
591 /// Return a negative value on error or 0.
592 #[no_mangle]
593 pub unsafe extern fn rav1e_config_set_color_description(
594 cfg: *mut Config, matrix: MatrixCoefficients, primaries: ColorPrimaries,
595 transfer: TransferCharacteristics,
596 ) -> c_int {
597 (*cfg).cfg.enc.color_description = Some(rav1e::ColorDescription {
598 matrix_coefficients: matrix,
599 color_primaries: primaries,
600 transfer_characteristics: transfer,
601 });
602
603 if (*cfg).cfg.enc.color_description.is_some() {
604 0
605 } else {
606 -1
607 }
608 }
609
610 /// Set the content light level information for HDR10 streams.
611 ///
612 /// Return a negative value on error or 0.
613 #[no_mangle]
614 pub unsafe extern fn rav1e_config_set_content_light(
615 cfg: *mut Config, max_content_light_level: u16,
616 max_frame_average_light_level: u16,
617 ) -> c_int {
618 (*cfg).cfg.enc.content_light = Some(rav1e::ContentLight {
619 max_content_light_level,
620 max_frame_average_light_level,
621 });
622
623 if (*cfg).cfg.enc.content_light.is_some() {
624 0
625 } else {
626 -1
627 }
628 }
629
630 /// Set the mastering display information for HDR10 streams.
631 ///
632 /// `primaries` and `white_point` arguments are `RaChromaticityPoint`,
633 /// containing 0.16 fixed point values.
634 /// `max_luminance` is a 24.8 fixed point value.
635 /// `min_luminance` is a 18.14 fixed point value.
636 ///
637 /// Returns a negative value on error or 0.
638 /// cbindgen:ptrs-as-arrays=[[primaries;3]]
639 #[no_mangle]
640 pub unsafe extern fn rav1e_config_set_mastering_display(
641 cfg: *mut Config, primaries: *const rav1e::ChromaticityPoint,
642 white_point: rav1e::ChromaticityPoint, max_luminance: u32,
643 min_luminance: u32,
644 ) -> c_int {
645 let primaries = *(primaries as *const [rav1e::ChromaticityPoint; 3]);
646
647 (*cfg).cfg.enc.mastering_display = Some(rav1e::MasteringDisplay {
648 primaries,
649 white_point,
650 max_luminance,
651 min_luminance,
652 });
653
654 if (*cfg).cfg.enc.mastering_display.is_some() {
655 0
656 } else {
657 -1
658 }
659 }
660
661 /// Free the `RaConfig`.
662 #[no_mangle]
663 pub unsafe extern fn rav1e_config_unref(cfg: *mut Config) {
664 if !cfg.is_null() {
665 let _ = Box::from_raw(cfg);
666 }
667 }
668
669 unsafe fn option_match(
670 cfg: *mut Config, key: *const c_char, value: *const c_char,
671 ) -> Result<(), ()> {
672 let key = CStr::from_ptr(key).to_str().map_err(|_| ())?;
673 let value = CStr::from_ptr(value).to_str().map_err(|_| ())?;
674 let enc = &mut (*cfg).cfg.enc;
675
676 match key {
677 "width" => enc.width = value.parse().map_err(|_| ())?,
678 "height" => enc.height = value.parse().map_err(|_| ())?,
679 "speed" => {
680 enc.speed_settings =
681 rav1e::SpeedSettings::from_preset(value.parse().map_err(|_| ())?)
682 }
683
684 "threads" => (*cfg).cfg.threads = value.parse().map_err(|_| ())?,
685
686 "tiles" => enc.tiles = value.parse().map_err(|_| ())?,
687 "tile_rows" => enc.tile_rows = value.parse().map_err(|_| ())?,
688 "tile_cols" => enc.tile_cols = value.parse().map_err(|_| ())?,
689
690 "tune" => enc.tune = value.parse().map_err(|_| ())?,
691 "quantizer" => enc.quantizer = value.parse().map_err(|_| ())?,
692 "min_quantizer" => enc.min_quantizer = value.parse().map_err(|_| ())?,
693 "bitrate" => enc.bitrate = value.parse().map_err(|_| ())?,
694
695 "key_frame_interval" => {
696 enc.set_key_frame_interval(
697 enc.min_key_frame_interval,
698 value.parse().map_err(|_| ())?,
699 );
700 }
701 "min_key_frame_interval" => {
702 enc.set_key_frame_interval(
703 value.parse().map_err(|_| ())?,
704 enc.max_key_frame_interval,
705 );
706 }
707 "switch_frame_interval" => {
708 enc.switch_frame_interval = value.parse().map_err(|_| ())?
709 }
710 "reservoir_frame_delay" => {
711 enc.reservoir_frame_delay = Some(value.parse().map_err(|_| ())?)
712 }
713 "rdo_lookahead_frames" => {
714 enc.speed_settings.rdo_lookahead_frames =
715 value.parse().map_err(|_| ())?
716 }
717 "low_latency" => enc.low_latency = value.parse().map_err(|_| ())?,
718 "enable_timing_info" => {
719 enc.enable_timing_info = value.parse().map_err(|_| ())?
720 }
721 "still_picture" => enc.still_picture = value.parse().map_err(|_| ())?,
722 "no_scene_detection" => {
723 if value.parse::<bool>().map_err(|_| ())? {
724 enc.speed_settings.scene_detection_mode = SceneDetectionSpeed::None;
725 }
726 }
727
728 "level" => {
729 enc.level_idx = match value {
730 "auto" => None,
731 "unconstrained" => Some(31),
732 _ => {
733 let (major, minor) =
734 scan_fmt!(value, "{}.{}", u8, u8).map_err(|_| ())?;
735 if major > 7 || minor > 3 {
736 return Err(());
737 }
738 Some(((major - 2) << 2) + minor)
739 }
740 };
741 }
742
743 _ => return Err(()),
744 }
745
746 Ok(())
747 }
748
749 /// Set a configuration parameter using its key and value as string.
750 ///
751 /// Available keys and values
752 /// - `"width"`: width of the frame, default `640`
753 /// - `"height"`: height of the frame, default `480`
754 /// - `"speed"`: 0-10, default `6`
755 /// - `"threads"`: maximum number of threads to be used, default auto
756 /// - `"tune"`: `"psnr"` or `"psychovisual"`, default `"psychovisual"`
757 /// - `"quantizer"`: 0-255, default `100`
758 /// - `"tiles"`: total number of tiles desired (0 denotes auto), default `0`
759 /// - `"tile_rows"`: number of tiles horizontally (must be a power of two, overridden by tiles if present), default `0`
760 /// - `"tile_cols"`: number of tiles vertically (must be a power of two, overridden by tiles if present), default `0`
761 /// - `"min_quantizer"`: minimum allowed base quantizer to use in bitrate mode, default `0`
762 /// - `"bitrate"`: target bitrate for the bitrate mode (required for two pass mode), default `0`
763 /// - `"key_frame_interval"`: maximum interval between two keyframes, default `240`
764 /// - `"min_key_frame_interval"`: minimum interval between two keyframes, default `12`
765 /// - `"switch_frame_interval"`: interval between switch frames, default `0`
766 /// - `"reservoir_frame_delay"`: number of temporal units over which to distribute the reservoir usage, default `None`
767 /// - `"rdo_lookahead_frames"`: number of frames to read ahead for the RDO lookahead computation, default `40`
768 /// - `"low_latency"`: flag to enable low latency mode, default `false`
769 /// - `"enable_timing_info"`: flag to enable signaling timing info in the bitstream, default `false`
770 /// - `"still_picture"`: flag for still picture mode, default `false`
771 /// - `"no_scene_detection"`: flag to disable scene detection, default `false`
772 ///
773 /// Return a negative value on error or 0.
774 #[no_mangle]
775 pub unsafe extern fn rav1e_config_parse(
776 cfg: *mut Config, key: *const c_char, value: *const c_char,
777 ) -> c_int {
778 if option_match(cfg, key, value) == Ok(()) {
779 0
780 } else {
781 -1
782 }
783 }
784
785 /// Set a configuration parameter using its key and value as integer.
786 ///
787 /// Available keys and values are the same as `rav1e_config_parse()`
788 ///
789 /// Return a negative value on error or 0.
790 #[no_mangle]
791 // Panic can never occur here
792 #[allow(clippy::missing_panics_doc)]
793 pub unsafe extern fn rav1e_config_parse_int(
794 cfg: *mut Config, key: *const c_char, value: c_int,
795 ) -> c_int {
796 let val = CString::new(value.to_string()).unwrap();
797 if option_match(cfg, key, val.as_ptr()) == Ok(()) {
798 0
799 } else {
800 config_parse_bool(cfg, key, value)
801 }
802 }
803
804 unsafe fn config_parse_bool(
805 cfg: *mut Config, key: *const c_char, value: c_int,
806 ) -> c_int {
807 let val = CString::new(if value != 0 { "true" } else { "false" }).unwrap();
808 if option_match(cfg, key, val.as_ptr()) == Ok(()) {
809 0
810 } else {
811 -1
812 }
813 }
814
815 /// Generate a new encoding context from a populated encoder configuration
816 ///
817 /// Multiple contexts can be generated through it.
818 /// Returns `Null` if context creation failed, e.g. by passing
819 /// an invalid `Config`.
820 #[no_mangle]
821 pub unsafe extern fn rav1e_context_new(cfg: *const Config) -> *mut Context {
822 let cfg = &(*cfg).cfg;
823 let enc = &cfg.enc;
824
825 let ctx = match enc.bit_depth {
826 8 => cfg.new_context().map(EncContext::U8),
827 _ => cfg.new_context().map(EncContext::U16),
828 };
829
830 if let Ok(ctx) = ctx {
831 Box::into_raw(Box::new(Context { ctx, last_err: None }))
832 } else {
833 std::ptr::null_mut()
834 }
835 }
836
837 /// Free the `RaContext`.
838 #[no_mangle]
839 pub unsafe extern fn rav1e_context_unref(ctx: *mut Context) {
840 if !ctx.is_null() {
841 let _ = Box::from_raw(ctx);
842 }
843 }
844
845 /// Produce a new frame from the encoding context
846 ///
847 /// It must be populated using `rav1e_frame_fill_plane()`.
848 ///
849 /// The frame is reference counted and must be released passing it to `rav1e_frame_unref()`,
850 /// see `rav1e_send_frame()`.
851 #[no_mangle]
852 pub unsafe extern fn rav1e_frame_new(ctx: *const Context) -> *mut Frame {
853 let fi = (*ctx).ctx.new_frame();
854 let frame_type = rav1e::FrameTypeOverride::No;
855 let f = Frame { fi, frame_type, opaque: None, t35_metadata: Vec::new() };
856 let frame = Box::new(f);
857
858 Box::into_raw(frame)
859 }
860
861 /// Free the `RaFrame`.
862 #[no_mangle]
863 pub unsafe extern fn rav1e_frame_unref(frame: *mut Frame) {
864 if !frame.is_null() {
865 let _ = Box::from_raw(frame);
866 }
867 }
868
869 /// Overrides the encoders frame type decision for a frame
870 ///
871 /// Must be called before `rav1e_send_frame()` if used.
872 #[no_mangle]
873 pub unsafe extern fn rav1e_frame_set_type(
874 frame: *mut Frame, frame_type: FrameTypeOverride,
875 ) -> c_int {
876 let frame_type_val =
877 std::mem::transmute::<FrameTypeOverride, i32>(frame_type);
878 if FrameTypeOverride::from_i32(frame_type_val).is_none() {
879 return -1;
880 }
881 (*frame).frame_type = frame_type;
882
883 0
884 }
885
886 /// Register an opaque data and a destructor to the frame
887 ///
888 /// It takes the ownership of its memory:
889 /// - it will relinquish the ownership to the context if
890 /// `rav1e_send_frame` is called.
891 /// - it will call the destructor if `rav1e_frame_unref` is called
892 /// otherwise.
893 #[no_mangle]
894 pub unsafe extern fn rav1e_frame_set_opaque(
895 frame: *mut Frame, opaque: *mut c_void, cb: FrameOpaqueCb,
896 ) {
897 if opaque.is_null() {
898 (*frame).opaque = None;
899 } else {
900 (*frame).opaque = Some(FrameOpaque { opaque, cb });
901 }
902 }
903
904 /// Add generic T35 metadata to a frame
905 ///
906 /// The buffer will be copied into the frame and can be freed
907 /// immediately after this call.
908 ///
909 /// Can be called multiple times to add multiple T35 metadata
910 /// blocks.
911 #[no_mangle]
912 pub unsafe extern fn rav1e_frame_add_t35_metadata(
913 frame: *mut Frame, country_code: u8, country_code_extension_byte: u8,
914 data: *const u8, data_len: size_t,
915 ) {
916 (*frame).t35_metadata.push(T35 {
917 country_code,
918 country_code_extension_byte,
919 data: slice::from_raw_parts(data, data_len).into(),
920 });
921 }
922
923 /// Retrieve the first-pass data of a two-pass encode for the frame that was
924 /// just encoded. This should be called BEFORE every call to `rav1e_receive_packet()`
925 /// (including the very first one), even if no packet was produced by the
926 /// last call to `rav1e_receive_packet`, if any (i.e., `RA_ENCODER_STATUS_ENCODED`
927 /// was returned). It needs to be called once more after
928 /// `RA_ENCODER_STATUS_LIMIT_REACHED` is returned, to retrieve the header that
929 /// should be written to the front of the stats file (overwriting the
930 /// placeholder header that was emitted at the start of encoding).
931 ///
932 /// It is still safe to call this function when `rav1e_receive_packet()` returns any
933 /// other error. It will return `NULL` instead of returning a duplicate copy
934 /// of the previous frame's data.
935 ///
936 /// Must be freed with `rav1e_data_unref()`.
937 #[no_mangle]
938 // Panic can never occur here
939 #[allow(clippy::missing_panics_doc)]
940 pub unsafe extern fn rav1e_twopass_out(ctx: *mut Context) -> *mut Data {
941 let buf = (*ctx).ctx.twopass_out();
942
943 if buf.is_none() {
944 return std::ptr::null_mut();
945 }
946
947 let v = buf.unwrap().to_vec();
948 Box::into_raw(Box::new(Data {
949 len: v.len(),
950 data: Box::into_raw(v.into_boxed_slice()) as *mut u8,
951 }))
952 }
953
954 /// Rate Control Data
955 #[derive(Debug, PartialEq)]
956 #[repr(C)]
957 pub enum RcDataKind {
958 /// A Rate Control Summary Packet
959 ///
960 /// It is emitted once, after the encoder is flushed.
961 ///
962 /// It contains a summary of the rate control information for the
963 /// encoding process that just terminated.
964 Summary,
965 /// A Rate Control Frame-specific Packet
966 ///
967 /// It is emitted every time a frame is processed.
968 ///
969 /// The information contained is required to encode its matching
970 /// frame in a second pass encoding.
971 Frame,
972 /// There is no pass data available for now
973 ///
974 /// This is emitted if `rav1e_rc_receive_pass_data` is called more
975 /// often than it should.
976 Empty,
977 }
978
979 /// Return the Rate Control Summary Packet size
980 ///
981 /// It is useful mainly to preserve space when saving
982 /// both Rate Control Summary and Frame Packets in a single file
983 #[no_mangle]
984 pub unsafe extern fn rav1e_rc_summary_size(ctx: *const Context) -> size_t {
985 (*ctx).ctx.rc_summary_size() as size_t + 8
986 }
987
988 /// Return the first pass data
989 ///
990 /// Call it after `rav1e_receive_packet()` returns a normal condition status:
991 /// - `EncoderStatus::Encoded`,
992 /// - `EncoderStatus::Success`,
993 /// - `EncoderStatus::LimitReached`.
994 ///
995 /// use `rav1e_data_unref()` to free the data.
996 ///
997 /// It will return a `RcDataKind::Summary` once the encoder is flushed.
998 #[no_mangle]
999 pub unsafe extern fn rav1e_rc_receive_pass_data(
1000 ctx: *mut Context, data: *mut *mut Data,
1001 ) -> RcDataKind {
1002 use crate::api::RcData::*;
1003 let (buf, kind) = match (*ctx).ctx.rc_receive_pass_data() {
1004 Some(Summary(data)) => (data, RcDataKind::Summary),
1005 Some(Frame(data)) => (data, RcDataKind::Frame),
1006 None => return RcDataKind::Empty,
1007 };
1008
1009 let mut full_buf = Vec::with_capacity(buf.len() + 8);
1010
1011 full_buf.extend_from_slice(&(buf.len() as u64).to_be_bytes());
1012 full_buf.extend_from_slice(&buf);
1013
1014 let full_buf = full_buf.into_boxed_slice();
1015
1016 *data = Box::into_raw(Box::new(Data {
1017 len: full_buf.len(),
1018 data: Box::into_raw(full_buf) as *mut u8,
1019 }));
1020
1021 kind
1022 }
1023
1024 /// Number of pass data packets required to progress the encoding process.
1025 ///
1026 /// At least that number of packets must be passed before the encoder can
1027 /// progress.
1028 ///
1029 /// Stop feeding-in pass data packets once the function returns 0.
1030 ///
1031 /// ``` c
1032 /// while (rav1e_rc_second_pass_data_required(ctx) > 0) {
1033 /// int more = rav1e_rc_send_pass_data(ctx, &data, &len);
1034 /// if (more > 0) {
1035 /// refill(&data, &len);
1036 /// } else if (more < 0) {
1037 /// goto fail;
1038 /// }
1039 /// }
1040 /// ```
1041 ///
1042 #[no_mangle]
1043 pub unsafe extern fn rav1e_rc_second_pass_data_required(
1044 ctx: *const Context,
1045 ) -> i32 {
1046 (*ctx).ctx.rc_second_pass_data_required() as i32
1047 }
1048
1049 /// Feed the first pass Rate Control data to the encoder,
1050 /// Frame-specific Packets only.
1051 ///
1052 /// Call it before `receive_packet()`
1053 ///
1054 /// If additional data is required, pointer and len stay unchanged, otherwise
1055 /// they are updated.
1056 ///
1057 /// Returns:
1058 /// - `0` on success,
1059 /// - `> 0` the amount of bytes needed
1060 /// - `< 0` on unrecoverable failure
1061 #[no_mangle]
1062 // Panic can never occur here
1063 #[allow(clippy::missing_panics_doc)]
1064 pub unsafe extern fn rav1e_rc_send_pass_data(
1065 ctx: *mut Context, data: *mut *const u8, len: *mut size_t,
1066 ) -> c_int {
1067 let (need, maybe_buf) = decode_slice(data, len);
1068
1069 if maybe_buf.is_none() {
1070 return need;
1071 }
1072
1073 let ret = (*ctx)
1074 .ctx
1075 .rc_send_pass_data(maybe_buf.unwrap())
1076 .map(|_v| None)
1077 .unwrap_or_else(Some);
1078
1079 (*ctx).last_err = ret;
1080
1081 if ret.is_some() {
1082 -1
1083 } else {
1084 0
1085 }
1086 }
1087
1088 /// Ask how many bytes of the stats file are needed before the next frame
1089 /// of the second pass in a two-pass encode can be encoded. This is a lower
1090 /// bound (more might be required), but if 0 is returned, then encoding can
1091 /// proceed. This is just a hint to the application, and does not need to
1092 /// be called for encoding the second pass to work, so long as the
1093 /// application continues to provide more data to `rav1e_twopass_in()` in a loop
1094 /// until `rav1e_twopass_in()` returns 0.
1095 #[no_mangle]
1096 pub unsafe extern fn rav1e_twopass_bytes_needed(ctx: *mut Context) -> size_t {
1097 (*ctx).ctx.twopass_bytes_needed() as size_t
1098 }
1099
1100 /// Provide stats data produced in the first pass of a two-pass encode to the
1101 /// second pass. On success this returns the number of bytes of that data
1102 /// which were consumed. When encoding the second pass of a two-pass encode,
1103 /// this should be called repeatedly in a loop before every call to
1104 /// `rav1e_receive_packet()` (including the very first one) until no bytes are
1105 /// consumed, or until `twopass_bytes_needed()` returns 0. Returns -1 on failure.
1106 #[no_mangle]
1107 pub unsafe extern fn rav1e_twopass_in(
1108 ctx: *mut Context, buf: *mut u8, buf_size: size_t,
1109 ) -> c_int {
1110 let buf_slice = slice::from_raw_parts(buf, buf_size as usize);
1111 let r = (*ctx).ctx.twopass_in(buf_slice);
1112 match r {
1113 Ok(v) => v as c_int,
1114 Err(v) => {
1115 (*ctx).last_err = Some(v);
1116 -1
1117 }
1118 }
1119 }
1120
1121 /// Send the frame for encoding
1122 ///
1123 /// The function increases the frame internal reference count and it can be passed multiple
1124 /// times to different `rav1e_send_frame()` with a caveat:
1125 ///
1126 /// The opaque data, if present, will be moved from the `Frame` to the `Context`
1127 /// and returned by `rav1e_receive_packet` in the `Packet` `opaque` field or
1128 /// the destructor will be called on `rav1e_context_unref` if the frame is
1129 /// still pending in the encoder.
1130 ///
1131 /// Returns:
1132 /// - `0` on success,
1133 /// - `> 0` if the input queue is full
1134 /// - `< 0` on unrecoverable failure
1135 #[no_mangle]
1136 pub unsafe extern fn rav1e_send_frame(
1137 ctx: *mut Context, frame: *mut Frame,
1138 ) -> EncoderStatus {
1139 if !frame.is_null() {
1140 let rav1e::EncoderConfig { width, height, chroma_sampling, .. } =
1141 (*ctx).ctx.config();
1142 let planes = if chroma_sampling == ChromaSampling::Cs400 { 1 } else { 3 };
1143 match (*frame).fi {
1144 FrameInternal::U8(ref mut f) => {
1145 rav1e_frame_pad_internal(f, planes, width, height)
1146 }
1147 FrameInternal::U16(ref mut f) => {
1148 rav1e_frame_pad_internal(f, planes, width, height)
1149 }
1150 }
1151 }
1152
1153 let frame_internal =
1154 if frame.is_null() { None } else { Some((*frame).fi.clone()) };
1155 let frame_type = if frame.is_null() {
1156 rav1e::FrameTypeOverride::No
1157 } else {
1158 (*frame).frame_type
1159 };
1160
1161 let maybe_opaque = if frame.is_null() {
1162 None
1163 } else {
1164 (*frame).opaque.take().map(rav1e::Opaque::new)
1165 };
1166
1167 let t35_metadata = if frame.is_null() {
1168 Box::new([])
1169 } else {
1170 mem::take(&mut (*frame).t35_metadata).into_boxed_slice()
1171 };
1172
1173 let ret = (*ctx)
1174 .ctx
1175 .send_frame(frame_internal, frame_type, maybe_opaque, t35_metadata)
1176 .map(|_v| None)
1177 .unwrap_or_else(Some);
1178
1179 (*ctx).last_err = ret;
1180
1181 ret.into()
1182 }
1183
1184 /// Return the last encoder status
1185 #[no_mangle]
1186 pub unsafe extern fn rav1e_last_status(ctx: *const Context) -> EncoderStatus {
1187 (*ctx).last_err.into()
1188 }
1189
1190 /// Return a static string matching the `EncoderStatus` variant.
1191 ///
1192 #[no_mangle]
1193 pub unsafe extern fn rav1e_status_to_str(
1194 status: EncoderStatus,
1195 ) -> *const c_char {
1196 if EncoderStatus::from_i32(std::mem::transmute(status)).is_none() {
1197 return std::ptr::null();
1198 }
1199
1200 status.to_c() as *const c_char
1201 }
1202
1203 /// Receive encoded data
1204 ///
1205 /// Returns:
1206 /// - `0` on success
1207 /// - `> 0` if additional frame data is required
1208 /// - `< 0` on unrecoverable failure
1209 #[no_mangle]
1210 pub unsafe extern fn rav1e_receive_packet(
1211 ctx: *mut Context, pkt: *mut *mut Packet,
1212 ) -> EncoderStatus {
1213 let ret = (*ctx)
1214 .ctx
1215 .receive_packet()
1216 .map(|packet| {
1217 *pkt = Box::into_raw(Box::new(packet));
1218 None
1219 })
1220 .unwrap_or_else(Some);
1221
1222 (*ctx).last_err = ret;
1223
1224 ret.into()
1225 }
1226
1227 /// Free the `RaPacket`.
1228 #[no_mangle]
1229 pub unsafe extern fn rav1e_packet_unref(pkt: *mut Packet) {
1230 if !pkt.is_null() {
1231 let pkt = Box::from_raw(pkt);
1232 let _ = Vec::from_raw_parts(
1233 pkt.data as *mut u8,
1234 pkt.len as usize,
1235 pkt.len as usize,
1236 );
1237 rav1e_frame_unref(pkt.rec);
1238 rav1e_frame_unref(pkt.source);
1239 }
1240 }
1241
1242 /// Produce a sequence header matching the current encoding context
1243 ///
1244 /// Its format is compatible with the AV1 Matroska and ISOBMFF specification.
1245 ///
1246 /// Use `rav1e_data_unref()` to free it.
1247 #[no_mangle]
1248 pub unsafe extern fn rav1e_container_sequence_header(
1249 ctx: *const Context,
1250 ) -> *mut Data {
1251 let buf = (*ctx).ctx.container_sequence_header();
1252
1253 Box::into_raw(Box::new(Data {
1254 len: buf.len(),
1255 data: Box::into_raw(buf.into_boxed_slice()) as *mut u8,
1256 }))
1257 }
1258
1259 fn rav1e_frame_fill_plane_internal<T: rav1e::Pixel>(
1260 f: &mut Arc<rav1e::Frame<T>>, plane: c_int, data_slice: &[u8],
1261 stride: ptrdiff_t, bytewidth: c_int,
1262 ) {
1263 let input = Arc::get_mut(f).unwrap();
1264 input.planes[plane as usize].copy_from_raw_u8(
1265 data_slice,
1266 stride as usize,
1267 bytewidth as usize,
1268 );
1269 }
1270
1271 fn rav1e_frame_pad_internal<T: rav1e::Pixel>(
1272 f: &mut Arc<rav1e::Frame<T>>, planes: usize, width: usize, height: usize,
1273 ) {
1274 if let Some(ref mut input) = Arc::get_mut(f) {
1275 for plane in input.planes[..planes].iter_mut() {
1276 plane.pad(width, height);
1277 }
1278 }
1279 }
1280
1281 fn rav1e_frame_extract_plane_internal<T: rav1e::Pixel>(
1282 f: &Arc<rav1e::Frame<T>>, plane: c_int, data_slice: &mut [u8],
1283 stride: ptrdiff_t, bytewidth: c_int,
1284 ) {
1285 f.planes[plane as usize].copy_to_raw_u8(
1286 data_slice,
1287 stride as usize,
1288 bytewidth as usize,
1289 );
1290 }
1291
1292 /// Fill a frame plane
1293 ///
1294 /// Currently the frame contains 3 planes, the first is luminance followed by
1295 /// chrominance.
1296 ///
1297 /// The data is copied and this function has to be called for each plane.
1298 ///
1299 /// `frame`: A frame provided by `rav1e_frame_new()`
1300 /// `plane`: The index of the plane starting from 0
1301 /// `data`: The data to be copied
1302 /// `data_len`: Length of the buffer
1303 /// `stride`: Plane line in bytes, including padding
1304 /// `bytewidth`: Number of bytes per component, either 1 or 2
1305 #[no_mangle]
1306 pub unsafe extern fn rav1e_frame_fill_plane(
1307 frame: *mut Frame, plane: c_int, data: *const u8, data_len: size_t,
1308 stride: ptrdiff_t, bytewidth: c_int,
1309 ) {
1310 let data_slice = slice::from_raw_parts(data, data_len as usize);
1311
1312 match (*frame).fi {
1313 FrameInternal::U8(ref mut f) => {
1314 rav1e_frame_fill_plane_internal(f, plane, data_slice, stride, bytewidth)
1315 }
1316 FrameInternal::U16(ref mut f) => {
1317 rav1e_frame_fill_plane_internal(f, plane, data_slice, stride, bytewidth)
1318 }
1319 }
1320 }
1321
1322 /// Extract a frame plane
1323 ///
1324 /// This is the reverse of `rav1e_frame_fill_plane()`, primarily used for
1325 /// extracting the source and reconstruction data from a `RaPacket`.
1326 ///
1327 /// Currently the frame contains 3 planes, the first is luminance followed by
1328 /// chrominance.
1329 ///
1330 /// The data is copied out of the frame for a single plane.
1331 ///
1332 /// `frame`: A frame provided inside a packet returned by `rav1e_receive_packet()`
1333 /// `plane`: The index of the plane starting from 0
1334 /// `data`: The destination for the data
1335 /// `data_len`: Length of the buffer
1336 /// `stride`: Plane line in bytes, including padding
1337 /// `bytewidth`: Number of bytes per component, either 1 or 2
1338 #[no_mangle]
1339 pub unsafe extern fn rav1e_frame_extract_plane(
1340 frame: *const Frame, plane: c_int, data: *mut u8, data_len: size_t,
1341 stride: ptrdiff_t, bytewidth: c_int,
1342 ) {
1343 let data_slice = slice::from_raw_parts_mut(data, data_len as usize);
1344
1345 match (*frame).fi {
1346 FrameInternal::U8(ref f) => rav1e_frame_extract_plane_internal(
1347 f, plane, data_slice, stride, bytewidth,
1348 ),
1349 FrameInternal::U16(ref f) => rav1e_frame_extract_plane_internal(
1350 f, plane, data_slice, stride, bytewidth,
1351 ),
1352 }
1353 }
1354
1355 #[cfg(test)]
1356 mod test {
1357 use super::*;
1358
1359 use std::ffi::CString;
1360
1361 #[test]
1362 fn forward_opaque() {
1363 unsafe {
1364 let rac = rav1e_config_default();
1365 let w = CString::new("width").unwrap();
1366 rav1e_config_parse_int(rac, w.as_ptr(), 64);
1367 let h = CString::new("height").unwrap();
1368 rav1e_config_parse_int(rac, h.as_ptr(), 64);
1369 let s = CString::new("speed").unwrap();
1370 rav1e_config_parse_int(rac, s.as_ptr(), 10);
1371 let l = CString::new("level").unwrap();
1372 let lo = CString::new("6.2").unwrap();
1373 rav1e_config_parse(rac, l.as_ptr(), lo.as_ptr());
1374
1375 let rax = rav1e_context_new(rac);
1376
1377 let f = rav1e_frame_new(rax);
1378
1379 let pixels = [42; 64 * 64];
1380 rav1e_frame_fill_plane(f, 0, pixels.as_ptr(), pixels.len(), 64, 1);
1381
1382 for i in 0..30 {
1383 let v = Box::new(i as u8);
1384 extern fn cb(o: *mut c_void) {
1385 let v = unsafe { Box::from_raw(o as *mut u8) };
1386 eprintln!("Would free {}", v);
1387 }
1388 rav1e_frame_set_opaque(f, Box::into_raw(v) as *mut c_void, Some(cb));
1389 rav1e_send_frame(rax, f);
1390 }
1391
1392 rav1e_send_frame(rax, std::ptr::null_mut());
1393
1394 for _ in 0..15 {
1395 let mut p: *mut Packet = std::ptr::null_mut();
1396 let ret = rav1e_receive_packet(rax, &mut p);
1397
1398 if ret == EncoderStatus::Success {
1399 let mut source = vec![1; 64 * 64];
1400 rav1e_frame_extract_plane(
1401 (*p).source,
1402 0,
1403 source.as_mut_ptr(),
1404 64 * 64,
1405 64,
1406 1,
1407 );
1408 assert_eq!(source, vec![42; 64 * 64]);
1409 let v = Box::from_raw((*p).opaque as *mut u8);
1410 eprintln!("Opaque {}", v);
1411 }
1412
1413 if ret == EncoderStatus::LimitReached {
1414 break;
1415 }
1416 }
1417
1418 let v = Box::new(42u64);
1419 extern fn cb(o: *mut c_void) {
1420 let v = unsafe { Box::from_raw(o as *mut u64) };
1421 eprintln!("Would free {}", v);
1422 }
1423 rav1e_frame_set_opaque(f, Box::into_raw(v) as *mut c_void, Some(cb));
1424
1425 // 42 would be freed after this
1426 rav1e_frame_unref(f);
1427 // 15 - reorder delay .. 29 would be freed after this
1428 rav1e_context_unref(rax);
1429 rav1e_config_unref(rac);
1430 }
1431 }
1432
1433 #[test]
1434 fn two_pass_encoding() {
1435 unsafe {
1436 let rac = rav1e_config_default();
1437 let w = CString::new("width").unwrap();
1438 rav1e_config_parse_int(rac, w.as_ptr(), 64);
1439 let h = CString::new("height").unwrap();
1440 rav1e_config_parse_int(rac, h.as_ptr(), 64);
1441 let s = CString::new("speed").unwrap();
1442 rav1e_config_parse_int(rac, s.as_ptr(), 10);
1443 let s = CString::new("bitrate").unwrap();
1444 rav1e_config_parse_int(rac, s.as_ptr(), 1000);
1445 rav1e_config_set_emit_data(rac, 1);
1446
1447 let rax = rav1e_context_new(rac);
1448 let f = rav1e_frame_new(rax);
1449
1450 let pixels = [42; 64 * 64];
1451 rav1e_frame_fill_plane(f, 0, pixels.as_ptr(), pixels.len(), 64, 1);
1452
1453 for _ in 0..10 {
1454 rav1e_send_frame(rax, f);
1455 }
1456
1457 rav1e_send_frame(rax, std::ptr::null_mut());
1458
1459 let mut frame_data = std::collections::VecDeque::new();
1460 let mut summary: *mut Data = std::ptr::null_mut();
1461
1462 loop {
1463 let mut p: *mut Packet = std::ptr::null_mut();
1464 let ret = rav1e_receive_packet(rax, &mut p);
1465 rav1e_packet_unref(p);
1466 if ret == EncoderStatus::LimitReached {
1467 let kind = rav1e_rc_receive_pass_data(rax, &mut summary);
1468 assert_eq!(kind, RcDataKind::Summary);
1469 eprintln!("Got rc summary {} bytes", (*summary).len);
1470 break;
1471 } else if ret == EncoderStatus::Encoded
1472 || ret == EncoderStatus::Success
1473 {
1474 let mut p: *mut Data = std::ptr::null_mut();
1475 let kind = rav1e_rc_receive_pass_data(rax, &mut p);
1476 assert_eq!(kind, RcDataKind::Frame);
1477 eprintln!("Got rc frame data {} bytes", (*p).len);
1478 frame_data.push_back(p);
1479 }
1480 }
1481
1482 rav1e_config_set_emit_data(rac, 0);
1483 let mut data = (*summary).data;
1484 let mut len = (*summary).len;
1485 let ret = rav1e_config_set_rc_summary(rac, &mut data, &mut len);
1486 assert_eq!(ret, 0);
1487
1488 rav1e_data_unref(summary);
1489
1490 for _ in 0..10 {
1491 rav1e_send_frame(rax, f);
1492 }
1493
1494 rav1e_send_frame(rax, std::ptr::null_mut());
1495
1496 loop {
1497 let mut p: *mut Packet = std::ptr::null_mut();
1498 while rav1e_rc_second_pass_data_required(rax) > 0 {
1499 let d = frame_data.pop_front().unwrap();
1500 let mut data = (*d).data;
1501 let mut len = (*d).len;
1502 rav1e_rc_send_pass_data(rax, &mut data, &mut len);
1503 rav1e_data_unref(d);
1504 }
1505
1506 let ret = rav1e_receive_packet(rax, &mut p);
1507 rav1e_packet_unref(p);
1508 if ret == EncoderStatus::LimitReached {
1509 break;
1510 }
1511 }
1512
1513 rav1e_frame_unref(f);
1514 rav1e_context_unref(rax);
1515 rav1e_config_unref(rac);
1516 }
1517 }
1518
1519 #[test]
1520 fn invalid_level() {
1521 unsafe {
1522 let rac = rav1e_config_default();
1523 let l = CString::new("level").unwrap();
1524 let lo = CString::new("8.3").unwrap();
1525 assert_eq!(rav1e_config_parse(rac, l.as_ptr(), lo.as_ptr()), -1);
1526 rav1e_config_unref(rac);
1527 }
1528 }
1529 }