Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Better GIF export (#883)

Oscar Beaumontf35e0dc4c8db
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ba3d2867b..ebb490afc 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -59,7 +59,9 @@ jobs:
- name: Setup Biome
uses: biomejs/setup-biome@v2
with:
- version: latest
+ # Don't use `latest` as Biome throws an error when it doesn't match the
+ # schema version in the config file.
+ version: 2.2.0
- name: Run Biome
run: biome ci . --linter-enabled=false
diff --git a/Cargo.lock b/Cargo.lock
index bc354bfc8..71b460c92 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1205,7 +1205,9 @@ dependencies = [
"cap-project",
"cidre",
"ffmpeg-next",
- "gif",
+ "gifski",
+ "imgref",
+ "rgb",
"thiserror 1.0.69",
"tracing",
]
@@ -2685,6 +2687,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a3d7db9596fecd151c5f638c0ee5d5bd487b6e0ea232e5dc96d5250f6f94b1d"
dependencies = [
"crc32fast",
+ "libz-rs-sys",
"miniz_oxide",
]
@@ -3145,6 +3148,45 @@ dependencies = [
"weezl",
]
+[[package]]
+name = "gif-dispose"
+version = "5.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e1aa07391f3d9c279f388cea6faf291555dd891df59bed01d4378583df946ac"
+dependencies = [
+ "gif",
+ "imgref",
+ "rgb",
+]
+
+[[package]]
+name = "gifski"
+version = "1.34.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c246c795a61d4a2476fb1c8ab70bedfaa825c734882adc40e117fc837df81190"
+dependencies = [
+ "clap",
+ "crossbeam-channel",
+ "crossbeam-utils",
+ "dunce",
+ "gif",
+ "gif-dispose",
+ "imagequant",
+ "imgref",
+ "lodepng",
+ "loop9",
+ "natord",
+ "num-traits",
+ "ordered-channel",
+ "pbr",
+ "quick-error",
+ "resize",
+ "rgb",
+ "wild",
+ "y4m",
+ "yuv",
+]
+
[[package]]
name = "gimli"
version = "0.31.1"
@@ -3868,6 +3910,19 @@ dependencies = [
"quick-error",
]
+[[package]]
+name = "imagequant"
+version = "4.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caf5d73b959dfbe5d6b5cd3ca8de5265c7bc58297f20560a60a1d2ba6a19991f"
+dependencies = [
+ "arrayvec",
+ "once_cell",
+ "rayon",
+ "rgb",
+ "thread_local",
+]
+
[[package]]
name = "imagesize"
version = "0.13.0"
@@ -4379,6 +4434,15 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "libz-rs-sys"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "172a788537a2221661b480fee8dc5f96c580eb34fa88764d3205dc356c7e4221"
+dependencies = [
+ "zlib-rs",
+]
+
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
@@ -4413,6 +4477,18 @@ dependencies = [
"scopeguard",
]
+[[package]]
+name = "lodepng"
+version = "3.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77a32335d22e44238e2bb0b4d726964d18952ce1f1279ec3305305d2c61539eb"
+dependencies = [
+ "crc32fast",
+ "flate2",
+ "libc",
+ "rgb",
+]
+
[[package]]
name = "log"
version = "0.4.27"
@@ -4749,6 +4825,12 @@ dependencies = [
"tempfile",
]
+[[package]]
+name = "natord"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "308d96db8debc727c3fd9744aac51751243420e46edf401010908da7f8d5e57c"
+
[[package]]
name = "ndk"
version = "0.8.0"
@@ -5464,6 +5546,15 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c04f5d74368e4d0dfe06c45c8627c81bd7c317d52762d118fb9b3076f6420fd"
+[[package]]
+name = "ordered-channel"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95be4d57809897b5a7539fc15a7dfe0e84141bc3dfaa2e9b1b27caa90acf61ab"
+dependencies = [
+ "crossbeam-channel",
+]
+
[[package]]
name = "ordered-float"
version = "4.6.0"
@@ -5601,6 +5692,17 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
+[[package]]
+name = "pbr"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5827dfa0d69b6c92493d6c38e633bbaa5937c153d0d7c28bf12313f8c6d514"
+dependencies = [
+ "crossbeam-channel",
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "percent-encoding"
version = "2.3.1"
@@ -6519,6 +6621,16 @@ dependencies = [
"webpki-roots",
]
+[[package]]
+name = "resize"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87a103d0b47e783f4579149402f7499397ab25540c7a57b2f70487a5d2d20ef0"
+dependencies = [
+ "rayon",
+ "rgb",
+]
+
[[package]]
name = "resvg"
version = "0.45.1"
@@ -9917,6 +10029,15 @@ dependencies = [
"fs_extra",
]
+[[package]]
+name = "wild"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3131afc8c575281e1e80f36ed6a092aa502c08b18ed7524e86fbbb12bb410e1"
+dependencies = [
+ "glob",
+]
+
[[package]]
name = "winapi"
version = "0.3.9"
@@ -10795,6 +10916,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
+[[package]]
+name = "y4m"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"
+
[[package]]
name = "yansi"
version = "1.0.1"
@@ -10840,6 +10967,16 @@ dependencies = [
"synstructure",
]
+[[package]]
+name = "yuv"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8cbe2d856acbe6d86c0fa6f458b73e962834061ca2f7f94c6e4633afc9efd4d4"
+dependencies = [
+ "num-traits",
+ "rgb",
+]
+
[[package]]
name = "zbus"
version = "5.9.0"
@@ -10999,6 +11136,12 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "zlib-rs"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "626bd9fa9734751fc50d6060752170984d7053f5a39061f524cda68023d4db8a"
+
[[package]]
name = "zune-core"
version = "0.4.12"
diff --git a/apps/desktop/src-tauri/src/target_select_overlay.rs b/apps/desktop/src-tauri/src/target_select_overlay.rs
index a9bf72810..e3bf77e8a 100644
--- a/apps/desktop/src-tauri/src/target_select_overlay.rs
+++ b/apps/desktop/src-tauri/src/target_select_overlay.rs
@@ -178,7 +178,7 @@ impl WindowFocusManager {
pub fn destroy<R: tauri::Runtime>(&self, id: &DisplayId, global_shortcut: &GlobalShortcut<R>) {
let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(task) = tasks.remove(&id.to_string()) {
- let _ = task.abort();
+ task.abort();
}
// When all overlay windows are closed cleanup shared resources.
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index 41b4ad79c..1b3e145e1 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -224,7 +224,7 @@ impl ShowCapWindow {
.build()?,
Self::Main => {
if permissions::do_permissions_check(false).necessary_granted() {
- let new_recording_flow = GeneralSettingsStore::get(&app)
+ let new_recording_flow = GeneralSettingsStore::get(app)
.ok()
.flatten()
.map(|s| s.enable_new_recording_flow)
diff --git a/apps/desktop/src/routes/editor/ExportDialog.tsx b/apps/desktop/src/routes/editor/ExportDialog.tsx
index 2f00cee24..fae79de5c 100644
--- a/apps/desktop/src/routes/editor/ExportDialog.tsx
+++ b/apps/desktop/src/routes/editor/ExportDialog.tsx
@@ -509,10 +509,14 @@ export function ExportDialog() {
if (
option.value === "Gif" &&
- settings.resolution.value !== "720p"
+ !(
+ settings.resolution.value === "720p" ||
+ settings.resolution.value === "1080p"
+ )
)
- newSettings.resolution =
- RESOLUTION_OPTIONS._720p;
+ newSettings.resolution = {
+ ...RESOLUTION_OPTIONS._720p,
+ };
if (
option.value === "Gif" &&
@@ -642,7 +646,7 @@ export function ExportDialog() {
<For
each={
settings.format === "Gif"
- ? [RESOLUTION_OPTIONS._720p]
+ ? [RESOLUTION_OPTIONS._720p, RESOLUTION_OPTIONS._1080p]
: [
RESOLUTION_OPTIONS._720p,
RESOLUTION_OPTIONS._1080p,
diff --git a/biome.json b/biome.json
index db2a0e06d..6ef579271 100644
--- a/biome.json
+++ b/biome.json
@@ -1,5 +1,5 @@
{
- "$schema": "https://biomejs.dev/schemas/2.1.4/schema.json",
+ "$schema": "https://biomejs.dev/schemas/2.2.0/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
diff --git a/crates/displays/src/main.rs b/crates/displays/src/main.rs
index 1d04899e2..fd498328d 100644
--- a/crates/displays/src/main.rs
+++ b/crates/displays/src/main.rs
@@ -29,7 +29,7 @@ fn main() {
}
// Check if this is the main display
- let main_display_id = cap_displays::Display::list().get(0).map(|d| d.id());
+ let main_display_id = cap_displays::Display::list().first().map(|d| d.id());
if let Some(main_id) = main_display_id {
if display.id() == main_id {
@@ -90,18 +90,18 @@ fn main() {
}
println!("\n=== Topmost Window Icon Test ===");
- if let Some(topmost) = cap_displays::Window::get_topmost_at_cursor() {
- if let Some(owner) = topmost.owner_name() {
- println!("Testing icon extraction for: {}", owner);
-
- match topmost.app_icon() {
- Some(icon_data) => {
- println!(" ✅ Icon found: {} bytes", icon_data.len());
- println!(" Format: PNG (Raw bytes)");
- println!(" Size: {} bytes", icon_data.len());
- }
- None => println!(" ❌ No icon found"),
+ if let Some(topmost) = cap_displays::Window::get_topmost_at_cursor()
+ && let Some(owner) = topmost.owner_name()
+ {
+ println!("Testing icon extraction for: {}", owner);
+
+ match topmost.app_icon() {
+ Some(icon_data) => {
+ println!(" ✅ Icon found: {} bytes", icon_data.len());
+ println!(" Format: PNG (Raw bytes)");
+ println!(" Size: {} bytes", icon_data.len());
}
+ None => println!(" ❌ No icon found"),
}
}
@@ -120,11 +120,11 @@ fn main() {
relevant_windows.sort_by(|a, b| b.1.cmp(&a.1));
// Print current topmost window info
- if let Some((topmost_window, level)) = relevant_windows.first() {
- if let Some(owner) = topmost_window.owner_name() {
- print!("\rTopmost: {} (level: {}) ", owner, level);
- std::io::Write::flush(&mut std::io::stdout()).unwrap();
- }
+ if let Some((topmost_window, level)) = relevant_windows.first()
+ && let Some(owner) = topmost_window.owner_name()
+ {
+ print!("\rTopmost: {} (level: {}) ", owner, level);
+ std::io::Write::flush(&mut std::io::stdout()).unwrap();
}
std::thread::sleep(Duration::from_millis(100));
diff --git a/crates/displays/src/platform/macos.rs b/crates/displays/src/platform/macos.rs
index 324036ef1..c83d5e92b 100644
--- a/crates/displays/src/platform/macos.rs
+++ b/crates/displays/src/platform/macos.rs
@@ -268,7 +268,7 @@ impl WindowImpl {
unsafe {
window_dict
.find(kCGWindowBounds)
- .and_then(|v| CGRect::from_dict_representation(&*CFDictionary::from_void(*v)))
+ .and_then(|v| CGRect::from_dict_representation(&CFDictionary::from_void(*v)))
}
.map(|rect| LogicalBounds {
position: LogicalPosition {
diff --git a/crates/export/src/gif.rs b/crates/export/src/gif.rs
index bd4f3a066..8d31b78f9 100644
--- a/crates/export/src/gif.rs
+++ b/crates/export/src/gif.rs
@@ -1,6 +1,6 @@
use std::path::PathBuf;
-use cap_media_encoders::GifEncoderWrapper;
+use cap_media_encoders::{GifEncoderWrapper, GifQuality as EncoderGifQuality};
use cap_project::XY;
use cap_rendering::{ProjectUniforms, RenderSegment, RenderedFrame};
use futures::FutureExt;
@@ -10,10 +10,29 @@ use tracing::trace;
use crate::{ExportError, ExporterBase};
+#[derive(Deserialize, Clone, Copy, Debug, Type)]
+pub struct GifQuality {
+ /// Encoding quality from 1-100 (default: 90)
+ pub quality: Option<u8>,
+ /// Whether to prioritize speed over quality (default: false)
+ pub fast: Option<bool>,
+}
+
#[derive(Deserialize, Clone, Copy, Debug, Type)]
pub struct GifExportSettings {
pub fps: u32,
pub resolution_base: XY<u32>,
+ pub quality: Option<GifQuality>,
+}
+
+impl Default for GifExportSettings {
+ fn default() -> Self {
+ Self {
+ fps: 30,
+ resolution_base: XY { x: 1920, y: 1080 },
+ quality: None,
+ }
+ }
}
impl GifExportSettings {
@@ -46,9 +65,24 @@ impl GifExportSettings {
"Creating GIF encoder at path '{}'",
gif_output_path.display()
);
- let mut gif_encoder =
- GifEncoderWrapper::new(&gif_output_path, output_size.0, output_size.1, fps)
- .map_err(|e| format!("Failed to create GIF encoder: {e}"))?;
+
+ // Create GIF encoder with quality settings
+ let quality = self
+ .quality
+ .map(|q| EncoderGifQuality {
+ quality: q.quality.unwrap_or(90),
+ fast: q.fast.unwrap_or(false),
+ })
+ .unwrap_or_default();
+
+ let mut gif_encoder = GifEncoderWrapper::new_with_quality(
+ &gif_output_path,
+ output_size.0,
+ output_size.1,
+ fps,
+ quality,
+ )
+ .map_err(|e| format!("Failed to create GIF encoder: {e}"))?;
let encoder_thread = tokio::task::spawn_blocking(move || {
let mut frame_count = 0;
diff --git a/crates/media-encoders/Cargo.toml b/crates/media-encoders/Cargo.toml
index ed4e2b035..311f6496c 100644
--- a/crates/media-encoders/Cargo.toml
+++ b/crates/media-encoders/Cargo.toml
@@ -13,7 +13,9 @@ cap-media-info = { path = "../media-info" }
ffmpeg.workspace = true
thiserror.workspace = true
tracing.workspace = true
-gif = "0.13.3"
+gifski = "1.32"
+imgref = "1.10"
+rgb = "0.8"
[target.'cfg(target_os = "macos")'.dependencies]
cidre = { workspace = true }
diff --git a/crates/media-encoders/src/gif.rs b/crates/media-encoders/src/gif.rs
index 0f1a79d5e..53f3127d1 100644
--- a/crates/media-encoders/src/gif.rs
+++ b/crates/media-encoders/src/gif.rs
@@ -1,23 +1,54 @@
-use gif::{Encoder, Frame, Repeat};
+use gifski::{Collector, Repeat, Settings};
+use rgb::RGBA8;
use std::fs::File;
use std::path::Path;
+use std::thread::{self, JoinHandle};
use thiserror::Error;
+/// Errors that can occur during GIF encoding
#[derive(Error, Debug)]
pub enum GifEncodingError {
+ /// IO error occurred during encoding
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
- #[error("GIF encoding error: {0}")]
- Gif(#[from] gif::EncodingError),
+ /// Error from the gifski encoder
+ #[error("Gifski error: {0}")]
+ Gifski(String),
+ /// Invalid frame data provided
#[error("Invalid frame data")]
InvalidFrameData,
+ /// Encoder has been finished and cannot accept more frames
+ #[error("Encoder already finished")]
+ EncoderFinished,
}
+/// Quality settings for GIF encoding
+#[derive(Clone, Debug)]
+pub struct GifQuality {
+ /// Encoding quality from 1-100 (default: 90)
+ pub quality: u8,
+ /// Whether to prioritize speed over quality (default: false)
+ pub fast: bool,
+}
+
+impl Default for GifQuality {
+ fn default() -> Self {
+ Self {
+ quality: 90,
+ fast: false,
+ }
+ }
+}
+
+/// Wrapper around gifski for encoding GIF animations
pub struct GifEncoderWrapper {
- encoder: Encoder<File>,
- width: u16,
- height: u16,
- frame_delay: u16,
+ collector: Option<Collector>,
+ writer_thread: Option<JoinHandle<Result<(), GifEncodingError>>>,
+ width: u32,
+ height: u32,
+ frame_index: u32,
+ fps: u32,
+ finished: bool,
}
impl GifEncoderWrapper {
@@ -27,175 +58,165 @@ impl GifEncoderWrapper {
height: u32,
fps: u32,
) -> Result<Self, GifEncodingError> {
- let file = File::create(path)?;
-
- let global_palette = create_default_palette();
- let mut encoder = Encoder::new(file, width as u16, height as u16, &global_palette)?;
- encoder.set_repeat(Repeat::Infinite)?;
+ Self::new_with_quality(path, width, height, fps, GifQuality::default())
+ }
- let frame_delay = (100.0 / fps as f32) as u16;
+ pub fn new_with_quality<P: AsRef<Path>>(
+ path: P,
+ width: u32,
+ height: u32,
+ fps: u32,
+ quality: GifQuality,
+ ) -> Result<Self, GifEncodingError> {
+ if fps == 0 || width == 0 || height == 0 {
+ return Err(GifEncodingError::InvalidFrameData);
+ }
+ let settings = Settings {
+ width: Some(width),
+ height: Some(height),
+ quality: quality.quality,
+ fast: quality.fast,
+ repeat: Repeat::Infinite,
+ };
+ let (collector, writer) =
+ gifski::new(settings).map_err(|e| GifEncodingError::Gifski(e.to_string()))?;
+
+ let output_path = path.as_ref().to_path_buf();
+ let writer_thread = thread::spawn(move || {
+ let file = File::create(output_path).map_err(GifEncodingError::Io)?;
+ writer
+ .write(file, &mut gifski::progress::NoProgress {})
+ .map_err(|e| GifEncodingError::Gifski(e.to_string()))
+ });
Ok(Self {
- encoder,
- width: width as u16,
- height: height as u16,
- frame_delay,
+ collector: Some(collector),
+ writer_thread: Some(writer_thread),
+ width,
+ height,
+ frame_index: 0,
+ fps,
+ finished: false,
})
}
+ /// Add a frame to the GIF
pub fn add_frame(
&mut self,
frame_data: &[u8],
- padded_bytes_per_row: usize,
+ bytes_per_row: usize,
) -> Result<(), GifEncodingError> {
- let width = self.width as usize;
- let height = self.height as usize;
- let mut indexed_data = Vec::with_capacity(width * height);
-
- let mut rgb_data = Vec::with_capacity(width * height * 3);
- for y in 0..height {
- let row_start = y * padded_bytes_per_row;
- for x in 0..width {
- let pixel_start = row_start + x * 4;
- if pixel_start + 2 < frame_data.len() {
- rgb_data.push(frame_data[pixel_start] as i32);
- rgb_data.push(frame_data[pixel_start + 1] as i32);
- rgb_data.push(frame_data[pixel_start + 2] as i32);
- } else {
- return Err(GifEncodingError::InvalidFrameData);
- }
- }
+ if self.finished {
+ return Err(GifEncodingError::EncoderFinished);
}
- for y in 0..height {
- for x in 0..width {
- let idx = (y * width + x) * 3;
- let r = rgb_data[idx].clamp(0, 255) as u8;
- let g = rgb_data[idx + 1].clamp(0, 255) as u8;
- let b = rgb_data[idx + 2].clamp(0, 255) as u8;
+ let collector = self
+ .collector
+ .as_mut()
+ .ok_or(GifEncodingError::EncoderFinished)?;
- let palette_idx = find_closest_palette_index(r, g, b);
- indexed_data.push(palette_idx);
+ // Calculate expected size
+ let expected_bytes_per_row = (self.width as usize) * 4; // RGBA
+ let expected_total_bytes = expected_bytes_per_row * (self.height as usize);
- let (pr, pg, pb) = get_palette_color(palette_idx);
+ // Validate frame data size
+ if bytes_per_row < expected_bytes_per_row || frame_data.len() < expected_total_bytes {
+ return Err(GifEncodingError::InvalidFrameData);
+ }
- let er = r as i32 - pr as i32;
- let eg = g as i32 - pg as i32;
- let eb = b as i32 - pb as i32;
+ // Convert RGBA data to gifski's expected format
+ let mut rgba_pixels = Vec::with_capacity(self.width as usize * self.height as usize);
- if x + 1 < width {
- let idx_right = (y * width + x + 1) * 3;
- rgb_data[idx_right] += (er * 7) / 16;
- rgb_data[idx_right + 1] += (eg * 7) / 16;
- rgb_data[idx_right + 2] += (eb * 7) / 16;
- }
- if y + 1 < height {
- if x > 0 {
- let idx_bottom_left = ((y + 1) * width + x - 1) * 3;
- rgb_data[idx_bottom_left] += (er * 3) / 16;
- rgb_data[idx_bottom_left + 1] += (eg * 3) / 16;
- rgb_data[idx_bottom_left + 2] += (eb * 3) / 16;
- }
- let idx_bottom = ((y + 1) * width + x) * 3;
- rgb_data[idx_bottom] += (er * 5) / 16;
- rgb_data[idx_bottom + 1] += (eg * 5) / 16;
- rgb_data[idx_bottom + 2] += (eb * 5) / 16;
-
- if x + 1 < width {
- let idx_bottom_right = ((y + 1) * width + x + 1) * 3;
- rgb_data[idx_bottom_right] += er / 16;
- rgb_data[idx_bottom_right + 1] += eg / 16;
- rgb_data[idx_bottom_right + 2] += eb / 16;
- }
+ for y in 0..self.height {
+ let src_row_start = (y as usize) * bytes_per_row;
+
+ for x in 0..self.width {
+ let pixel_start = src_row_start + (x as usize) * 4;
+
+ if pixel_start + 3 < frame_data.len() {
+ let r = frame_data[pixel_start];
+ let g = frame_data[pixel_start + 1];
+ let b = frame_data[pixel_start + 2];
+ let a = frame_data[pixel_start + 3];
+
+ rgba_pixels.push(RGBA8::new(r, g, b, a));
+ } else {
+ return Err(GifEncodingError::InvalidFrameData);
}
}
}
- let mut frame = Frame::from_indexed_pixels(self.width, self.height, indexed_data, None);
- frame.delay = self.frame_delay;
+ // Create imgref for gifski
+ let img = imgref::Img::new(rgba_pixels, self.width as usize, self.height as usize);
- self.encoder.write_frame(&frame)?;
- Ok(())
- }
+ // Calculate presentation timestamp based on frame index and fps
+ let pts = (self.frame_index as f64) / (self.fps as f64);
+
+ // Add frame to collector
+ collector
+ .add_frame_rgba(self.frame_index as usize, img, pts)
+ .map_err(|e| GifEncodingError::Gifski(e.to_string()))?;
- pub fn finish(self) -> Result<(), GifEncodingError> {
- drop(self.encoder);
+ self.frame_index += 1;
Ok(())
}
-}
-fn create_default_palette() -> Vec<u8> {
- let mut palette = Vec::with_capacity(256 * 3);
+ /// Finish encoding and close the GIF file
+ ///
+ /// This will wait for the encoding to complete and return any errors
+ /// that occurred during the writing process.
+ pub fn finish(mut self) -> Result<(), GifEncodingError> {
+ if self.finished {
+ return Ok(());
+ }
- for r in 0..6 {
- for g in 0..7 {
- for b in 0..6 {
- palette.push((r * 255 / 5) as u8);
- palette.push((g * 255 / 6) as u8);
- palette.push((b * 255 / 5) as u8);
+ // Drop the collector to signal that we're done adding frames
+ drop(self.collector.take());
+
+ // Wait for the writer thread to complete
+ if let Some(writer_thread) = self.writer_thread.take() {
+ match writer_thread.join() {
+ Ok(result) => result?,
+ Err(_) => {
+ return Err(GifEncodingError::Gifski(
+ "Writer thread panicked".to_string(),
+ ));
+ }
}
}
+
+ self.finished = true;
+ Ok(())
}
- palette.push(0);
- palette.push(0);
- palette.push(0);
- palette.push(85);
- palette.push(85);
- palette.push(85);
- palette.push(170);
- palette.push(170);
- palette.push(170);
- palette.push(255);
- palette.push(255);
- palette.push(255);
-
- assert_eq!(palette.len(), 256 * 3, "Palette must be exactly 256 colors");
- palette
-}
+ /// Get the current frame count
+ pub fn frame_count(&self) -> u32 {
+ self.frame_index
+ }
-fn find_closest_palette_index(r: u8, g: u8, b: u8) -> u8 {
- let r_idx = ((r as u32 * 5) / 255).min(5) as u8;
- let g_idx = ((g as u32 * 6) / 255).min(6) as u8;
- let b_idx = ((b as u32 * 5) / 255).min(5) as u8;
-
- if (r as i32 - g as i32).abs() < 30
- && (g as i32 - b as i32).abs() < 30
- && (r as i32 - b as i32).abs() < 30
- {
- let gray = ((r as u32 + g as u32 + b as u32) / 3) as u8;
- if gray < 43 {
- return 252;
- } else if gray < 128 {
- return 253;
- } else if gray < 213 {
- return 254;
- } else {
- return 255;
- }
+ /// Get the dimensions of the GIF
+ pub fn dimensions(&self) -> (u32, u32) {
+ (self.width, self.height)
}
- r_idx * 42 + g_idx * 6 + b_idx
+ /// Get the target FPS
+ pub fn fps(&self) -> u32 {
+ self.fps
+ }
}
-fn get_palette_color(index: u8) -> (u8, u8, u8) {
- if index < 252 {
- let r_idx = (index / 42) as u32;
- let rem = index % 42;
- let g_idx = (rem / 6) as u32;
- let b_idx = (rem % 6) as u32;
-
- let r = ((r_idx * 255) / 5) as u8;
- let g = ((g_idx * 255) / 6) as u8;
- let b = ((b_idx * 255) / 5) as u8;
- (r, g, b)
- } else {
- match index {
- 252 => (0, 0, 0),
- 253 => (85, 85, 85),
- 254 => (170, 170, 170),
- 255 => (255, 255, 255),
- _ => (0, 0, 0),
+impl Drop for GifEncoderWrapper {
+ fn drop(&mut self) {
+ if !self.finished && self.collector.is_some() {
+ // Drop the collector to signal completion
+ drop(self.collector.take());
+
+ // Try to join the writer thread
+ if let Some(thread) = self.writer_thread.take() {
+ let _ = thread.join();
+ }
+
+ self.finished = true;
}
}
}
diff --git a/crates/scap-screencapturekit/src/capture.rs b/crates/scap-screencapturekit/src/capture.rs
index fd1e6e49b..26d6ef058 100644
--- a/crates/scap-screencapturekit/src/capture.rs
+++ b/crates/scap-screencapturekit/src/capture.rs
@@ -60,20 +60,12 @@ impl sc::stream::DelegateImpl for CapturerCallbacks {
type DidOutputSampleBufCallback = Box<dyn FnMut(Frame)>;
type StreamDidStopwithErrCallback = Box<dyn FnMut(&sc::Stream, &ns::Error)>;
+#[derive(Default)]
pub struct CapturerCallbacksInner {
did_output_sample_buf_cb: Option<DidOutputSampleBufCallback>,
did_stop_with_err_cb: Option<StreamDidStopwithErrCallback>,
}
-impl Default for CapturerCallbacksInner {
- fn default() -> Self {
- Self {
- did_output_sample_buf_cb: None,
- did_stop_with_err_cb: None,
- }
- }
-}
-
pub struct Capturer {
target: arc::R<sc::ContentFilter>,
config: arc::R<sc::StreamCfg>,
diff --git a/crates/scap-screencapturekit/src/targets.rs b/crates/scap-screencapturekit/src/targets.rs
index 39225e5f1..be8aee9af 100644
--- a/crates/scap-screencapturekit/src/targets.rs
+++ b/crates/scap-screencapturekit/src/targets.rs
@@ -171,7 +171,7 @@ impl Window {
let windows = content
.windows()
.iter()
- .filter_map(|window| Some(Self::from_sc(window)))
+ .map(Self::from_sc)
.collect::<Vec<_>>();
Ok(windows)
diff --git a/package.json b/package.json
index 94d5ce6e2..bee43acc5 100644
--- a/package.json
+++ b/package.json
@@ -26,7 +26,7 @@
"clean": "find . -name node_modules -o -name .next -o -name .output -o -name .turbo -o -name dist -type d -prune | xargs rm -rf"
},
"devDependencies": {
- "@biomejs/biome": "2.1.4",
+ "@biomejs/biome": "2.2.0",
"@clack/prompts": "^0.10.0",
"@effect/language-service": "^0.34.0",
"dotenv-cli": "latest",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6a8feac05..44e8dc170 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -9,8 +9,8 @@ importers:
.:
devDependencies:
'@biomejs/biome':
- specifier: 2.1.4
- version: 2.1.4
+ specifier: 2.2.0
+ version: 2.2.0
'@clack/prompts':
specifier: ^0.10.0
version: 0.10.1
@@ -1668,55 +1668,55 @@ packages:
resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==}
- '@biomejs/[email protected]':
- resolution: {integrity: sha512-QWlrqyxsU0FCebuMnkvBIkxvPqH89afiJzjMl+z67ybutse590jgeaFdDurE9XYtzpjRGTI1tlUZPGWmbKsElA==}
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-3On3RSYLsX+n9KnoSgfoYlckYBoU6VRM22cw1gB4Y0OuUVSYd/O/2saOJMrA4HFfA1Ff0eacOvMN1yAAvHtzIw==}
engines: {node: '>=14.21.3'}
hasBin: true
- '@biomejs/[email protected]':
- resolution: {integrity: sha512-sCrNENE74I9MV090Wq/9Dg7EhPudx3+5OiSoQOkIe3DLPzFARuL1dOwCWhKCpA3I5RHmbrsbNSRfZwCabwd8Qg==}
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-zKbwUUh+9uFmWfS8IFxmVD6XwqFcENjZvEyfOxHs1epjdH3wyyMQG80FGDsmauPwS2r5kXdEM0v/+dTIA9FXAg==}
engines: {node: '>=14.21.3'}
cpu: [arm64]
os: [darwin]
- '@biomejs/[email protected]':
- resolution: {integrity: sha512-gOEICJbTCy6iruBywBDcG4X5rHMbqCPs3clh3UQ+hRKlgvJTk4NHWQAyHOXvaLe+AxD1/TNX1jbZeffBJzcrOw==}
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-+OmT4dsX2eTfhD5crUOPw3RPhaR+SKVspvGVmSdZ9y9O/AgL8pla6T4hOn1q+VAFBHuHhsdxDRJgFCSC7RaMOw==}
engines: {node: '>=14.21.3'}
cpu: [x64]
os: [darwin]
- '@biomejs/[email protected]':
- resolution: {integrity: sha512-nYr7H0CyAJPaLupFE2cH16KZmRC5Z9PEftiA2vWxk+CsFkPZQ6dBRdcC6RuS+zJlPc/JOd8xw3uCCt9Pv41WvQ==}
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-egKpOa+4FL9YO+SMUMLUvf543cprjevNc3CAgDNFLcjknuNMcZ0GLJYa3EGTCR2xIkIUJDVneBV3O9OcIlCEZQ==}
engines: {node: '>=14.21.3'}
cpu: [arm64]
os: [linux]
- '@biomejs/[email protected]':
- resolution: {integrity: sha512-juhEkdkKR4nbUi5k/KRp1ocGPNWLgFRD4NrHZSveYrD6i98pyvuzmS9yFYgOZa5JhaVqo0HPnci0+YuzSwT2fw==}
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-6eoRdF2yW5FnW9Lpeivh7Mayhq0KDdaDMYOJnH9aT02KuSIX5V1HmWJCQQPwIQbhDh68Zrcpl8inRlTEan0SXw==}
engines: {node: '>=14.21.3'}
cpu: [arm64]
os: [linux]
- '@biomejs/[email protected]':
- resolution: {integrity: sha512-lvwvb2SQQHctHUKvBKptR6PLFCM7JfRjpCCrDaTmvB7EeZ5/dQJPhTYBf36BE/B4CRWR2ZiBLRYhK7hhXBCZAg==}
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-I5J85yWwUWpgJyC1CcytNSGusu2p9HjDnOPAFG4Y515hwRD0jpR9sT9/T1cKHtuCvEQ/sBvx+6zhz9l9wEJGAg==}
engines: {node: '>=14.21.3'}
cpu: [x64]
os: [linux]
- '@biomejs/[email protected]':
- resolution: {integrity: sha512-Eoy9ycbhpJVYuR+LskV9s3uyaIkp89+qqgqhGQsWnp/I02Uqg2fXFblHJOpGZR8AxdB9ADy87oFVxn9MpFKUrw==}
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-5UmQx/OZAfJfi25zAnAGHUMuOd+LOsliIt119x2soA2gLggQYrVPA+2kMUxR6Mw5M1deUF/AWWP2qpxgH7Nyfw==}
engines: {node: '>=14.21.3'}
cpu: [x64]
os: [linux]
- '@biomejs/[email protected]':
- resolution: {integrity: sha512-3WRYte7orvyi6TRfIZkDN9Jzoogbv+gSvR+b9VOXUg1We1XrjBg6WljADeVEaKTvOcpVdH0a90TwyOQ6ue4fGw==}
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-n9a1/f2CwIDmNMNkFs+JI0ZjFnMO0jdOyGNtihgUNFnlmd84yIYY2KMTBmMV58ZlVHjgmY5Y6E1hVTnSRieggA==}
engines: {node: '>=14.21.3'}
cpu: [arm64]
os: [win32]
- '@biomejs/[email protected]':
- resolution: {integrity: sha512-tBc+W7anBPSFXGAoQW+f/+svkpt8/uXfRwDzN1DvnatkRMt16KIYpEi/iw8u9GahJlFv98kgHcIrSsZHZTR0sw==}
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-Nawu5nHjP/zPKTIryh2AavzTc/KEg4um/MxWdXW0A6P/RZOyIpa7+QSjeXwAwX/utJGaCoXRPWtF3m5U/bB3Ww==}
engines: {node: '>=14.21.3'}
cpu: [x64]
os: [win32]
@@ -14718,39 +14718,39 @@ snapshots:
'@bcoe/[email protected]': {}
- '@biomejs/[email protected]':
+ '@biomejs/[email protected]':
optionalDependencies:
- '@biomejs/cli-darwin-arm64': 2.1.4
- '@biomejs/cli-darwin-x64': 2.1.4
- '@biomejs/cli-linux-arm64': 2.1.4
- '@biomejs/cli-linux-arm64-musl': 2.1.4
- '@biomejs/cli-linux-x64': 2.1.4
- '@biomejs/cli-linux-x64-musl': 2.1.4
- '@biomejs/cli-win32-arm64': 2.1.4
- '@biomejs/cli-win32-x64': 2.1.4
+ '@biomejs/cli-darwin-arm64': 2.2.0
+ '@biomejs/cli-darwin-x64': 2.2.0
+ '@biomejs/cli-linux-arm64': 2.2.0
+ '@biomejs/cli-linux-arm64-musl': 2.2.0
+ '@biomejs/cli-linux-x64': 2.2.0
+ '@biomejs/cli-linux-x64-musl': 2.2.0
+ '@biomejs/cli-win32-arm64': 2.2.0
+ '@biomejs/cli-win32-x64': 2.2.0
- '@biomejs/[email protected]':
+ '@biomejs/[email protected]':
optional: true
- '@biomejs/[email protected]':
+ '@biomejs/[email protected]':
optional: true
- '@biomejs/[email protected]':
+ '@biomejs/[email protected]':
optional: true
- '@biomejs/[email protected]':
+ '@biomejs/[email protected]':
optional: true
- '@biomejs/[email protected]':
+ '@biomejs/[email protected]':
optional: true
- '@biomejs/[email protected]':
+ '@biomejs/[email protected]':
optional: true
- '@biomejs/[email protected]':
+ '@biomejs/[email protected]':
optional: true
- '@biomejs/[email protected]':
+ '@biomejs/[email protected]':
optional: true
@@ -22234,8 +22234,8 @@ snapshots:
'@typescript-eslint/parser': 5.62.0([email protected]([email protected]))([email protected])
eslint: 9.30.1([email protected])
eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 4.6.2([email protected]([email protected]))
@@ -22263,33 +22263,33 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.0([email protected])
- eslint: 8.57.1
+ eslint: 9.30.1([email protected])
get-tsconfig: 4.10.0
is-bun-module: 2.0.0
stable-hash: 0.0.5
tinyglobby: 0.2.13
unrs-resolver: 1.7.2
optionalDependencies:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.0([email protected])
- eslint: 9.30.1([email protected])
+ eslint: 8.57.1
get-tsconfig: 4.10.0
is-bun-module: 2.0.0
stable-hash: 0.0.5
tinyglobby: 0.2.13
unrs-resolver: 1.7.2
optionalDependencies:
transitivePeerDependencies:
- supports-color
@@ -22304,14 +22304,14 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 5.62.0([email protected]([email protected]))([email protected])
eslint: 9.30.1([email protected])
eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
@@ -22355,7 +22355,7 @@ snapshots:
- eslint-import-resolver-webpack
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.8
@@ -22366,7 +22366,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.30.1([email protected])
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.16.1
is-glob: 4.0.3