key out gif backgrounds
This commit is contained in:
+80
-8
@@ -102,6 +102,7 @@ pub(crate) struct TranscodeRequest {
|
||||
pub crop: Option<CaptureRect>,
|
||||
pub gif_budget_mode: GifBudgetMode,
|
||||
pub gif_colors: u16,
|
||||
pub gif_color_key: Option<GifColorKey>,
|
||||
pub gif_removed_ranges: Vec<SourceRange>,
|
||||
pub trim_start_secs: Option<f64>,
|
||||
pub trim_end_secs: Option<f64>,
|
||||
@@ -116,6 +117,12 @@ pub(crate) struct TranscodeRequest {
|
||||
pub cancel: Option<Arc<AtomicBool>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, serde::Deserialize)]
|
||||
pub(crate) struct GifColorKey {
|
||||
pub rgb: u32,
|
||||
pub tolerance: u8,
|
||||
}
|
||||
|
||||
const MAX_CLICK_HIGHLIGHTS: usize = 50;
|
||||
|
||||
const BOX_SIZE: i32 = 24;
|
||||
@@ -870,7 +877,7 @@ fn gif_filters(req: &TranscodeRequest, scale_width: u32, effective_fps: u32) ->
|
||||
.map(|c| format!("{c},"))
|
||||
.unwrap_or_default();
|
||||
let timeline = gif_timeline_filter(req, effective_fps);
|
||||
let stats = if req.gif_removed_ranges.is_empty() { "diff" } else { "full" };
|
||||
let stats = if req.gif_removed_ranges.is_empty() && req.gif_color_key.is_none() { "diff" } else { "full" };
|
||||
|
||||
let dither = match req.gif_dither {
|
||||
GifDither::FloydSteinberg => "floyd_steinberg",
|
||||
@@ -880,8 +887,8 @@ fn gif_filters(req: &TranscodeRequest, scale_width: u32, effective_fps: u32) ->
|
||||
|
||||
// Single-pass approach: split the stream, generate palette from one copy,
|
||||
// apply palette to the other. The fps filter handles frame rate conversion.
|
||||
let scale = gif_rgb_scale_filter(scale_width);
|
||||
let colors = req.gif_colors;
|
||||
let scale = gif_rgb_scale_filter(scale_width, req.gif_color_key);
|
||||
let colors = if req.gif_color_key.is_some() { req.gif_colors.max(3) } else { req.gif_colors };
|
||||
let reserve = u8::from(colors > 2);
|
||||
format!(
|
||||
"{kprefix}{cprefix}{timeline},{scale},split[s0][s1];[s0]palettegen=stats_mode={stats}:max_colors={colors}:reserve_transparent={reserve}[p];[s1][p]paletteuse=dither={d}",
|
||||
@@ -931,10 +938,20 @@ fn encode_gif_pass(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn gif_rgb_scale_filter(width: u32) -> String {
|
||||
format!(
|
||||
"scale={width}:-1:flags=lanczos:in_color_matrix=bt709:in_range=tv:out_range=pc:in_primaries=bt709:in_transfer=bt709:out_primaries=bt709:out_transfer=srgb,format=rgb24"
|
||||
)
|
||||
fn gif_source_rgb_scale(width: u32) -> String {
|
||||
format!("scale={width}:-1:flags=lanczos:in_color_matrix=bt709:in_range=tv:out_range=pc")
|
||||
}
|
||||
|
||||
fn gif_rgb_scale_filter(width: u32, key: Option<GifColorKey>) -> String {
|
||||
let scale = gif_source_rgb_scale(width);
|
||||
let transfer = "in_primaries=bt709:in_transfer=bt709:out_primaries=bt709:out_transfer=srgb";
|
||||
if let Some(key) = key {
|
||||
// Match before the transfer conversion changes the RGB values.
|
||||
let similarity = f64::from(key.tolerance) / 100.0;
|
||||
format!("{scale},format=rgba,colorkey=0x{:06x}:{similarity:.2}:0,scale={transfer},format=rgba", key.rgb)
|
||||
} else {
|
||||
format!("{scale}:{transfer},format=rgb24")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -1605,6 +1622,7 @@ mod tests {
|
||||
crop: None,
|
||||
gif_budget_mode: GifBudgetMode::Balanced,
|
||||
gif_colors: 256,
|
||||
gif_color_key: None,
|
||||
gif_removed_ranges: vec![],
|
||||
trim_start_secs: None,
|
||||
trim_end_secs: None,
|
||||
@@ -1693,7 +1711,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn gif_scale_forces_bt709_rgb() {
|
||||
let filter = gif_rgb_scale_filter(640);
|
||||
let filter = gif_rgb_scale_filter(640, None);
|
||||
assert!(filter.contains("in_color_matrix=bt709"));
|
||||
assert!(filter.contains("in_range=tv"));
|
||||
assert!(filter.contains("in_transfer=bt709"));
|
||||
@@ -1761,6 +1779,60 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires FFmpeg; set BYTESIZE_TEST_FFMPEG"]
|
||||
fn gif_color_key_clears_the_background_across_frames() -> Result<()> {
|
||||
let ffmpeg = std::env::var_os("BYTESIZE_TEST_FFMPEG").map(PathBuf::from)
|
||||
.ok_or_else(|| anyhow!("set BYTESIZE_TEST_FFMPEG to ffmpeg.exe"))?;
|
||||
let dir = std::env::temp_dir().join(format!("bytesize-gif-key-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let input = TempFileGuard::create_in(&dir, "source", "mp4")?;
|
||||
let mut source = Command::new(&ffmpeg);
|
||||
source.args(["-y", "-hide_banner"]);
|
||||
for (color, x) in [("0x00ff00", 8), ("0x00f000", 72)] {
|
||||
let frame = format!("color=c={color}:size=128x96:rate=5:duration=1,format=rgb24,drawbox=x={x}:y=16:w=48:h=64:color=red:t=fill");
|
||||
source.args(["-f", "lavfi", "-i", &frame]);
|
||||
}
|
||||
source.args(["-filter_complex", "concat=n=2:v=1:a=0,scale=out_color_matrix=bt709:out_range=tv,format=yuv420p",
|
||||
"-c:v", "libx264", "-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709"]).arg(&input.0);
|
||||
run(&mut source, "test recording")?;
|
||||
|
||||
for key in [None, Some(GifColorKey { rgb: 0x00_ff_00, tolerance: 8 })] {
|
||||
let output = TempFileGuard::create_in(&dir, "review", "gif")?;
|
||||
let mut request = dummy_request();
|
||||
request.format = Format::Gif;
|
||||
request.input = input.0.clone();
|
||||
request.output = output.0.clone();
|
||||
request.scratch_dir = dir.clone();
|
||||
request.target_bytes = 1_000_000;
|
||||
request.clip_width = 128;
|
||||
request.clip_height = 96;
|
||||
request.duration_secs = 2.0;
|
||||
request.fps = 5;
|
||||
request.gif_colors = if key.is_some() { 3 } else { 256 };
|
||||
request.gif_color_key = key;
|
||||
transcode(&ffmpeg, &request)?;
|
||||
let media = inspect_output(&ffmpeg, &output.0)?;
|
||||
let decoded = Command::new(&ffmpeg).args(["-v", "error", "-i"]).arg(&output.0)
|
||||
.args(["-fps_mode", "passthrough", "-pix_fmt", "rgba", "-f", "rawvideo", "pipe:1"]).output()?;
|
||||
assert!(decoded.status.success());
|
||||
let (width, height) = (media.width as usize, media.height as usize);
|
||||
let frames: Vec<_> = decoded.stdout.chunks_exact(width * height * 4).collect();
|
||||
assert_eq!(frames.len(), 10);
|
||||
let background_alpha = if key.is_some() { 0 } else { 255 };
|
||||
for (index, frame) in frames.into_iter().enumerate() {
|
||||
let (foreground_x, background_x) = if index < 5 { (width / 4, width * 3 / 4) } else { (width * 3 / 4, width / 4) };
|
||||
let pixel = |x| (width * (height / 2) + x) * 4;
|
||||
assert_eq!(frame[pixel(background_x) + 3], background_alpha, "frame {index}");
|
||||
assert_eq!(frame[pixel(foreground_x) + 3], 255, "frame {index}");
|
||||
assert!(frame[pixel(foreground_x)] > 180, "frame {index} lost its red subject");
|
||||
}
|
||||
}
|
||||
drop(input);
|
||||
std::fs::remove_dir(dir)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_alignment_pads_whole_sample_frames_and_preserves_retry_gaps() {
|
||||
let dir = std::env::temp_dir();
|
||||
|
||||
@@ -812,6 +812,8 @@ pub struct ExportRequest {
|
||||
pub gif_dither: Option<GifDither>,
|
||||
#[serde(default)]
|
||||
pub gif_colors: Option<u16>,
|
||||
#[serde(default)]
|
||||
gif_color_key: Option<encode::GifColorKey>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -1012,7 +1014,7 @@ mod tests {
|
||||
let artifact = encode::TempFileGuard::create_in(&dir, "output-review", ext_for(format))?;
|
||||
let req = encode::TranscodeRequest {
|
||||
input: source.0.clone(), output: artifact.0.clone(), format, target_bytes: 102_400,
|
||||
duration_secs: 1.0, fps: 10, keep_audio: false, gif_colors: 128,
|
||||
duration_secs: 1.0, fps: 10, keep_audio: false, gif_colors: 128, gif_color_key: None,
|
||||
gif_dither: GifDither::Bayer, gif_budget_mode: GifBudgetMode::Balanced,
|
||||
webm_codec: config::WebmCodec::Vp9, mp4_codec: config::Mp4Codec::H264,
|
||||
scratch_dir: dir.clone(), crop: None, gif_removed_ranges: Vec::new(),
|
||||
@@ -2057,6 +2059,10 @@ fn transcode_request(
|
||||
|
||||
let mut duration_secs = end - start;
|
||||
let mut gif_removed_ranges = Vec::new();
|
||||
let gif_color_key = if request.format == Format::Gif { request.gif_color_key } else { None };
|
||||
if gif_color_key.is_some_and(|key| key.rgb > 0xff_ffff || !(1..=100).contains(&key.tolerance)) {
|
||||
return Err("choose an RGB key color and a tolerance between 1% and 100%".to_string());
|
||||
}
|
||||
if request.format == Format::Gif {
|
||||
let rate = f64::from(request.fps);
|
||||
request.gif_removed_ranges.extend(request.deleted_frame_indices.iter().map(|index| SourceRange {
|
||||
@@ -2095,6 +2101,7 @@ fn transcode_request(
|
||||
keep_audio: request.keep_audio,
|
||||
gif_dither: request.gif_dither.unwrap_or(cfg.export.gif_dither),
|
||||
gif_colors: request.gif_colors.unwrap_or(256),
|
||||
gif_color_key,
|
||||
webm_codec: cfg.export.webm_codec,
|
||||
mp4_codec: cfg.export.mp4_codec,
|
||||
scratch_dir: temp_dir(&state.app_dir),
|
||||
|
||||
Reference in New Issue
Block a user