Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Merge upstream branch main into ft/structured-logging-on-desktop

PJd31f774b984d
diff --cc apps/desktop/src-tauri/src/main.rs
index 0e0117af7,6cac81597..49985c91e
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@@ -1,23 -1,22 +1,26 @@@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
- use std::collections::LinkedList;
- use std::sync::{Arc};
- use std::path::PathBuf;
use cpal::Devices;
use regex::Regex;
- use tokio::sync::Mutex;
- use std::sync::atomic::{AtomicBool};
- use std::{vec};
- use tauri::{CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTraySubmenu, Window};
- use window_vibrancy::{apply_blur, apply_vibrancy, NSVisualEffectMaterial};
- use window_shadows::set_shadow;
- use tauri_plugin_positioner::{WindowExt, Position};
++use sentry_tracing::EventFilter;
+ use std::collections::LinkedList;
+ use std::path::PathBuf;
+ use std::sync::atomic::AtomicBool;
+ use std::sync::Arc;
+ use std::vec;
+ use tauri::{
+ CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTraySubmenu, Window,
+ };
use tauri_plugin_oauth::start;
+ use tauri_plugin_positioner::{Position, WindowExt};
+ use tokio::sync::Mutex;
+use tracing::Level;
+use tracing_subscriber::prelude::*;
- use sentry_tracing::EventFilter;
+ use window_shadows::set_shadow;
+ use window_vibrancy::{apply_blur, apply_vibrancy, NSVisualEffectMaterial};
+mod app;
+ mod media;
mod recording;
mod upload;
mod utils;
diff --cc apps/desktop/src-tauri/src/media.rs
index f600a8c80,0f1ff1ce0..87f9c001c
--- a/apps/desktop/src-tauri/src/media.rs
+++ b/apps/desktop/src-tauri/src/media.rs
@@@ -1,24 -1,24 +1,25 @@@
- use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
+ use byteorder::{ ByteOrder, LittleEndian };
+ use cpal::traits::{ DeviceTrait, HostTrait, StreamTrait };
use cpal::SampleFormat;
- use std::process::{Stdio};
- use byteorder::{ByteOrder, LittleEndian};
- use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
- use std::io::{ErrorKind::WouldBlock, Error};
- use std::time::{Instant, Duration};
- use std::path::Path;
- use image::{ImageBuffer, Rgba, ImageFormat};
use image::codecs::jpeg::JpegEncoder;
-
- use tokio::io::{AsyncWriteExt};
- use tokio::process::{Command, Child, ChildStdin};
- use tokio::sync::{mpsc, Mutex};
+ use image::{ ImageBuffer, ImageFormat, Rgba };
+ use std::io::{ Error, ErrorKind::WouldBlock };
+ use std::path::{ Path, PathBuf };
+ use std::process::Stdio;
+ use std::sync::{ atomic::{ AtomicBool, Ordering }, Arc };
+ use std::time::{ Duration, Instant };
+ use tokio::fs::File;
+
+ use tokio::io::AsyncWriteExt;
+ use tokio::process::{ Child, ChildStdin, Command };
+ use tokio::sync::{ mpsc, Mutex };
use tokio::try_join;
+use crate::app::config;
use crate::recording::RecordingOptions;
- use crate::utils::{ffmpeg_path_as_str};
- use crate::upload::upload_file;
- use capture::{Capturer, Display};
+ use crate::upload::{ self, upload_file };
+ use crate::utils::{ create_named_pipe, ffmpeg_path_as_str };
+ use capture::{ Capturer, Display };
const FRAME_RATE: u64 = 30;
@@@ -62,11 -57,19 +58,20 @@@ impl MediaRecorder
}
}
+ #[tracing::instrument(skip(self))]
- pub async fn start_media_recording(&mut self, options: RecordingOptions, audio_file_path: &str, video_file_path: &str, screenshot_file_path: &str, custom_device: Option<&str>, max_screen_width: usize, max_screen_height: usize) -> Result<(), String> {
+ pub async fn start_media_recording(
+ &mut self,
+ options: RecordingOptions,
+ screenshot_dir: &Path,
+ audio_chunks_dir: &Path,
+ video_chunks_dir: &Path,
+ custom_device: Option<&str>,
+ max_screen_width: usize,
+ max_screen_height: usize
+ ) -> Result<(), String> {
self.options = Some(options.clone());
- println!("Custom device: {:?}", custom_device);
+ tracing::debug!("Custom device: {:?}", custom_device);
let host = cpal::default_host();
let devices = host.devices().expect("Failed to get devices");
@@@ -123,14 -131,24 +133,24 @@@
host.default_input_device().expect("No default input device available")
};
- println!("Using audio device: {}", device.name().expect("Failed to get device name"));
+ tracing::info!("Using audio device: {}", device.name().expect("Failed to get device name"));
- let config = device.supported_input_configs()
+ let config = device
+ .supported_input_configs()
.expect("Failed to get supported input configs")
- .find(|c| c.sample_format() == SampleFormat::F32 || c.sample_format() == SampleFormat::I16 || c.sample_format() == SampleFormat::I8 || c.sample_format() == SampleFormat::I32)
- .unwrap_or_else(||
- device.supported_input_configs().expect("Failed to get supported input configs").next().expect("No supported input config")
- )
+ .find(|c| {
+ c.sample_format() == SampleFormat::F32 ||
+ c.sample_format() == SampleFormat::I16 ||
+ c.sample_format() == SampleFormat::I8 ||
+ c.sample_format() == SampleFormat::I32
+ })
+ .unwrap_or_else(|| {
+ device
+ .supported_input_configs()
+ .expect("Failed to get supported input configs")
+ .next()
+ .expect("No supported input config")
+ })
.with_max_sample_rate();
let sample_rate = config.sample_rate().0;
@@@ -149,132 -167,138 +169,138 @@@
let ffmpeg_binary_path_str = ffmpeg_path_as_str().unwrap().to_owned();
- println!("FFmpeg binary path: {}", ffmpeg_binary_path_str);
+ tracing::debug!("FFmpeg binary path: {}", ffmpeg_binary_path_str);
- let audio_file_path_owned = audio_file_path.to_owned();
- let video_file_path_owned = video_file_path.to_owned();
let sample_rate_str = sample_rate.to_string();
let channels_str = channels.to_string();
- let ffmpeg_audio_stdin = self.ffmpeg_audio_stdin.clone();
- let ffmpeg_video_stdin = self.ffmpeg_video_stdin.clone();
-
let err_fn = move |err| {
- eprintln!("an error occurred on stream: {}", err);
+ tracing::error!("an error occurred on stream: {}", err);
};
- if custom_device != Some("None") {
+ let needs_audio = custom_device != Some("None");
+
+ if needs_audio {
- println!("Building input stream...");
+ tracing::trace!("Building input stream...");
- let stream_result: Result<cpal::Stream, cpal::BuildStreamError> = match config.sample_format() {
- SampleFormat::I8 => device.build_input_stream(
- &config.into(),
- {
- let audio_start_time = Arc::clone(&audio_start_time);
- move |data: &[i8], _: &_| {
- let mut first_frame_time_guard = audio_start_time.try_lock();
-
- let bytes = data.iter().map(|&sample| sample as u8).collect::<Vec<u8>>();
- if let Some(sender) = &audio_channel_sender {
- if sender.try_send(bytes).is_err() {
- tracing::warn!("Channel send error. Dropping data.");
+ let stream_result: Result<cpal::Stream, cpal::BuildStreamError> = match
+ config.sample_format()
+ {
+ SampleFormat::I8 =>
+ device.build_input_stream(
+ &config.into(),
+ {
+ let audio_start_time = Arc::clone(&audio_start_time);
+ move |data: &[i8], _: &_| {
+ let mut first_frame_time_guard = audio_start_time.try_lock();
+
+ let bytes = data
+ .iter()
+ .map(|&sample| sample as u8)
+ .collect::<Vec<u8>>();
+ if let Some(sender) = &audio_channel_sender {
+ if sender.try_send(bytes).is_err() {
- eprintln!("Channel send error. Dropping data.");
++ tracing::warn!("Channel send error. Dropping data.");
+ }
+ }
+
+ if let Ok(ref mut start_time_option) = first_frame_time_guard {
+ if start_time_option.is_none() {
+ **start_time_option = Some(Instant::now());
+
- println!("Audio start time captured");
++ tracing::trace!("Audio start time captured");
+ }
+ }
}
- }
-
- if let Ok(ref mut start_time_option) = first_frame_time_guard {
- if start_time_option.is_none() {
- **start_time_option = Some(Instant::now());
-
- tracing::trace!("Audio start time captured");
- }
- }
- }
- },
- err_fn,
- None,
- ),
- SampleFormat::I16 => device.build_input_stream(
- &config.into(),
- {
- let audio_start_time = Arc::clone(&audio_start_time);
- move |data: &[i16], _: &_| {
- let mut first_frame_time_guard = audio_start_time.try_lock();
-
- let mut bytes = vec![0; data.len() * 2];
- LittleEndian::write_i16_into(data, &mut bytes);
- if let Some(sender) = &audio_channel_sender {
- if sender.try_send(bytes).is_err() {
- tracing::warn!("Channel send error. Dropping data.");
- }
- }
-
- if let Ok(ref mut start_time_option) = first_frame_time_guard {
- if start_time_option.is_none() {
- **start_time_option = Some(Instant::now());
-
- tracing::trace!("Audio start time captured");
- }
- }
- }
- },
- err_fn,
- None,
- ),
- SampleFormat::I32 => device.build_input_stream(
- &config.into(),
- {
- let audio_start_time = Arc::clone(&audio_start_time);
- move |data: &[i32], _: &_| {
- let mut first_frame_time_guard = audio_start_time.try_lock();
-
- let mut bytes = vec![0; data.len() * 2];
- LittleEndian::write_i32_into(data, &mut bytes);
- if let Some(sender) = &audio_channel_sender {
- if sender.try_send(bytes).is_err() {
- tracing::warn!("Channel send error. Dropping data.");
- }
- }
-
- if let Ok(ref mut start_time_option) = first_frame_time_guard {
- if start_time_option.is_none() {
- **start_time_option = Some(Instant::now());
-
- tracing::trace!("Audio start time captured");
- }
- }
- }
- },
- err_fn,
- None,
- ),
- SampleFormat::F32 => device.build_input_stream(
- &config.into(),
- {
- let audio_start_time = Arc::clone(&audio_start_time);
- move |data: &[f32], _: &_| {
- let mut first_frame_time_guard = audio_start_time.try_lock();
-
- let mut bytes = vec![0; data.len() * 4];
- LittleEndian::write_f32_into(data, &mut bytes);
- if let Some(sender) = &audio_channel_sender {
- if sender.try_send(bytes).is_err() {
- tracing::warn!("Channel send error. Dropping data.");
- }
- }
-
- if let Ok(ref mut start_time_option) = first_frame_time_guard {
- if start_time_option.is_none() {
- **start_time_option = Some(Instant::now());
-
- tracing::trace!("Audio start time captured");
- }
- }
- }
- },
- err_fn,
- None,
- ),
- _sample_format => Err(cpal::BuildStreamError::DeviceNotAvailable),
+ },
+ err_fn,
+ None
+ ),
+ SampleFormat::I16 =>
+ device.build_input_stream(
+ &config.into(),
+ {
+ let audio_start_time = Arc::clone(&audio_start_time);
+ move |data: &[i16], _: &_| {
+ let mut first_frame_time_guard = audio_start_time.try_lock();
+
+ let mut bytes = vec![0; data.len() * 2];
+ LittleEndian::write_i16_into(data, &mut bytes);
+ if let Some(sender) = &audio_channel_sender {
+ if sender.try_send(bytes).is_err() {
- eprintln!("Channel send error. Dropping data.");
++ tracing::warn!("Channel send error. Dropping data.");
+ }
+ }
+
+ if let Ok(ref mut start_time_option) = first_frame_time_guard {
+ if start_time_option.is_none() {
+ **start_time_option = Some(Instant::now());
+
- println!("Audio start time captured");
++ tracing::trace!("Audio start time captured");
+ }
+ }
+ }
+ },
+ err_fn,
+ None
+ ),
+ SampleFormat::I32 =>
+ device.build_input_stream(
+ &config.into(),
+ {
+ let audio_start_time = Arc::clone(&audio_start_time);
+ move |data: &[i32], _: &_| {
+ let mut first_frame_time_guard = audio_start_time.try_lock();
+
+ let mut bytes = vec![0; data.len() * 2];
+ LittleEndian::write_i32_into(data, &mut bytes);
+ if let Some(sender) = &audio_channel_sender {
+ if sender.try_send(bytes).is_err() {
- eprintln!("Channel send error. Dropping data.");
++ tracing::warn!("Channel send error. Dropping data.");
+ }
+ }
+
+ if let Ok(ref mut start_time_option) = first_frame_time_guard {
+ if start_time_option.is_none() {
+ **start_time_option = Some(Instant::now());
+
- println!("Audio start time captured");
++ tracing::trace!("Audio start time captured");
+ }
+ }
+ }
+ },
+ err_fn,
+ None
+ ),
+ SampleFormat::F32 =>
+ device.build_input_stream(
+ &config.into(),
+ {
+ let audio_start_time = Arc::clone(&audio_start_time);
+ move |data: &[f32], _: &_| {
+ let mut first_frame_time_guard = audio_start_time.try_lock();
+
+ let mut bytes = vec![0; data.len() * 4];
+ LittleEndian::write_f32_into(data, &mut bytes);
+ if let Some(sender) = &audio_channel_sender {
+ if sender.try_send(bytes).is_err() {
- eprintln!("Channel send error. Dropping data.");
++ tracing::warn!("Channel send error. Dropping data.");
+ }
+ }
+
+ if let Ok(ref mut start_time_option) = first_frame_time_guard {
+ if start_time_option.is_none() {
+ **start_time_option = Some(Instant::now());
+
- println!("Audio start time captured");
++ tracing::trace!("Audio start time captured");
+ }
+ }
+ }
+ },
+ err_fn,
+ None
+ ),
+ _sample_format => Err(cpal::BuildStreamError::DeviceNotAvailable),
};
let stream = stream_result.map_err(|_| "Failed to build input stream")?;
@@@ -287,11 -311,18 +313,15 @@@
let capture_frame_at = Duration::from_secs(3);
std::thread::spawn(move || {
- println!("Starting video recording capture thread...");
+ tracing::trace!("Starting video recording capture thread...");
- let is_local_mode = match dotenv_codegen::dotenv!("NEXT_PUBLIC_LOCAL_MODE") {
- "true" => true,
- _ => false,
- };
+ let is_local_mode = config::is_local_mode();
- let mut capturer = Capturer::new(Display::primary().expect("Failed to find primary display"), w.try_into().unwrap(), h.try_into().unwrap()).expect("Failed to start capture");
+ let mut capturer = Capturer::new(
+ Display::primary().expect("Failed to find primary display"),
+ w.try_into().unwrap(),
+ h.try_into().unwrap()
+ ).expect("Failed to start capture");
let fps = FRAME_RATE;
let spf = Duration::from_nanos(1_000_000_000 / fps);
@@@ -337,25 -377,46 +376,46 @@@
frame_data_clone
).expect("Failed to create image buffer");
- let mut output_file = std::fs::File::create(&path).expect("Failed to create output file");
- let mut encoder = JpegEncoder::new_with_quality(&mut output_file, 20);
+ let mut output_file = std::fs::File
+ ::create(&screenshot_file_path)
+ .expect("Failed to create output file");
+ let mut encoder = JpegEncoder::new_with_quality(
+ &mut output_file,
+ 20
+ );
if let Err(e) = encoder.encode_image(&image) {
- eprintln!("Failed to save screenshot: {}", e);
+ tracing::warn!("Failed to save screenshot: {}", e);
} else {
+ println!(
+ "Screenshot captured and saved to {:?}",
+ screenshot_file_path
+ );
+
if !is_local_mode {
let rt = tokio::runtime::Runtime::new().unwrap();
- let screenshot_file_path_owned_cloned_copy = screenshot_file_path_owned_cloned.clone();
- rt.block_on(async {
- let upload_task = tokio::spawn(upload_file(Some(options_clone), screenshot_file_path_owned_cloned_copy.clone(), "screenshot".to_string()));
+ rt.block_on(async move {
+ let upload_task = tokio::spawn(
+ upload_file(
+ Some(options_clone),
+ screenshot_file_path.clone(),
+ upload::FileType::Screenshot
+ )
+ );
match upload_task.await {
- Ok(result) => {
+ Ok(result) =>
match result {
- Ok(_) => tracing::info!("Screenshot captured and saved to {:?}", path),
- Err(e) => tracing::warn!("Failed to upload file: {}", e),
+ Ok(_) =>
- println!(
++ tracing::info!(
+ "Screenshot captured and saved to {:?}",
+ screenshot_file_path
+ ),
+ Err(e) =>
- eprintln!("Failed to upload file: {}", e),
++ tracing::warn!("Failed to upload file: {}", e),
}
- },
- Err(e) => tracing::error!("Failed to join task: {}", e),
+ Err(e) => {
- eprintln!("Failed to join task: {}", e)
++ tracing::error!("Failed to join task: {}", e)
+ }
}
});
}
@@@ -385,11 -445,11 +444,11 @@@
Err(error) if error.kind() == WouldBlock => {
std::thread::sleep(Duration::from_millis(1));
continue;
- },
+ }
Err(error) => {
- eprintln!("Capture error: {}", error);
+ tracing::error!("Capture error: {}", error);
break;
- },
+ }
}
time_next += spf;
@@@ -403,15 -463,15 +462,15 @@@
}
let elapsed_total_time = start_time.elapsed();
- let fps = frame_count as f64 / elapsed_total_time.as_secs_f64();
+ let fps = (frame_count as f64) / elapsed_total_time.as_secs_f64();
- println!("Current FPS: {}", fps);
+ tracing::trace!("Current FPS: {}", fps);
});
- println!("Starting audio recording and processing...");
+ tracing::info!("Starting audio recording and processing...");
- let audio_output_chunk_pattern = format!("{}/audio_recording_%03d.aac", audio_file_path_owned);
- let audio_segment_list_filename = format!("{}/segment_list.txt", audio_file_path_owned);
- let video_output_chunk_pattern = format!("{}/video_recording_%03d.ts", video_file_path_owned);
- let video_segment_list_filename = format!("{}/segment_list.txt", video_file_path_owned);
+ let audio_chunk_pattern = audio_chunks_dir.join("audio_recording_%03d.aac");
+ let video_chunk_pattern = video_chunks_dir.join("video_recording_%03d.ts");
+ let audio_segment_list_filename = audio_chunks_dir.join("segment_list.txt");
+ let video_segment_list_filename = video_chunks_dir.join("segment_list.txt");
let mut audio_filters = Vec::new();
@@@ -421,134 -481,132 +480,132 @@@
audio_filters.push("loudnorm");
- let mut ffmpeg_audio_command: Vec<String> = vec![
- "-f", sample_format,
- "-ar", &sample_rate_str,
- "-ac", &channels_str,
- "-thread_queue_size", "4096",
- "-i", "pipe:0",
- "-af", "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
- "-c:a", "aac",
- "-b:a", "128k",
- "-async", "1",
- "-f", "segment",
- "-segment_time", "3",
- "-segment_time_delta", "0.01",
- "-segment_list", &audio_segment_list_filename,
- "-reset_timestamps", "1",
- &audio_output_chunk_pattern,
- ].into_iter().map(|s| s.to_string()).collect();
-
- let mut ffmpeg_video_command: Vec<String> = vec![
- "-f", "rawvideo",
- "-pix_fmt", "bgra",
- "-s", &format!("{}x{}", adjusted_width, adjusted_height),
- "-r", "30",
- "-thread_queue_size", "4096",
- "-i", "pipe:0",
- "-vf", "fps=30,scale=in_range=full:out_range=limited",
- "-c:v", "libx264",
- "-preset", "ultrafast",
- "-pix_fmt", "yuv420p",
- "-tune", "zerolatency",
- "-vsync", "1",
- "-force_key_frames", "expr:gte(t,n_forced*3)",
- "-f", "segment",
- "-segment_time", "3",
- "-segment_time_delta", "0.01",
- "-segment_list", &video_segment_list_filename,
- "-segment_format", "ts",
- "-movflags", "frag_keyframe+empty_moov",
- "-reset_timestamps", "1",
- &video_output_chunk_pattern,
- ].into_iter().map(|s| s.to_string()).collect();
-
- if custom_device != Some("None") {
+ let video_pipe_path = video_chunks_dir.join("pipe.pipe");
+
+ std::fs::remove_file(&video_pipe_path).ok();
+ create_named_pipe(&video_pipe_path).map_err(|e| e.to_string())?;
+
+ let audio_pipe_path = audio_chunks_dir.join("pipe.pipe");
+
+ std::fs::remove_file(&audio_pipe_path).ok();
+ create_named_pipe(&audio_pipe_path).map_err(|e| e.to_string())?;
+
+ let time_offset = if needs_audio {
- println!("Adjusting FFmpeg commands based on start times...");
+ tracing::trace!("Adjusting FFmpeg commands based on start times...");
- adjust_ffmpeg_commands_based_on_start_times(
- Arc::clone(&audio_start_time),
- Arc::clone(&video_start_time),
- &mut ffmpeg_audio_command,
- &mut ffmpeg_video_command,
- ).await;
- }
+ create_time_offset_args(&audio_start_time, &video_start_time).await
+ } else {
+ None
+ };
- tracing::trace!("Starting FFmpeg audio and video processes...");
+ let size = format!("{}x{}", adjusted_width, adjusted_height);
- let mut audio_stdin: Option<ChildStdin> = None;
- let mut audio_child: Option<Child> = None;
+ let mut ffmpeg_command = Command::new(ffmpeg_binary_path_str);
- if custom_device != Some("None") {
- let (child, stdin) = self.start_audio_ffmpeg_processes(&ffmpeg_binary_path_str, &ffmpeg_audio_command).await.map_err(|e| e.to_string())?;
- audio_child = Some(child);
- audio_stdin = Some(stdin);
- tracing::trace!("Audio process started");
+ if let Some((TimeOffsetTarget::Video, args)) = &time_offset {
+ ffmpeg_command.args(args);
}
- let (video_child, video_stdin) = self.start_video_ffmpeg_processes(&ffmpeg_binary_path_str, &ffmpeg_video_command).await.map_err(|e| e.to_string())?;
- tracing::trace!("Video process started");
+ ffmpeg_command
+ // video in
+ .args(["-f", "rawvideo", "-pix_fmt", "bgra"])
+ .args(["-s", &size, "-r", "30"])
+ .args(["-thread_queue_size", "4096", "-i"])
+ .arg(&video_pipe_path)
+ // video out
+ .args(["-vf", "fps=30,scale=in_range=full:out_range=limited"])
+ .args(["-c:v", "libx264", "-preset", "ultrafast"])
+ .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
+ .args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
+ .args(["-f", "segment", "-movflags", "frag_keyframe+empty_moov"])
+ .args(["-reset_timestamps", "1", "-an"])
+ .args(["-segment_time", "3"])
+ .args(["-segment_format", "ts"])
+ .args(["-segment_time_delta", "0.01", "-segment_list"])
+ .args([&video_segment_list_filename, &video_chunk_pattern]);
+
+ if needs_audio {
+ if let Some((TimeOffsetTarget::Audio, args)) = &time_offset {
+ ffmpeg_command.args(args);
+ }
- if let Some(ffmpeg_audio_stdin) = &self.ffmpeg_audio_stdin {
- let mut audio_stdin_lock = ffmpeg_audio_stdin.lock().await;
- *audio_stdin_lock = audio_stdin;
- drop(audio_stdin_lock);
- tracing::trace!("Audio stdin set");
+ ffmpeg_command
+ // audio in
+ .args(["-f", sample_format, "-ar", &sample_rate_str])
+ .args(["-ac", &channels_str, "-thread_queue_size", "4096", "-i"])
+ .arg(&audio_pipe_path)
+ // out
+ .args(["-af", "aresample=async=1:min_hard_comp=0.100000:first_pts=0"])
+ .args(["-codec:a", "aac", "-b:a", "128k"])
+ .args(["-async", "1", "-f", "segment"])
+ .args(["-segment_time", "3", "-segment_time_delta", "0.01"])
+ .args(["-reset_timestamps", "1", "-vn", "-segment_list"])
+ .args([&audio_segment_list_filename, &audio_chunk_pattern]);
}
- if let Some(ffmpeg_video_stdin) = &self.ffmpeg_video_stdin {
- let mut video_stdin_lock = ffmpeg_video_stdin.lock().await;
- *video_stdin_lock = Some(video_stdin);
- drop(video_stdin_lock);
- tracing::trace!("Video stdin set");
- println!("Starting FFmpeg process...");
++ tracing::trace!("Starting FFmpeg process...");
+
+ let (ffmpeg_child, ffmpeg_stdin) = self
+ .start_ffmpeg_process(ffmpeg_command).await
+ .map_err(|e| e.to_string())?;
- println!("Ffmpeg process started");
++ tracing::trace!("Ffmpeg process started");
+
+ if let Some(ffmpeg_stdin_mutex) = &self.ffmpeg_stdin {
+ let mut stdin_lock = ffmpeg_stdin_mutex.lock().await;
+ *stdin_lock = Some(ffmpeg_stdin);
+ drop(stdin_lock);
- println!("Ffmpeg stdin set");
++ tracing::trace!("Ffmpeg stdin set");
}
- if custom_device != Some("None") {
+ if needs_audio {
- println!("Starting audio channel senders...");
+ tracing::trace!("Starting audio channel senders...");
+
tokio::spawn(async move {
- while let Some(bytes) = &audio_channel_receiver.lock().await.as_mut().unwrap().recv().await {
- if let Some(audio_stdin_arc) = &ffmpeg_audio_stdin{
- let mut audio_stdin_guard = audio_stdin_arc.lock().await;
- if let Some(ref mut stdin) = *audio_stdin_guard {
- stdin.write_all(&bytes).await.expect("Failed to write audio data to FFmpeg stdin");
- }
- drop(audio_stdin_guard);
- }
+ let mut audio_pipe = File::create(audio_pipe_path).await.unwrap();
+
+ while
+ let Some(bytes) = &audio_channel_receiver
+ .lock().await
+ .as_mut()
+ .unwrap()
+ .recv().await
+ {
+ audio_pipe
+ .write_all(&bytes).await
+ .expect("Failed to write audio data to FFmpeg stdin");
}
});
}
- println!("Starting video channel senders...");
+ tracing::trace!("Starting video channel senders...");
tokio::spawn(async move {
- while let Some(bytes) = &video_channel_receiver.lock().await.as_mut().unwrap().recv().await {
- if let Some(video_stdin_arc) = &ffmpeg_video_stdin {
- let mut video_stdin_guard = video_stdin_arc.lock().await;
- if let Some(ref mut stdin) = *video_stdin_guard {
- stdin.write_all(&bytes).await.expect("Failed to write video data to FFmpeg stdin");
- }
- drop(video_stdin_guard);
- }
+ let mut pipe = File::create(video_pipe_path).await.unwrap();
+
+ while
+ let Some(bytes) = &video_channel_receiver
+ .lock().await
+ .as_mut()
+ .unwrap()
+ .recv().await
+ {
+ pipe.write_all(&bytes).await.expect("Failed to write video data to FFmpeg stdin");
}
});
- if custom_device != Some("None") {
- self.ffmpeg_audio_process = audio_child;
- }
-
self.start_time = Some(Instant::now());
- self.audio_file_path = Some(audio_file_path_owned);
- self.video_file_path = Some(video_file_path_owned);
- self.ffmpeg_video_process = Some(video_child);
+ self.audio_file_path = Some(audio_chunks_dir.to_path_buf());
+ self.video_file_path = Some(video_chunks_dir.to_path_buf());
+ self.ffmpeg_process = Some(ffmpeg_child);
self.device_name = Some(device.name().expect("Failed to get device name"));
- println!("End of the start_audio_recording function");
+ tracing::trace!("End of the start_audio_recording function");
Ok(())
}
pub fn trigger_play(&mut self) -> Result<(), &'static str> {
- if let Some(ref mut stream) = self.stream {
+ if let Some(ref mut stream) = self.audio_stream {
stream.play().map_err(|_| "Failed to play stream")?;
- println!("Audio recording playing.");
+ tracing::info!("Audio recording playing.");
} else {
return Err("Starting the recording did not work");
}
@@@ -574,8 -635,11 +635,11 @@@
let audio_segment_count = audio_segments.lines().count();
let video_segment_count = video_segments.lines().count();
- if audio_segment_count >= expected_segments as usize && video_segment_count >= expected_segments as usize {
+ if
+ audio_segment_count >= (expected_segments as usize) &&
+ video_segment_count >= (expected_segments as usize)
+ {
- println!("All segments generated");
+ tracing::info!("All segments generated");
break;
}
@@@ -583,23 -647,13 +647,13 @@@
}
}
- if let Some(ref ffmpeg_audio_stdin) = self.ffmpeg_audio_stdin {
- let mut audio_stdin_guard = ffmpeg_audio_stdin.lock().await;
- if let Some(mut audio_stdin) = audio_stdin_guard.take() {
- if let Err(e) = audio_stdin.write_all(b"q\n").await {
- tracing::error!("Failed to send 'q' to audio FFmpeg process: {}", e);
- }
- let _ = audio_stdin.shutdown().await.map_err(|e| e.to_string());
- }
- }
-
- if let Some(ref ffmpeg_video_stdin) = self.ffmpeg_video_stdin {
- let mut video_stdin_guard = ffmpeg_video_stdin.lock().await;
- if let Some(mut video_stdin) = video_stdin_guard.take() {
- if let Err(e) = video_stdin.write_all(b"q\n").await {
+ if let Some(ref ffmpeg_stdin) = self.ffmpeg_stdin {
+ let mut stdin_guard = ffmpeg_stdin.lock().await;
+ if let Some(mut stdin) = stdin_guard.take() {
+ if let Err(e) = stdin.write_all(b"q\n").await {
- eprintln!("Failed to send 'q' to video FFmpeg process: {}", e);
+ tracing::error!("Failed to send 'q' to video FFmpeg process: {}", e);
}
- let _ = video_stdin.shutdown().await.map_err(|e| e.to_string());
+ let _ = stdin.shutdown().await.map_err(|e| e.to_string());
}
}
@@@ -613,9 -667,9 +667,9 @@@
drop(sender);
}
- if let Some(ref mut stream) = self.stream {
+ if let Some(ref mut stream) = self.audio_stream {
stream.pause().map_err(|_| "Failed to pause stream")?;
- println!("Audio recording paused.");
+ tracing::info!("Audio recording paused.");
} else {
return Err("Original recording was not started".to_string());
}
@@@ -632,31 -682,9 +682,9 @@@
Ok(())
}
- async fn start_audio_ffmpeg_processes(
- &self,
- ffmpeg_binary_path: &str,
- audio_ffmpeg_command: &[String],
- ) -> Result<(Child, ChildStdin), Error> {
- let mut audio_process = start_recording_process(ffmpeg_binary_path, audio_ffmpeg_command).await.map_err(|e| {
- tracing::error!("Failed to start audio recording process: {}", e);
- std::io::Error::new(std::io::ErrorKind::Other, e.to_string())
- })?;
-
- let audio_stdin = audio_process.stdin.take().ok_or_else(|| {
- tracing::error!("Failed to take audio stdin");
- std::io::Error::new(std::io::ErrorKind::Other, "Failed to take audio stdin")
- })?;
-
- Ok((audio_process, audio_stdin))
- }
-
- async fn start_video_ffmpeg_processes(
- &self,
- ffmpeg_binary_path: &str,
- video_ffmpeg_command: &[String],
- ) -> Result<(Child, ChildStdin), Error> {
- let mut video_process = start_recording_process(ffmpeg_binary_path, video_ffmpeg_command).await.map_err(|e| {
+ async fn start_ffmpeg_process(&self, cmd: Command) -> Result<(Child, ChildStdin), Error> {
+ let mut video_process = start_recording_process(cmd).await.map_err(|e| {
- eprintln!("Failed to start video recording process: {}", e);
+ tracing::error!("Failed to start video recording process: {}", e);
std::io::Error::new(std::io::ErrorKind::Other, e.to_string())
})?;
@@@ -696,25 -722,18 +723,20 @@@ pub fn enumerate_audio_devices() -> Vec
input_device_names
}
- use tokio::io::{BufReader, AsyncBufReadExt};
+ use tokio::io::{ AsyncBufReadExt, BufReader };
+#[tracing::instrument]
async fn start_recording_process(
- ffmpeg_binary_path_str: &str,
- args: &[String],
+ mut cmd: Command
) -> Result<tokio::process::Child, std::io::Error> {
- let mut process = Command::new(ffmpeg_binary_path_str)
- .args(args)
- .stdin(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()?;
+ let mut process = cmd.stdin(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
if let Some(process_stderr) = process.stderr.take() {
- tokio::spawn(async move {
+ tokio::spawn(async move {
let mut process_reader = BufReader::new(process_stderr).lines();
while let Ok(Some(line)) = process_reader.next_line().await {
- eprintln!("FFmpeg process STDERR: {}", line);
+ // TODO: Collect this into one event. Custom implementation of Into<Stdio>?
+ tracing::error!("FFmpeg process STDERR: {}", line);
}
});
}
@@@ -722,10 -741,9 +744,10 @@@
Ok(process)
}
+#[tracing::instrument]
async fn wait_for_start_times(
- audio_start_time: Arc<Mutex<Option<Instant>>>,
- video_start_time: Arc<Mutex<Option<Instant>>>,
+ audio_start_time: &Mutex<Option<Instant>>,
+ video_start_time: &Mutex<Option<Instant>>
) -> (Instant, Instant) {
loop {
let audio_start_locked = audio_start_time.lock().await;
@@@ -742,13 -760,15 +764,16 @@@
}
}
+ pub enum TimeOffsetTarget {
+ Audio,
+ Video,
+ }
+
+#[tracing::instrument]
- async fn adjust_ffmpeg_commands_based_on_start_times(
- audio_start_time: Arc<Mutex<Option<Instant>>>,
- video_start_time: Arc<Mutex<Option<Instant>>>,
- ffmpeg_audio_command: &mut Vec<String>,
- ffmpeg_video_command: &mut Vec<String>,
- ) {
+ async fn create_time_offset_args(
+ audio_start_time: &Mutex<Option<Instant>>,
+ video_start_time: &Mutex<Option<Instant>>
+ ) -> Option<(TimeOffsetTarget, Vec<String>)> {
let (audio_start, video_start) = wait_for_start_times(audio_start_time, video_start_time).await;
let duration_difference = if audio_start > video_start {
audio_start.duration_since(video_start)
@@@ -756,27 -776,32 +781,32 @@@
video_start.duration_since(audio_start)
};
- println!("Duration difference: {:?}", duration_difference);
- println!("Audio start: {:?}", audio_start);
- println!("Video start: {:?}", video_start);
+ tracing::debug!("Duration difference: {:?}", duration_difference);
+ tracing::debug!("Audio start: {:?}", audio_start);
+ tracing::debug!("Video start: {:?}", video_start);
// Convert the duration difference to a float representing seconds
- let offset_seconds = duration_difference.as_secs() as f64
- + duration_difference.subsec_nanos() as f64 * 1e-9;
+ let offset_seconds =
+ (duration_difference.as_secs() as f64) + (duration_difference.subsec_nanos() as f64) * 1e-9;
// Depending on which started first, adjust the relevant FFmpeg command
if audio_start > video_start {
// Offset the video start time
- ffmpeg_video_command.splice(0..0, vec![
- "-itsoffset".to_string(), format!("{:.3}", offset_seconds)
- ]);
- println!("Applying -itsoffset {:.3} to video", offset_seconds);
+ tracing::info!("Applying -itsoffset {:.3} to video", offset_seconds);
+
+ Some((
+ TimeOffsetTarget::Video,
+ vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],
+ ))
} else if video_start > audio_start {
// Offset the audio start time
- ffmpeg_audio_command.splice(0..0, vec![
- "-itsoffset".to_string(), format!("{:.3}", offset_seconds)
- ]);
- println!("Applying -itsoffset {:.3} to audio", offset_seconds);
+ tracing::info!("Applying -itsoffset {:.3} to audio", offset_seconds);
- }
+ Some((
+ TimeOffsetTarget::Audio,
+ vec!["-itsoffset".to_string(), format!("{:.3}", offset_seconds)],
+ ))
+ } else {
+ None
+ }
}
diff --cc apps/desktop/src-tauri/src/recording.rs
index 111c2b383,488dcf082..5e3c8605c
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@@ -1,17 -1,20 +1,21 @@@
- use std::path::{Path, PathBuf};
+ use futures::future::join_all;
+ use serde::{Deserialize, Serialize};
use std::collections::HashSet;
- use std::io::{self, BufReader, BufRead, ErrorKind};
use std::fs::File;
- use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
- use tokio::sync:: {Mutex};
- use tokio::task::JoinHandle;
- use tokio::time::{Duration};
- use serde::{Serialize, Deserialize};
+ use std::io::{self, BufRead, BufReader, ErrorKind};
+ use std::path::{Path, PathBuf};
+ use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ };
use tauri::State;
- use futures::future::join_all;
+ use tokio::sync::Mutex;
+ use tokio::task::JoinHandle;
+ use tokio::time::Duration;
+use crate::app::config;
- use crate::upload::{upload_file};
+ use crate::upload::{self, upload_file};
+
use crate::media::MediaRecorder;
pub struct RecordingState {
@@@ -43,84 -46,125 +47,116 @@@ pub struct RecordingOptions
#[tauri::command]
#[specta::specta]
++#[tracing::instrument(skip(state))]
pub async fn start_dual_recording(
- state: State<'_, Arc<Mutex<RecordingState>>>,
- options: RecordingOptions,
+ state: State<'_, Arc<Mutex<RecordingState>>>,
+ options: RecordingOptions,
) -> Result<(), String> {
- tracing::info!("Starting screen recording...");
- let mut state_guard = state.lock().await;
-
- let shutdown_flag = Arc::new(AtomicBool::new(false));
-
- let data_dir = state_guard.data_dir.as_ref()
- .ok_or("Data directory is not set in the recording state".to_string())?.clone();
-
- tracing::debug!("data_dir: {:?}", data_dir);
-
- let audio_chunks_dir = data_dir.join("chunks/audio");
- let video_chunks_dir = data_dir.join("chunks/video");
- let screenshot_dir = data_dir.join("screenshots");
- println!("Starting screen recording...");
++ tracing::info!("Starting screen recording...");
+ let mut state_guard = state.lock().await;
- clean_and_create_dir(&audio_chunks_dir)?;
- clean_and_create_dir(&video_chunks_dir)?;
- clean_and_create_dir(&screenshot_dir)?;
+ let shutdown_flag = Arc::new(AtomicBool::new(false));
- let audio_name = if options.audio_name.is_empty() {
- None
- } else {
- Some(options.audio_name.clone())
- };
+ let data_dir = state_guard
+ .data_dir
+ .as_ref()
+ .ok_or("Data directory is not set in the recording state".to_string())?
+ .clone();
- let media_recording_preparation = prepare_media_recording(&options, &audio_chunks_dir, &video_chunks_dir, &screenshot_dir, audio_name, state_guard.max_screen_width, state_guard.max_screen_height);
- let media_recording_result = media_recording_preparation.await.map_err(|e| e.to_string())?;
- println!("data_dir: {:?}", data_dir);
++ tracing::debug!("data_dir: {:?}", data_dir);
- state_guard.media_process = Some(media_recording_result);
- state_guard.recording_options = Some(options.clone());
- state_guard.shutdown_flag = shutdown_flag.clone();
- state_guard.video_uploading_finished = Arc::new(AtomicBool::new(false));
- state_guard.audio_uploading_finished = Arc::new(AtomicBool::new(false));
+ let screenshot_dir = data_dir.join("screenshots");
+ let audio_chunks_dir = data_dir.join("chunks/audio");
+ let video_chunks_dir = data_dir.join("chunks/video");
- if !config::is_local_mode() {
- let screen_upload = start_upload_loop(video_chunks_dir.clone(), options.clone(), "video".to_string(), shutdown_flag.clone(), state_guard.video_uploading_finished.clone());
- let audio_upload = start_upload_loop(audio_chunks_dir, options.clone(), "audio".to_string(), shutdown_flag.clone(), state_guard.audio_uploading_finished.clone());
+ clean_and_create_dir(&screenshot_dir)?;
+ clean_and_create_dir(&audio_chunks_dir)?;
+ clean_and_create_dir(&video_chunks_dir)?;
- drop(state_guard);
-
- tracing::info!("Starting upload loops...");
+ let audio_name = if options.audio_name.is_empty() {
+ None
+ } else {
+ Some(options.audio_name.clone())
+ };
+
+ let media_recording_preparation = prepare_media_recording(
+ &options,
+ &screenshot_dir,
+ &audio_chunks_dir,
+ &video_chunks_dir,
+ audio_name,
+ state_guard.max_screen_width,
+ state_guard.max_screen_height,
+ );
+ let media_recording_result = media_recording_preparation
+ .await
+ .map_err(|e| e.to_string())?;
+
+ state_guard.media_process = Some(media_recording_result);
+ state_guard.recording_options = Some(options.clone());
+ state_guard.shutdown_flag = shutdown_flag.clone();
+ state_guard.video_uploading_finished = Arc::new(AtomicBool::new(false));
+ state_guard.audio_uploading_finished = Arc::new(AtomicBool::new(false));
- match tokio::try_join!(screen_upload, audio_upload) {
- Ok(_) => {
- tracing::info!("Both upload loops completed successfully.");
- },
- Err(e) => {
- tracing::error!("An error occurred: {}", e);
- },
- }
- } else {
- tracing::info!("Skipping upload loops due to NEXT_PUBLIC_LOCAL_MODE being set to 'true'.");
- }
- let is_local_mode = match dotenv_codegen::dotenv!("NEXT_PUBLIC_LOCAL_MODE") {
- "true" => true,
- _ => false,
- };
-
- if !is_local_mode {
++ if !config::is_local_mode() {
+ let video_upload = start_upload_loop(
+ video_chunks_dir.clone(),
+ options.clone(),
+ upload::FileType::Video,
+ shutdown_flag.clone(),
+ state_guard.video_uploading_finished.clone(),
+ );
+ let audio_upload = start_upload_loop(
+ audio_chunks_dir,
+ options.clone(),
+ upload::FileType::Audio,
+ shutdown_flag.clone(),
+ state_guard.audio_uploading_finished.clone(),
+ );
+
+ drop(state_guard);
+
- println!("Starting upload loops...");
++ tracing::info!("Starting upload loops...");
+
+ match tokio::try_join!(video_upload, audio_upload) {
+ Ok(_) => {
- println!("Both upload loops completed successfully.");
++ tracing::info!("Both upload loops completed successfully.");
+ }
+ Err(e) => {
- eprintln!("An error occurred: {}", e);
++ tracing::error!("An error occurred: {}", e);
+ }
+ }
+ } else {
- println!("Skipping upload loops due to NEXT_PUBLIC_LOCAL_MODE being set to 'true'.");
++ tracing::info!("Skipping upload loops due to NEXT_PUBLIC_LOCAL_MODE being set to 'true'.");
+ }
- Ok(())
+ Ok(())
}
#[tauri::command]
#[specta::specta]
- pub async fn stop_all_recordings(state: State<'_, Arc<Mutex<RecordingState>>>) -> Result<(), String> {
+ pub async fn stop_all_recordings(
+ state: State<'_, Arc<Mutex<RecordingState>>>,
+ ) -> Result<(), String> {
let mut guard = state.lock().await;
- println!("Stopping media recording...");
+ tracing::info!("Stopping media recording...");
guard.shutdown_flag.store(true, Ordering::SeqCst);
if let Some(mut media_process) = guard.media_process.take() {
- println!("Stopping media recording...");
+ tracing::info!("Stopping media recording...");
- media_process.stop_media_recording().await.expect("Failed to stop media recording");
+ media_process
+ .stop_media_recording()
+ .await
+ .expect("Failed to stop media recording");
}
- let is_local_mode = match dotenv_codegen::dotenv!("NEXT_PUBLIC_LOCAL_MODE") {
- "true" => true,
- _ => false,
- };
-
- if !is_local_mode {
+ if !config::is_local_mode() {
while !guard.video_uploading_finished.load(Ordering::SeqCst)
- || !guard.audio_uploading_finished.load(Ordering::SeqCst) {
+ || !guard.audio_uploading_finished.load(Ordering::SeqCst)
+ {
- println!("Waiting for uploads to finish...");
+ tracing::debug!("Waiting for uploads to finish...");
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
@@@ -181,12 -225,11 +217,11 @@@ async fn start_upload_loop
let segment_path = chunks_dir.join(segment_filename);
if segment_path.is_file() {
let options_clone = options.clone();
- let video_type_clone = video_type.clone();
- let segment_path_clone = segment_path.clone();
upload_tasks.push(tokio::spawn(async move {
- let filepath_str = segment_path_clone.to_str().unwrap_or_default().to_owned();
- tracing::debug!("Uploading video for {}: {}", video_type_clone, filepath_str);
- upload_file(Some(options_clone), filepath_str, video_type_clone).await.map(|_| ())
- println!("Uploading video for {file_type}: {segment_path:?}");
++ tracing::debug!("Uploading video for {file_type}: {segment_path:?}");
+ upload_file(Some(options_clone), segment_path, file_type)
+ .await
+ .map(|_| ())
}));
}
watched_segments.insert(segment_filename.clone());
diff --cc apps/desktop/src-tauri/src/upload.rs
index 3c1fc0871,89ed6beb7..38fe07566
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@@ -1,26 -1,40 +1,41 @@@
+ use regex::Regex;
use reqwest;
- use std::fs::File;
- use std::io::Read;
- use std::path::Path;
+ use serde_json::Value as JsonValue;
+ use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::str;
- use std::fs;
- use regex::Regex;
- use serde_json::Value as JsonValue;
use crate::recording::RecordingOptions;
- use crate::utils::{ffmpeg_path_as_str};
+ use crate::utils::ffmpeg_path_as_str;
+
-#[derive(Clone, Copy)]
++#[derive(Clone, Copy, Debug)]
+ pub enum FileType {
+ Video,
+ Audio,
+ Screenshot,
+ }
+
+ impl std::fmt::Display for FileType {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ match self {
+ FileType::Video => write!(f, "video"),
+ FileType::Audio => write!(f, "audio"),
+ FileType::Screenshot => write!(f, "screenshot"),
+ }
+ }
+ }
+#[tracing::instrument]
pub async fn upload_file(
options: Option<RecordingOptions>,
- file_path: String,
- file_type: String,
+ file_path: PathBuf,
+ file_type: FileType,
) -> Result<String, String> {
if let Some(ref options) = options {
- println!("Uploading video...");
+ tracing::info!("Uploading video...");
- let duration = get_video_duration(&file_path).map_err(|e| format!("Failed to get video duration: {}", e))?;
+ let duration = get_video_duration(&file_path)
+ .map_err(|e| format!("Failed to get video duration: {}", e))?;
let duration_str = duration.to_string();
let file_name = Path::new(&file_path)
@@@ -71,9 -90,8 +91,8 @@@
.await
.map_err(|e| format!("Failed to read response from Next.js handler: {}", e))?;
- println!("Server response: {}", server_response);
+ tracing::debug!("Server response: {}", server_response);
-
// Deserialize the server response
let presigned_post_data: JsonValue = serde_json::from_str(&server_response)
.map_err(|e| format!("Failed to deserialize server response: {}", e))?;
@@@ -90,19 -110,18 +111,18 @@@
form = form.text(key.to_string(), value_str.to_owned());
}
- tracing::info!("Uploading file: {}", file_path);
-
- let mime_type = if file_path.to_lowercase().ends_with(".aac") {
- "audio/aac"
- } else if file_path.to_lowercase().ends_with(".webm") {
- "audio/webm"
- } else if file_path.to_lowercase().ends_with(".mp3") {
- "audio/mpeg"
- } else {
- "video/mp2t"
- println!("Uploading file: {file_path:?}");
++ tracing::info!("Uploading file: {file_path:?}");
+
+ let mime_type = match file_path.extension() {
+ Some(ext) if ext == "aac" => "audio/aac",
+ Some(ext) if ext == "mp3" => "audio/mpeg",
+ Some(ext) if ext == "webm" => "audio/webm",
+ _ => "video/mp2t",
};
- let file_bytes = tokio::fs::read(&file_path).await.map_err(|e| format!("Failed to read file: {}", e))?;
+ let file_bytes = tokio::fs::read(&file_path)
+ .await
+ .map_err(|e| format!("Failed to read file: {}", e))?;
let file_part = reqwest::multipart::Part::bytes(file_bytes)
.file_name(file_name.clone())
.mime_str(mime_type)
@@@ -110,15 -129,13 +130,13 @@@
form = form.part("file", file_part);
- let post_url = presigned_post_data["presignedPostData"]["url"].as_str()
+ let post_url = presigned_post_data["presignedPostData"]["url"]
+ .as_str()
.ok_or("URL is missing or not a string")?;
- println!("Uploading file to: {}", post_url);
+ tracing::info!("Uploading file to: {}", post_url);
- let response = client.post(post_url)
- .multipart(form)
- .send()
- .await;
+ let response = client.post(post_url).multipart(form).send().await;
match response {
Ok(response) if response.status().is_success() => {
@@@ -126,20 -143,29 +144,29 @@@
}
Ok(response) => {
let status = response.status();
- let error_body = response.text().await.unwrap_or_else(|_| "<no response body>".to_string());
- tracing::error!("Failed to upload file. Status: {}. Body: {}", status, error_body);
- return Err(format!("Failed to upload file. Status: {}. Body: {}", status, error_body));
+ let error_body = response
+ .text()
+ .await
+ .unwrap_or_else(|_| "<no response body>".to_string());
- eprintln!(
++ tracing::error!(
+ "Failed to upload file. Status: {}. Body: {}",
+ status, error_body
+ );
+ return Err(format!(
+ "Failed to upload file. Status: {}. Body: {}",
+ status, error_body
+ ));
}
Err(e) => {
return Err(format!("Failed to send upload file request: {}", e));
}
}
- tracing::info!("Removing file after upload: {}", file_path);
- println!("Removing file after upload: {file_path:?}");
++ tracing::info!("Removing file after upload: {file_path:?}");
let remove_result = tokio::fs::remove_file(&file_path).await;
match &remove_result {
- Ok(_) => println!("File removed successfully"),
- Err(e) => println!("Failed to remove file after upload: {}", e),
+ Ok(_) => tracing::info!("File removed successfully"),
+ Err(e) => tracing::info!("Failed to remove file after upload: {}", e),
}
remove_result.map_err(|e| format!("Failed to remove file after upload: {}", e))?;