use std::fmt;
use crate::enc::config_enc::{webp_config_lossless_preset, webp_validate_config};
use crate::enc::picture_csp_enc::{
webp_picture_import_bgr, webp_picture_import_bgra, webp_picture_import_bgrx,
webp_picture_import_rgb, webp_picture_import_rgba, webp_picture_import_rgbx,
};
use crate::enc::picture_enc::{
LOSSLESS_DEFAULT_QUALITY, webp_memory_write, webp_memory_writer_init,
};
use crate::enc::webp_enc::webp_encode;
pub use crate::webp::encode::WebPAuxStats;
use crate::webp::encode::{
WEBP_MAX_DIMENSION, WebPConfig, WebPEncCSP, WebPEncodingError, WebPImageHint, WebPMemoryWriter,
WebPPicture, WebPPreset, webp_config_init, webp_config_preset, webp_picture_init,
};
use crate::webp::types::{PlaneOffset, PlaneStorage};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Preset {
#[default]
Default,
Picture,
Photo,
Drawing,
Icon,
Text,
}
impl Preset {
const fn raw(self) -> WebPPreset {
match self {
Self::Default => WebPPreset::WEBP_PRESET_DEFAULT,
Self::Picture => WebPPreset::WEBP_PRESET_PICTURE,
Self::Photo => WebPPreset::WEBP_PRESET_PHOTO,
Self::Drawing => WebPPreset::WEBP_PRESET_DRAWING,
Self::Icon => WebPPreset::WEBP_PRESET_ICON,
Self::Text => WebPPreset::WEBP_PRESET_TEXT,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ImageHint {
#[default]
Default,
Picture,
Photo,
Graph,
}
impl ImageHint {
const fn raw(self) -> WebPImageHint {
match self {
Self::Default => WebPImageHint::WEBP_HINT_DEFAULT,
Self::Picture => WebPImageHint::WEBP_HINT_PICTURE,
Self::Photo => WebPImageHint::WEBP_HINT_PHOTO,
Self::Graph => WebPImageHint::WEBP_HINT_GRAPH,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AlphaFilter {
None,
#[default]
Fast,
Best,
}
impl AlphaFilter {
const fn raw(self) -> i32 {
match self {
Self::None => 0,
Self::Fast => 1,
Self::Best => 2,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PixelLayout {
Rgb,
Rgba,
Rgbx,
Bgr,
Bgra,
Bgrx,
}
impl PixelLayout {
#[must_use]
pub const fn bytes_per_pixel(self) -> usize {
match self {
Self::Rgb | Self::Bgr => 3,
Self::Rgba | Self::Rgbx | Self::Bgra | Self::Bgrx => 4,
}
}
fn importer(self) -> fn(&mut WebPPicture<'_>, &[u8], i32) -> bool {
match self {
Self::Rgb => webp_picture_import_rgb,
Self::Rgba => webp_picture_import_rgba,
Self::Rgbx => webp_picture_import_rgbx,
Self::Bgr => webp_picture_import_bgr,
Self::Bgra => webp_picture_import_bgra,
Self::Bgrx => webp_picture_import_bgrx,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SampleForm {
Yuva,
Argb,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Plane {
Pixels,
Y,
U,
V,
A,
Argb,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EncodeError {
OutOfMemory,
BitstreamOutOfMemory,
NullParameter,
InvalidConfiguration,
BadDimension,
Partition0Overflow,
PartitionOverflow,
BadWrite,
FileTooBig,
UserAbort,
Unreported,
InvalidDimensions {
width: u32,
height: u32,
},
InvalidStride {
plane: Plane,
stride: usize,
},
BufferTooShort {
plane: Plane,
len: usize,
needed: usize,
},
InvalidParameter {
name: &'static str,
},
}
impl EncodeError {
#[must_use]
pub const fn code(&self) -> Option<WebPEncodingError> {
Some(match self {
Self::OutOfMemory => WebPEncodingError::VP8_ENC_ERROR_OUT_OF_MEMORY,
Self::BitstreamOutOfMemory => WebPEncodingError::VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY,
Self::NullParameter => WebPEncodingError::VP8_ENC_ERROR_NULL_PARAMETER,
Self::InvalidConfiguration => WebPEncodingError::VP8_ENC_ERROR_INVALID_CONFIGURATION,
Self::BadDimension => WebPEncodingError::VP8_ENC_ERROR_BAD_DIMENSION,
Self::Partition0Overflow => WebPEncodingError::VP8_ENC_ERROR_PARTITION0_OVERFLOW,
Self::PartitionOverflow => WebPEncodingError::VP8_ENC_ERROR_PARTITION_OVERFLOW,
Self::BadWrite => WebPEncodingError::VP8_ENC_ERROR_BAD_WRITE,
Self::FileTooBig => WebPEncodingError::VP8_ENC_ERROR_FILE_TOO_BIG,
Self::UserAbort => WebPEncodingError::VP8_ENC_ERROR_USER_ABORT,
Self::Unreported => WebPEncodingError::VP8_ENC_OK,
Self::InvalidDimensions { .. }
| Self::InvalidStride { .. }
| Self::BufferTooShort { .. }
| Self::InvalidParameter { .. } => return None,
})
}
const fn from_code(code: WebPEncodingError) -> Self {
match code {
WebPEncodingError::VP8_ENC_ERROR_OUT_OF_MEMORY => Self::OutOfMemory,
WebPEncodingError::VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY => Self::BitstreamOutOfMemory,
WebPEncodingError::VP8_ENC_ERROR_NULL_PARAMETER => Self::NullParameter,
WebPEncodingError::VP8_ENC_ERROR_INVALID_CONFIGURATION => Self::InvalidConfiguration,
WebPEncodingError::VP8_ENC_ERROR_BAD_DIMENSION => Self::BadDimension,
WebPEncodingError::VP8_ENC_ERROR_PARTITION0_OVERFLOW => Self::Partition0Overflow,
WebPEncodingError::VP8_ENC_ERROR_PARTITION_OVERFLOW => Self::PartitionOverflow,
WebPEncodingError::VP8_ENC_ERROR_BAD_WRITE => Self::BadWrite,
WebPEncodingError::VP8_ENC_ERROR_FILE_TOO_BIG => Self::FileTooBig,
WebPEncodingError::VP8_ENC_ERROR_USER_ABORT => Self::UserAbort,
_ => Self::Unreported,
}
}
}
impl fmt::Display for EncodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::OutOfMemory => f.write_str("out of memory"),
Self::BitstreamOutOfMemory => f.write_str("out of memory for the bitstream"),
Self::NullParameter => f.write_str("a required plane is missing"),
Self::InvalidConfiguration => f.write_str("invalid configuration"),
Self::BadDimension => f.write_str("invalid picture dimensions"),
Self::Partition0Overflow => f.write_str("the first partition exceeds 512 KiB"),
Self::PartitionOverflow => f.write_str("a token partition exceeds 16 MiB"),
Self::BadWrite => f.write_str("the writer failed"),
Self::FileTooBig => f.write_str("the file would exceed 4 GiB"),
Self::UserAbort => f.write_str("aborted by the progress hook"),
Self::Unreported => f.write_str("the encoder failed without an error code"),
Self::InvalidDimensions { width, height } => write!(
f,
"invalid dimensions {width} by {height}: each must be 1 to {WEBP_MAX_DIMENSION}"
),
Self::InvalidStride { plane, stride } => {
write!(f, "invalid stride {stride} for the {plane:?} plane")
}
Self::BufferTooShort { plane, len, needed } => write!(
f,
"the {plane:?} plane holds {len} elements, its rows need {needed}"
),
Self::InvalidParameter { name } => write!(f, "invalid parameter: {name}"),
}
}
}
impl std::error::Error for EncodeError {}
fn check_quality(quality: f32) -> Result<(), EncodeError> {
if quality.is_finite() && (0.0..=100.0).contains(&quality) {
Ok(())
} else {
Err(EncodeError::InvalidParameter { name: "quality" })
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Config {
raw: WebPConfig,
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
impl From<WebPConfig> for Config {
fn from(raw: WebPConfig) -> Self {
Self { raw }
}
}
impl Config {
#[must_use]
pub fn new() -> Self {
let mut raw = WebPConfig::default();
let valid = webp_config_init(&mut raw);
debug_assert!(valid, "the default configuration is valid");
Self { raw }
}
pub fn preset(preset: Preset, quality: f32) -> Result<Self, EncodeError> {
check_quality(quality)?;
let mut raw = WebPConfig::default();
if webp_config_preset(&mut raw, preset.raw(), quality) {
Ok(Self { raw })
} else {
Err(EncodeError::InvalidConfiguration)
}
}
pub fn lossless_level(mut self, level: u8) -> Result<Self, EncodeError> {
if webp_config_lossless_preset(&mut self.raw, i32::from(level)) {
Ok(self)
} else {
Err(EncodeError::InvalidParameter {
name: "lossless_level",
})
}
}
#[must_use]
pub fn lossless(mut self, on: bool) -> Self {
self.raw.lossless = i32::from(on);
self
}
#[must_use]
pub fn quality(mut self, quality: f32) -> Self {
self.raw.quality = quality;
self
}
#[must_use]
pub fn method(mut self, method: u8) -> Self {
self.raw.method = i32::from(method);
self
}
#[must_use]
pub fn image_hint(mut self, hint: ImageHint) -> Self {
self.raw.image_hint = hint.raw();
self
}
#[must_use]
pub fn target_size(mut self, bytes: u32) -> Self {
self.raw.target_size = i32::try_from(bytes).unwrap_or(i32::MAX);
self
}
#[must_use]
pub fn target_psnr(mut self, db: f32) -> Self {
self.raw.target_psnr = db;
self
}
#[must_use]
pub fn alpha_compression(mut self, on: bool) -> Self {
self.raw.alpha_compression = i32::from(on);
self
}
#[must_use]
pub fn alpha_filter(mut self, filter: AlphaFilter) -> Self {
self.raw.alpha_filtering = filter.raw();
self
}
#[must_use]
pub fn alpha_quality(mut self, quality: u8) -> Self {
self.raw.alpha_quality = i32::from(quality);
self
}
#[must_use]
pub fn exact(mut self, on: bool) -> Self {
self.raw.exact = i32::from(on);
self
}
#[must_use]
pub fn near_lossless(mut self, level: u8) -> Self {
self.raw.near_lossless = i32::from(level);
self
}
#[must_use]
pub fn sharp_yuv(mut self, on: bool) -> Self {
self.raw.use_sharp_yuv = i32::from(on);
self
}
#[must_use]
pub fn multithreaded(mut self, on: bool) -> Self {
self.raw.thread_level = i32::from(on);
self
}
pub fn validate(&self) -> Result<(), EncodeError> {
check_quality(self.raw.quality)?;
if !self.raw.target_psnr.is_finite() {
return Err(EncodeError::InvalidParameter {
name: "target_psnr",
});
}
if webp_validate_config(&self.raw) {
Ok(())
} else {
Err(EncodeError::InvalidConfiguration)
}
}
#[must_use]
pub const fn as_raw(&self) -> &WebPConfig {
&self.raw
}
pub const fn raw_mut(&mut self) -> &mut WebPConfig {
&mut self.raw
}
}
fn check_dimensions(width: u32, height: u32) -> Result<(i32, i32), EncodeError> {
let limit = WEBP_MAX_DIMENSION.unsigned_abs();
if width == 0 || height == 0 || width > limit || height > limit {
return Err(EncodeError::InvalidDimensions { width, height });
}
let invalid = EncodeError::InvalidDimensions { width, height };
Ok((
i32::try_from(width).map_err(|_| invalid)?,
i32::try_from(height).map_err(|_| invalid)?,
))
}
fn check_plane(
plane: Plane,
len: usize,
columns: usize,
rows: usize,
stride: usize,
) -> Result<i32, EncodeError> {
let invalid = EncodeError::InvalidStride { plane, stride };
if stride < columns {
return Err(invalid);
}
let c_stride = i32::try_from(stride).map_err(|_| invalid)?;
let needed = rows
.checked_sub(1)
.and_then(|rows| rows.checked_mul(stride))
.and_then(|start| start.checked_add(columns))
.ok_or(invalid)?;
if len < needed {
return Err(EncodeError::BufferTooShort { plane, len, needed });
}
Ok(c_stride)
}
fn count(value: i32) -> usize {
usize::try_from(value).unwrap_or(0)
}
#[derive(Clone, Copy)]
pub struct PixelRows<'p> {
pub layout: PixelLayout,
pub data: &'p [u8],
pub width: u32,
pub height: u32,
pub stride: usize,
}
impl fmt::Debug for PixelRows<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PixelRows")
.field("layout", &self.layout)
.field("data_len", &self.data.len())
.field("width", &self.width)
.field("height", &self.height)
.field("stride", &self.stride)
.finish()
}
}
pub struct YuvaPlanes<'a> {
pub y: &'a mut [u8],
pub y_stride: usize,
pub u: &'a mut [u8],
pub v: &'a mut [u8],
pub uv_stride: usize,
pub a: Option<&'a mut [u8]>,
pub a_stride: usize,
}
impl fmt::Debug for YuvaPlanes<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("YuvaPlanes")
.field("y_len", &self.y.len())
.field("y_stride", &self.y_stride)
.field("u_len", &self.u.len())
.field("v_len", &self.v.len())
.field("uv_stride", &self.uv_stride)
.field("a_len", &self.a.as_ref().map(|a| a.len()))
.field("a_stride", &self.a_stride)
.finish()
}
}
#[derive(Clone, Copy, Default)]
struct Specs {
use_argb: i32,
colorspace: WebPEncCSP,
width: i32,
height: i32,
y: Option<PlaneOffset>,
u: Option<PlaneOffset>,
v: Option<PlaneOffset>,
a: Option<PlaneOffset>,
y_stride: i32,
uv_stride: i32,
a_stride: i32,
argb: Option<PlaneOffset>,
argb_stride: i32,
}
impl Specs {
fn of(pic: &WebPPicture<'_>) -> Self {
Self {
use_argb: pic.use_argb,
colorspace: pic.colorspace,
width: pic.width,
height: pic.height,
y: pic.y,
u: pic.u,
v: pic.v,
a: pic.a,
y_stride: pic.y_stride,
uv_stride: pic.uv_stride,
a_stride: pic.a_stride,
argb: pic.argb,
argb_stride: pic.argb_stride,
}
}
fn apply(self, pic: &mut WebPPicture<'_>) {
pic.use_argb = self.use_argb;
pic.colorspace = self.colorspace;
pic.width = self.width;
pic.height = self.height;
pic.y = self.y;
pic.u = self.u;
pic.v = self.v;
pic.a = self.a;
pic.y_stride = self.y_stride;
pic.uv_stride = self.uv_stride;
pic.a_stride = self.a_stride;
pic.argb = self.argb;
pic.argb_stride = self.argb_stride;
}
}
const fn region_start(region: usize) -> PlaneOffset {
PlaneOffset { region, offset: 0 }
}
fn lend<'s, T>(storage: &'s mut PlaneStorage<'_, T>) -> PlaneStorage<'s, T> {
match storage {
PlaneStorage::Internal(samples) => PlaneStorage::Internal(std::mem::take(samples)),
PlaneStorage::External(slices) => {
PlaneStorage::External(slices.iter_mut().map(|slice| &mut **slice).collect())
}
PlaneStorage::Shared(slices) => PlaneStorage::Shared(slices.clone()),
}
}
fn owned<T>(storage: PlaneStorage<'_, T>) -> Option<Vec<T>> {
match storage {
PlaneStorage::Internal(samples) => Some(samples),
PlaneStorage::External(_) | PlaneStorage::Shared(_) => None,
}
}
struct Returned {
specs: Specs,
yuva: Option<Vec<u8>>,
argb: Option<Vec<u32>>,
error: WebPEncodingError,
}
impl Returned {
fn take(pic: WebPPicture<'_>) -> Self {
Self {
specs: Specs::of(&pic),
error: pic.error_code,
yuva: owned(pic.yuva),
argb: owned(pic.argb_storage),
}
}
}
pub struct Picture<'a> {
specs: Specs,
yuva: PlaneStorage<'a, u8>,
argb_storage: PlaneStorage<'a, u32>,
}
impl fmt::Debug for Picture<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Picture")
.field("width", &self.width())
.field("height", &self.height())
.field("use_argb", &self.specs.use_argb)
.field("owned_sample_bytes", &self.owned_sample_bytes())
.finish_non_exhaustive()
}
}
impl Picture<'static> {
pub fn import(rows: PixelRows<'_>, form: SampleForm) -> Result<Self, EncodeError> {
let (width, height) = check_dimensions(rows.width, rows.height)?;
let columns = count(width)
.checked_mul(rows.layout.bytes_per_pixel())
.ok_or(EncodeError::InvalidDimensions {
width: rows.width,
height: rows.height,
})?;
let stride = check_plane(
Plane::Pixels,
rows.data.len(),
columns,
count(height),
rows.stride,
)?;
let mut pic = WebPPicture::default();
let initialized = webp_picture_init(&mut pic);
debug_assert!(initialized, "the picture's version is the crate's");
pic.width = width;
pic.height = height;
pic.use_argb = i32::from(form == SampleForm::Argb);
if !(rows.layout.importer())(&mut pic, rows.data, stride) {
return Err(if pic.error_code == WebPEncodingError::VP8_ENC_OK {
EncodeError::InvalidStride {
plane: Plane::Pixels,
stride: rows.stride,
}
} else {
EncodeError::from_code(pic.error_code)
});
}
Ok(Self {
specs: Specs::of(&pic),
yuva: pic.yuva,
argb_storage: pic.argb_storage,
})
}
}
impl<'a> Picture<'a> {
pub fn from_argb(
argb: &'a mut [u32],
width: u32,
height: u32,
stride: usize,
) -> Result<Self, EncodeError> {
let (c_width, c_height) = check_dimensions(width, height)?;
let argb_stride = check_plane(
Plane::Argb,
argb.len(),
count(c_width),
count(c_height),
stride,
)?;
Ok(Self {
specs: Specs {
use_argb: 1,
width: c_width,
height: c_height,
argb: Some(region_start(0)),
argb_stride,
..Specs::default()
},
yuva: PlaneStorage::default(),
argb_storage: PlaneStorage::External(vec![argb]),
})
}
pub fn from_yuva(width: u32, height: u32, planes: YuvaPlanes<'a>) -> Result<Self, EncodeError> {
let (c_width, c_height) = check_dimensions(width, height)?;
let (columns, rows) = (count(c_width), count(c_height));
let (uv_columns, uv_rows) = (count((c_width + 1) >> 1), count((c_height + 1) >> 1));
let y_stride = check_plane(Plane::Y, planes.y.len(), columns, rows, planes.y_stride)?;
let uv_stride = check_plane(
Plane::U,
planes.u.len(),
uv_columns,
uv_rows,
planes.uv_stride,
)?;
check_plane(
Plane::V,
planes.v.len(),
uv_columns,
uv_rows,
planes.uv_stride,
)?;
let a_stride = match &planes.a {
Some(a) => check_plane(Plane::A, a.len(), columns, rows, planes.a_stride)?,
None => 0,
};
let has_alpha = planes.a.is_some();
let mut regions = vec![planes.y, planes.u, planes.v];
regions.extend(planes.a);
Ok(Self {
specs: Specs {
use_argb: 0,
colorspace: if has_alpha {
WebPEncCSP::WEBP_YUV420A
} else {
WebPEncCSP::WEBP_YUV420
},
width: c_width,
height: c_height,
y: Some(region_start(0)),
u: Some(region_start(1)),
v: Some(region_start(2)),
a: has_alpha.then_some(region_start(3)),
y_stride,
uv_stride,
a_stride,
..Specs::default()
},
yuva: PlaneStorage::External(regions),
argb_storage: PlaneStorage::default(),
})
}
#[must_use]
pub const fn width(&self) -> u32 {
self.specs.width.unsigned_abs()
}
#[must_use]
pub const fn height(&self) -> u32 {
self.specs.height.unsigned_abs()
}
#[must_use]
pub fn owned_sample_bytes(&self) -> usize {
let yuva = match &self.yuva {
PlaneStorage::Internal(samples) => samples.len(),
PlaneStorage::External(_) | PlaneStorage::Shared(_) => 0,
};
let argb = match &self.argb_storage {
PlaneStorage::Internal(samples) => samples.len() * std::mem::size_of::<u32>(),
PlaneStorage::External(_) | PlaneStorage::Shared(_) => 0,
};
yuva + argb
}
fn encode_with<'c>(
&'c mut self,
config: &WebPConfig,
writer: &'c mut dyn FnMut(&[u8]) -> bool,
progress: Option<Box<dyn FnMut(i32) -> bool + 'c>>,
stats: Option<&'c mut WebPAuxStats>,
) -> Result<(), EncodeError> {
let specs = self.specs;
self.specs = Specs {
y: None,
u: None,
v: None,
a: None,
argb: None,
..specs
};
let mut call = WebPPicture::default();
let initialized = webp_picture_init(&mut call);
debug_assert!(initialized, "the picture's version is the crate's");
specs.apply(&mut call);
call.yuva = lend(&mut self.yuva);
call.argb_storage = lend(&mut self.argb_storage);
call.writer = Some(Box::new(move |data: &[u8]| writer(data)));
call.progress_hook = progress;
call.stats = stats;
let ok = webp_encode(config, &mut call);
let returned = Returned::take(call);
self.specs = returned.specs;
if let Some(samples) = returned.yuva {
self.yuva = PlaneStorage::Internal(samples);
}
if let Some(samples) = returned.argb {
self.argb_storage = PlaneStorage::Internal(samples);
}
if ok {
Ok(())
} else {
Err(EncodeError::from_code(returned.error))
}
}
}
pub struct Encoder<'e> {
config: &'e Config,
progress: Option<Box<dyn FnMut(i32) -> bool + 'e>>,
stats: Option<&'e mut WebPAuxStats>,
}
impl fmt::Debug for Encoder<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Encoder")
.field("config", self.config)
.field("progress", &self.progress.is_some())
.field("stats", &self.stats.is_some())
.finish()
}
}
impl<'e> Encoder<'e> {
#[must_use]
pub const fn new(config: &'e Config) -> Self {
Self {
config,
progress: None,
stats: None,
}
}
#[must_use]
pub fn progress(mut self, hook: impl FnMut(i32) -> bool + 'e) -> Self {
self.progress = Some(Box::new(hook));
self
}
#[must_use]
pub fn stats(mut self, stats: &'e mut WebPAuxStats) -> Self {
self.stats = Some(stats);
self
}
pub fn encode(self, picture: &mut Picture<'_>) -> Result<Vec<u8>, EncodeError> {
let mut memory = WebPMemoryWriter::default();
webp_memory_writer_init(&mut memory);
self.encode_to(picture, |data| webp_memory_write(&mut memory, data))?;
let mut bytes = memory.mem;
bytes.truncate(memory.size);
Ok(bytes)
}
pub fn encode_to(
self,
picture: &mut Picture<'_>,
mut writer: impl FnMut(&[u8]) -> bool,
) -> Result<(), EncodeError> {
self.config.validate()?;
picture.encode_with(&self.config.raw, &mut writer, self.progress, self.stats)
}
}
fn encode_simple(
rows: PixelRows<'_>,
quality: f32,
lossless: bool,
) -> Result<Vec<u8>, EncodeError> {
let config = Config::preset(Preset::Default, quality)?.lossless(lossless);
let form = if lossless {
SampleForm::Argb
} else {
SampleForm::Yuva
};
let mut picture = Picture::import(rows, form)?;
Encoder::new(&config).encode(&mut picture)
}
pub fn encode_lossy(rows: PixelRows<'_>, quality: f32) -> Result<Vec<u8>, EncodeError> {
encode_simple(rows, quality, false)
}
pub fn encode_lossless(rows: PixelRows<'_>) -> Result<Vec<u8>, EncodeError> {
encode_simple(rows, LOSSLESS_DEFAULT_QUALITY, true)
}