Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

wip: JavaScript powered video renderer

Richie McIlroy1d46f0758d93
diff --git a/Cargo.lock b/Cargo.lock
index b02108775..ee0e2cb61 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1428,6 +1428,7 @@ dependencies = [
"tauri-build",
"tauri-nspanel",
"tauri-plugin-decorum",
+ "tauri-plugin-fs",
"tauri-plugin-shell",
"tauri-specta",
"tokio",
diff --git a/apps/desktop-solid/package.json b/apps/desktop-solid/package.json
index 3835b375e..a75c3d424 100644
--- a/apps/desktop-solid/package.json
+++ b/apps/desktop-solid/package.json
@@ -17,17 +17,21 @@
"@solidjs/start": "^1.0.6",
"@tanstack/solid-query": "^5.51.21",
"@tauri-apps/api": ">=2.0.0-rc.0",
+ "@tauri-apps/plugin-fs": "2.0.0-rc.0",
"@tauri-apps/plugin-shell": ">=2.0.0-rc.0",
"cva": "npm:class-variance-authority@^0.7.0",
+ "mp4box": "^0.5.2",
"solid-js": "^1.7.8",
"solid-presence": "^0.1.8",
"unplugin-auto-import": "^0.18.2",
"unplugin-icons": "^0.19.2",
- "vinxi": "^0.4.1"
+ "vinxi": "^0.4.1",
+ "webcodecs": "^0.1.0"
},
"devDependencies": {
"@iconify/json": "^2.2.237",
"@tauri-apps/cli": ">=2.0.0-rc.0",
+ "@types/dom-webcodecs": "^0.1.11",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.41",
"tailwindcss": "^3.4.10",
diff --git a/apps/desktop-solid/src-tauri/Cargo.toml b/apps/desktop-solid/src-tauri/Cargo.toml
index f76ba0ec5..6b8240feb 100644
--- a/apps/desktop-solid/src-tauri/Cargo.toml
+++ b/apps/desktop-solid/src-tauri/Cargo.toml
@@ -41,4 +41,5 @@ tauri-nspanel = { git = "https://github.com/ahkohd/tauri-nspanel", branch = "v2"
ffmpeg-sidecar = { git = "https://github.com/CapSoftware/ffmpeg-sidecar", branch = "main" }
wgpu = "22.1.0"
bytemuck = { version = "1.7", features = ["derive"] }
-image = "0.25.2"
\ No newline at end of file
+image = "0.25.2"
+tauri-plugin-fs = "2.0.0-rc.0"
diff --git a/apps/desktop-solid/src-tauri/capabilities/default.json b/apps/desktop-solid/src-tauri/capabilities/default.json
index 827d87e81..3cc11bb86 100644
--- a/apps/desktop-solid/src-tauri/capabilities/default.json
+++ b/apps/desktop-solid/src-tauri/capabilities/default.json
@@ -2,7 +2,11 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
- "windows": ["main", "camera", "prev-recordings"],
+ "windows": [
+ "main",
+ "camera",
+ "prev-recordings"
+ ],
"permissions": [
"core:default",
"core:window:allow-close",
@@ -17,6 +21,7 @@
"core:window:allow-start-dragging",
"core:window:allow-set-position",
"core:webview:allow-create-webview-window",
- "shell:default"
+ "shell:default",
+ "fs:default"
]
-}
+}
\ No newline at end of file
diff --git a/apps/desktop-solid/src-tauri/src/ffmpeg.rs b/apps/desktop-solid/src-tauri/src/ffmpeg.rs
index 8f0517c22..432f1438b 100644
--- a/apps/desktop-solid/src-tauri/src/ffmpeg.rs
+++ b/apps/desktop-solid/src-tauri/src/ffmpeg.rs
@@ -1,22 +1,25 @@
use std::{
ffi::OsString,
- io::{ Write, Read },
+ io::{Read, Write},
ops::Deref,
path::PathBuf,
- process::{ Child, ChildStdin, Command, Stdio },
- sync::{ atomic::{ AtomicBool, Ordering }, Arc },
+ process::{Child, ChildStdin, Command, Stdio},
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
};
use ffmpeg_sidecar::{
command::ffmpeg_is_installed,
- download::{ check_latest_version, download_ffmpeg_package, ffmpeg_download_url, unpack_ffmpeg },
+ download::{check_latest_version, download_ffmpeg_package, ffmpeg_download_url, unpack_ffmpeg},
paths::sidecar_dir,
version::ffmpeg_version,
};
use std::io;
-use crate::utils::{ create_named_pipe, ffmpeg_path_as_str };
+use crate::utils::{create_named_pipe, ffmpeg_path_as_str};
pub struct FFmpegProcess {
ffmpeg_stdin: ChildStdin,
@@ -41,10 +44,7 @@ impl FFmpegProcess {
panic!("Failed to capture FFmpeg stdin");
});
- Self {
- ffmpeg_stdin,
- cmd,
- }
+ Self { ffmpeg_stdin, cmd }
}
pub fn write(&mut self, data: &[u8]) -> std::io::Result<()> {
@@ -58,7 +58,7 @@ impl FFmpegProcess {
pub fn read_video_frame(
&mut self,
- frame_size: usize
+ frame_size: usize,
) -> Result<Option<Vec<u8>>, std::io::Error> {
let mut buffer = vec![0u8; frame_size];
match self.cmd.stdout.as_mut().unwrap().read_exact(&mut buffer) {
@@ -204,7 +204,12 @@ impl FFmpeg {
pub fn add_output(&mut self, output: FFmpegOutput) {
match output {
- FFmpegOutput::File { path, codec, preset, crf } => {
+ FFmpegOutput::File {
+ path,
+ codec,
+ preset,
+ crf,
+ } => {
self.command
.arg("-i")
.arg("pipe:0")
@@ -213,7 +218,11 @@ impl FFmpeg {
.args(&["-crf", &crf.to_string()])
.arg(path);
}
- FFmpegOutput::RawVideo { format, width, height } => {
+ FFmpegOutput::RawVideo {
+ format,
+ width,
+ height,
+ } => {
self.command
.arg("-i")
.arg("pipe:0")
@@ -242,9 +251,8 @@ pub fn handle_ffmpeg_installation() -> Result<(), String> {
let download_url = ffmpeg_download_url().map_err(|e| e.to_string())?;
let destination = sidecar_dir().map_err(|e| e.to_string())?;
- let archive_path = download_ffmpeg_package(download_url, &destination).map_err(|e|
- e.to_string()
- )?;
+ let archive_path =
+ download_ffmpeg_package(download_url, &destination).map_err(|e| e.to_string())?;
unpack_ffmpeg(&archive_path, &destination).map_err(|e| e.to_string())?;
diff --git a/apps/desktop-solid/src-tauri/src/lib.rs b/apps/desktop-solid/src-tauri/src/lib.rs
index 7dd321fad..0316e38d7 100644
--- a/apps/desktop-solid/src-tauri/src/lib.rs
+++ b/apps/desktop-solid/src-tauri/src/lib.rs
@@ -6,31 +6,31 @@ mod recording;
mod utils;
mod video_renderer;
-use objc2_app_kit::{ NSPopUpMenuWindowLevel, NSScreenSaverWindowLevel };
-use recording::{ DisplaySource, InProgressRecording };
+use objc2_app_kit::{NSPopUpMenuWindowLevel, NSScreenSaverWindowLevel};
+use recording::{DisplaySource, InProgressRecording};
// use macos::Bounds;
use scap::Target;
-use serde::{ Deserialize, Serialize };
+use serde::{Deserialize, Serialize};
use serde_json::json;
use specta::Type;
use std::{
collections::HashMap,
marker::PhantomData,
path::PathBuf,
- process::{ Command, Stdio },
+ process::{Command, Stdio},
sync::Arc,
time::Duration,
};
-use tauri::{ AppHandle, Manager, State, WebviewWindow };
-use tauri_nspanel::{ cocoa::appkit::NSMainMenuWindowLevel, ManagerExt };
+use tauri::{AppHandle, Manager, State, WebviewWindow};
+use tauri_nspanel::{cocoa::appkit::NSMainMenuWindowLevel, ManagerExt};
use tauri_plugin_decorum::WebviewWindowExt;
use tauri_specta::Event;
-use tokio::{ sync::RwLock, time::sleep };
+use tokio::{sync::RwLock, time::sleep};
-use camera::{ create_camera_window, get_cameras };
-use display::{ get_capture_windows, CaptureTarget };
+use crate::utils::ffmpeg_path_as_str;
+use camera::{create_camera_window, get_cameras};
+use display::{get_capture_windows, CaptureTarget};
use ffmpeg::handle_ffmpeg_installation;
-use crate::utils::{ ffmpeg_path_as_str };
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
@@ -69,7 +69,7 @@ async fn get_recording_options(state: MutableState<'_, AppState>) -> Result<Reco
async fn set_recording_options(
app: AppHandle,
state: MutableState<'_, AppState>,
- options: RecordingOptions
+ options: RecordingOptions,
) -> Result<(), ()> {
let mut state = state.write().await;
state.start_recording_options = options;
@@ -82,7 +82,10 @@ async fn set_recording_options(
type Bruh<T> = (T,);
#[derive(Serialize, Type)]
-struct JsonValue<T>(#[serde(skip)] PhantomData<T>, #[specta(type = Bruh<T>)] serde_json::Value);
+struct JsonValue<T>(
+ #[serde(skip)] PhantomData<T>,
+ #[specta(type = Bruh<T>)] serde_json::Value,
+);
impl<T: Serialize> JsonValue<T> {
fn new(value: &T) -> Self {
@@ -93,7 +96,7 @@ impl<T: Serialize> JsonValue<T> {
#[tauri::command]
#[specta::specta]
async fn get_current_recording(
- state: MutableState<'_, AppState>
+ state: MutableState<'_, AppState>,
) -> Result<JsonValue<Option<InProgressRecording>>, ()> {
let state = state.read().await;
Ok(JsonValue::new(&state.current_recording))
@@ -132,26 +135,28 @@ async fn start_recording(app: AppHandle, state: MutableState<'_, AppState>) -> R
let occluder_window = WebviewWindow::builder(
&app,
"window-capture-occluder",
- tauri::WebviewUrl::App("/window-capture-occluder".into())
+ tauri::WebviewUrl::App("/window-capture-occluder".into()),
)
- .title("Cap Window Capture Occluder")
- .maximized(false)
- .resizable(false)
- .fullscreen(false)
- .decorations(false)
- .shadow(false)
- .always_on_top(true)
- .visible_on_all_workspaces(true)
- .content_protected(true)
- .inner_size(
- (monitor.size().width as f64) / monitor.scale_factor(),
- (monitor.size().height as f64) / monitor.scale_factor()
- )
- .position(0.0, 0.0)
- .build()
- .unwrap();
+ .title("Cap Window Capture Occluder")
+ .maximized(false)
+ .resizable(false)
+ .fullscreen(false)
+ .decorations(false)
+ .shadow(false)
+ .always_on_top(true)
+ .visible_on_all_workspaces(true)
+ .content_protected(true)
+ .inner_size(
+ (monitor.size().width as f64) / monitor.scale_factor(),
+ (monitor.size().height as f64) / monitor.scale_factor(),
+ )
+ .position(0.0, 0.0)
+ .build()
+ .unwrap();
- occluder_window.set_window_level(NSScreenSaverWindowLevel as u32).unwrap();
+ occluder_window
+ .set_window_level(NSScreenSaverWindowLevel as u32)
+ .unwrap();
occluder_window.set_ignore_cursor_events(true).unwrap();
occluder_window.make_transparent().unwrap();
}
@@ -170,7 +175,9 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, AppState>) -> Re
current_recording.stop();
println!("Recording stopped");
- state.prev_recordings.push(current_recording.recording_dir.clone());
+ state
+ .prev_recordings
+ .push(current_recording.recording_dir.clone());
println!("Added to previous recordings");
drop(state);
@@ -198,7 +205,7 @@ async fn render_video(
webcam_position: (f32, f32),
webcam_style: video_renderer::WebcamStyle,
output_size: (u32, u32),
- background: video_renderer::Background
+ background: video_renderer::Background,
) -> Result<String, String> {
let options = video_renderer::RenderOptions {
screen_recording_path: PathBuf::from(screen_recording_path),
@@ -238,7 +245,7 @@ async fn set_fake_window_bounds(
window: tauri::Window,
name: String,
bounds: Bounds,
- state: tauri::State<'_, FakeWindowBounds>
+ state: tauri::State<'_, FakeWindowBounds>,
) -> Result<(), String> {
let mut state = state.0.write().await;
let map = state.entry(window.label().to_string()).or_default();
@@ -253,7 +260,7 @@ async fn set_fake_window_bounds(
async fn remove_fake_window(
window: tauri::Window,
name: String,
- state: tauri::State<'_, FakeWindowBounds>
+ state: tauri::State<'_, FakeWindowBounds>,
) -> Result<(), String> {
let mut state = state.0.write().await;
let Some(map) = state.get_mut(window.label()) else {
@@ -291,24 +298,24 @@ fn show_previous_recordings_window(app: AppHandle) {
let window = WebviewWindow::builder(
&app,
PREV_RECORDINGS_WINDOW,
- tauri::WebviewUrl::App("/prev-recordings".into())
+ tauri::WebviewUrl::App("/prev-recordings".into()),
)
- .title("Cap Recordings")
- .maximized(false)
- .resizable(false)
- .fullscreen(false)
- .decorations(false)
- .shadow(false)
- .always_on_top(true)
- .visible_on_all_workspaces(true)
- .content_protected(true)
- .inner_size(
- (monitor.size().width as f64) / monitor.scale_factor(),
- (monitor.size().height as f64) / monitor.scale_factor()
- )
- .position(0.0, 0.0)
- .build()
- .unwrap();
+ .title("Cap Recordings")
+ .maximized(false)
+ .resizable(false)
+ .fullscreen(false)
+ .decorations(false)
+ .shadow(false)
+ .always_on_top(true)
+ .visible_on_all_workspaces(true)
+ .content_protected(true)
+ .inner_size(
+ (monitor.size().width as f64) / monitor.scale_factor(),
+ (monitor.size().height as f64) / monitor.scale_factor(),
+ )
+ .position(0.0, 0.0)
+ .build()
+ .unwrap();
println!("Window built successfully");
use tauri_nspanel::cocoa::appkit::NSWindowCollectionBehavior;
@@ -326,10 +333,10 @@ fn show_previous_recordings_window(app: AppHandle) {
println!("Setting panel collection behaviour");
panel.set_collection_behaviour(
- NSWindowCollectionBehavior::NSWindowCollectionBehaviorTransient |
- NSWindowCollectionBehavior::NSWindowCollectionBehaviorMoveToActiveSpace |
- NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary |
- NSWindowCollectionBehavior::NSWindowCollectionBehaviorIgnoresCycle
+ NSWindowCollectionBehavior::NSWindowCollectionBehaviorTransient
+ | NSWindowCollectionBehavior::NSWindowCollectionBehaviorMoveToActiveSpace
+ | NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
+ | NSWindowCollectionBehavior::NSWindowCollectionBehaviorIgnoresCycle,
);
println!("Panel collection behaviour set");
@@ -367,11 +374,10 @@ fn show_previous_recordings_window(app: AppHandle) {
let y_max =
(window_position.y as f64) + (bounds.y + bounds.height) * scale_factor;
- if
- mouse_position.x >= x_min &&
- mouse_position.x <= x_max &&
- mouse_position.y >= y_min &&
- mouse_position.y <= y_max
+ if mouse_position.x >= x_min
+ && mouse_position.x <= x_max
+ && mouse_position.y >= y_min
+ && mouse_position.y <= y_max
{
ignore = false;
FocusCapturesPanel.emit(&app).ok();
@@ -409,35 +415,39 @@ fn focus_captures_panel(app: AppHandle) {
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
- let specta_builder = tauri_specta::Builder
- ::new()
- .commands(
- tauri_specta::collect_commands![
- get_recording_options,
- set_recording_options,
- create_camera_window,
- start_recording,
- stop_recording,
- get_cameras,
- get_capture_windows,
- get_prev_recordings,
- open_previous_recordings_window,
- set_fake_window_bounds,
- remove_fake_window,
- focus_captures_panel,
- get_current_recording,
- render_video
- ]
- )
- .events(tauri_specta::collect_events![RecordingOptionsChanged, FocusCapturesPanel]);
+ let specta_builder = tauri_specta::Builder::new()
+ .commands(tauri_specta::collect_commands![
+ get_recording_options,
+ set_recording_options,
+ create_camera_window,
+ start_recording,
+ stop_recording,
+ get_cameras,
+ get_capture_windows,
+ get_prev_recordings,
+ open_previous_recordings_window,
+ set_fake_window_bounds,
+ remove_fake_window,
+ focus_captures_panel,
+ get_current_recording,
+ render_video
+ ])
+ .events(tauri_specta::collect_events![
+ RecordingOptionsChanged,
+ FocusCapturesPanel
+ ]);
#[cfg(debug_assertions)] // <- Only export on non-release builds
specta_builder
- .export(specta_typescript::Typescript::default(), "../src/utils/tauri.ts")
+ .export(
+ specta_typescript::Typescript::default(),
+ "../src/utils/tauri.ts",
+ )
.expect("Failed to export typescript bindings");
tauri::Builder
::default()
+ .plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_shell::init())
.plugin(tauri_nspanel::init())
.invoke_handler(specta_builder.invoke_handler())
diff --git a/apps/desktop-solid/src-tauri/src/recording.rs b/apps/desktop-solid/src-tauri/src/recording.rs
index 20d210b8f..17ee613ae 100644
--- a/apps/desktop-solid/src-tauri/src/recording.rs
+++ b/apps/desktop-solid/src-tauri/src/recording.rs
@@ -4,19 +4,16 @@ use std::path::PathBuf;
use crate::{
camera,
- display::{ self, get_window_bounds, CaptureTarget },
+ display::{self, get_window_bounds, CaptureTarget},
ffmpeg::*,
- Bounds,
- RecordingOptions,
+ Bounds, RecordingOptions,
};
#[derive(Clone, Type, Serialize)]
#[serde(rename_all = "camelCase", tag = "variant")]
pub enum DisplaySource {
Screen,
- Window {
- bounds: Bounds,
- },
+ Window { bounds: Bounds },
}
#[derive(Type, Serialize)]
@@ -51,7 +48,7 @@ pub struct FFmpegCaptureOutput<T> {
pub async fn start(
recording_dir: PathBuf,
- recording_options: &RecordingOptions
+ recording_options: &RecordingOptions,
) -> InProgressRecording {
let content_dir = recording_dir.join("content");
@@ -70,10 +67,9 @@ pub async fn start(
display,
display_source: match recording_options.capture_target {
CaptureTarget::Screen => DisplaySource::Screen,
- CaptureTarget::Window(window_number) =>
- DisplaySource::Window {
- bounds: get_window_bounds(window_number).unwrap(),
- },
+ CaptureTarget::Window(window_number) => DisplaySource::Window {
+ bounds: get_window_bounds(window_number).unwrap(),
+ },
},
camera,
}
@@ -82,11 +78,13 @@ pub async fn start(
async fn start_camera_recording(
content_path: &PathBuf,
recording_options: &RecordingOptions,
- ffmpeg: &mut FFmpeg
+ ffmpeg: &mut FFmpeg,
) -> Option<FFmpegCaptureOutput<FFmpegRawVideoInput>> {
- let Some(camera_info) = recording_options.camera_label
+ let Some(camera_info) = recording_options
+ .camera_label
.as_ref()
- .and_then(|camera_label| camera::find_camera_by_label(camera_label)) else {
+ .and_then(|camera_label| camera::find_camera_by_label(camera_label))
+ else {
return None;
};
@@ -110,13 +108,20 @@ async fn start_camera_recording(
},
});
- ffmpeg.command
+ ffmpeg
+ .command
.args(["-f", "mp4", "-map", &format!("{}:v", ffmpeg_input.index)])
.args(["-codec:v", "libx264", "-preset", "ultrafast"])
.args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
.args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
.args(["-movflags", "frag_keyframe+empty_moov"])
- .args(["-vf", &format!("fps={},scale=in_range=full:out_range=limited", ffmpeg_input.fps)])
+ .args([
+ "-vf",
+ &format!(
+ "fps={},scale=in_range=full:out_range=limited",
+ ffmpeg_input.fps
+ ),
+ ])
.arg(&output_path);
Some(FFmpegCaptureOutput {
@@ -129,15 +134,13 @@ async fn start_camera_recording(
async fn start_display_recording(
content_path: &PathBuf,
recording_options: &RecordingOptions,
- ffmpeg: &mut FFmpeg
+ ffmpeg: &mut FFmpeg,
) -> FFmpegCaptureOutput<FFmpegRawVideoInput> {
let pipe_path = content_path.join("display.pipe");
let output_path = content_path.join("display.mp4");
- let ((width, height), capture) = display::start_capturing(
- pipe_path.clone(),
- &recording_options.capture_target
- );
+ let ((width, height), capture) =
+ display::start_capturing(pipe_path.clone(), &recording_options.capture_target);
let ffmpeg_input = ffmpeg.add_input(FFmpegRawVideoInput {
input: pipe_path.into_os_string(),
@@ -147,13 +150,20 @@ async fn start_display_recording(
pix_fmt: "bgra",
});
- ffmpeg.command
+ ffmpeg
+ .command
.args(["-f", "mp4", "-map", &format!("{}:v", ffmpeg_input.index)])
.args(["-codec:v", "libx264", "-preset", "ultrafast"])
.args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
.args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
.args(["-movflags", "frag_keyframe+empty_moov"])
- .args(["-vf", &format!("fps={},scale=in_range=full:out_range=limited", ffmpeg_input.fps)])
+ .args([
+ "-vf",
+ &format!(
+ "fps={},scale=in_range=full:out_range=limited",
+ ffmpeg_input.fps
+ ),
+ ])
.arg(&output_path);
FFmpegCaptureOutput {
diff --git a/apps/desktop-solid/src-tauri/src/utils.rs b/apps/desktop-solid/src-tauri/src/utils.rs
index faa1e33d8..dc77e34d5 100644
--- a/apps/desktop-solid/src-tauri/src/utils.rs
+++ b/apps/desktop-solid/src-tauri/src/utils.rs
@@ -1,5 +1,5 @@
-use std::path::Path;
use ffmpeg_sidecar::paths::sidecar_dir;
+use std::path::Path;
#[cfg(unix)]
pub fn create_named_pipe(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
@@ -11,11 +11,13 @@ pub fn create_named_pipe(path: &Path) -> Result<(), Box<dyn std::error::Error>>
}
pub fn ffmpeg_path_as_str() -> Result<String, String> {
- let binary_name = if cfg!(target_os = "windows") { "ffmpeg.exe" } else { "ffmpeg" };
+ let binary_name = if cfg!(target_os = "windows") {
+ "ffmpeg.exe"
+ } else {
+ "ffmpeg"
+ };
- let path = sidecar_dir()
- .map_err(|e| e.to_string())?
- .join(binary_name);
+ let path = sidecar_dir().map_err(|e| e.to_string())?.join(binary_name);
if Path::new(&path).exists() {
path.to_str()
diff --git a/apps/desktop-solid/src-tauri/src/video_renderer.rs b/apps/desktop-solid/src-tauri/src/video_renderer.rs
index 94677d041..8e1973b4b 100644
--- a/apps/desktop-solid/src-tauri/src/video_renderer.rs
+++ b/apps/desktop-solid/src-tauri/src/video_renderer.rs
@@ -1,16 +1,16 @@
-use std::path::PathBuf;
-use std::collections::HashMap;
-use serde::{ Serialize, Deserialize };
+use bytemuck::{Pod, Zeroable};
+use image::{ImageBuffer, Rgba, RgbaImage};
+use serde::{Deserialize, Serialize};
use specta::Type;
+use std::collections::HashMap;
+use std::path::PathBuf;
use wgpu::util::DeviceExt;
use wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
-use bytemuck::{ Pod, Zeroable };
-use image::{ ImageBuffer, Rgba, RgbaImage };
use crate::utils::ffmpeg_path_as_str;
-use std::process::Command;
use std::io::Read;
+use std::process::Command;
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct RenderOptions {
@@ -60,11 +60,19 @@ pub enum Background {
pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std::error::Error>> {
println!("Initializing wgpu...");
- println!("Size of CompositeParams: {} bytes", std::mem::size_of::<CompositeParams>());
+ println!(
+ "Size of CompositeParams: {} bytes",
+ std::mem::size_of::<CompositeParams>()
+ );
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());
- let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions::default()).await.unwrap();
- let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor::default(), None).await?;
+ let adapter = instance
+ .request_adapter(&wgpu::RequestAdapterOptions::default())
+ .await
+ .unwrap();
+ let (device, queue) = adapter
+ .request_device(&wgpu::DeviceDescriptor::default(), None)
+ .await?;
println!("Creating output texture...");
let texture_size = wgpu::Extent3d {
@@ -82,7 +90,7 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
label: Some("output_texture"),
view_formats: &[],
- })
+ }),
);
let output_view = output_texture.create_view(&wgpu::TextureViewDescriptor::default());
@@ -145,7 +153,7 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
count: None,
},
],
- })
+ }),
);
let pipeline_layout = device.create_pipeline_layout(
@@ -153,7 +161,7 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[&bind_group_layout],
push_constant_ranges: &[],
- })
+ }),
);
let compilation_options = wgpu::PipelineCompilationOptions {
@@ -175,13 +183,11 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
- targets: &[
- Some(wgpu::ColorTargetState {
- format: wgpu::TextureFormat::Rgba8UnormSrgb,
- blend: Some(wgpu::BlendState::REPLACE),
- write_mask: wgpu::ColorWrites::ALL,
- }),
- ],
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ blend: Some(wgpu::BlendState::REPLACE),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
compilation_options,
}),
primitive: wgpu::PrimitiveState {
@@ -201,7 +207,7 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
},
multiview: None,
cache: None,
- })
+ }),
);
println!("Creating uniform buffer...");
@@ -229,53 +235,49 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
label: Some("Uniform Buffer"),
contents: bytemuck::cast_slice(&[uniform_data]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- })
+ }),
);
println!("Setting up FFmpeg input for screen recording...");
let ffmpeg_binary_path_str = ffmpeg_path_as_str().unwrap().to_owned();
let mut screen_command = Command::new(&ffmpeg_binary_path_str);
screen_command
- .args(
- &[
- "-i",
- options.screen_recording_path.to_str().unwrap(),
- "-f",
- "rawvideo",
- "-pix_fmt",
- "rgba",
- "-s",
- &format!("{}x{}", options.output_size.0, options.output_size.1),
- "-c:v",
- "rawvideo",
- "-frames:v",
- "1",
- "pipe:1",
- ]
- )
+ .args(&[
+ "-i",
+ options.screen_recording_path.to_str().unwrap(),
+ "-f",
+ "rawvideo",
+ "-pix_fmt",
+ "rgba",
+ "-s",
+ &format!("{}x{}", options.output_size.0, options.output_size.1),
+ "-c:v",
+ "rawvideo",
+ "-frames:v",
+ "1",
+ "pipe:1",
+ ])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null());
println!("Setting up FFmpeg input for webcam recording...");
let mut webcam_command = Command::new(&ffmpeg_binary_path_str);
webcam_command
- .args(
- &[
- "-i",
- options.webcam_recording_path.to_str().unwrap(),
- "-f",
- "rawvideo",
- "-pix_fmt",
- "rgba",
- "-s",
- &format!("{}x{}", options.webcam_size.0, options.webcam_size.1),
- "-c:v",
- "rawvideo",
- "-frames:v",
- "1",
- "pipe:1",
- ]
- )
+ .args(&[
+ "-i",
+ options.webcam_recording_path.to_str().unwrap(),
+ "-f",
+ "rawvideo",
+ "-pix_fmt",
+ "rgba",
+ "-s",
+ &format!("{}x{}", options.webcam_size.0, options.webcam_size.1),
+ "-c:v",
+ "rawvideo",
+ "-frames:v",
+ "1",
+ "pipe:1",
+ ])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null());
@@ -286,15 +288,21 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
let mut screen_frame = vec![0u8; screen_frame_size];
let mut webcam_frame = vec![0u8; webcam_frame_size];
- let mut screen_output = screen_command.spawn().expect("Failed to spawn screen FFmpeg process");
- let mut webcam_output = webcam_command.spawn().expect("Failed to spawn webcam FFmpeg process");
+ let mut screen_output = screen_command
+ .spawn()
+ .expect("Failed to spawn screen FFmpeg process");
+ let mut webcam_output = webcam_command
+ .spawn()
+ .expect("Failed to spawn webcam FFmpeg process");
- screen_output.stdout
+ screen_output
+ .stdout
.as_mut()
.unwrap()
.read_exact(&mut screen_frame)
.expect("Failed to read screen frame data");
- webcam_output.stdout
+ webcam_output
+ .stdout
.as_mut()
.unwrap()
.read_exact(&mut webcam_frame)
@@ -310,8 +318,9 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
let screen_image: RgbaImage = ImageBuffer::from_raw(
options.output_size.0,
options.output_size.1,
- screen_frame.clone()
- ).expect("Failed to create screen image buffer");
+ screen_frame.clone(),
+ )
+ .expect("Failed to create screen image buffer");
screen_image.save(&screen_frame_path)?;
println!("Saved screen frame to {:?}", screen_frame_path);
@@ -322,8 +331,9 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
let webcam_image: RgbaImage = ImageBuffer::from_raw(
options.webcam_size.0,
options.webcam_size.1,
- webcam_frame.clone()
- ).expect("Failed to create webcam image buffer");
+ webcam_frame.clone(),
+ )
+ .expect("Failed to create webcam image buffer");
webcam_image.save(&webcam_frame_path)?;
println!("Saved webcam frame to {:?}", webcam_frame_path);
@@ -345,7 +355,7 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
view_formats: &[],
}),
wgpu::util::TextureDataOrder::LayerMajor,
- &screen_frame
+ &screen_frame,
);
let webcam_texture = device.create_texture_with_data(
@@ -365,7 +375,7 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
view_formats: &[],
}),
wgpu::util::TextureDataOrder::LayerMajor,
- &webcam_frame
+ &webcam_frame,
);
let screen_view = screen_texture.create_view(&wgpu::TextureViewDescriptor::default());
@@ -383,7 +393,7 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(
- &device.create_sampler(&wgpu::SamplerDescriptor::default())
+ &device.create_sampler(&wgpu::SamplerDescriptor::default()),
),
},
wgpu::BindGroupEntry {
@@ -393,7 +403,7 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler(
- &device.create_sampler(&wgpu::SamplerDescriptor::default())
+ &device.create_sampler(&wgpu::SamplerDescriptor::default()),
),
},
wgpu::BindGroupEntry {
@@ -402,34 +412,32 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
},
],
label: Some("Bind Group"),
- })
+ }),
);
println!("Starting render pass...");
let mut encoder = device.create_command_encoder(
&(wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
- })
+ }),
);
{
let mut render_pass = encoder.begin_render_pass(
&(wgpu::RenderPassDescriptor {
label: Some("Render Pass"),
- color_attachments: &[
- Some(wgpu::RenderPassColorAttachment {
- view: &output_view,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
- store: wgpu::StoreOp::Store,
- },
- }),
- ],
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &output_view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
- })
+ }),
);
render_pass.set_pipeline(&render_pipeline);
@@ -456,13 +464,13 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
label: Some("Output Buffer"),
mapped_at_creation: false,
- })
+ }),
);
let mut encoder = device.create_command_encoder(
&(wgpu::CommandEncoderDescriptor {
label: Some("Copy Encoder"),
- })
+ }),
);
encoder.copy_texture_to_buffer(
@@ -480,7 +488,7 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
rows_per_image: Some(height),
},
},
- texture_size
+ texture_size,
);
queue.submit(std::iter::once(encoder.finish()));
@@ -502,11 +510,8 @@ pub async fn render_video(options: RenderOptions) -> Result<PathBuf, Box<dyn std
for chunk in padded_data.chunks(padded_bytes_per_row as usize) {
image_data.extend_from_slice(&chunk[..unpadded_bytes_per_row as usize]);
}
- let image_buffer: ImageBuffer<Rgba<u8>, _> = ImageBuffer::from_raw(
- width,
- height,
- image_data
- ).ok_or("Failed to create image buffer")?;
+ let image_buffer: ImageBuffer<Rgba<u8>, _> =
+ ImageBuffer::from_raw(width, height, image_data).ok_or("Failed to create image buffer")?;
let output_image_path = PathBuf::from(
"/Users/richie/Library/Application Support/so.cap.desktop-solid/recordings/ac2909e0-2f5e-45ff-95e3-8efb50a56a12.cap/output/result.png"
diff --git a/apps/desktop-solid/src/global.d.ts b/apps/desktop-solid/src/global.d.ts
new file mode 100644
index 000000000..38fdd93ad
--- /dev/null
+++ b/apps/desktop-solid/src/global.d.ts
@@ -0,0 +1,1881 @@
+// https://github.com/gpac/mp4box.js/issues/233
+
+declare module "mp4box";
+
+export interface MP4MediaTrack {
+ id: number;
+ created: Date;
+ modified: Date;
+ movie_duration: number;
+ layer: number;
+ alternate_group: number;
+ volume: number;
+ track_width: number;
+ track_height: number;
+ timescale: number;
+ duration: number;
+ bitrate: number;
+ codec: string;
+ language: string;
+ nb_samples: number;
+}
+
+export interface MP4VideoData {
+ width: number;
+ height: number;
+}
+
+export interface MP4VideoTrack extends MP4MediaTrack {
+ video: MP4VideoData;
+}
+
+export interface MP4AudioData {
+ sample_rate: number;
+ channel_count: number;
+ sample_size: number;
+}
+
+export interface MP4AudioTrack extends MP4MediaTrack {
+ audio: MP4AudioData;
+}
+
+export type MP4Track = MP4VideoTrack | MP4AudioTrack;
+
+export interface MP4Info {
+ duration: number;
+ timescale: number;
+ fragment_duration: number;
+ isFragmented: boolean;
+ isProgressive: boolean;
+ hasIOD: boolean;
+ brands: string[];
+ created: Date;
+ modified: Date;
+ tracks: MP4Track[];
+ mime: string;
+ audioTracks: MP4AudioTrack[];
+ videoTracks: MP4VideoTrack[];
+}
+
+export type MP4ArrayBuffer = ArrayBuffer & { fileStart: number };
+
+export interface MP4File {
+ onMoovStart?: () => void;
+ onReady?: (info: MP4Info) => void;
+ onError?: (e: string) => void;
+ onSamples?: (id: number, user: any, samples: Sample[]) => void;
+
+ appendBuffer(data: MP4ArrayBuffer): number;
+ start(): void;
+ stop(): void;
+ flush(): void;
+
+ setExtractionOptions(id: number, user: any, options: ExtractionOptions): void;
+}
+
+export function createFile(): MP4File;
+
+export interface Sample {
+ number: number;
+ track_id: number;
+ timescale: number;
+ description_index: number;
+ description: {
+ avcC?: BoxParser.avcCBox; // h.264
+ hvcC?: BoxParser.hvcCBox; // hevc
+ vpcC?: BoxParser.vpcCBox; // vp9
+ av1C?: BoxParser.av1CBox; // av1
+ };
+ data: ArrayBuffer;
+ size: number;
+ alreadyRead?: number;
+ duration: number;
+ cts: number;
+ dts: number;
+ is_sync: boolean;
+ is_leading?: number;
+ depends_on?: number;
+ is_depended_on?: number;
+ has_redundancy?: number;
+ degradation_priority?: number;
+ offset?: number;
+ subsamples?: any;
+}
+
+export interface ExtractionOptions {
+ nbSamples: number;
+}
+
+export class DataStream {
+ // WARNING, the default is little endian, which is not what MP4 uses.
+ constructor(buffer?: ArrayBuffer, byteOffset?: number, endianness?: boolean);
+ getPosition(): number;
+
+ get byteLength(): number;
+ get buffer(): ArrayBuffer;
+ set buffer(v: ArrayBuffer);
+ get byteOffset(): number;
+ set byteOffset(v: number);
+ get dataView(): DataView;
+ set dataView(v: DataView);
+
+ seek(pos: number): void;
+ isEof(): boolean;
+
+ mapFloat32Array(length: number, e?: boolean): any;
+ mapFloat64Array(length: number, e?: boolean): any;
+ mapInt16Array(length: number, e?: boolean): any;
+ mapInt32Array(length: number, e?: boolean): any;
+ mapInt8Array(length: number): any;
+ mapUint16Array(length: number, e?: boolean): any;
+ mapUint32Array(length: number, e?: boolean): any;
+ mapUint8Array(length: number): any;
+
+ readInt32Array(length: number, endianness?: boolean): Int32Array;
+ readInt16Array(length: number, endianness?: boolean): Int16Array;
+ readInt8Array(length: number): Int8Array;
+ readUint32Array(length: number, endianness?: boolean): Uint32Array;
+ readUint16Array(length: number, endianness?: boolean): Uint16Array;
+ readUint8Array(length: number): Uint8Array;
+ readFloat64Array(length: number, endianness?: boolean): Float64Array;
+ readFloat32Array(length: number, endianness?: boolean): Float32Array;
+
+ readInt32(endianness?: boolean): number;
+ readInt16(endianness?: boolean): number;
+ readInt8(): number;
+ readUint32(endianness?: boolean): number;
+ //readUint32Array(length: any, e: any): any
+ readUint24(): number;
+ readUint16(endianness?: boolean): number;
+ readUint8(): number;
+ //readUint64(): any
+ readFloat32(endianness?: boolean): number;
+ readFloat64(endianness?: boolean): number;
+ //readCString(length: number): any
+ //readString(length: number, encoding: any): any
+
+ static endianness: boolean;
+
+ memcpy(
+ dst: ArrayBufferLike,
+ dstOffset: number,
+ src: ArrayBufferLike,
+ srcOffset: number,
+ byteLength: number
+ ): void;
+
+ // TODO I got bored porting all functions
+
+ save(filename: string): void;
+ shift(offset: number): void;
+
+ writeInt32Array(arr: Int32Array, endianness?: boolean): void;
+ writeInt16Array(arr: Int16Array, endianness?: boolean): void;
+ writeInt8Array(arr: Int8Array): void;
+ writeUint32Array(arr: Uint32Array, endianness?: boolean): void;
+ writeUint16Array(arr: Uint16Array, endianness?: boolean): void;
+ writeUint8Array(arr: Uint8Array): void;
+ writeFloat64Array(arr: Float64Array, endianness?: boolean): void;
+ writeFloat32Array(arr: Float32Array, endianness?: boolean): void;
+ writeInt32(v: number, endianness?: boolean): void;
+ writeInt16(v: number, endianness?: boolean): void;
+ writeInt8(v: number): void;
+ writeUint32(v: number, endianness?: boolean): void;
+ writeUint16(v: number, endianness?: boolean): void;
+ writeUint8(v: number): void;
+ writeFloat32(v: number, endianness?: boolean): void;
+ writeFloat64(v: number, endianness?: boolean): void;
+ writeUCS2String(s: string, endianness?: boolean, length?: number): void;
+ writeString(s: string, encoding?: string, length?: number): void;
+ writeCString(s: string, length?: number): void;
+ writeUint64(v: number): void;
+ writeUint24(v: number): void;
+ adjustUint32(pos: number, v: number): void;
+
+ static LITTLE_ENDIAN: boolean;
+ static BIG_ENDIAN: boolean;
+
+ // TODO add correct types; these are exported by dts-gen
+ readCString(length: any): any;
+ readInt64(): any;
+ readString(length: any, encoding: any): any;
+ readUint64(): any;
+ writeStruct(structDefinition: any, struct: any): void;
+ writeType(t: any, v: any, struct: any): any;
+
+ static arrayToNative(array: any, arrayIsLittleEndian: any): any;
+ static flipArrayEndianness(array: any): any;
+ static memcpy(
+ dst: any,
+ dstOffset: any,
+ src: any,
+ srcOffset: any,
+ byteLength: any
+ ): void;
+ static nativeToEndian(array: any, littleEndian: any): any;
+}
+
+export interface TrackOptions {
+ id?: number;
+ type?: string;
+ width?: number;
+ height?: number;
+ duration?: number;
+ layer?: number;
+ timescale?: number;
+ media_duration?: number;
+ language?: string;
+ hdlr?: string;
+
+ // video
+ avcDecoderConfigRecord?: any;
+ hevcDecoderConfigRecord?: any;
+
+ // audio
+ balance?: number;
+ channel_count?: number;
+ samplesize?: number;
+ samplerate?: number;
+
+ //captions
+ namespace?: string;
+ schema_location?: string;
+ auxiliary_mime_types?: string;
+
+ description?: BoxParser.Box;
+ description_boxes?: BoxParser.Box[];
+
+ default_sample_description_index_id?: number;
+ default_sample_duration?: number;
+ default_sample_size?: number;
+ default_sample_flags?: number;
+}
+
+export interface FileOptions {
+ brands?: string[];
+ timescale?: number;
+ rate?: number;
+ duration?: number;
+ width?: number;
+}
+
+export interface SampleOptions {
+ sample_description_index?: number;
+ duration?: number;
+ cts?: number;
+ dts?: number;
+ is_sync?: boolean;
+ is_leading?: number;
+ depends_on?: number;
+ is_depended_on?: number;
+ has_redundancy?: number;
+ degradation_priority?: number;
+ subsamples?: any;
+}
+
+// TODO add the remaining functions
+// TODO move to another module
+export class ISOFile {
+ constructor(stream?: DataStream);
+
+ init(options?: FileOptions): ISOFile;
+ addTrack(options?: TrackOptions): number;
+ addSample(track: number, data: ArrayBuffer, options?: SampleOptions): Sample;
+
+ createSingleSampleMoof(sample: Sample): BoxParser.moofBox;
+
+ // helpers
+ getTrackById(id: number): BoxParser.trakBox | undefined;
+ getTrexById(id: number): BoxParser.trexBox | undefined;
+
+ // boxes that are added to the root
+ boxes: BoxParser.Box[];
+ mdats: BoxParser.mdatBox[];
+ moofs: BoxParser.moofBox[];
+
+ ftyp?: BoxParser.ftypBox;
+ moov?: BoxParser.moovBox;
+
+ static writeInitializationSegment(
+ ftyp: BoxParser.ftypBox,
+ moov: BoxParser.moovBox,
+ total_duration: number,
+ sample_duration: number
+ ): ArrayBuffer;
+
+ // TODO add correct types; these are exported by dts-gen
+ add(name: any): any;
+ addBox(box: any): any;
+ appendBuffer(ab: any, last: any): any;
+ buildSampleLists(): void;
+ buildTrakSampleLists(trak: any): void;
+ checkBuffer(ab: any): any;
+ createFragment(track_id: any, sampleNumber: any, stream_: any): any;
+ equal(b: any): any;
+ flattenItemInfo(): void;
+ flush(): void;
+ getAllocatedSampleDataSize(): any;
+ getBox(type: any): any;
+ getBoxes(type: any, returnEarly: any): any;
+ getBuffer(): any;
+ getCodecs(): any;
+ getInfo(): any;
+ getItem(item_id: any): any;
+ getMetaHandler(): any;
+ getPrimaryItem(): any;
+ getSample(trak: any, sampleNum: any): any;
+ getTrackSample(track_id: any, number: any): any;
+ getTrackSamplesInfo(track_id: any): any;
+ hasIncompleteMdat(): any;
+ hasItem(name: any): any;
+ initializeSegmentation(): any;
+ itemToFragmentedTrackFile(_options: any): any;
+ parse(): void;
+ print(output: any): void;
+ processIncompleteBox(ret: any): any;
+ processIncompleteMdat(): any;
+ processItems(callback: any): void;
+ processSamples(last: any): void;
+ releaseItem(item_id: any): any;
+ releaseSample(trak: any, sampleNum: any): any;
+ releaseUsedSamples(id: any, sampleNum: any): void;
+ resetTables(): void;
+ restoreParsePosition(): any;
+ save(name: any): void;
+ saveParsePosition(): void;
+ seek(time: any, useRap: any): any;
+ seekTrack(time: any, useRap: any, trak: any): any;
+ setExtractionOptions(id: any, user: any, options: any): void;
+ setSegmentOptions(id: any, user: any, options: any): void;
+ start(): void;
+ stop(): void;
+ unsetExtractionOptions(id: any): void;
+ unsetSegmentOptions(id: any): void;
+ updateSampleLists(): void;
+ updateUsedBytes(box: any, ret: any): void;
+ write(outstream: any): void;
+
+ static initSampleGroups(
+ trak: any,
+ traf: any,
+ sbgps: any,
+ trak_sgpds: any,
+ traf_sgpds: any
+ ): void;
+ static process_sdtp(sdtp: any, sample: any, number: any): void;
+ static setSampleGroupProperties(
+ trak: any,
+ sample: any,
+ sample_number: any,
+ sample_groups_info: any
+ ): void;
+}
+
+export namespace BoxParser {
+ export class Box {
+ size?: number;
+ data?: Uint8Array;
+
+ constructor(type?: string, size?: number);
+
+ add(name: string): Box;
+ addBox(box: Box): Box;
+ set(name: string, value: any): void;
+ addEntry(value: string, prop?: string): void;
+ printHeader(output: any): void;
+ write(stream: DataStream): void;
+ writeHeader(stream: DataStream, msg?: string): void;
+ computeSize(): void;
+
+ // TODO add types for these
+ parse(stream: any): void;
+ parseDataAndRewind(stream: any): void;
+ parseLanguage(stream: any): void;
+ print(output: any): void;
+ }
+
+ // TODO finish add types for these classes
+ export class AudioSampleEntry extends SampleEntry {
+ constructor(type: any, size: any);
+
+ getChannelCount(): any;
+ getSampleRate(): any;
+ getSampleSize(): any;
+ isAudio(): any;
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class CoLLBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class ContainerBox extends Box {
+ constructor(type: any, size: any, uuid: any);
+
+ parse(stream: any): void;
+ print(output: any): void;
+ write(stream: any): void;
+ }
+
+ export class FullBox extends Box {
+ constructor(type: any, size: any, uuid: any);
+
+ parse(stream: any): void;
+ parseDataAndRewind(stream: any): void;
+ parseFullHeader(stream: any): void;
+ printHeader(output: any): void;
+ writeHeader(stream: any): void;
+ }
+
+ export class HintSampleEntry extends SampleEntry {
+ constructor(type: any, size: any);
+ }
+
+ export class MetadataSampleEntry extends SampleEntry {
+ constructor(type: any, size: any);
+
+ isMetadata(): any;
+ }
+
+ export class OpusSampleEntry extends SampleEntry {
+ constructor(size: any);
+ }
+
+ export class SampleEntry extends Box {
+ constructor(type: any, size: any, hdr_size: any, start: any);
+
+ getChannelCount(): any;
+ getCodec(): any;
+ getHeight(): any;
+ getSampleRate(): any;
+ getSampleSize(): any;
+ getWidth(): any;
+ isAudio(): any;
+ isHint(): any;
+ isMetadata(): any;
+ isSubtitle(): any;
+ isVideo(): any;
+ parse(stream: any): void;
+ parseDataAndRewind(stream: any): void;
+ parseFooter(stream: any): void;
+ parseHeader(stream: any): void;
+ write(stream: any): void;
+ writeFooter(stream: any): void;
+ writeHeader(stream: any): void;
+ }
+
+ export class SampleGroupEntry {
+ constructor(type: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class SingleItemTypeReferenceBox extends ContainerBox {
+ constructor(type: any, size: any, hdr_size: any, start: any);
+
+ parse(stream: any): void;
+ }
+
+ export class SingleItemTypeReferenceBoxLarge {
+ constructor(type: any, size: any, hdr_size: any, start: any);
+
+ parse(stream: any): void;
+ }
+
+ export class SmDmBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class SubtitleSampleEntry extends SampleEntry {
+ constructor(type: any, size: any);
+
+ isSubtitle(): any;
+ }
+
+ export class SystemSampleEntry extends SampleEntry {
+ constructor(type: any, size: any);
+ }
+
+ export class TextSampleEntry extends SampleEntry {
+ constructor(type: any, size: any);
+ }
+
+ export class TrackGroupTypeBox extends FullBox {
+ constructor(type: any, size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class TrackReferenceTypeBox extends ContainerBox {
+ constructor(type: any, size: any, hdr_size: any, start: any);
+
+ parse(stream: any): void;
+
+ write(stream: any): void;
+ }
+
+ export class VisualSampleEntry extends SampleEntry {
+ constructor(type: any, size: any);
+
+ getHeight(): any;
+ getWidth(): any;
+ isVideo(): any;
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class a1lxBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class a1opBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class alstSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class auxCBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class av01SampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class av1CBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class avc1SampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class avc2SampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class avc3SampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class avc4SampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class avcCBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class avllSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class avssSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class btrtBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class bxmlBox extends FullBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class clapBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class clefBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class clliBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class co64Box extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class colrBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class cprtBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class cslgBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class cttsBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ unpack(samples: any): void;
+ write(stream: any): void;
+ }
+
+ export class dOpsBox extends ContainerBox {
+ constructor(size?: number);
+
+ parse(stream: DataStream): void;
+
+ Version: number;
+ OutputChannelCount: number;
+ PreSkip: number;
+ InputSampleRate: number;
+ OutputGain: number;
+ ChannelMappingFamily: number;
+
+ // When channelMappingFamily != 0
+ StreamCount?: number;
+ CoupledCount?: number;
+ ChannelMapping?: number[];
+ }
+
+ export class dac3Box extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class dec3Box extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class dfLaBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class dimmBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class dinfBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class dmaxBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class dmedBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class drefBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class drepBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class dtrtSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class edtsBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class elngBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class elstBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class emsgBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class encaSampleEntry extends SampleEntry {
+ constructor(size: any);
+ }
+
+ export class encmSampleEntry extends SampleEntry {
+ constructor(size: any);
+ }
+
+ export class encsSampleEntry extends SampleEntry {
+ constructor(size: any);
+ }
+
+ export class enctSampleEntry extends SampleEntry {
+ constructor(size: any);
+ }
+
+ export class encuSampleEntry extends SampleEntry {
+ constructor(size: any);
+ }
+
+ export class encvSampleEntry extends SampleEntry {
+ constructor(size: any);
+ }
+
+ export class enofBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class esdsBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class fielBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class freeBox extends Box {
+ constructor(size: any);
+ }
+
+ export class frmaBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class ftypBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class hdlrBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class hev1SampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class hinfBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class hmhdBox extends FullBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class hntiBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class hvc1SampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class hvcCBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class idatBox extends Box {
+ constructor(size: any);
+ }
+
+ export class iinfBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class ilocBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class imirBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class infeBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class iodsBox extends FullBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class ipcoBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class ipmaBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class iproBox extends FullBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class iprpBox extends ContainerBox {
+ constructor(size: any);
+ ipmas: ipmaBox[];
+ }
+
+ export class irefBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class irotBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class ispeBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class kindBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+
+ write(stream: any): void;
+ }
+
+ export class levaBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class lselBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class maxrBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class mdatBox extends Box {
+ constructor(size: any);
+ }
+
+ export class mdcvBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class mdhdBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+
+ write(stream: any): void;
+ }
+
+ export class mdiaBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class mecoBox extends Box {
+ constructor(size: any);
+ }
+
+ export class mehdBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+
+ write(stream: any): void;
+ }
+
+ export class mereBox extends FullBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class metaBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class mettSampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class metxSampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class mfhdBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+
+ write(stream: any): void;
+ }
+
+ export class mfraBox extends ContainerBox {
+ constructor(size: any);
+ tfras: tfraBox[];
+ }
+
+ export class mfroBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class minfBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class moofBox extends ContainerBox {
+ constructor(size: any);
+ trafs: trafBox[];
+ }
+
+ export class moovBox extends ContainerBox {
+ constructor(size: any);
+ traks: trakBox[];
+ psshs: psshBox[];
+ }
+
+ export class mp4aSampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class msrcTrackGroupTypeBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class mvexBox extends ContainerBox {
+ constructor(size: any);
+
+ trexs: trexBox[];
+ }
+
+ export class mvhdBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ print(output: any): void;
+ write(stream: any): void;
+ }
+
+ export class mvifSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class nmhdBox extends FullBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class npckBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class numpBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class padbBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class paspBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class paylBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class paytBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class pdinBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class pitmBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class pixiBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class pmaxBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class prftBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class profBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class prolSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class psshBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class rashSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class rinfBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class rollSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class saioBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class saizBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class sbgpBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+
+ write(stream: any): void;
+ }
+
+ export class sbttSampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class schiBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class schmBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class scifSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class scnmSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class sdtpBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class seigSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class sencBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class sgpdBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class sidxBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class sinfBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class skipBox extends Box {
+ constructor(size: any);
+ }
+
+ export class smhdBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class ssixBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class stblBox extends ContainerBox {
+ constructor(size: any);
+
+ sgpds: sgpdBox[];
+ sbgps: sbgpBox[];
+ }
+
+ export class stcoBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ unpack(samples: any): void;
+ write(stream: any): void;
+ }
+
+ export class stdpBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class sthdBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class stppSampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class strdBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class striBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class strkBox extends Box {
+ constructor(size: any);
+ }
+
+ export class stsaSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class stscBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ unpack(samples: any): void;
+ write(stream: any): void;
+ }
+
+ export class stsdBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class stsgBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class stshBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class stssBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class stszBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ unpack(samples: any): void;
+ write(stream: any): void;
+ }
+
+ export class sttsBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ unpack(samples: any): void;
+ write(stream: any): void;
+ }
+
+ export class stviBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class stxtSampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ parse(stream: any): void;
+ }
+
+ export class stypBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class stz2Box extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class subsBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class syncSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class taptBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class teleSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class tencBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class tfdtBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class tfhdBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class tfraBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class tkhdBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ print(output: any): void;
+ write(stream: any): void;
+ }
+
+ export class tmaxBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class tminBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class totlBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class tpayBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class tpylBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class trafBox extends ContainerBox {
+ constructor(size: any);
+ truns: trunBox[];
+ sgpd: sgpdBox[];
+ sbgp: sbgpBox[];
+ }
+
+ export class trakBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class trefBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class trepBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class trexBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class trgrBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class trpyBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class trunBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class tsasSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class tsclSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class tselBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class tx3gSampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class txtCBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class udtaBox extends ContainerBox {
+ constructor(size: any);
+ kinds: kindBox[];
+ }
+
+ export class viprSampleGroupEntry extends SampleGroupEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class vmhdBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ write(stream: any): void;
+ }
+
+ export class vp08SampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class vp09SampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class vpcCBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class vttCBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class vttcBox extends ContainerBox {
+ constructor(size: any);
+ }
+
+ export class vvc1SampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class vvcCBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class vvcNSampleEntry extends SampleEntry {
+ constructor(size: any);
+ }
+
+ export class vvi1SampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ getCodec(): any;
+ }
+
+ export class vvnCBox extends ContainerBox {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export class vvs1SampleEntry extends SampleEntry {
+ constructor(size: any);
+ }
+
+ export class wvttSampleEntry extends SampleEntry {
+ constructor(size: any);
+
+ parse(stream: any): void;
+ }
+
+ export const BASIC_BOXES: string[];
+ export const CONTAINER_BOXES: string[][];
+ export const DIFF_BOXES_PROP_NAMES: string[];
+ export const DIFF_PRIMITIVE_ARRAY_PROP_NAMES: string[];
+ export const ERR_INVALID_DATA: number;
+ export const ERR_NOT_ENOUGH_DATA: number;
+ export const FULL_BOXES: string[];
+ export const OK: number;
+ export const SAMPLE_ENTRY_TYPE_AUDIO: string;
+ export const SAMPLE_ENTRY_TYPE_HINT: string;
+ export const SAMPLE_ENTRY_TYPE_METADATA: string;
+ export const SAMPLE_ENTRY_TYPE_SUBTITLE: string;
+ export const SAMPLE_ENTRY_TYPE_SYSTEM: string;
+ export const SAMPLE_ENTRY_TYPE_TEXT: string;
+ export const SAMPLE_ENTRY_TYPE_VISUAL: string;
+ export const TFHD_FLAG_BASE_DATA_OFFSET: number;
+ export const TFHD_FLAG_DEFAULT_BASE_IS_MOOF: number;
+ export const TFHD_FLAG_DUR_EMPTY: number;
+ export const TFHD_FLAG_SAMPLE_DESC: number;
+ export const TFHD_FLAG_SAMPLE_DUR: number;
+ export const TFHD_FLAG_SAMPLE_FLAGS: number;
+ export const TFHD_FLAG_SAMPLE_SIZE: number;
+ export const TKHD_FLAG_ENABLED: number;
+ export const TKHD_FLAG_IN_MOVIE: number;
+ export const TKHD_FLAG_IN_PREVIEW: number;
+ export const TRUN_FLAGS_CTS_OFFSET: number;
+ export const TRUN_FLAGS_DATA_OFFSET: number;
+ export const TRUN_FLAGS_DURATION: number;
+ export const TRUN_FLAGS_FIRST_FLAG: number;
+ export const TRUN_FLAGS_FLAGS: number;
+ export const TRUN_FLAGS_SIZE: number;
+ export const UUIDs: string[];
+ export const boxCodes: string[];
+ export const containerBoxCodes: any[];
+ export const fullBoxCodes: any[];
+
+ export const sampleEntryCodes: {
+ Audio: string[];
+ Hint: any[];
+ Metadata: string[];
+ Subtitle: string[];
+ System: string[];
+ Text: string[];
+ Visual: string[];
+ };
+
+ export const sampleGroupEntryCodes: any[];
+
+ export const trackGroupTypes: any[];
+
+ export function addSubBoxArrays(subBoxNames: any): void;
+ export function boxEqual(box_a: any, box_b: any): any;
+ export function boxEqualFields(box_a: any, box_b: any): any;
+ export function createBoxCtor(type: any, parseMethod: any): void;
+ export function createContainerBoxCtor(
+ type: any,
+ parseMethod: any,
+ subBoxNames: any
+ ): void;
+ export function createEncryptedSampleEntryCtor(
+ mediaType: any,
+ type: any,
+ parseMethod: any
+ ): void;
+ export function createFullBoxCtor(type: any, parseMethod: any): void;
+ export function createMediaSampleEntryCtor(
+ mediaType: any,
+ parseMethod: any,
+ subBoxNames: any
+ ): void;
+ export function createSampleEntryCtor(
+ mediaType: any,
+ type: any,
+ parseMethod: any,
+ subBoxNames: any
+ ): void;
+ export function createSampleGroupCtor(type: any, parseMethod: any): void;
+ export function createTrackGroupCtor(type: any, parseMethod: any): void;
+ export function createUUIDBox(
+ uuid: any,
+ isFullBox: any,
+ isContainerBox: any,
+ parseMethod: any
+ ): void;
+ export function decimalToHex(d: any, padding: any): any;
+ export function initialize(): void;
+ export function parseHex16(stream: any): any;
+ export function parseOneBox(
+ stream: any,
+ headerOnly: any,
+ parentSize: any
+ ): any;
+ export function parseUUID(stream: any): any;
+
+ /* ???
+ namespace UUIDBoxes {
+ export class a2394f525a9b4f14a2446c427c648df4 {
+ constructor(size: any)
+ }
+
+ export class a5d40b30e81411ddba2f0800200c9a66 {
+ constructor(size: any)
+
+ parse(stream: any): void
+ }
+
+ export class d08a4f1810f34a82b6c832d8aba183d3 {
+ constructor(size: any)
+
+ parse(stream: any): void
+ }
+
+ export class d4807ef2ca3946958e5426cb9e46a79f {
+ constructor(size: any)
+
+ parse(stream: any): void
+ }
+ }
+ */
+}
+
+// TODO Add types for the remaining classes found via dts-gen
+export class MP4BoxStream {
+ constructor(arrayBuffer: any);
+
+ getEndPosition(): any;
+ getLength(): any;
+ getPosition(): any;
+ isEos(): any;
+ readAnyInt(size: any, signed: any): any;
+ readCString(): any;
+ readInt16(): any;
+ readInt16Array(length: any): any;
+ readInt32(): any;
+ readInt32Array(length: any): any;
+ readInt64(): any;
+ readInt8(): any;
+ readString(length: any): any;
+ readUint16(): any;
+ readUint16Array(length: any): any;
+ readUint24(): any;
+ readUint32(): any;
+ readUint32Array(length: any): any;
+ readUint64(): any;
+ readUint8(): any;
+ readUint8Array(length: any): any;
+ seek(pos: any): any;
+}
+
+export class MultiBufferStream {
+ constructor(buffer: any);
+
+ addUsedBytes(nbBytes: any): void;
+ cleanBuffers(): void;
+ findEndContiguousBuf(inputindex: any): any;
+ findPosition(fromStart: any, filePosition: any, markAsUsed: any): any;
+ getEndFilePositionAfter(pos: any): any;
+ getEndPosition(): any;
+ getLength(): any;
+ getPosition(): any;
+ initialized(): any;
+ insertBuffer(ab: any): void;
+ logBufferLevel(info: any): void;
+ mergeNextBuffer(): any;
+ reduceBuffer(buffer: any, offset: any, newLength: any): any;
+ seek(filePosition: any, fromStart: any, markAsUsed: any): any;
+ setAllUsedBytes(): void;
+}
+
+export class Textin4Parser {
+ constructor();
+
+ parseConfig(data: any): any;
+ parseSample(sample: any): any;
+}
+
+export class XMLSubtitlein4Parser {
+ constructor();
+
+ parseSample(sample: any): any;
+}
+
+export function MPEG4DescriptorParser(): any;
+
+export namespace BoxParser {}
+
+export namespace Log {
+ export const LOG_LEVEL_ERROR = 4;
+ export const LOG_LEVEL_WARNING = 3;
+ export const LOG_LEVEL_INFO = 2;
+ export const LOG_LEVEL_DEBUG = 1;
+
+ export function debug(module: any, msg: any): void;
+ export function error(module: any, msg: any): void;
+ export function getDurationString(duration: any, _timescale: any): any;
+ export function info(module: any, msg: any): void;
+ export function log(module: any, msg: any): void;
+ export function printRanges(ranges: any): any;
+ export function setLogLevel(level: any): void;
+ export function warn(module: any, msg: any): void;
+}
diff --git a/apps/desktop-solid/src/routes/index.tsx b/apps/desktop-solid/src/routes/index.tsx
index 181cb190b..d2cdead48 100644
--- a/apps/desktop-solid/src/routes/index.tsx
+++ b/apps/desktop-solid/src/routes/index.tsx
@@ -4,6 +4,34 @@ import { For, Show, Suspense, createSignal } from "solid-js";
import { createCameraForLabel, createCameras } from "../utils/media";
import { createOptionsQuery, createWindowsQuery } from "../utils/queries";
import { commands } from "../utils/tauri";
+import { renderVideo } from "../utils/render";
+
+const screenInputFilePath =
+ "/Users/richie/Library/Application Support/so.cap.desktop-solid/recordings/ac2909e0-2f5e-45ff-95e3-8efb50a56a12.cap/content/display.mp4";
+const webcamInputFilePath =
+ "/Users/richie/Library/Application Support/so.cap.desktop-solid/recordings/ac2909e0-2f5e-45ff-95e3-8efb50a56a12.cap/content/camera.mp4";
+
+const settings = {
+ webcamSize: { width: 320, height: 240 },
+ webcamPosition: { x: 10, y: 10 },
+ webcamStyle: { borderRadius: 50, shadow: "rgba(0, 0, 0, 0.5)" },
+ videoOutputSize: { width: 1280, height: 720 },
+ videoBackground: "#000000",
+ videoPadding: 20,
+};
+
+async function testRender() {
+ try {
+ const outputFilePath = await renderVideo(
+ screenInputFilePath,
+ webcamInputFilePath,
+ settings
+ );
+ console.log(`Video rendered successfully: ${outputFilePath}`);
+ } catch (error) {
+ console.error("Error rendering video:", error);
+ }
+}
export default function () {
const cameras = createCameras();
@@ -179,6 +207,11 @@ export default function () {
)}
</div>
}
+ <div>
+ <button type="button" onClick={() => testRender()}>
+ Test Render
+ </button>
+ </div>
</div>
</>
)}
diff --git a/apps/desktop-solid/src/utils/render.ts b/apps/desktop-solid/src/utils/render.ts
index 43385fa85..65a1ad3bf 100644
--- a/apps/desktop-solid/src/utils/render.ts
+++ b/apps/desktop-solid/src/utils/render.ts
@@ -1,154 +1,301 @@
-import { convertFileSrc } from "@tauri-apps/api/core";
+import { writeFile, readFile } from "@tauri-apps/plugin-fs";
+import MP4Box from "mp4box";
-interface RenderOptions {
- screenRecordingPath: string;
- webcamRecordingPath: string;
+const outputFilePath =
+ "/Users/richie/Library/Application Support/so.cap.desktop-solid/recordings/ac2909e0-2f5e-45ff-95e3-8efb50a56a12.cap/output/result.mp4";
+
+interface VideoSettings {
webcamSize: { width: number; height: number };
webcamPosition: { x: number; y: number };
- webcamStyle: {
- borderRadius: number;
- shadowColor: string;
- shadowBlur: number;
- shadowOffsetX: number;
- shadowOffsetY: number;
- };
- outputSize: { width: number; height: number };
- background: {
- type: "color" | "gradient";
- value: string | { start: string; end: string; angle: number };
- };
- padding: number;
+ webcamStyle: { borderRadius: number; shadow: string };
+ videoOutputSize: { width: number; height: number };
+ videoBackground: string;
+ videoPadding: number;
}
-export async function renderVideo(options: RenderOptions): Promise<string> {
- const canvas = new OffscreenCanvas(
- options.outputSize.width,
- options.outputSize.height
- );
- const ctx = canvas.getContext("2d")!;
+async function loadVideo(filePath: string): Promise<VideoFrame[]> {
+ console.log(`Loading video from ${filePath}`);
+ const response = await readFile(filePath);
+ const arrayBuffer = response.buffer;
+ const frames: VideoFrame[] = [];
- const screenVideo = document.createElement("video");
- screenVideo.src = convertFileSrc(options.screenRecordingPath);
- await screenVideo.play();
+ return new Promise<VideoFrame[]>((resolve, reject) => {
+ const mp4boxFile = MP4Box.createFile();
- const webcamVideo = document.createElement("video");
- webcamVideo.src = convertFileSrc(options.webcamRecordingPath);
- await webcamVideo.play();
+ mp4boxFile.onReady = async (info: any) => {
+ console.log("MP4Box file ready:", info);
+ const videoTrack = info.tracks.find(
+ (track: any) => track.type === "video"
+ );
- const duration = Math.max(screenVideo.duration, webcamVideo.duration);
- const fps = 30;
- const totalFrames = Math.ceil(duration * fps);
+ if (!videoTrack) {
+ reject(new Error("No video track found"));
+ return;
+ }
- const encoder = new VideoEncoder({
- output: (chunk, metadata) => {
- // Handle encoded video chunks
- },
- error: (error) => {
- console.error("Encoding error:", error);
- },
- });
+ console.log("Video track found:", videoTrack);
+
+ const codecs = [
+ "avc1.42001E",
+ "avc1.42E01E",
+ "avc1.4D401E",
+ "vp8",
+ "vp09.00.10.08",
+ "av01.0.04M.08",
+ ];
+ const accelerations = [
+ "prefer-hardware",
+ "prefer-software",
+ "no-preference",
+ ];
+
+ let supportedConfig = null;
+ let videoDecoder: VideoDecoder | null = null;
+
+ for (const codec of codecs) {
+ for (const acceleration of accelerations) {
+ const config = {
+ codec,
+ hardwareAcceleration: acceleration as HardwareAcceleration,
+ codedWidth: videoTrack.video.width,
+ codedHeight: videoTrack.video.height,
+ };
+
+ try {
+ const support = await VideoDecoder.isConfigSupported(config);
+ console.log(
+ `VideoDecoder config ${JSON.stringify(config)} support: ${
+ support.supported
+ }`
+ );
+
+ if (support.supported) {
+ supportedConfig = config;
+ videoDecoder = new VideoDecoder({
+ output: (frame: VideoFrame) => {
+ console.log("Decoded frame:", frame);
+ frames.push(frame);
+ },
+ error: (e: DOMException) => {},
+ });
+
+ try {
+ videoDecoder.configure(supportedConfig);
+ console.log(
+ "Successfully configured decoder with:",
+ supportedConfig
+ );
+ break;
+ } catch (configError) {
+ console.error("Error configuring decoder:", configError);
+ videoDecoder = null;
+ }
+ }
+ } catch (error) {
+ console.error(`Error checking config support: ${error}`);
+ }
+ }
+
+ if (videoDecoder) break;
+ }
+
+ if (!supportedConfig || !videoDecoder) {
+ reject(new Error("No supported codec configuration found"));
+ return;
+ }
+
+ try {
+ mp4boxFile.setExtractionOptions(videoTrack.id, null, {
+ nbSamples: Infinity,
+ });
+ mp4boxFile.start();
+
+ mp4boxFile.onSamples = async (
+ track_id: number,
+ user: any,
+ samples: any[]
+ ) => {
+ console.log(
+ `Received ${samples.length} samples for track ${track_id}`
+ );
+ let decodedSampleCount = 0;
+ for (const sample of samples) {
+ const retryDecode = (attempts: number = 0) => {
+ if (attempts >= 3 || !videoDecoder) {
+ console.error(
+ `Failed to decode sample ${
+ decodedSampleCount + 1
+ } after ${attempts} attempts`
+ );
+ return;
+ }
+
+ try {
+ videoDecoder.decode(
+ new EncodedVideoChunk({
+ type: sample.is_sync ? "key" : "delta",
+ timestamp: sample.cts,
+ duration: sample.duration,
+ data: new Uint8Array(sample.data),
+ })
+ );
+ decodedSampleCount++;
+ } catch (decodeError) {
+ console.error(
+ `Error decoding sample ${decodedSampleCount + 1} (attempt ${
+ attempts + 1
+ }):`,
+ decodeError
+ );
+ retryDecode(attempts + 1);
+ }
+ };
+
+ retryDecode();
+
+ if (decodedSampleCount === samples.length) {
+ console.log("Flushing decoder");
+ mp4boxFile.flush();
+ await videoDecoder.flush();
+ console.log("Video decoding complete");
+ if (frames.length > 0) {
+ console.log("Resolving frames");
+ resolve(frames);
+ } else {
+ reject(new Error("No frames were decoded"));
+ }
+ }
+ }
+ console.log(`Total samples decoded: ${decodedSampleCount}`);
+ };
+
+ const mp4ArrayBuffer = arrayBuffer as ArrayBuffer & {
+ fileStart: number;
+ };
+ mp4ArrayBuffer.fileStart = 0;
+ mp4boxFile.appendBuffer(mp4ArrayBuffer);
+ } catch (error) {
+ console.error("Error setting up video decoding:", error);
+ reject(error);
+ }
+ };
- await encoder.configure({
- codec: "vp9",
- width: options.outputSize.width,
- height: options.outputSize.height,
- bitrate: 5_000_000, // 5 Mbps
- framerate: fps,
+ mp4boxFile.onError = (e: Error) => {
+ console.error("MP4Box error:", e);
+ reject(e);
+ };
+
+ const mp4ArrayBuffer = arrayBuffer as ArrayBuffer & { fileStart: number };
+ mp4ArrayBuffer.fileStart = 0;
+ mp4boxFile.appendBuffer(mp4ArrayBuffer);
});
+}
- for (let frame = 0; frame < totalFrames; frame++) {
- const time = frame / fps;
+function applyTransformations(
+ screenFrames: VideoFrame[],
+ webcamFrames: VideoFrame[],
+ settings: VideoSettings
+): VideoFrame[] {
+ console.log("Applying transformations with settings:", settings);
+ return screenFrames.map((screenFrame, index) => {
+ const webcamFrame = webcamFrames[index % webcamFrames.length];
+ console.log(`Transforming frame ${index}`);
- // Clear canvas
- ctx.clearRect(0, 0, canvas.width, canvas.height);
+ // Create a canvas to draw the frame
+ const canvas = document.createElement("canvas");
+ const ctx = canvas.getContext("2d");
+ canvas.width = settings.videoOutputSize.width;
+ canvas.height = settings.videoOutputSize.height;
- // Draw background
- if (options.background.type === "color") {
- ctx.fillStyle = options.background.value as string;
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- } else {
- const gradient = ctx.createLinearGradient(
- 0,
- 0,
- canvas.width,
- canvas.height
- );
- const { start, end, angle } = options.background.value as {
- start: string;
- end: string;
- angle: number;
- };
- gradient.addColorStop(0, start);
- gradient.addColorStop(1, end);
- ctx.fillStyle = gradient;
- ctx.fillRect(0, 0, canvas.width, canvas.height);
+ if (!ctx) {
+ throw new Error("Failed to get 2D context");
}
- // Draw screen recording
- const screenX = options.padding;
- const screenY = options.padding;
- const screenWidth = canvas.width - options.padding * 2;
- const screenHeight = canvas.height - options.padding * 2;
- ctx.drawImage(screenVideo, screenX, screenY, screenWidth, screenHeight);
+ // Draw background
+ ctx.fillStyle = settings.videoBackground;
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+
+ // Draw screen recording frame
+ ctx.drawImage(screenFrame, settings.videoPadding, settings.videoPadding);
- // Draw webcam
+ // Draw webcam frame with transformations
ctx.save();
+ ctx.shadowColor = settings.webcamStyle.shadow;
+ ctx.shadowBlur = 10;
ctx.beginPath();
- ctx.roundRect(
- options.webcamPosition.x,
- options.webcamPosition.y,
- options.webcamSize.width,
- options.webcamSize.height,
- options.webcamStyle.borderRadius
+ ctx.arc(
+ settings.webcamPosition.x + settings.webcamSize.width / 2,
+ settings.webcamPosition.y + settings.webcamSize.height / 2,
+ settings.webcamSize.width / 2,
+ 0,
+ Math.PI * 2
);
ctx.clip();
ctx.drawImage(
- webcamVideo,
- options.webcamPosition.x,
- options.webcamPosition.y,
- options.webcamSize.width,
- options.webcamSize.height
+ webcamFrame,
+ settings.webcamPosition.x,
+ settings.webcamPosition.y,
+ settings.webcamSize.width,
+ settings.webcamSize.height
);
ctx.restore();
- // Apply webcam shadow
- ctx.shadowColor = options.webcamStyle.shadowColor;
- ctx.shadowBlur = options.webcamStyle.shadowBlur;
- ctx.shadowOffsetX = options.webcamStyle.shadowOffsetX;
- ctx.shadowOffsetY = options.webcamStyle.shadowOffsetY;
- ctx.strokeStyle = "rgba(0,0,0,0)";
- ctx.strokeRect(
- options.webcamPosition.x,
- options.webcamPosition.y,
- options.webcamSize.width,
- options.webcamSize.height
- );
- ctx.shadowColor = "transparent";
-
- // Encode frame
- const videoFrame = new VideoFrame(canvas, { timestamp: time * 1000000 });
- encoder.encode(videoFrame);
- videoFrame.close();
-
- // Seek videos to next frame
- screenVideo.currentTime = time;
- webcamVideo.currentTime = time;
-
- // Wait for videos to seek
- await Promise.all([
- new Promise((resolve) =>
- screenVideo.addEventListener("seeked", resolve, { once: true })
- ),
- new Promise((resolve) =>
- webcamVideo.addEventListener("seeked", resolve, { once: true })
- ),
- ]);
+ // Convert canvas to VideoFrame
+ const transformedFrame = new VideoFrame(canvas);
+ console.log("Transformed frame:", transformedFrame);
+ return transformedFrame;
+ });
+}
+
+async function encodeVideo(frames: VideoFrame[]): Promise<string> {
+ console.log("Encoding video with frames:", frames);
+ const chunks: Uint8Array[] = [];
+ const videoEncoder = new VideoEncoder({
+ output: (chunk: EncodedVideoChunk) => {
+ console.log("Encoded chunk:", chunk);
+ const data = new Uint8Array(chunk.byteLength);
+ chunk.copyTo(data);
+ chunks.push(data);
+ },
+ error: (e: Error) => console.error("VideoEncoder error:", e),
+ });
+
+ for (const frame of frames) {
+ console.log("Encoding frame:", frame);
+ videoEncoder.encode(frame);
}
- await encoder.flush();
- encoder.close();
+ await videoEncoder.flush();
+ console.log("Video encoding complete");
+
+ // Save chunks to file
+ const blob = new Blob(chunks, { type: "video/mp4" });
+
+ // Convert Blob to Buffer
+ const arrayBuffer = await blob.arrayBuffer();
- // TODO: Implement muxing of encoded video chunks into an MP4 file
- // For now, we'll return a placeholder path
- return "/path/to/rendered/video.mp4";
+ await writeFile(outputFilePath, new Uint8Array(arrayBuffer));
+ console.log(`Video saved to ${outputFilePath}`);
+
+ return outputFilePath;
+}
+
+export async function renderVideo(
+ screenRecordingPath: string,
+ webcamRecordingPath: string,
+ settings: VideoSettings
+): Promise<string> {
+ console.log("Rendering video with settings:", settings);
+ const screenFrames = await loadVideo(screenRecordingPath);
+ console.log("Loaded screen frames:", screenFrames);
+ const webcamFrames = await loadVideo(webcamRecordingPath);
+ console.log("Loaded webcam frames:", webcamFrames);
+
+ const transformedFrames = applyTransformations(
+ screenFrames,
+ webcamFrames,
+ settings
+ );
+ console.log("Transformed frames:", transformedFrames);
+ return await encodeVideo(transformedFrames);
}
diff --git a/apps/desktop-solid/src/utils/tauri.ts b/apps/desktop-solid/src/utils/tauri.ts
index b9aa13c95..9963e0ac2 100644
--- a/apps/desktop-solid/src/utils/tauri.ts
+++ b/apps/desktop-solid/src/utils/tauri.ts
@@ -84,9 +84,9 @@ async getCurrentRecording() : Promise<Result<JsonValue<InProgressRecording | nul
else return { status: "error", error: e as any };
}
},
-async renderVideo(screenRecordingPath: string, webcamRecordingPath: string, webcamSize: [number, number], webcamPosition: [number, number], webcamStyle: WebcamStyle, outputSize: [number, number], background: Background, padding: number) : Promise<Result<string, string>> {
+async renderVideo(screenRecordingPath: string, webcamRecordingPath: string, webcamSize: [number, number], webcamPosition: [number, number], webcamStyle: WebcamStyle, outputSize: [number, number], background: Background) : Promise<Result<string, string>> {
try {
- return { status: "ok", data: await TAURI_INVOKE("render_video", { screenRecordingPath, webcamRecordingPath, webcamSize, webcamPosition, webcamStyle, outputSize, background, padding }) };
+ return { status: "ok", data: await TAURI_INVOKE("render_video", { screenRecordingPath, webcamRecordingPath, webcamSize, webcamPosition, webcamStyle, outputSize, background }) };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index dd1290800..870ee7122 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -150,12 +150,18 @@ importers:
'@tauri-apps/api':
specifier: '>=2.0.0-rc.0'
version: 2.0.0-rc.0
+ '@tauri-apps/plugin-fs':
+ specifier: 2.0.0-rc.0
+ version: 2.0.0-rc.0
'@tauri-apps/plugin-shell':
specifier: '>=2.0.0-rc.0'
version: 2.0.0-rc.0
cva:
specifier: npm:class-variance-authority@^0.7.0
+ mp4box:
+ specifier: ^0.5.2
+ version: 0.5.2
solid-js:
specifier: ^1.7.8
version: 1.8.21
@@ -171,6 +177,9 @@ importers:
vinxi:
specifier: ^0.4.1
version: 0.4.1(@types/[email protected])
+ webcodecs:
+ specifier: ^0.1.0
+ version: 0.1.0
devDependencies:
'@iconify/json':
specifier: ^2.2.237
@@ -178,6 +187,9 @@ importers:
'@tauri-apps/cli':
specifier: '>=2.0.0-rc.0'
version: 2.0.0-rc.0
+ '@types/dom-webcodecs':
+ specifier: ^0.1.11
+ version: 0.1.11
autoprefixer:
specifier: ^10.4.20
version: 10.4.20([email protected])
@@ -9391,11 +9403,11 @@ packages:
util-deprecate: 1.0.2
dev: true
- resolution: {integrity: sha512-r8O+6hRBNCql6f5NykbDUr5U/clNeDRJoBF+FpWkpQT9dXFoYor54u6JMEJmseHPdmiJemhiIZ0xo54ktWUJLg==}
+ resolution: {integrity: sha512-7PTe8neeo/itoFGZXer79KH87KFGbp3Ru16Tb9SscSfP2RkVk72Joth8aYY6lL0ah+AS7RmTiN7HvzGf2D2/Eg==}
peerDependencies:
'@preact/preset-vite': '*'
- storybook: ^8.3.0-alpha.6
+ storybook: ^8.3.0-alpha.7
typescript: '>= 4.3.x'
vite: ^4.0.0 || ^5.0.0
vite-plugin-glimmerx: '*'
@@ -9407,7 +9419,7 @@ packages:
vite-plugin-glimmerx:
optional: true
dependencies:
- '@storybook/csf-plugin': 8.3.0-alpha.6([email protected])
+ '@storybook/csf-plugin': 8.3.0-alpha.7([email protected])
'@types/find-cache-dir': 3.2.1
browser-assert: 1.2.1
es-module-lexer: 1.5.4
@@ -9474,10 +9486,10 @@ packages:
unplugin: 1.12.1
dev: true
- resolution: {integrity: sha512-zGJ3qaF/Zx1EQZr5blS611vBzR0U+EwFjs7qwl0gYYrV+TSTCCZpIP6v7jDtpJ8vF2QVeem7iXreERi0L5Y8sQ==}
+ resolution: {integrity: sha512-xSb9gfURa/mbkF1/cg39NvADzJsSPuF82s1SAQO3ptflNgesPVABMyzRgTcNJO53lIZ7T36eAstbE3t5Mf4Kjw==}
peerDependencies:
- storybook: ^8.3.0-alpha.6
+ storybook: ^8.3.0-alpha.7
dependencies:
storybook: 8.2.9
unplugin: 1.12.1
@@ -10264,6 +10276,10 @@ packages:
'@types/ms': 0.7.34
dev: false
+ resolution: {integrity: sha512-yPEZ3z7EohrmOxbk/QTAa0yonMFkNkjnVXqbGb7D4rMr+F1dGQ8ZUFxXkyLLJuiICPejZ0AZE9Rrk9wUCczx4A==}
+ dev: true
+
resolution: {integrity: sha512-cFq+fO/isvhvmuP/+Sl4K4jtU6E23DoivtbO4r50e3odaxAiVdbfSYRDdJ4gCdxx+3aRjhphS5ZMwIH4hFy/Cw==}
dev: true
@@ -17884,6 +17900,10 @@ packages:
- supports-color
dev: false
+ resolution: {integrity: sha512-zRmGlvxy+YdW3Dmt+TR4xPHynbxwXtAQDTN/Fo9N3LMxaUlB2C5KmZpzYyGKy4c7k4Jf3RCR0A2pm9SZELOLXw==}
+ dev: false
+
resolution: {integrity: sha512-WgeIwxAqkmb9uTn4ClicXpEQYCEduDqRKfmUdp4X8vmghKfBNXZLYpREn9eqrDx/Tf5LhzRcJLSpi4ohfV742Q==}
hasBin: true
@@ -20497,7 +20517,7 @@ packages:
resolution: {integrity: sha512-dD+VMYC5fBBQNesVb+mjB0LOkZIf100SQFbjAt9/sDstNUvc5ce3yZwLYXzgcOc7jcSMkrBu/cZNRzEM4YIAyw==}
engines: {node: ^14.18 || >=16}
dependencies:
- '@storybook/builder-vite': 8.3.0-alpha.6([email protected])([email protected])([email protected])
+ '@storybook/builder-vite': 8.3.0-alpha.7([email protected])([email protected])([email protected])
transitivePeerDependencies:
- '@preact/preset-vite'
- storybook
@@ -21645,6 +21665,26 @@ packages:
vfile: 5.3.7
dev: false
+ resolution: {integrity: sha512-/UvKRfWx3mNDWwWQhR62HsoM3wxHwYdTq8ellZzMOHnnw4Dp8tovgthyW7DjTrbjDL+i4idOp06voz2VKlvrLw==}
+ dependencies:
+ '@rollup/pluginutils': 5.1.0([email protected])
+ acorn: 8.12.1
+ escape-string-regexp: 5.0.0
+ estree-walker: 3.0.3
+ fast-glob: 3.3.2
+ local-pkg: 0.5.0
+ magic-string: 0.30.11
+ mlly: 1.7.1
+ pathe: 1.1.2
+ pkg-types: 1.1.3
+ scule: 1.3.0
+ strip-literal: 2.1.0
+ unplugin: 1.12.1
+ transitivePeerDependencies:
+ - rollup
+ dev: false
+
resolution: {integrity: sha512-/UvKRfWx3mNDWwWQhR62HsoM3wxHwYdTq8ellZzMOHnnw4Dp8tovgthyW7DjTrbjDL+i4idOp06voz2VKlvrLw==}
dependencies:
@@ -21772,12 +21812,12 @@ packages:
optional: true
dependencies:
'@antfu/utils': 0.7.10
- '@rollup/pluginutils': 5.1.0([email protected])
+ '@rollup/pluginutils': 5.1.0([email protected])
fast-glob: 3.3.2
local-pkg: 0.5.0
magic-string: 0.30.11
minimatch: 9.0.5
- unimport: 3.10.0([email protected])
+ unimport: 3.10.0
unplugin: 1.12.1
transitivePeerDependencies:
- rollup
@@ -22247,7 +22287,7 @@ packages:
optional: true
dependencies:
'@antfu/utils': 0.7.10
- '@rollup/pluginutils': 5.1.0([email protected])
+ '@rollup/pluginutils': 5.1.0([email protected])
debug: 4.3.6
error-stack-parser-es: 0.1.5
fs-extra: 11.1.1
@@ -22423,6 +22463,10 @@ packages:
engines: {node: '>= 14'}
dev: false
+ resolution: {integrity: sha512-orPnYDqIbUQLQgJI6tkfZvlOULu71cpylnAK8Wh5Hgo0v84mhPHgCbbzKtqn6m6QP7yVAlNrHD+snVhqcGVFfA==}
+ dev: false
+
resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
dev: false