use base64::Engine as _;
use serde::{Deserialize, Serialize};
use crate::types::media::Media;
use rs_plugin_common_interfaces::video::{
RsVideoCodec, RsVideoFormat, VideoAlignment, VideoConvertInterval, VideoConvertRequest,
VideoOverlay, VideoOverlayPosition, VideoOverlayType, VideoTextOverlay,
};
#[cfg(feature = "mirror")]
mod conversions;
#[cfg(test)]
mod tests;
#[cfg(feature = "mirror")]
pub use conversions::{Conversion, ConversionStatus, Conversions};
pub const MAX_SIDE: u32 = 16384;
pub const MAX_FRAMERATE: u32 = 240;
pub const MAX_CRF: u32 = 63;
pub const MAX_FONT_SIZE: u32 = 512;
pub const RATIOS: [&str; 4] = ["1/1", "16/9", "9/16", "4/5"];
pub const FORMATS: [RsVideoFormat; 3] =
[RsVideoFormat::Mp4, RsVideoFormat::WebM, RsVideoFormat::Mkv];
pub const CODECS: [Option<RsVideoCodec>; 4] = [
None,
Some(RsVideoCodec::H264),
Some(RsVideoCodec::H265),
Some(RsVideoCodec::AV1),
];
pub const WATERMARK_POSITIONS: [VideoOverlayPosition; 4] = [
VideoOverlayPosition::TopLeft,
VideoOverlayPosition::TopRight,
VideoOverlayPosition::BottomLeft,
VideoOverlayPosition::BottomRight,
];
pub const TEXT_POSITIONS: [VideoOverlayPosition; 7] = [
VideoOverlayPosition::TopLeft,
VideoOverlayPosition::TopCenter,
VideoOverlayPosition::TopRight,
VideoOverlayPosition::Center,
VideoOverlayPosition::BottomLeft,
VideoOverlayPosition::BottomCenter,
VideoOverlayPosition::BottomRight,
];
pub const ALIGNMENTS: [VideoAlignment; 3] = [
VideoAlignment::Left,
VideoAlignment::Center,
VideoAlignment::Right,
];
pub fn new_id() -> String {
let bytes = redseat_crypto::random_iv().unwrap_or_else(|_| {
let mut bytes = [0u8; 16];
bytes[..8].copy_from_slice(&crate::client::now_ms().to_le_bytes());
bytes
});
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
}
pub fn format_label(format: &RsVideoFormat) -> String {
match format {
RsVideoFormat::WebM => "WebM".to_owned(),
other => other.to_string().to_uppercase(),
}
}
pub fn codec_label(codec: Option<&RsVideoCodec>) -> String {
match codec {
None => "Copy source".to_owned(),
Some(RsVideoCodec::H264) => "H.264".to_owned(),
Some(RsVideoCodec::H265) => "HEVC".to_owned(),
Some(RsVideoCodec::AV1) => "AV1".to_owned(),
Some(other) => other.to_string(),
}
}
pub fn position_label(position: &VideoOverlayPosition) -> &'static str {
match position {
VideoOverlayPosition::TopLeft => "Top left",
VideoOverlayPosition::TopRight => "Top right",
VideoOverlayPosition::TopCenter => "Top center",
VideoOverlayPosition::BottomLeft => "Bottom left",
VideoOverlayPosition::BottomRight => "Bottom right",
VideoOverlayPosition::BottomCenter => "Bottom center",
VideoOverlayPosition::Center => "Center",
}
}
pub fn alignment_label(alignment: &VideoAlignment) -> &'static str {
match alignment {
VideoAlignment::Left => "Left",
VideoAlignment::Center => "Center",
VideoAlignment::Right => "Right",
}
}
pub fn format_time(seconds: f64) -> String {
let seconds = seconds.max(0.0);
let tenths = (seconds * 10.0).round() as u64;
let whole = super::text::duration(tenths / 10);
match tenths % 10 {
0 => whole,
tenth => format!("{whole}.{tenth}"),
}
}
pub fn parse_time(text: &str) -> Option<f64> {
let text = text.trim();
if text.is_empty() {
return None;
}
let parts: Vec<&str> = text.split(':').collect();
if parts.len() > 3 {
return None;
}
let (last, units) = parts.split_last()?;
let seconds: f64 = last.trim().parse().ok()?;
if !seconds.is_finite() || seconds < 0.0 || (!units.is_empty() && seconds >= 60.0) {
return None;
}
let mut total = 0.0;
for (index, unit) in units.iter().enumerate() {
let value: u32 = unit.trim().parse().ok()?;
if index > 0 && value >= 60 {
return None;
}
total = total * 60.0 + f64::from(value);
}
Some(total * 60.0 + seconds)
}
pub fn parse_ratio(text: &str) -> Option<f64> {
let (width, height) = text.trim().split_once(['/', ':'])?;
let width: u32 = width.trim().parse().ok()?;
let height: u32 = height.trim().parse().ok()?;
let range = 1..=65535;
(range.contains(&width) && range.contains(&height))
.then(|| f64::from(width) / f64::from(height))
}
fn whole(text: &str, range: std::ops::RangeInclusive<u32>) -> Result<Option<u32>, ()> {
let text = text.trim();
if text.is_empty() {
return Ok(None);
}
match text.parse::<u32>() {
Ok(value) if range.contains(&value) => Ok(Some(value)),
_ => Err(()),
}
}
pub fn parse_color(text: &str) -> Option<String> {
let hex = text.trim().trim_start_matches('#');
(hex.len() == 6 && hex.chars().all(|c| c.is_ascii_hexdigit())).then(|| hex.to_uppercase())
}
pub fn media_duration(media: &Media) -> Option<f64> {
media.duration.filter(|d| *d > 0).map(|d| d as f64)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Quality {
High,
Medium,
Low,
VeryLow,
}
impl Quality {
pub const ALL: [Quality; 4] = [
Quality::High,
Quality::Medium,
Quality::Low,
Quality::VeryLow,
];
pub fn label(self) -> &'static str {
match self {
Quality::High => "High Quality",
Quality::Medium => "Medium Quality",
Quality::Low => "Low Quality",
Quality::VeryLow => "Very Low (Mobile)",
}
}
pub fn crf(self, media: &Media) -> u16 {
let side = media.width.unwrap_or(0).max(media.height.unwrap_or(0));
let size = match side {
s if s >= 3840 => 0,
s if s >= 2560 => 1,
_ => 2,
};
let table: [u16; 3] = match self {
Quality::High => [26, 25, 24],
Quality::Medium => [30, 27, 26],
Quality::Low => [34, 29, 28],
Quality::VeryLow => [36, 34, 32],
};
table[size]
}
pub fn request(self, media: &Media) -> VideoConvertRequest {
let fast = media.fps.is_some_and(|fps| fps > 30.0);
let framerate = (matches!(self, Quality::Medium | Quality::Low) && fast).then_some(30);
VideoConvertRequest {
framerate,
..crf_request(self.crf(media))
}
}
}
pub fn crf_request(crf: u16) -> VideoConvertRequest {
VideoConvertRequest {
id: new_id(),
format: RsVideoFormat::Mp4,
codec: Some(RsVideoCodec::H265),
crf: Some(crf),
..Default::default()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConvertPreset {
pub name: String,
pub preset: VideoConvertRequest,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub plugin: Option<String>,
}
impl ConvertPreset {
pub fn request(&self) -> VideoConvertRequest {
VideoConvertRequest {
id: new_id(),
..self.preset.clone()
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct WatermarkForm {
pub name: String,
pub position: VideoOverlayPosition,
pub size: u8,
pub opacity: u8,
}
impl WatermarkForm {
pub fn new(name: &str) -> Self {
WatermarkForm {
name: name.to_owned(),
position: VideoOverlayPosition::TopRight,
size: 30,
opacity: 40,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TextForm {
pub text: String,
pub position: VideoOverlayPosition,
pub font_size: String,
pub opacity: String,
pub margin: String,
pub color: String,
pub shadow: String,
pub start: String,
pub end: String,
}
impl TextForm {
pub fn new(start: f64, end: f64) -> Self {
TextForm {
text: "Overlay".to_owned(),
position: VideoOverlayPosition::BottomLeft,
font_size: "36".to_owned(),
opacity: "80".to_owned(),
margin: "0".to_owned(),
color: "FFFFFF".to_owned(),
shadow: "000000".to_owned(),
start: format_time(start),
end: format_time(end),
}
}
pub fn font_size(&self) -> Option<u32> {
whole(&self.font_size, 1..=MAX_FONT_SIZE).ok().flatten()
}
pub fn opacity(&self) -> Option<f32> {
whole(&self.opacity, 0..=100)
.ok()
.flatten()
.map(|o| o as f32 / 100.0)
}
pub fn margin(&self) -> Option<u32> {
whole(&self.margin, 0..=MAX_SIDE).ok().flatten()
}
pub fn shows_at(&self, seconds: f64) -> bool {
match (parse_time(&self.start), parse_time(&self.end)) {
(Some(start), Some(end)) => (start..end).contains(&seconds),
_ => true,
}
}
fn error(&self, number: usize, duration: Option<f64>) -> Option<String> {
let name = format!("Text overlay {number}");
if self.text.trim().is_empty() {
return Some(format!("{name} needs text."));
}
if self.font_size().is_none() {
return Some(format!(
"{name} needs a font size between 1 and {MAX_FONT_SIZE}."
));
}
if self.opacity().is_none() {
return Some(format!("{name} opacity must be between 0% and 100%."));
}
if self.margin().is_none() {
return Some(format!("{name} margin must be a non-negative number."));
}
if parse_color(&self.color).is_none() || parse_color(&self.shadow).is_none() {
return Some(format!(
"{name} colors must be six hex digits, like FFFFFF."
));
}
let (Some(start), Some(end)) = (parse_time(&self.start), parse_time(&self.end)) else {
return Some(format!("{name} needs a valid start and end time."));
};
if end <= start {
return Some(format!("{name} must end after it starts."));
}
if duration.is_some_and(|d| end > d.ceil()) {
return Some(format!("{name} must end within the video duration."));
}
None
}
fn overlay(&self) -> VideoTextOverlay {
let margin = self.margin().map(|m| m as i32);
VideoTextOverlay {
text: self.text.clone(),
font_color: parse_color(&self.color),
position: self.position.clone(),
margin_vertical: margin,
margin_horizontal: margin,
font_size: self.font_size().unwrap_or(36) as i32,
opacity: self.opacity(),
shadow_color: parse_color(&self.shadow),
start: parse_time(&self.start).map(|s| s.round() as u32),
end: parse_time(&self.end).map(|s| s.round() as u32),
..Default::default()
}
}
fn from_overlay(overlay: &VideoTextOverlay, duration: Option<f64>) -> Self {
let margin = overlay.margin_horizontal.or(overlay.margin_vertical);
TextForm {
text: overlay.text.clone(),
position: overlay.position.clone(),
font_size: overlay.font_size.to_string(),
opacity: ((overlay.opacity.unwrap_or(0.8) * 100.0).round() as u32).to_string(),
margin: margin.unwrap_or(0).max(0).to_string(),
color: overlay
.font_color
.clone()
.unwrap_or_else(|| "FFFFFF".to_owned()),
shadow: (overlay.shadow_color.clone()).unwrap_or_else(|| "000000".to_owned()),
start: format_time(f64::from(overlay.start.unwrap_or(0))),
end: format_time(
(overlay.end.map(f64::from))
.or(duration)
.unwrap_or_default(),
),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Frame {
pub left: f64,
pub top: f64,
pub width: f64,
pub height: f64,
pub output: (f64, f64),
}
#[derive(Debug, Clone, PartialEq)]
pub struct ConvertForm {
pub start: String,
pub end: String,
pub ratio: String,
pub alignment: VideoAlignment,
pub width: String,
pub height: String,
pub crop_width: String,
pub crop_height: String,
pub watermark: Option<WatermarkForm>,
pub texts: Vec<TextForm>,
pub format: RsVideoFormat,
pub codec: Option<RsVideoCodec>,
pub crf: String,
pub framerate: String,
pub no_audio: bool,
pub plugin: Option<String>,
}
impl Default for ConvertForm {
fn default() -> Self {
ConvertForm {
start: String::new(),
end: String::new(),
ratio: String::new(),
alignment: VideoAlignment::Center,
width: String::new(),
height: String::new(),
crop_width: String::new(),
crop_height: String::new(),
watermark: None,
texts: Vec::new(),
format: RsVideoFormat::Mp4,
codec: None,
crf: String::new(),
framerate: String::new(),
no_audio: false,
plugin: None,
}
}
}
impl ConvertForm {
pub fn from_preset(preset: &ConvertPreset, duration: Option<f64>) -> Self {
let request = &preset.preset;
let interval = request.intervals.first();
let format = if FORMATS.contains(&request.format) {
request.format.clone()
} else {
RsVideoFormat::Mp4
};
let codec = request
.codec
.clone()
.filter(|c| CODECS.contains(&Some(c.clone())));
let text = |value: Option<String>| value.unwrap_or_default();
let number = |value: Option<u16>| value.map(|v| v.to_string()).unwrap_or_default();
ConvertForm {
start: interval.map(|i| format_time(i.start)).unwrap_or_default(),
end: interval
.and_then(|i| i.duration.map(|d| i.start + d))
.map(format_time)
.unwrap_or_default(),
ratio: text(request.aspect_ratio.clone()),
alignment: (request.aspect_ratio_alignment.clone()).unwrap_or(VideoAlignment::Center),
width: text(request.width.clone()),
height: text(request.height.clone()),
crop_width: number(request.crop_width),
crop_height: number(request.crop_height),
watermark: request.overlay.as_ref().map(|overlay| WatermarkForm {
name: overlay.path.clone(),
position: overlay.position.clone(),
size: (overlay.ratio * 100.0).round().clamp(1.0, 100.0) as u8,
opacity: (overlay.opacity * 100.0).round().clamp(0.0, 100.0) as u8,
}),
texts: (request.texts.iter().flatten())
.map(|t| TextForm::from_overlay(t, duration))
.collect(),
format,
codec,
crf: number(request.crf),
framerate: number(request.framerate),
no_audio: request.no_audio,
plugin: preset.plugin.clone(),
}
}
pub fn set_watermark(&mut self, name: Option<&str>) {
self.watermark = name.map(WatermarkForm::new);
self.overlays_need_codec();
}
pub fn add_text(&mut self, duration: Option<f64>) {
let start = (self.texts.iter())
.filter_map(|t| parse_time(&t.end))
.fold(0.0, f64::max);
let end = duration.unwrap_or(start + 5.0).max(start);
self.texts.push(TextForm::new(start, end));
self.overlays_need_codec();
}
fn overlays_need_codec(&mut self) {
if (self.watermark.is_some() || !self.texts.is_empty()) && self.codec.is_none() {
self.codec = Some(RsVideoCodec::H265);
}
}
pub fn reset_framing(&mut self) {
self.ratio.clear();
self.alignment = VideoAlignment::Center;
self.width.clear();
self.height.clear();
self.crop_width.clear();
self.crop_height.clear();
}
pub fn has_framing(&self) -> bool {
[
&self.ratio,
&self.width,
&self.height,
&self.crop_width,
&self.crop_height,
]
.iter()
.any(|field| !field.trim().is_empty())
}
pub fn framing_label(&self) -> String {
if !self.ratio.trim().is_empty() {
format!("{} crop", self.ratio.trim())
} else if !self.crop_width.trim().is_empty() || !self.crop_height.trim().is_empty() {
"Custom crop".to_owned()
} else if !self.width.trim().is_empty() || !self.height.trim().is_empty() {
"Resized output".to_owned()
} else {
"Source frame".to_owned()
}
}
pub fn trim_length(&self, duration: Option<f64>) -> Option<f64> {
let duration = duration?;
let start = self.trim_point(&self.start)?.unwrap_or(0.0);
let end = self.trim_point(&self.end)?.unwrap_or(duration);
(end > start).then_some(end - start)
}
fn trim_point(&self, text: &str) -> Option<Option<f64>> {
if text.trim().is_empty() {
Some(None)
} else {
parse_time(text).map(Some)
}
}
pub fn frame(&self, source: (f64, f64)) -> Frame {
let (source_width, source_height) = source;
let full = Frame {
left: 0.0,
top: 0.0,
width: 1.0,
height: 1.0,
output: source,
};
if source_width <= 0.0 || source_height <= 0.0 {
return full;
}
let side = |text: &str| whole(text, 1..=MAX_SIDE).ok().flatten().map(f64::from);
let (width, height) = (side(&self.width), side(&self.height));
let scaled_width = width
.or(height.map(|h| source_width * h / source_height))
.unwrap_or(source_width);
let scaled_height = height
.or(width.map(|w| source_height * w / source_width))
.unwrap_or(source_height);
let (mut left, mut top) = (0.0, 0.0);
let (mut kept_width, mut kept_height) = (scaled_width, scaled_height);
if let (Some(crop_width), Some(crop_height)) =
(side(&self.crop_width), side(&self.crop_height))
&& crop_width <= kept_width
&& crop_height <= kept_height
{
left += (kept_width - crop_width) / 2.0;
top += (kept_height - crop_height) / 2.0;
(kept_width, kept_height) = (crop_width, crop_height);
}
if let Some(ratio) = parse_ratio(&self.ratio) {
let square = (ratio - 1.0).abs() < f64::EPSILON;
let (ratio_width, ratio_height) = if square {
let side = kept_width.min(kept_height);
(side, side)
} else if kept_width >= kept_height {
(kept_height * ratio, kept_height)
} else {
(kept_width, kept_width / ratio)
};
if ratio_width <= kept_width && ratio_height <= kept_height {
match (&self.alignment, square) {
(VideoAlignment::Center, _) | (_, true) => {
left += (kept_width - ratio_width) / 2.0;
top += (kept_height - ratio_height) / 2.0;
}
(VideoAlignment::Right, _) => left += kept_width - ratio_width,
(VideoAlignment::Left, _) => {}
}
(kept_width, kept_height) = (ratio_width, ratio_height);
}
}
Frame {
left: left / scaled_width,
top: top / scaled_height,
width: kept_width / scaled_width,
height: kept_height / scaled_height,
output: (kept_width, kept_height),
}
}
pub fn errors(&self, duration: Option<f64>) -> Vec<String> {
let mut errors = Vec::new();
let start = self.trim_point(&self.start);
let end = self.trim_point(&self.end);
if start.is_none() {
errors.push("Trim start must be a time, like 1:05 or 65.".to_owned());
}
match end {
None => errors.push("Trim end must be a time, like 1:05 or 65.".to_owned()),
Some(Some(end)) if end <= 0.0 => {
errors.push("Trim end time must be a positive number of seconds.".to_owned());
}
_ => {}
}
let (start, end) = (start.flatten(), end.flatten());
if (start.is_some() || end.is_some()) && duration.is_none() {
errors.push("Wait for the video duration before selecting a trim range.".to_owned());
}
if let Some(duration) = duration {
let duration = duration.ceil();
if start.is_some_and(|s| s > duration) {
errors.push("Trim start time must be within the source duration.".to_owned());
}
if end.is_some_and(|e| e > duration) {
errors.push("Trim end time must be within the source duration.".to_owned());
}
}
if let (Some(start), Some(end)) = (start, end)
&& end <= start
{
errors.push("Trim end time must be later than the start time.".to_owned());
}
for (label, value, maximum) in [
("Width", &self.width, MAX_SIDE),
("Height", &self.height, MAX_SIDE),
("Crop width", &self.crop_width, MAX_SIDE),
("Crop height", &self.crop_height, MAX_SIDE),
("Frame rate", &self.framerate, MAX_FRAMERATE),
] {
if whole(value, 1..=maximum).is_err() {
errors.push(format!(
"{label} must be a whole number between 1 and {maximum}."
));
}
}
if whole(&self.crf, 0..=MAX_CRF).is_err() {
errors.push(format!(
"CRF must be a whole number between 0 and {MAX_CRF}."
));
}
if !self.ratio.trim().is_empty() && parse_ratio(&self.ratio).is_none() {
errors
.push("Aspect ratio must use whole numbers from 1 to 65535, like 16/9.".to_owned());
}
if let Some(watermark) = &self.watermark {
if watermark.name.is_empty() {
errors.push("Choose a watermark before converting.".to_owned());
}
if !(1..=100).contains(&watermark.size) {
errors.push("Watermark size must be between 1% and 100%.".to_owned());
}
if watermark.opacity > 100 {
errors.push("Watermark opacity must be between 0% and 100%.".to_owned());
}
}
for (index, text) in self.texts.iter().enumerate() {
errors.extend(text.error(index + 1, duration));
}
errors
}
pub fn request(&self, duration: Option<f64>) -> VideoConvertRequest {
let start = self.trim_point(&self.start).flatten();
let end = self.trim_point(&self.end).flatten();
let intervals = if start.is_some() || end.is_some() {
let start = start.unwrap_or(0.0);
let end = end.or(duration);
vec![VideoConvertInterval {
start,
duration: end.map(|end| end - start),
input: None,
}]
} else {
Vec::new()
};
let small = |text: &str, max: u32| -> Option<u16> {
whole(text, 0..=max)
.ok()
.flatten()
.and_then(|v| u16::try_from(v).ok())
};
let text = |value: &str| Some(value.trim().to_owned()).filter(|v| !v.is_empty());
VideoConvertRequest {
id: new_id(),
format: self.format.clone(),
codec: self.codec.clone(),
crf: self.codec.as_ref().and_then(|_| small(&self.crf, MAX_CRF)),
no_audio: self.no_audio,
width: text(&self.width),
height: text(&self.height),
framerate: small(&self.framerate, MAX_FRAMERATE),
crop_width: small(&self.crop_width, MAX_SIDE),
crop_height: small(&self.crop_height, MAX_SIDE),
aspect_ratio: text(&self.ratio),
aspect_ratio_alignment: Some(self.alignment.clone()),
overlay: self.watermark.as_ref().map(|watermark| VideoOverlay {
kind: VideoOverlayType::Watermark,
path: watermark.name.clone(),
position: watermark.position.clone(),
margin: None,
ratio: f32::from(watermark.size) / 100.0,
opacity: f32::from(watermark.opacity) / 100.0,
}),
texts: (!self.texts.is_empty())
.then(|| self.texts.iter().map(TextForm::overlay).collect()),
intervals,
}
}
pub fn preset(&self, name: &str, duration: Option<f64>) -> ConvertPreset {
ConvertPreset {
name: name.trim().to_owned(),
preset: self.request(duration),
plugin: self.plugin.clone(),
}
}
}