use crate::Error;
use crate::converter::DEPENDENCIES;
use crate::converter::traits::ThreadBudget;
use crate::format::ImageFormat;
use clap::ValueEnum;
use image::DynamicImage;
use ravif_new::*;
use rgb::FromSlice;
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum, serde::Serialize, serde::Deserialize)]
pub enum BitDepth {
Eight,
Ten,
Auto,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum, serde::Serialize, serde::Deserialize)]
pub enum ColorModel {
YCbCr,
RGB,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum, serde::Serialize, serde::Deserialize)]
pub enum AlphaColorMode {
UnassociatedDirty,
UnassociatedClean,
Premultiplied,
}
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct AvifOptions {
pub quality: f32,
pub speed: u8,
pub bit_depth: Option<BitDepth>,
pub color_model: Option<ColorModel>,
pub alpha_color_mode: Option<AlphaColorMode>,
pub alpha_quality: f32,
}
impl Default for AvifOptions {
fn default() -> Self {
AvifOptions {
quality: 90.,
speed: 3,
bit_depth: None,
color_model: None,
alpha_color_mode: None,
alpha_quality: 90.,
}
}
}
fn convert_bit_depth_to_ext(bit_depth: Option<BitDepth>) -> ravif_new::BitDepth {
match bit_depth.unwrap_or(BitDepth::Auto) {
BitDepth::Eight => ravif_new::BitDepth::Eight,
BitDepth::Ten => ravif_new::BitDepth::Ten,
BitDepth::Auto => ravif_new::BitDepth::Auto,
}
}
fn convert_color_model_to_ext(color_model: Option<ColorModel>) -> ravif_new::ColorModel {
match color_model.unwrap_or(ColorModel::YCbCr) {
ColorModel::YCbCr => ravif_new::ColorModel::YCbCr,
ColorModel::RGB => ravif_new::ColorModel::RGB,
}
}
fn convert_alpha_color_mode_to_ext(
alpha_color_mode: Option<AlphaColorMode>,
) -> ravif_new::AlphaColorMode {
match alpha_color_mode.unwrap_or(AlphaColorMode::UnassociatedClean) {
AlphaColorMode::UnassociatedDirty => ravif_new::AlphaColorMode::UnassociatedDirty,
AlphaColorMode::UnassociatedClean => ravif_new::AlphaColorMode::UnassociatedClean,
AlphaColorMode::Premultiplied => ravif_new::AlphaColorMode::Premultiplied,
}
}
pub struct AvifEncoder {
pub options: AvifOptions,
num_threads: Option<usize>,
}
impl AvifEncoder {
pub fn new(options: AvifOptions) -> Self {
AvifEncoder {
options,
num_threads: None,
}
}
}
impl super::ImageEncoder for AvifEncoder {
fn format(&self) -> ImageFormat {
ImageFormat::Avif
}
fn extension(&self) -> &'static str {
"avif"
}
fn describe(&self) -> String {
format!(
"still-image AV1 encoder (ravif {})",
super::dependency_version("ravif")
)
}
fn describe_options(&self) -> String {
encoder_info(
self.options.quality,
self.options.speed,
self.options.bit_depth,
self.options.color_model,
)
}
fn supports_animation(&self) -> bool {
false
}
fn adjust_threading(&mut self, budget: ThreadBudget) {
self.num_threads = budget.threads_per_encoder;
}
fn encode_still_image(&self, image: &DynamicImage) -> Result<Vec<u8>, Error> {
encode_avif(image, &self.options, self.num_threads, None)
}
fn encode_still_image_with_metadata(
&self,
image: &DynamicImage,
metadata: &crate::metadata::ImageMetadata,
) -> Result<Vec<u8>, Error> {
let exif = metadata.exif.as_deref();
encode_avif(image, &self.options, self.num_threads, exif)
}
}
fn encoder_info(
quality: f32,
speed: u8,
bit_depth: Option<BitDepth>,
color_model: Option<ColorModel>,
) -> String {
let mut ravif_version = "";
match DEPENDENCIES.iter().rfind(|&&(name, _)| name == "ravif") {
Some((_name, version)) => {
ravif_version = version;
}
None => {
println!("Package 'ravif' not found");
}
};
format!(
"Using \"ravif\" ({}) with options (quality: {}, speed: {}, bit depth: {:?}, color model: {:?})",
ravif_version,
quality,
speed,
convert_bit_depth_to_ext(bit_depth),
convert_color_model_to_ext(color_model)
)
}
fn encode_avif(
image: &DynamicImage,
options: &AvifOptions,
num_threads: Option<usize>,
exif: Option<&[u8]>,
) -> Result<Vec<u8>, Error> {
let mut encoder = Encoder::new()
.with_quality(options.quality)
.with_speed(options.speed) .with_num_threads(num_threads) .with_bit_depth(convert_bit_depth_to_ext(options.bit_depth))
.with_internal_color_model(convert_color_model_to_ext(options.color_model));
if let Some(exif) = exif.filter(|payload| !payload.is_empty()) {
encoder = encoder.with_exif(exif);
}
let avif_res: EncodedImage = if image.color().has_alpha() {
let source_image = image.to_rgba8();
let image = Img::new(
source_image.as_rgba(),
image.width() as usize,
image.height() as usize,
);
encoder
.with_alpha_quality(options.alpha_quality) .with_alpha_color_mode(convert_alpha_color_mode_to_ext(options.alpha_color_mode)) .encode_rgba(image)
.map_err(|e| Error::from_string(format!("avif encoding failed: {:?}", e)))?
} else {
let source_image = image.to_rgb8();
let image = Img::new(
source_image.as_rgb(),
image.width() as usize,
image.height() as usize,
);
encoder
.encode_rgb(image)
.map_err(|e| Error::from_string(format!("avif encoding failed: {:?}", e)))?
};
Ok(avif_res.avif_file)
}