Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

better preview logic and fixed editor instance

Brendan Allan071585357194
diff --git a/Cargo.lock b/Cargo.lock
index 9a78967c5..0d887f317 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -917,6 +917,7 @@ dependencies = [
"cap-project",
"ffmpeg-next",
"futures-intrusive",
+ "lru",
"nix 0.29.0",
"serde",
"serde_json",
@@ -3571,6 +3572,15 @@ dependencies = [
"imgref",
]
+[[package]]
+name = "lru"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37ee39891760e7d94734f6f63fedc29a2e4a152f836120753a72503f09fcf904"
+dependencies = [
+ "hashbrown 0.14.5",
+]
+
[[package]]
name = "mac"
version = "0.1.1"
diff --git a/apps/desktop-solid/src-tauri/src/display.rs b/apps/desktop-solid/src-tauri/src/display.rs
index aafe10285..d85cea8bc 100644
--- a/apps/desktop-solid/src-tauri/src/display.rs
+++ b/apps/desktop-solid/src-tauri/src/display.rs
@@ -1,10 +1,4 @@
-use std::{
- fs::File,
- io::Write,
- path::PathBuf,
- sync::atomic::Ordering,
- time::Instant,
-};
+use std::{fs::File, io::Write, path::PathBuf, sync::atomic::Ordering, time::Instant};
use scap::{
capturer::{Area, Capturer, Options, Point, Resolution, Size},
@@ -68,7 +62,7 @@ pub fn list_capture_windows() -> Vec<CaptureWindow> {
.collect::<Vec<_>>()
}
-pub const FPS: u32 = 60;
+pub const FPS: u32 = 30;
pub async fn start_capturing(
pipe_path: PathBuf,
diff --git a/apps/desktop-solid/src-tauri/src/editor.rs b/apps/desktop-solid/src-tauri/src/editor.rs
index 9426a178d..fb51457d8 100644
--- a/apps/desktop-solid/src-tauri/src/editor.rs
+++ b/apps/desktop-solid/src-tauri/src/editor.rs
@@ -1,7 +1,7 @@
use std::sync::Arc;
use cap_project::{BackgroundSource, ProjectConfiguration};
-use cap_rendering::{produce_frame, ProjectUniforms, RenderVideoConstants};
+use cap_rendering::{decoder::DecodedFrame, produce_frame, ProjectUniforms, RenderVideoConstants};
use tokio::{
sync::{mpsc, oneshot},
task::JoinHandle,
@@ -97,8 +97,8 @@ impl EditorHandle {
pub enum RendererMessage {
RenderFrame {
- screen_frame: Vec<u8>,
- camera_frame: Option<Vec<u8>>,
+ screen_frame: DecodedFrame,
+ camera_frame: Option<DecodedFrame>,
background: BackgroundSource,
uniforms: ProjectUniforms,
finished: oneshot::Sender<()>,
@@ -161,7 +161,7 @@ impl Renderer {
let frame = produce_frame(
&render_constants,
&screen_frame,
- camera_frame.as_ref(),
+ &camera_frame,
cap_rendering::Background::from(background),
&uniforms,
)
@@ -185,8 +185,8 @@ impl RendererHandle {
pub async fn render_frame(
&self,
- screen_frame: Vec<u8>,
- camera_frame: Option<Vec<u8>>,
+ screen_frame: DecodedFrame,
+ camera_frame: Option<DecodedFrame>,
background: BackgroundSource,
uniforms: ProjectUniforms,
) {
diff --git a/apps/desktop-solid/src-tauri/src/editor_instance.rs b/apps/desktop-solid/src-tauri/src/editor_instance.rs
index a2ab4e1df..b0a9d743e 100644
--- a/apps/desktop-solid/src-tauri/src/editor_instance.rs
+++ b/apps/desktop-solid/src-tauri/src/editor_instance.rs
@@ -2,10 +2,12 @@ use crate::playback::{self, PlaybackHandle};
use crate::{editor, AudioData};
use cap_project::ProjectConfiguration;
use cap_rendering::{ProjectUniforms, RenderOptions, RenderVideoConstants, VideoDecoderActor};
+use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering};
use std::{path::PathBuf, process::Command, sync::Arc};
-use tauri::{AppHandle, Manager};
-use tokio::sync::{mpsc, Mutex};
+use tokio::sync::{mpsc, watch, Mutex};
+
+type PreviewFrameInstruction = (u32, ProjectConfiguration);
pub struct EditorState {
pub playhead_position: u32,
@@ -24,6 +26,7 @@ pub struct EditorInstance {
pub state: Mutex<EditorState>,
on_state_change: Box<dyn Fn(&EditorState) + Send + Sync + 'static>,
rendering: Arc<AtomicBool>,
+ pub preview_tx: watch::Sender<Option<PreviewFrameInstruction>>,
}
impl EditorInstance {
@@ -31,14 +34,8 @@ impl EditorInstance {
projects_path: PathBuf,
video_id: String,
on_state_change: impl Fn(&EditorState) + Send + Sync + 'static,
- ) -> Self {
- let project_path = projects_path
- // app
- // .path()
- // .app_data_dir()
- // .unwrap()
- // .join("recordings")
- .join(format!("{video_id}.cap"));
+ ) -> Arc<Self> {
+ let project_path = projects_path.join(format!("{video_id}.cap"));
if !project_path.exists() {
println!("Video path {} not found!", project_path.display());
@@ -95,7 +92,9 @@ impl EditorInstance {
let renderer = Arc::new(editor::Renderer::spawn(render_constants.clone(), frame_tx));
- Self {
+ let (preview_tx, mut preview_rx) = watch::channel(None);
+
+ let this = Arc::new(Self {
id: video_id,
path: project_path,
screen_decoder,
@@ -110,7 +109,12 @@ impl EditorInstance {
}),
rendering: Arc::new(AtomicBool::new(false)),
on_state_change: Box::new(on_state_change),
- }
+ preview_tx,
+ });
+
+ this.clone().spawn_preview_renderer(preview_rx);
+
+ this
}
pub async fn dispose(&self) {
@@ -176,35 +180,35 @@ impl EditorInstance {
}
}
- pub fn try_render_frame(self: &Arc<Self>, frame_number: u32, project: ProjectConfiguration) {
- if self.rendering.load(Ordering::Relaxed) {
- return;
- }
-
- let this = self.clone();
-
+ fn spawn_preview_renderer(
+ self: Arc<Self>,
+ mut preview_rx: watch::Receiver<Option<PreviewFrameInstruction>>,
+ ) {
tokio::spawn(async move {
- this.rendering.store(true, Ordering::Relaxed);
-
- let Some(screen_frame) = this.screen_decoder.get_frame(frame_number).await else {
- return;
- };
-
- let camera_frame = match &this.camera_decoder {
- Some(d) => d.get_frame(frame_number).await,
- None => None,
- };
-
- this.renderer
- .render_frame(
- screen_frame,
- camera_frame,
- project.background.source.clone(),
- ProjectUniforms::new(&this.render_constants, &project),
- )
- .await;
-
- this.rendering.store(false, Ordering::Relaxed);
+ loop {
+ preview_rx.changed().await.ok();
+ let Some((frame_number, project)) = preview_rx.borrow().deref().clone() else {
+ continue;
+ };
+
+ let Some(screen_frame) = self.screen_decoder.get_frame(frame_number).await else {
+ return;
+ };
+
+ let camera_frame = match &self.camera_decoder {
+ Some(d) => d.get_frame(frame_number).await,
+ None => None,
+ };
+
+ self.renderer
+ .render_frame(
+ screen_frame,
+ camera_frame,
+ project.background.source.clone(),
+ ProjectUniforms::new(&self.render_constants, &project),
+ )
+ .await;
+ }
});
}
}
diff --git a/apps/desktop-solid/src-tauri/src/lib.rs b/apps/desktop-solid/src-tauri/src/lib.rs
index bef1f7979..7896152f5 100644
--- a/apps/desktop-solid/src-tauri/src/lib.rs
+++ b/apps/desktop-solid/src-tauri/src/lib.rs
@@ -403,7 +403,7 @@ impl EditorStateChanged {
}
#[derive(Clone)]
-struct AudioData {
+pub struct AudioData {
pub buffer: Arc<Vec<f64>>,
pub sample_rate: u32,
// pub channels: u18
@@ -981,22 +981,27 @@ pub async fn upsert_editor_instance(app: &AppHandle, video_id: String) -> Arc<Ed
}
async fn create_editor_instance_impl(app: &AppHandle, video_id: String) -> Arc<EditorInstance> {
- let instance = Arc::new(
- EditorInstance::new(app, video_id, {
- let app = app.clone();
- move |state| {
- EditorStateChanged::new(state).emit(&app).ok();
- }
- })
- .await,
- );
+ let instance = EditorInstance::new(recordings_path(app), video_id, {
+ let app = app.clone();
+ move |state| {
+ EditorStateChanged::new(state).emit(&app).ok();
+ }
+ })
+ .await;
RenderFrameEvent::listen_any(app, {
let instance = instance.clone();
move |e| {
- instance.try_render_frame(e.payload.frame_number, e.payload.project);
+ instance
+ .preview_tx
+ .send(Some((e.payload.frame_number, e.payload.project)))
+ .ok();
}
});
instance
}
+
+fn recordings_path(app: &AppHandle) -> PathBuf {
+ app.path().app_data_dir().unwrap().join("recordings")
+}
diff --git a/apps/desktop-solid/src-tauri/src/playback.rs b/apps/desktop-solid/src-tauri/src/playback.rs
index f5670b590..c3493871c 100644
--- a/apps/desktop-solid/src-tauri/src/playback.rs
+++ b/apps/desktop-solid/src-tauri/src/playback.rs
@@ -38,9 +38,6 @@ pub struct PlaybackHandle {
impl Playback {
pub async fn start(self) -> PlaybackHandle {
- let fps = 60.0;
- let duration = 10.0;
-
let (stop_tx, mut stop_rx) = watch::channel(false);
stop_rx.borrow_and_update();
@@ -68,7 +65,7 @@ impl Playback {
};
loop {
- if frame_number as f32 > fps * duration {
+ if frame_number as f32 > (FPS * DURATION) as f32 {
break;
};
@@ -94,7 +91,7 @@ impl Playback {
event_tx.send(PlaybackEvent::Frame(frame_number)).ok();
- tokio::time::sleep_until(start + Duration::from_secs_f32(1.0 / fps)).await;
+ tokio::time::sleep_until(start + Duration::from_secs_f32(1.0 / FPS as f32)).await;
frame_number += 1;
}
diff --git a/apps/desktop-solid/src/routes/editor/Editor.tsx b/apps/desktop-solid/src/routes/editor/Editor.tsx
index ac721e82b..462f80d37 100644
--- a/apps/desktop-solid/src/routes/editor/Editor.tsx
+++ b/apps/desktop-solid/src/routes/editor/Editor.tsx
@@ -120,7 +120,7 @@ function Inner() {
frame_number: Math.floor(time * 30),
project: state,
});
- }, 10);
+ }, 1000 / 60);
const frameNumberToRender = createMemo(() => {
const preview = previewTime();
@@ -700,6 +700,7 @@ function SettingsSidebar() {
onChange={(v) => setState("background", "padding", v[0])}
minValue={0}
maxValue={40}
+ step={0.1}
/>
</Field>
<Field name="Rounded Corners" icon={<IconCapCorners />}>
@@ -708,6 +709,7 @@ function SettingsSidebar() {
onChange={(v) => setState("background", "rounding", v[0])}
minValue={0}
maxValue={100}
+ step={0.1}
/>
</Field>
<Field name="Inset" icon={<IconCapInset />}>
@@ -784,6 +786,7 @@ function SettingsSidebar() {
onChange={(v) => setState("camera", "rounding", v[0])}
minValue={0}
maxValue={100}
+ step={0.1}
/>
</Field>
<Field name="Shadow" icon={<IconCapShadow />}>
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index f94479222..5a7b310f3 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -34,8 +34,8 @@ impl Default for BackgroundSource {
pub struct BackgroundConfiguration {
pub source: BackgroundSource,
pub blur: u32,
- pub padding: u32,
- pub rounding: u32,
+ pub padding: f32,
+ pub rounding: f32,
pub inset: u32,
}
@@ -69,7 +69,7 @@ pub struct CameraConfiguration {
pub hide: bool,
pub mirror: bool,
pub position: CameraPosition,
- pub rounding: u32,
+ pub rounding: f32,
pub shadow: u32,
}
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 87378a377..b69c6f4c0 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -17,3 +17,4 @@ tokio = { version = "1.39.3", features = ["macros", "sync", "rt", "rt-multi-thre
nix = { version = "0.29.0", features = ["fs"] }
serde_json = "1.0.127"
ffmpeg-next = "7.0.4"
+lru = "0.12.4"
diff --git a/crates/rendering/src/decoder.rs b/crates/rendering/src/decoder.rs
new file mode 100644
index 000000000..569d5622c
--- /dev/null
+++ b/crates/rendering/src/decoder.rs
@@ -0,0 +1,295 @@
+use std::{
+ num::NonZeroUsize,
+ path::PathBuf,
+ sync::{mpsc, Arc},
+ thread,
+};
+
+use ffmpeg_next::{frame, rescale, Rational, Rescale};
+use lru::LruCache;
+
+pub type DecodedFrame = Arc<Vec<u8>>;
+
+pub struct VideoDecoder {
+ input: ffmpeg_next::format::context::Input,
+ decoder: ffmpeg_next::codec::decoder::Video,
+ scaler: ffmpeg_next::software::scaling::context::Context,
+ input_stream_index: usize,
+ temp_frame: ffmpeg_next::frame::Video,
+ time_base: ffmpeg_next::Rational,
+ frame_rate: ffmpeg_next::Rational,
+ last_decoded_frame: Option<u32>,
+ frame_cache: LruCache<u32, DecodedFrame>,
+}
+
+impl VideoDecoder {
+ pub fn new(path: &PathBuf) -> Self {
+ println!("creating decoder for {}", path.display());
+ let ictx = ffmpeg_next::format::input(path).unwrap();
+
+ let input_stream = ictx
+ .streams()
+ .best(ffmpeg_next::media::Type::Video)
+ .ok_or("Could not find a video stream")
+ .unwrap();
+ let input_stream_index = input_stream.index();
+ let time_base = input_stream.time_base();
+ let frame_rate = input_stream.rate();
+
+ // Create a decoder for the video stream
+ let decoder =
+ ffmpeg_next::codec::context::Context::from_parameters(input_stream.parameters())
+ .unwrap()
+ .decoder()
+ .video()
+ .unwrap();
+
+ use ffmpeg_next::format::Pixel;
+ use ffmpeg_next::software::scaling::{context::Context, flag::Flags};
+
+ let scaler = Context::get(
+ decoder.format(),
+ decoder.width(),
+ decoder.height(),
+ Pixel::RGBA,
+ decoder.width(),
+ decoder.height(),
+ Flags::BILINEAR,
+ )
+ .unwrap();
+
+ Self {
+ input: ictx,
+ decoder,
+ scaler,
+ input_stream_index,
+ temp_frame: ffmpeg_next::frame::Video::empty(),
+ time_base,
+ frame_rate,
+ frame_cache: LruCache::new(NonZeroUsize::new(FRAME_CACHE_SIZE).unwrap()),
+ last_decoded_frame: None,
+ }
+ }
+
+ pub fn get_frame(&mut self, frame_number: u32) -> Option<DecodedFrame> {
+ if let Some(frame) = self.frame_cache.get(&frame_number) {
+ return Some(frame.clone());
+ }
+
+ if frame_number <= 0 || self.last_decoded_frame != Some(frame_number - 1) {
+ let timestamp_us =
+ ((frame_number as f32 / self.frame_rate.numerator() as f32) * 1_000_000.0) as i64;
+ let position = timestamp_us.rescale((1, 1_000_000), rescale::TIME_BASE);
+
+ println!("seeeking to {position} for frame {frame_number}");
+
+ self.decoder.flush();
+ self.input.seek(position, ..position).unwrap();
+ }
+
+ for (stream, packet) in self.input.packets() {
+ if stream.index() == self.input_stream_index {
+ let current_frame =
+ ts_to_frame(packet.pts().unwrap(), self.time_base, self.frame_rate);
+
+ self.decoder.send_packet(&packet).unwrap();
+
+ while self.decoder.receive_frame(&mut self.temp_frame).is_ok() {
+ // Convert the frame to RGB
+ let mut rgb_frame = frame::Video::empty();
+ self.scaler.run(&self.temp_frame, &mut rgb_frame).unwrap();
+
+ let frame = Arc::new(rgb_frame.data(0).to_vec());
+
+ self.last_decoded_frame = Some(current_frame);
+ self.frame_cache.put(current_frame, frame.clone());
+
+ if current_frame == frame_number {
+ return Some(frame);
+ }
+ }
+ }
+ }
+
+ None
+ }
+}
+
+enum VideoDecoderActorMessage {
+ GetFrame(u32, tokio::sync::oneshot::Sender<Option<Arc<Vec<u8>>>>),
+}
+
+#[derive(Clone)]
+pub struct VideoDecoderActor {
+ tx: mpsc::Sender<VideoDecoderActorMessage>,
+}
+
+impl VideoDecoderActor {
+ pub fn new(path: PathBuf) -> Self {
+ let (tx, rx) = mpsc::channel();
+
+ thread::spawn(move || {
+ let mut decoder = VideoDecoder::new(&path);
+
+ loop {
+ match rx.recv() {
+ Ok(VideoDecoderActorMessage::GetFrame(frame_number, sender)) => {
+ let frame = decoder.get_frame(frame_number);
+ sender.send(frame).ok();
+ }
+ Err(_) => break,
+ }
+ }
+ });
+
+ Self { tx }
+ }
+
+ pub async fn get_frame(&self, frame_number: u32) -> Option<Arc<Vec<u8>>> {
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ self.tx
+ .send(VideoDecoderActorMessage::GetFrame(frame_number, tx))
+ .unwrap();
+ rx.await.unwrap()
+ }
+}
+
+fn ts_to_frame(ts: i64, time_base: Rational, frame_rate: Rational) -> u32 {
+ // dbg!((ts, time_base, frame_rate));
+ ((ts * time_base.numerator() as i64 * frame_rate.numerator() as i64)
+ / (time_base.denominator() as i64 * frame_rate.denominator() as i64)) as u32
+}
+
+const FRAME_CACHE_SIZE: usize = 50;
+
+fn async_video_decoder(
+ path: PathBuf,
+ requests: std::sync::mpsc::Receiver<VideoDecoderActorMessage>,
+) {
+ std::thread::spawn(move || {
+ let mut input = ffmpeg_next::format::input(&path).unwrap();
+
+ let input_stream = input
+ .streams()
+ .best(ffmpeg_next::media::Type::Video)
+ .ok_or("Could not find a video stream")
+ .unwrap();
+ let input_stream_index = input_stream.index();
+ let time_base = input_stream.time_base();
+ let frame_rate = input_stream.rate();
+
+ // Create a decoder for the video stream
+ let mut decoder =
+ ffmpeg_next::codec::context::Context::from_parameters(input_stream.parameters())
+ .unwrap()
+ .decoder()
+ .video()
+ .unwrap();
+
+ use ffmpeg_next::format::Pixel;
+ use ffmpeg_next::software::scaling::{context::Context, flag::Flags};
+
+ let mut scaler = Context::get(
+ decoder.format(),
+ decoder.width(),
+ decoder.height(),
+ Pixel::RGBA,
+ decoder.width(),
+ decoder.height(),
+ Flags::BILINEAR,
+ )
+ .unwrap();
+
+ let mut temp_frame = ffmpeg_next::frame::Video::empty();
+
+ let mut frame_cache =
+ LruCache::<u32, Arc<Vec<u8>>>::new(NonZeroUsize::new(FRAME_CACHE_SIZE).unwrap());
+
+ let mut peekable_requests = PeekableReceiver {
+ rx: requests,
+ peeked: None,
+ };
+
+ while let Ok(r) = peekable_requests.recv() {
+ match r {
+ VideoDecoderActorMessage::GetFrame(frame_number, sender) => {
+ if let Some(frame) = frame_cache.get(&frame_number) {
+ sender.send(Some(frame.clone())).ok();
+ continue;
+ }
+
+ let mut sender = Some(sender);
+
+ for (stream, packet) in input.packets() {
+ if peekable_requests.peek().is_some() {
+ break;
+ }
+
+ if stream.index() == input_stream_index {
+ let current_frame =
+ ts_to_frame(packet.pts().unwrap(), time_base, frame_rate);
+
+ decoder.send_packet(&packet).unwrap();
+
+ if current_frame - frame_number >= FRAME_CACHE_SIZE as u32 / 2 {
+ break;
+ }
+
+ while decoder.receive_frame(&mut temp_frame).is_ok() {
+ let mut rgb_frame = frame::Video::empty();
+ scaler.run(&temp_frame, &mut rgb_frame).unwrap();
+
+ let frame = Arc::new(rgb_frame.data(0).to_vec());
+
+ frame_cache.put(current_frame, frame.clone());
+
+ if current_frame == frame_number {
+ if let Some(sender) = sender.take() {
+ sender.send(Some(frame)).ok();
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ });
+}
+
+struct PeekableReceiver<T> {
+ rx: mpsc::Receiver<T>,
+ peeked: Option<T>,
+}
+
+impl<T> PeekableReceiver<T> {
+ fn peek(&mut self) -> Option<&T> {
+ if self.peeked.is_some() {
+ self.peeked.as_ref()
+ } else {
+ match self.rx.try_recv() {
+ Ok(value) => {
+ self.peeked = Some(value);
+ self.peeked.as_ref()
+ }
+ Err(_) => None,
+ }
+ }
+ }
+
+ fn try_recv(&mut self) -> Result<T, mpsc::TryRecvError> {
+ if let Some(value) = self.peeked.take() {
+ Ok(value)
+ } else {
+ self.rx.try_recv()
+ }
+ }
+
+ fn recv(&mut self) -> Result<T, mpsc::RecvError> {
+ if let Some(value) = self.peeked.take() {
+ Ok(value)
+ } else {
+ self.rx.recv()
+ }
+ }
+}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 0be534f4d..69abfb1e6 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1,13 +1,9 @@
use anyhow::Result;
use bytemuck::{Pod, Zeroable};
-use ffmpeg_next::{frame, rescale, Rational, Rescale};
use futures_intrusive::channel::shared::oneshot_channel;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
-use std::path::PathBuf;
-use std::sync::mpsc::{channel, Sender};
-use std::thread;
use wgpu::util::DeviceExt;
use wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
@@ -15,6 +11,9 @@ use cap_project::{BackgroundSource, CameraXPosition, CameraYPosition, ProjectCon
use std::time::Instant;
+pub mod decoder;
+pub use decoder::{DecodedFrame, VideoDecoderActor};
+
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct RenderOptions {
pub camera_size: Option<(u32, u32)>,
@@ -129,7 +128,8 @@ pub async fn render_video_to_channel(
ffmpeg_next::init().unwrap();
- let (screen_tx, mut screen_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
+ let (screen_tx, mut screen_rx) =
+ tokio::sync::mpsc::unbounded_channel::<decoder::DecodedFrame>();
tokio::spawn(async move {
let now = Instant::now();
@@ -156,7 +156,7 @@ pub async fn render_video_to_channel(
let mut camera_rx = camera_recording_decoder.map(|camera_recording_decoder| {
println!("Setting up FFmpeg input for webcam recording...");
- let (camera_tx, camera_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
+ let (camera_tx, camera_rx) = tokio::sync::mpsc::unbounded_channel();
tokio::spawn(async move {
let now = Instant::now();
@@ -204,7 +204,7 @@ pub async fn render_video_to_channel(
let frame = match produce_frame(
&constants,
&screen_frame,
- camera_frame.as_ref(),
+ &camera_frame,
background,
&uniforms,
)
@@ -256,8 +256,8 @@ pub struct RenderVideoConstants {
pub queue: wgpu::Queue,
pub device: wgpu::Device,
pub options: RenderOptions,
- pub composite_video_frame_pipeline: CompositeVideoFramePipeline,
- pub gradient_or_color_pipeline: GradientOrColorPipeline,
+ composite_video_frame_pipeline: CompositeVideoFramePipeline,
+ gradient_or_color_pipeline: GradientOrColorPipeline,
pub output_texture: wgpu::Texture,
pub output_texture_view: wgpu::TextureView,
pub output_texture_size: wgpu::Extent3d,
@@ -454,7 +454,7 @@ pub async fn produce_frame(
..
}: &RenderVideoConstants,
screen_frame: &Vec<u8>,
- camera_frame: Option<&Vec<u8>>,
+ camera_frame: &Option<DecodedFrame>,
background: Background,
uniforms: &ProjectUniforms,
) -> Result<Vec<u8>, String> {
@@ -1077,162 +1077,6 @@ fn srgb_to_linear(c: u16) -> f32 {
}
}
-struct VideoDecoder {
- input: ffmpeg_next::format::context::Input,
- decoder: ffmpeg_next::codec::decoder::Video,
- scaler: ffmpeg_next::software::scaling::context::Context,
- input_stream_index: usize,
- temp_frame: ffmpeg_next::frame::Video,
- time_base: ffmpeg_next::Rational,
- frame_rate: ffmpeg_next::Rational,
- last_frame: Option<(u32, Vec<u8>)>,
- // cached_frames: HashMap<u32, Vec<u8>>,
-}
-
-impl VideoDecoder {
- fn new(path: &PathBuf) -> Self {
- println!("creating decoder for {}", path.display());
- let ictx = ffmpeg_next::format::input(path).unwrap();
-
- let input_stream = ictx
- .streams()
- .best(ffmpeg_next::media::Type::Video)
- .ok_or("Could not find a video stream")
- .unwrap();
- let input_stream_index = input_stream.index();
- let time_base = input_stream.time_base();
- let frame_rate = input_stream.rate();
-
- // Create a decoder for the video stream
- let decoder =
- ffmpeg_next::codec::context::Context::from_parameters(input_stream.parameters())
- .unwrap()
- .decoder()
- .video()
- .unwrap();
-
- use ffmpeg_next::format::Pixel;
- use ffmpeg_next::software::scaling::{context::Context, flag::Flags};
-
- let scaler = Context::get(
- decoder.format(),
- decoder.width(),
- decoder.height(),
- Pixel::RGBA,
- decoder.width(),
- decoder.height(),
- Flags::BILINEAR,
- )
- .unwrap();
-
- Self {
- input: ictx,
- decoder,
- scaler,
- input_stream_index,
- temp_frame: ffmpeg_next::frame::Video::empty(),
- time_base,
- frame_rate,
- last_frame: None,
- // cached_frames: Default::default(),
- }
- }
-
- // TODO: optimisations
- // - cache frames
- // - cache I frame positions to know whether seeking is actually necessary when going backwards
- fn get_frame(&mut self, frame_number: u32) -> Option<Vec<u8>> {
- if let Some((last_frame_number, frame)) = &self.last_frame {
- if *last_frame_number == frame_number {
- return Some(frame.clone());
- }
- }
-
- if self.last_frame.is_some()
- && (frame_number <= 0 || frame_number <= self.last_frame.as_ref().unwrap().0)
- {
- let timestamp_us =
- ((frame_number as f32 / self.frame_rate.numerator() as f32) * 1_000_000.0) as i64;
- let position = timestamp_us.rescale((1, 1_000_000), rescale::TIME_BASE);
-
- println!("seeeking to {position} for frame {frame_number}");
-
- self.decoder.flush();
- self.input.seek(position, ..position).unwrap();
- }
-
- for (stream, packet) in self.input.packets() {
- if stream.index() == self.input_stream_index {
- let current_frame =
- ts_to_frame(packet.pts().unwrap(), self.time_base, self.frame_rate);
-
- self.decoder.send_packet(&packet).unwrap();
-
- while self.decoder.receive_frame(&mut self.temp_frame).is_ok() {
- // Convert the frame to RGB
- let mut rgb_frame = frame::Video::empty();
- self.scaler.run(&self.temp_frame, &mut rgb_frame).unwrap();
-
- let frame = rgb_frame.data(0).to_vec();
-
- self.last_frame = Some((current_frame, frame.clone()));
-
- if current_frame == frame_number {
- return Some(frame);
- }
- }
- }
- }
-
- None
- }
-}
-
-enum VideoDecoderActorMessage {
- GetFrame(u32, tokio::sync::oneshot::Sender<Option<Vec<u8>>>),
-}
-
-#[derive(Clone)]
-pub struct VideoDecoderActor {
- tx: Sender<VideoDecoderActorMessage>,
-}
-
-impl VideoDecoderActor {
- pub fn new(path: PathBuf) -> Self {
- let (tx, rx) = channel();
-
- thread::spawn(move || {
- let mut decoder = VideoDecoder::new(&path);
-
- loop {
- match rx.recv() {
- Ok(VideoDecoderActorMessage::GetFrame(frame_number, sender)) => {
- let frame = decoder.get_frame(frame_number);
- sender.send(frame).ok();
- }
- Err(_) => break,
- }
- }
- });
-
- Self { tx }
- }
-
- pub async fn get_frame(&self, frame_number: u32) -> Option<Vec<u8>> {
- let (tx, rx) = tokio::sync::oneshot::channel();
- self.tx
- .send(VideoDecoderActorMessage::GetFrame(frame_number, tx))
- .unwrap();
- rx.await.unwrap()
- }
-}
-
-fn ts_to_frame(ts: i64, time_base: Rational, frame_rate: Rational) -> u32 {
- // dbg!((ts, time_base, frame_rate));
- ((ts * time_base.numerator() as i64 * frame_rate.numerator() as i64)
- / (time_base.denominator() as i64 * frame_rate.denominator() as i64)) as u32
-}
-
fn get_either<T>((a, b): (T, T), left: bool) -> T {
if left {
a