Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

camera in cli + logging

Brendan Allan611f3802a0d2
diff --git a/Cargo.lock b/Cargo.lock
index 83b87857e..5f2f4cdb4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -841,6 +841,9 @@ dependencies = [
"core-graphics 0.24.0",
"editor",
"ffmpeg-next",
+ "flume 0.11.0",
+ "nokhwa",
+ "nokhwa-bindings-macos",
"scap",
"serde",
"serde_json",
@@ -4299,7 +4302,7 @@ checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
[[package]]
name = "nokhwa"
version = "0.10.3"
-source = "git+https://github.com/CapSoftware/nokhwa?rev=0d3d1f30a78b#0d3d1f30a78bb4616b4a4d0939a29ad0c1a8e14f"
+source = "git+https://github.com/CapSoftware/nokhwa?rev=d37141b1883d#d37141b1883d7250f7d2ccc9bc199ecaee48d51b"
dependencies = [
"flume 0.10.14",
"image 0.24.9",
@@ -4315,7 +4318,7 @@ dependencies = [
[[package]]
name = "nokhwa-bindings-linux"
version = "0.1.0"
-source = "git+https://github.com/CapSoftware/nokhwa?rev=0d3d1f30a78b#0d3d1f30a78bb4616b4a4d0939a29ad0c1a8e14f"
+source = "git+https://github.com/CapSoftware/nokhwa?rev=d37141b1883d#d37141b1883d7250f7d2ccc9bc199ecaee48d51b"
dependencies = [
"nokhwa-core",
"v4l",
@@ -4325,7 +4328,7 @@ dependencies = [
[[package]]
name = "nokhwa-bindings-macos"
version = "0.2.0"
-source = "git+https://github.com/CapSoftware/nokhwa?rev=0d3d1f30a78b#0d3d1f30a78bb4616b4a4d0939a29ad0c1a8e14f"
+source = "git+https://github.com/CapSoftware/nokhwa?rev=d37141b1883d#d37141b1883d7250f7d2ccc9bc199ecaee48d51b"
dependencies = [
"block",
"cocoa-foundation 0.1.2",
@@ -4340,7 +4343,7 @@ dependencies = [
[[package]]
name = "nokhwa-bindings-windows"
version = "0.4.0"
-source = "git+https://github.com/CapSoftware/nokhwa?rev=0d3d1f30a78b#0d3d1f30a78bb4616b4a4d0939a29ad0c1a8e14f"
+source = "git+https://github.com/CapSoftware/nokhwa?rev=d37141b1883d#d37141b1883d7250f7d2ccc9bc199ecaee48d51b"
dependencies = [
"nokhwa-core",
"once_cell",
@@ -4350,7 +4353,7 @@ dependencies = [
[[package]]
name = "nokhwa-core"
version = "0.1.0"
-source = "git+https://github.com/CapSoftware/nokhwa?rev=0d3d1f30a78b#0d3d1f30a78bb4616b4a4d0939a29ad0c1a8e14f"
+source = "git+https://github.com/CapSoftware/nokhwa?rev=d37141b1883d#d37141b1883d7250f7d2ccc9bc199ecaee48d51b"
dependencies = [
"bytes",
"image 0.24.9",
diff --git a/Cargo.toml b/Cargo.toml
index 4b0761916..f17c601c6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
-members = [ "apps/cli","apps/desktop/src-tauri", "crates/*"]
+members = ["apps/cli", "apps/desktop/src-tauri", "crates/*"]
[workspace.dependencies]
anyhow = "1.0.86"
@@ -21,11 +21,11 @@ tokio = { version = "1.39.3", features = [
tauri = { version = "2.1.1" }
specta = { version = "=2.0.0-rc.20" }
scap = { git = "https://github.com/CapSoftware/scap", rev = "58d4410bf52f" }
-nokhwa = { git = "https://github.com/CapSoftware/nokhwa", rev = "0d3d1f30a78b", features = [
+nokhwa = { git = "https://github.com/CapSoftware/nokhwa", rev = "d37141b1883d", features = [
"input-native",
"serialize",
] }
-nokhwa-bindings-macos = { git = "https://github.com/CapSoftware/nokhwa", rev = "0d3d1f30a78b" }
+nokhwa-bindings-macos = { git = "https://github.com/CapSoftware/nokhwa", rev = "d37141b1883d" }
wgpu = "22.1.0"
flume = "0.11.0"
thiserror = "1.0"
diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.toml
index a81c4bc52..073a89724 100644
--- a/apps/cli/Cargo.toml
+++ b/apps/cli/Cargo.toml
@@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2021"
[dependencies]
+nokhwa-bindings-macos.workspace = true
clap = { version = "4.5.23", features = ["derive"] }
cap-utils = { path = "../../crates/utils" }
cap-project = { path = "../../crates/project" }
@@ -23,3 +24,5 @@ uuid = { version = "1.11.1", features = ["v4"] }
ffmpeg = { workspace = true }
tracing = "0.1.41"
tracing-subscriber = "0.3.19"
+nokhwa.workspace = true
+flume.workspace = true
diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rs
index c78de39f1..ac0d9894c 100644
--- a/apps/cli/src/main.rs
+++ b/apps/cli/src/main.rs
@@ -1,15 +1,15 @@
-use std::{env::current_dir, path::PathBuf, sync::Arc};
+mod record;
+
+use std::{path::PathBuf, sync::Arc};
use cap_editor::create_segments;
-use cap_media::sources::{get_target_fps, ScreenCaptureTarget};
+use cap_media::sources::get_target_fps;
use cap_project::{RecordingMeta, XY};
-use cap_recording::RecordingOptions;
use cap_rendering::RenderVideoConstants;
use clap::{Args, Parser, Subcommand};
-use instrument::WithSubscriber;
-use tokio::io::AsyncBufReadExt;
+use record::RecordStart;
+use serde_json::json;
use tracing::*;
-use uuid::Uuid;
#[derive(Parser)]
struct Cli {
@@ -20,10 +20,7 @@ struct Cli {
#[derive(Subcommand)]
enum Commands {
/// Export a '.cap' project to an mp4 file
- Export {
- project_path: PathBuf,
- output_path: Option<PathBuf>,
- },
+ Export(Export),
/// Start a recording or list available capture targets and devices
Record(RecordArgs),
}
@@ -36,7 +33,7 @@ struct RecordArgs {
command: Option<RecordCommands>,
#[command(flatten)]
- args: RecordStartArgs,
+ args: RecordStart,
}
#[derive(Subcommand)]
@@ -45,100 +42,17 @@ enum RecordCommands {
Screens,
/// List windows available for capturing
Windows,
- // Cameras,
+ /// List cameras available for capturing
+ Cameras,
// Mics,
}
-#[derive(Args)]
-struct RecordStartArgs {
- #[command(flatten)]
- target: RecordTargets,
- /// ID of the camera to record
- #[arg(long)]
- camera: Option<u32>,
- /// ID of the microphone to record
- #[arg(long)]
- mic: Option<u32>,
- #[arg(long)]
- /// Path to save the '.cap' project to
- path: Option<PathBuf>,
- /// Maximum fps to record at (max 60)
- #[arg(long)]
- fps: Option<u32>,
-}
-
-#[derive(Args)]
-struct RecordTargets {
- /// ID of the screen to capture
- #[arg(long, group = "target")]
- screen: Option<u32>,
- /// ID of the window to capture
- #[arg(long, group = "target")]
- window: Option<u32>,
-}
-
#[tokio::main]
async fn main() -> Result<(), String> {
let cli = Cli::parse();
match cli.command {
- Commands::Export {
- project_path,
- output_path,
- } => {
- let project = serde_json::from_reader(
- std::fs::File::open(project_path.join("project-config.json")).unwrap(),
- )
- .unwrap();
-
- let meta = RecordingMeta::load_for_project(&project_path).unwrap();
- let recordings = cap_rendering::ProjectRecordings::new(&meta);
-
- let render_options = cap_rendering::RenderOptions {
- screen_size: XY::new(
- recordings.segments[0].display.width,
- recordings.segments[0].display.height,
- ),
- camera_size: recordings.segments[0]
- .camera
- .as_ref()
- .map(|c| XY::new(c.width, c.height)),
- };
- let render_constants = Arc::new(
- RenderVideoConstants::new(render_options, &meta)
- .await
- .unwrap(),
- );
-
- let segments = create_segments(&meta);
-
- let fps = meta.content.max_fps();
- let project_output_path = project_path.join("output/result.mp4");
- let exporter = cap_export::Exporter::new(
- project,
- project_output_path.clone(),
- |_| {},
- project_path.clone(),
- meta,
- render_constants,
- &segments,
- fps,
- XY::new(1920, 1080),
- true,
- )
- .unwrap();
-
- exporter.export_with_custom_muxer().await.unwrap();
-
- let output_path = if let Some(output_path) = output_path {
- std::fs::copy(&project_output_path, &output_path).unwrap();
- output_path
- } else {
- project_output_path
- };
-
- println!("Exported video to '{}'", output_path.display());
- }
+ Commands::Export(e) => e.run().await,
Commands::Record(RecordArgs { command, args }) => match command {
Some(RecordCommands::Screens) => {
let screens = cap_media::sources::list_screens();
@@ -174,59 +88,40 @@ window {}:
);
}
}
- None => {
- let (target_info, scap_target) = args
- .target
- .screen
- .map(|id| {
- cap_media::sources::list_screens()
- .into_iter()
- .find(|s| s.0.id == id)
- .map(|(s, t)| (ScreenCaptureTarget::Screen(s), t))
- .ok_or(format!("Screen with id '{id}' not found"))
- })
- .or_else(|| {
- args.target.window.map(|id| {
- cap_media::sources::list_windows()
- .into_iter()
- .find(|s| s.0.id == id)
- .map(|(s, t)| (ScreenCaptureTarget::Window(s), t))
- .ok_or(format!("Window with id '{id}' not found"))
- })
- })
- .ok_or("No target specified".to_string())??;
-
- let id = Uuid::new_v4().to_string();
- let path = args
- .path
- .unwrap_or_else(|| current_dir().unwrap().join(format!("{id}.cap")));
-
- let actor = cap_recording::spawn_recording_actor(
- id,
- path,
- RecordingOptions {
- capture_target: target_info,
- camera_label: None,
- audio_input_name: None,
- fps: 30,
- output_resolution: None,
- },
- None,
- None,
- )
- .await
- .map_err(|e| e.to_string())?;
-
- info!("Recording starting, press Enter to stop");
-
- tokio::io::BufReader::new(tokio::io::stdin())
- .read_line(&mut String::new())
- .await
- .unwrap();
+ Some(RecordCommands::Cameras) => {
+ use nokhwa::{
+ pixel_format::RgbAFormat,
+ utils::{ApiBackend, RequestedFormat, RequestedFormatType},
+ Camera,
+ };
+
+ let cameras = nokhwa::query(ApiBackend::Auto).unwrap();
+
+ let mut info = vec![];
+ for camera_info in cameras {
+ let format = RequestedFormat::new::<RgbAFormat>(
+ RequestedFormatType::AbsoluteHighestFrameRate,
+ );
- info!("Recording stopped");
+ let mut camera = Camera::new(camera_info.index().clone(), format).unwrap();
+
+ info.push(json!({
+ "index": camera_info.index().to_string(),
+ "name": camera_info.human_name(),
+ "pixel_format": camera.frame_format(),
+ "formats": camera
+ .compatible_camera_formats()
+ .unwrap()
+ .into_iter()
+ .map(|f| format!("{}x{}@{}fps", f.resolution().x(), f.resolution().y(), f.frame_rate()))
+ .collect::<Vec<_>>()
+ }));
+ }
- actor.stop().await.unwrap();
+ println!("{}", serde_json::to_string_pretty(&info).unwrap());
+ }
+ None => {
+ args.run().await?;
}
_ => {}
},
@@ -235,6 +130,69 @@ window {}:
Ok(())
}
+#[derive(Args)]
+struct Export {
+ project_path: PathBuf,
+ output_path: Option<PathBuf>,
+}
+
+impl Export {
+ async fn run(self) {
+ let project = serde_json::from_reader(
+ std::fs::File::open(self.project_path.join("project-config.json")).unwrap(),
+ )
+ .unwrap();
+
+ let meta = RecordingMeta::load_for_project(&self.project_path).unwrap();
+ let recordings = cap_rendering::ProjectRecordings::new(&meta);
+
+ let render_options = cap_rendering::RenderOptions {
+ screen_size: XY::new(
+ recordings.segments[0].display.width,
+ recordings.segments[0].display.height,
+ ),
+ camera_size: recordings.segments[0]
+ .camera
+ .as_ref()
+ .map(|c| XY::new(c.width, c.height)),
+ };
+ let render_constants = Arc::new(
+ RenderVideoConstants::new(render_options, &meta)
+ .await
+ .unwrap(),
+ );
+
+ let segments = create_segments(&meta);
+
+ let fps = meta.content.max_fps();
+ let project_output_path = self.project_path.join("output/result.mp4");
+ let exporter = cap_export::Exporter::new(
+ project,
+ project_output_path.clone(),
+ |_| {},
+ self.project_path.clone(),
+ meta,
+ render_constants,
+ &segments,
+ fps,
+ XY::new(1920, 1080),
+ true,
+ )
+ .unwrap();
+
+ exporter.export_with_custom_muxer().await.unwrap();
+
+ let output_path = if let Some(output_path) = self.output_path {
+ std::fs::copy(&project_output_path, &output_path).unwrap();
+ output_path
+ } else {
+ project_output_path
+ };
+
+ println!("Exported video to '{}'", output_path.display());
+ }
+}
+
// fn ffmpeg_callback_experiment() {
// unsafe {
// unsafe extern "C" fn ffmpeg_log_callback(
diff --git a/apps/cli/src/record.rs b/apps/cli/src/record.rs
new file mode 100644
index 000000000..044e42235
--- /dev/null
+++ b/apps/cli/src/record.rs
@@ -0,0 +1,110 @@
+use std::{env::current_dir, hash::Hash, path::PathBuf, sync::Arc};
+
+use cap_media::{feeds::CameraFeed, sources::ScreenCaptureTarget};
+use cap_recording::RecordingOptions;
+use clap::Args;
+use nokhwa::utils::{ApiBackend, CameraIndex};
+use tokio::{io::AsyncBufReadExt, sync::Mutex};
+use uuid::Uuid;
+
+#[derive(Args)]
+pub struct RecordStart {
+ #[command(flatten)]
+ target: RecordTargets,
+ /// Index of the camera to record
+ #[arg(long)]
+ camera: Option<u32>,
+ /// ID of the microphone to record
+ #[arg(long)]
+ mic: Option<u32>,
+ #[arg(long)]
+ /// Path to save the '.cap' project to
+ path: Option<PathBuf>,
+ /// Maximum fps to record at (max 60)
+ #[arg(long)]
+ fps: Option<u32>,
+}
+
+impl RecordStart {
+ pub async fn run(self) -> Result<(), String> {
+ let (target_info, _) = self
+ .target
+ .screen
+ .map(|id| {
+ cap_media::sources::list_screens()
+ .into_iter()
+ .find(|s| s.0.id == id)
+ .map(|(s, t)| (ScreenCaptureTarget::Screen(s), t))
+ .ok_or(format!("Screen with id '{id}' not found"))
+ })
+ .or_else(|| {
+ self.target.window.map(|id| {
+ cap_media::sources::list_windows()
+ .into_iter()
+ .find(|s| s.0.id == id)
+ .map(|(s, t)| (ScreenCaptureTarget::Window(s), t))
+ .ok_or(format!("Window with id '{id}' not found"))
+ })
+ })
+ .ok_or("No target specified".to_string())??;
+
+ let camera = if let Some(camera_index) = self.camera {
+ if let Some(camera_info) = nokhwa::query(ApiBackend::Auto)
+ .unwrap()
+ .into_iter()
+ .find(|c| *c.index() == CameraIndex::Index(camera_index))
+ {
+ let name = camera_info.human_name();
+
+ let (tx, _) = flume::bounded(1);
+ Some(CameraFeed::init(&name, tx).await.unwrap())
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ let id = Uuid::new_v4().to_string();
+ let path = self
+ .path
+ .unwrap_or_else(|| current_dir().unwrap().join(format!("{id}.cap")));
+
+ let actor = cap_recording::spawn_recording_actor(
+ id,
+ path,
+ RecordingOptions {
+ capture_target: target_info,
+ camera_label: camera.as_ref().map(|c| c.camera_info.human_name()),
+ audio_input_name: None,
+ fps: 30,
+ output_resolution: None,
+ },
+ camera.map(|c| Arc::new(Mutex::new(c))),
+ None,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+
+ println!("Recording starting, press Enter to stop");
+
+ tokio::io::BufReader::new(tokio::io::stdin())
+ .read_line(&mut String::new())
+ .await
+ .unwrap();
+
+ actor.stop().await.unwrap();
+
+ Ok(())
+ }
+}
+
+#[derive(Args)]
+struct RecordTargets {
+ /// ID of the screen to capture
+ #[arg(long, group = "target")]
+ screen: Option<u32>,
+ /// ID of the window to capture
+ #[arg(long, group = "target")]
+ window: Option<u32>,
+}
diff --git a/apps/desktop/scripts/prepare.js b/apps/desktop/scripts/prepare.js
index 0f98ac05c..708291fa2 100644
--- a/apps/desktop/scripts/prepare.js
+++ b/apps/desktop/scripts/prepare.js
@@ -20,22 +20,6 @@ const rustInfo = execSync("rustc -vV");
const rsTargetTriple =
process.env.TARGET_TRIPLE || /host: (\S+)/.exec(rustInfo.toString())?.[1];
-const FFMPEG_BINARIES = {
- "aarch64-apple-darwin": {
- url: "https://cap-ffmpeg.s3.amazonaws.com/ffmpegarm.zip",
- path: "./ffmpeg",
- },
- "x86_64-apple-darwin": {
- url: "https://cap-ffmpeg.s3.amazonaws.com/ffmpeg-7.0.1.zip",
- path: "./ffmpeg",
- },
- "x86_64-pc-windows-msvc": {
- // TODO: Select a stable version, use Cap's own ffmpeg build to also support aarch64.
- url: "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl-shared.zip",
- path: "bin/ffmpeg.exe",
- },
-};
-
/**
* @param {string} filePath
* @returns {Promise<boolean>}
@@ -60,93 +44,6 @@ async function unzip(targetPath, outputPath) {
}
}
-async function prepareFfmpegSidecar() {
- const binaries = FFMPEG_BINARIES[rsTargetTriple];
- const ffmpegDownloadPath = path.join(binariesDir, "ffmpeg-download.zip");
-
- // Skip downloading if the archive already exists
- if (!(await exists(ffmpegDownloadPath))) {
- if (await exists(ffmpegUnzippedPath)) return;
- console.log(
- `Couldn't locate "ffmpeg-download.zip" in "${ffmpegDownloadPath}"`
- );
- console.log(`Downloading from: ${binaries.url}`);
- await fs.mkdir(binariesDir, { recursive: true });
-
- const response = await fetch(binaries.url);
- if (!response.ok || !response.body)
- throw new Error(`Failed to download: ${response.statusText}`);
-
- const contentLength = response.headers.get("content-length");
- if (!contentLength)
- throw new Error("Unable to determine file size for progress reporting.");
-
- const totalBytes = parseInt(contentLength, 10);
- let downloadedBytes = 0;
-
- const archiveBuffer = [];
- const reader = response.body.getReader();
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- downloadedBytes += value.length;
- archiveBuffer.push(value);
-
- const progress = ((downloadedBytes / totalBytes) * 100).toFixed(2);
- process.stdout.write(`\rDownloading: ${progress}%`);
- }
- console.log("\nDownload complete.");
- const archive = Buffer.concat(archiveBuffer);
- await fs.writeFile(ffmpegDownloadPath, archive);
- }
-
- // Skip unzipping if the directory already exists
- if (!(await exists(ffmpegUnzippedPath))) {
- console.log("Extracting ffmpeg archive...");
- await fs.mkdir(ffmpegUnzippedPath, { recursive: true });
- await unzip(ffmpegDownloadPath, ffmpegUnzippedPath);
- }
-
- // Check if there's a single nested folder and move its contents to the root
- const unzippedContents = await fs.readdir(ffmpegUnzippedPath);
- if (unzippedContents.length === 1) {
- const nestedPath = path.join(ffmpegUnzippedPath, unzippedContents[0]);
- const stat = await fs.stat(nestedPath);
-
- if (stat.isDirectory()) {
- console.log(
- `Detected nested folder '${unzippedContents[0]}'. Moving contents to root.`
- );
- const nestedContents = await fs.readdir(nestedPath);
-
- for (const entry of nestedContents) {
- const srcPath = path.join(nestedPath, entry);
- const destPath = path.join(ffmpegUnzippedPath, entry);
- await fs.rename(srcPath, destPath);
- }
-
- // Remove the now-empty nested folder
- await fs.rmdir(nestedPath);
- }
- }
-
- const ffmpegBinaryPath = path.join(ffmpegUnzippedPath, binaries.path);
- const ffmpegSidecarName = `ffmpeg-${rsTargetTriple}${fileExtension}`;
- const finalDestinationPath = path.join(binariesDir, ffmpegSidecarName);
- if (await exists(finalDestinationPath)) {
- console.log(`Using ffmpeg sidecar: ${ffmpegSidecarName}`);
- return;
- }
-
- console.log(`Copying ffmpeg binary to '${ffmpegSidecarName}'...`);
-
- await fs.copyFile(
- ffmpegBinaryPath,
- path.join(binariesDir, ffmpegSidecarName)
- );
-}
-
/**
* Creates a Microsoft Windows Installer (TM) compatible version from the provided crate's semver version.
* `major.minor.patch.build`
@@ -220,9 +117,6 @@ export async function createTauriPlatformConfigs(
baseConfig = {
...baseConfig,
bundle: {
- resources: {
- "../../../target/binaries/ffmpeg-unzipped/bin/*.dll": "",
- },
windows: {
wix: {
version: await semverToWIXCompatibleVersion(
@@ -255,14 +149,8 @@ export async function createTauriPlatformConfigs(
async function main() {
console.log("--- Preparing sidecars and configs...");
const targetTripleEnv = process.env.TARGET_TRIPLE || rsTargetTriple;
- const binaries = FFMPEG_BINARIES[targetTripleEnv];
- if (!binaries) {
- console.error(`Unsupported target: ${targetTripleEnv}`);
- return;
- }
console.log(`Target is ${targetTripleEnv}`);
- await prepareFfmpegSidecar();
await createTauriPlatformConfigs(process.platform);
console.log("--- Preparation finished");
}
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index 92e3d0ed6..5e08592c8 100644
--- a/apps/desktop/src-tauri/tauri.conf.json
+++ b/apps/desktop/src-tauri/tauri.conf.json
@@ -46,7 +46,6 @@
"icons/macos/icon.icns",
"icons/icon.ico"
],
- "externalBin": ["../../../target/binaries/ffmpeg"],
"macOS": {
"dmg": {
"background": "assets/dmg-background.png",
diff --git a/crates/media/src/encoders/h264.rs b/crates/media/src/encoders/h264.rs
index 4506daba1..48e267903 100644
--- a/crates/media/src/encoders/h264.rs
+++ b/crates/media/src/encoders/h264.rs
@@ -10,7 +10,7 @@ use ffmpeg::{
Dictionary, Rescale,
};
use ffmpeg_sys_next as sys;
-use tracing::{debug, info, trace};
+use tracing::{info, trace};
use super::Output;
@@ -18,9 +18,9 @@ pub struct H264Encoder {
tag: &'static str,
encoder: encoder::Video,
output_ctx: format::context::Output,
- last_pts: Option<i64>,
config: VideoInfo,
frame_count: i64,
+ converter: Option<ffmpeg::software::scaling::Context>,
}
impl H264Encoder {
@@ -31,6 +31,29 @@ impl H264Encoder {
let (codec, options) = get_codec_and_options(&config)?;
+ let (format, converter) = if !codec
+ .video()
+ .unwrap()
+ .formats()
+ .unwrap()
+ .any(|f| f == config.pixel_format)
+ {
+ let format = ffmpeg::format::Pixel::YUV420P;
+ (
+ format,
+ Some(
+ ffmpeg::software::converter(
+ (config.width, config.height),
+ config.pixel_format,
+ format,
+ )
+ .expect("Failed to create frame converter"),
+ ),
+ )
+ } else {
+ (config.pixel_format, None)
+ };
+
let mut encoder_ctx = context::Context::new_with_codec(codec);
// TODO: Configure this per system
@@ -39,7 +62,7 @@ impl H264Encoder {
encoder.set_width(config.width);
encoder.set_height(config.height);
- encoder.set_format(config.pixel_format);
+ encoder.set_format(format);
encoder.set_time_base(config.frame_rate.invert());
encoder.set_frame_rate(Some(config.frame_rate));
@@ -63,13 +86,27 @@ impl H264Encoder {
tag,
encoder: video_encoder,
output_ctx,
- last_pts: None,
config,
frame_count: 0,
+ converter,
})
}
fn queue_frame(&mut self, mut frame: FFVideo) {
+ // if self.tag == "camera" {
+ // dbg!(frame.width(), frame.planes(), frame.stride(0));
+ // }
+
+ if let Some(converter) = &mut self.converter {
+ let mut new_frame = FFVideo::empty();
+ if self.tag == "camera" {
+ dbg!(self.config);
+ dbg!(frame.format(), frame.width(), frame.height());
+ }
+ converter.run(&frame, &mut new_frame).unwrap();
+ frame = new_frame;
+ }
+
frame.set_pts(Some(self.frame_count));
self.frame_count += 1;
self.encoder.send_frame(&frame).unwrap();
@@ -114,6 +151,8 @@ impl H264Encoder {
}
}
+unsafe impl Send for H264Encoder {}
+
impl PipelineSinkTask for H264Encoder {
type Input = FFVideo;
@@ -122,18 +161,16 @@ impl PipelineSinkTask for H264Encoder {
ready_signal: crate::pipeline::task::PipelineReadySignal,
input: flume::Receiver<Self::Input>,
) {
- trace!("Starting {} video encoding thread", self.tag);
ready_signal.send(Ok(())).unwrap();
while let Ok(frame) = input.recv() {
self.queue_frame(frame);
self.process_frame();
}
+ }
- trace!("Received last {} frame. Finishing up encoding.", self.tag);
+ fn finish(&mut self) {
self.finish();
-
- info!("Shut down {} video encoding thread", self.tag);
}
}
diff --git a/crates/media/src/encoders/h264_avassetwriter.rs b/crates/media/src/encoders/h264_avassetwriter.rs
index 9d2d39e1b..431606b05 100644
--- a/crates/media/src/encoders/h264_avassetwriter.rs
+++ b/crates/media/src/encoders/h264_avassetwriter.rs
@@ -125,18 +125,16 @@ impl PipelineSinkTask for H264AVAssetWriterEncoder {
ready_signal: crate::pipeline::task::PipelineReadySignal,
input: flume::Receiver<Self::Input>,
) {
- trace!("Starting {} video encoding thread", self.tag);
ready_signal.send(Ok(())).ok();
while let Ok(frame) = input.recv() {
self.queue_frame(frame);
self.process_frame();
}
+ }
- trace!("Received last {} frame. Finishing up encoding.", self.tag);
+ fn finish(&mut self) {
self.finish();
-
- info!("Shut down {} video encoding thread", self.tag);
}
}
diff --git a/crates/media/src/encoders/mp3.rs b/crates/media/src/encoders/mp3.rs
index e10cab3dd..c0603b9b1 100644
--- a/crates/media/src/encoders/mp3.rs
+++ b/crates/media/src/encoders/mp3.rs
@@ -107,16 +107,14 @@ impl PipelineSinkTask for MP3Encoder {
ready_signal: crate::pipeline::task::PipelineReadySignal,
input: flume::Receiver<Self::Input>,
) {
- trace!("Starting {} audio encoding thread", self.tag);
ready_signal.send(Ok(())).unwrap();
while let Ok(frame) = input.recv() {
self.queue_frame(frame);
}
+ }
- trace!("Received last {} sample. Finishing up encoding.", self.tag);
+ fn finish(&mut self) {
self.finish();
-
- info!("Shut down {} audio encoding thread", self.tag);
}
}
diff --git a/crates/media/src/encoders/mp4.rs b/crates/media/src/encoders/mp4.rs
index aaccfb9c2..8730b4b92 100644
--- a/crates/media/src/encoders/mp4.rs
+++ b/crates/media/src/encoders/mp4.rs
@@ -374,7 +374,6 @@ impl PipelineSinkTask for MP4Encoder {
ready_signal: crate::pipeline::task::PipelineReadySignal,
input: flume::Receiver<Self::Input>,
) {
- trace!("Starting {} MP4 encoding thread", self.tag);
ready_signal.send(Ok(())).unwrap();
while let Ok(frame) = input.recv() {
@@ -383,11 +382,10 @@ impl PipelineSinkTask for MP4Encoder {
self.queue_audio_frame(audio);
}
}
+ }
- trace!("Received last {} frame. Finishing up encoding.", self.tag);
+ fn finish(&mut self) {
self.finish();
-
- info!("Shut down {} MP4 encoding thread", self.tag);
}
}
diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rs
index 1a7f162a2..b2fa630cf 100644
--- a/crates/media/src/feeds/camera.rs
+++ b/crates/media/src/feeds/camera.rs
@@ -36,7 +36,7 @@ impl CameraConnection {
let (sender, receiver) = flume::bounded(60);
self.control
.send(CameraControl::AttachRawConsumer(sender))
- .unwrap();
+ .ok();
receiver
}
@@ -44,7 +44,7 @@ impl CameraConnection {
// #[derive(Clone)]
pub struct CameraFeed {
- camera_info: CameraInfo,
+ pub camera_info: CameraInfo,
video_info: VideoInfo,
control: Sender<CameraControl>,
// join_handle: JoinHandle<()>,
@@ -267,6 +267,7 @@ fn run_camera_feed(
// Actual data capture
match camera.frame() {
Ok(raw_buffer) => {
+ dbg!(raw_buffer.source_frame_format());
let raw_buffer = if let FrameFormat::MJPEG = raw_buffer.source_frame_format() {
let rgba_buffer = raw_buffer
.decode_image::<nokhwa::pixel_format::RgbAFormat>()
@@ -497,73 +498,12 @@ impl FrameConverter {
}
fn raw(&mut self, buffer: &nokhwa::Buffer) -> FFVideo {
- let resolution = buffer.resolution();
-
- if self.format == FrameFormat::YUYV {
- // For YUYV, we need to handle the conversion differently
- let stride = resolution.width() as usize * 2; // YUYV uses 2 bytes per pixel
- let src = buffer.buffer();
-
- // Create input frame with YUYV format and copy data
- let mut input_frame = FFVideo::new(
- ffmpeg::format::Pixel::UYVY422,
- resolution.width(),
- resolution.height(),
- );
-
- // Copy data line by line
- {
- let dst_stride = input_frame.stride(0);
- let dst = input_frame.data_mut(0);
- for y in 0..resolution.height() as usize {
- let src_offset = y * stride;
- let dst_offset = y * dst_stride;
- dst[dst_offset..dst_offset + stride]
- .copy_from_slice(&src[src_offset..src_offset + stride]);
- }
- }
-
- input_frame
- } else {
- // For other formats, use the normal conversion path
- let stride = match self.format {
- FrameFormat::NV12 => resolution.width() as usize,
- FrameFormat::BGRA => resolution.width() as usize * 4,
- FrameFormat::MJPEG => resolution.width() as usize * 4,
- FrameFormat::GRAY => resolution.width() as usize,
- FrameFormat::RAWRGB => resolution.width() as usize * 3,
- _ => buffer.buffer_bytes().len() / resolution.height() as usize,
- };
-
- // Create input frame and copy data
- let mut input_frame = FFVideo::new(
- match self.format {
- FrameFormat::NV12 => ffmpeg::format::Pixel::NV12,
- FrameFormat::BGRA => ffmpeg::format::Pixel::BGRA,
- FrameFormat::MJPEG => ffmpeg::format::Pixel::RGBA,
- FrameFormat::GRAY => ffmpeg::format::Pixel::GRAY8,
- FrameFormat::RAWRGB => ffmpeg::format::Pixel::RGB24,
- _ => ffmpeg::format::Pixel::RGBA,
- },
- resolution.width(),
- resolution.height(),
- );
-
- // Copy data line by line
- {
- let dst_stride = input_frame.stride(0);
- let dst = input_frame.data_mut(0);
- let src = buffer.buffer();
- for y in 0..resolution.height() as usize {
- let src_offset = y * stride;
- let dst_offset = y * dst_stride;
- dst[dst_offset..dst_offset + stride]
- .copy_from_slice(&src[src_offset..src_offset + stride]);
- }
- }
-
- input_frame
- }
+ dbg!(buffer.source_frame_format());
+ self.video_info.wrap_frame(
+ buffer.buffer(),
+ 0,
+ buffer.buffer_bytes().len() / buffer.resolution().height() as usize,
+ )
}
}
diff --git a/crates/media/src/filters/audio.rs b/crates/media/src/filters/audio.rs
index 480eacc99..3a7c7b8f2 100644
--- a/crates/media/src/filters/audio.rs
+++ b/crates/media/src/filters/audio.rs
@@ -96,7 +96,6 @@ impl PipelinePipeTask for AudioFilter {
input: Receiver<Self::Input>,
output: Sender<Self::Output>,
) {
- println!("Starting {} audio filtering thread", self.tag);
ready_signal.send(Ok(())).unwrap();
while let Ok(raw_frame) = input.recv() {
@@ -104,12 +103,6 @@ impl PipelinePipeTask for AudioFilter {
self.process_frame(&output);
}
- println!(
- "Received last raw {} sample. Finishing up filtering.",
- self.tag
- );
self.finish(&output);
-
- println!("Shutting down {} audio filtering thread", self.tag);
}
}
diff --git a/crates/media/src/filters/video.rs b/crates/media/src/filters/video.rs
index 47353c935..9faa26927 100644
--- a/crates/media/src/filters/video.rs
+++ b/crates/media/src/filters/video.rs
@@ -1,4 +1,5 @@
use ffmpeg::filter;
+use tracing::{info, trace};
use crate::{
data::{FFVideo, VideoInfo},
@@ -100,7 +101,6 @@ impl PipelinePipeTask for VideoFilter {
input: flume::Receiver<Self::Input>,
output: Sender<Self::Output>,
) {
- println!("Starting {} video filtering thread", self.tag);
ready_signal.send(Ok(())).unwrap();
while let Ok(raw_frame) = input.recv() {
@@ -108,12 +108,6 @@ impl PipelinePipeTask for VideoFilter {
self.process_frame(&output);
}
- println!(
- "Received last raw {} frame. Finishing up filtering.",
- self.tag
- );
self.finish(&output);
-
- println!("Shutting down {} video filtering thread", self.tag);
}
}
diff --git a/crates/media/src/pipeline/builder.rs b/crates/media/src/pipeline/builder.rs
index c1b2a45f3..b3776b71a 100644
--- a/crates/media/src/pipeline/builder.rs
+++ b/crates/media/src/pipeline/builder.rs
@@ -1,7 +1,7 @@
use flume::Receiver;
use indexmap::IndexMap;
use std::thread::{self, JoinHandle};
-use tracing::Instrument;
+use tracing::{info, trace, Instrument};
use crate::pipeline::{
clock::CloneFrom,
@@ -133,7 +133,9 @@ impl<Clock, PreviousOutput: Send + 'static> PipelinePathBuilder<Clock, PreviousO
let (output, next_input) = flume::bounded(task.queue_size());
pipeline.spawn_task(name.into(), move |ready_signal| {
+ trace!("Pipe starting");
task.run(ready_signal, input, output);
+ info!("Pipe stopped");
});
PipelinePathBuilder {
@@ -153,7 +155,11 @@ impl<Clock, PreviousOutput: Send + 'static> PipelinePathBuilder<Clock, PreviousO
} = self;
pipeline.spawn_task(name.into(), move |ready_signal| {
+ trace!("Sink starting");
task.run(ready_signal, input);
+ info!("Sink stopped running");
+ task.finish();
+ info!("Sink stopped");
});
pipeline
diff --git a/crates/media/src/pipeline/control.rs b/crates/media/src/pipeline/control.rs
index 109cc0616..d957d3897 100644
--- a/crates/media/src/pipeline/control.rs
+++ b/crates/media/src/pipeline/control.rs
@@ -1,6 +1,6 @@
use flume::{Receiver, Sender, TryRecvError};
use indexmap::IndexMap;
-use tracing::debug;
+use tracing::{debug, error};
use crate::pipeline::MediaError;
@@ -77,7 +77,7 @@ impl ControlBroadcast {
for (name, listener) in self.listeners.iter() {
if let Err(_) = listener.send_async(value).await {
- eprintln!("{name} is unreachable!");
+ error!("{name} is unreachable!");
any_dropped = true;
}
}
diff --git a/crates/media/src/pipeline/mod.rs b/crates/media/src/pipeline/mod.rs
index 403a801bd..08f320b5e 100644
--- a/crates/media/src/pipeline/mod.rs
+++ b/crates/media/src/pipeline/mod.rs
@@ -49,12 +49,12 @@ impl<T: PipelineClock> Pipeline<T> {
return Err(MediaError::ShutdownPipeline);
};
- trace!("Shutting down pipeline execution");
+ trace!("Shutting down pipeline");
let _ = self.control.broadcast(Control::Shutdown).await;
for (_name, task) in self.task_handles.drain(..) {
let _ = task.join();
}
- info!("Pipeline has been stopped.");
+ info!("Pipeline stopped");
// TODO: Collect shutdown errors?
Ok(())
}
diff --git a/crates/media/src/pipeline/task.rs b/crates/media/src/pipeline/task.rs
index 072b977e3..f33e5e2f3 100644
--- a/crates/media/src/pipeline/task.rs
+++ b/crates/media/src/pipeline/task.rs
@@ -43,4 +43,6 @@ pub trait PipelineSinkTask: Send {
type Input;
fn run(&mut self, ready_signal: PipelineReadySignal, input: Receiver<Self::Input>);
+
+ fn finish(&mut self);
}
diff --git a/crates/media/src/sources/audio_input.rs b/crates/media/src/sources/audio_input.rs
index 3ac30b38b..439421655 100644
--- a/crates/media/src/sources/audio_input.rs
+++ b/crates/media/src/sources/audio_input.rs
@@ -129,6 +129,6 @@ impl PipelineSourceTask for AudioInputSource {
}
}
- info!("Shutting down audio input source thread.");
+ info!("Shut down audio input source thread.");
}
}
diff --git a/crates/media/src/sources/camera.rs b/crates/media/src/sources/camera.rs
index aed59134f..36fe0889a 100644
--- a/crates/media/src/sources/camera.rs
+++ b/crates/media/src/sources/camera.rs
@@ -1,6 +1,6 @@
use flume::{Receiver, Sender};
use std::time::Instant;
-use tracing::info;
+use tracing::{error, info, trace};
use crate::{
data::{FFVideo, VideoInfo},
@@ -82,8 +82,6 @@ impl PipelineSourceTask for CameraSource {
mut control_signal: crate::pipeline::control::PipelineControlSignal,
output: Sender<Self::Output>,
) {
- info!("Preparing camera source thread...");
-
let mut frames_rx: Option<Receiver<RawCameraFrame>> = None;
ready_signal.send(Ok(())).unwrap();
@@ -100,7 +98,7 @@ impl PipelineSourceTask for CameraSource {
}
}
Err(_) => {
- eprintln!("Lost connection with the camera feed");
+ error!("Lost connection with the camera feed");
break;
}
}
@@ -120,7 +118,5 @@ impl PipelineSourceTask for CameraSource {
}
}
}
-
- info!("Shutting down camera source thread.");
}
}
diff --git a/crates/recording/src/actor.rs b/crates/recording/src/actor.rs
index 0f6409cb1..534bfd34e 100644
--- a/crates/recording/src/actor.rs
+++ b/crates/recording/src/actor.rs
@@ -505,9 +505,12 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
&display_output_path,
)?;
- trace!(
+ info!(
r#"screen pipeline prepared, will output to "{}""#,
- display_output_path.strip_prefix(&dir).unwrap().display()
+ display_output_path
+ .strip_prefix(&segments_dir)
+ .unwrap()
+ .display()
);
let audio_output_path = if let Some(mic_source) = audio_input_feed.map(AudioInputSource::init) {
@@ -521,9 +524,9 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
.source("microphone_capture", mic_source)
.sink("microphone_encoder", mic_encoder);
- debug!(
+ info!(
"mic pipeline prepared, will output to {}",
- output_path.display()
+ output_path.strip_prefix(&segments_dir).unwrap().display()
);
Some(output_path)
@@ -533,21 +536,32 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(
let camera = if let Some(camera_source) = camera_feed.map(CameraSource::init) {
let camera_config = camera_source.info();
+ // <<<<<<< Updated upstream
let output_config = camera_config.scaled(1280_u32, 30_u32);
let output_path = dir.join("camera.mp4");
let camera_filter = VideoFilter::init("camera", camera_config, output_config)?;
let camera_encoder =
H264Encoder::init("camera", output_config, Output::File(output_path.clone()))?;
+ // =======
+ // camera_output_path = Some(dir.join("camera.mp4"));
+
+ // // let camera_filter = VideoFilter::init("camera", camera_config, camera_config)?;
+ // let camera_encoder = H264Encoder::init(
+ // "camera",
+ // camera_config,
+ // Output::File(camera_output_path.clone().unwrap()),
+ // )?;
+ // >>>>>>> Stashed changes
pipeline_builder = pipeline_builder
.source("camera_capture", camera_source)
.pipe("camera_filter", camera_filter)
.sink("camera_encoder", camera_encoder);
- debug!(
- "mic pipeline prepared, will output to {}",
- output_path.display()
+ info!(
+ "camera pipeline prepared, will output to {}",
+ output_path.strip_prefix(&segments_dir).unwrap().display()
);
Some(CameraPipelineInfo {
@@ -639,15 +653,15 @@ impl MakeCapturePipeline for cap_media::sources::AVFrameCapture {
Self: Sized,
{
let mut screen_config = source.info();
- let screen_filter = VideoFilter::init("screen", screen_config, {
- screen_config.pixel_format = Pixel::NV12;
- screen_config
- })?;
+ // let screen_filter = VideoFilter::init("screen", screen_config, {
+ // screen_config.pixel_format = Pixel::NV12;
+ // screen_config
+ // })?;
let screen_encoder =
H264Encoder::init("screen", screen_config, Output::File(output_path.into()))?;
Ok(builder
.source("screen_capture", source)
- .pipe("screen_capture_filter", screen_filter)
+ // .pipe("screen_capture_filter", screen_filter)
.sink("screen_capture_encoder", screen_encoder))
}
}