keep recording audio and video in sync
This commit is contained in:
+110
-16
@@ -2,7 +2,7 @@ use std::collections::HashSet;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::mpsc::Sender;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
@@ -1176,28 +1176,122 @@ pub(crate) fn mux_with_audio(
|
||||
run(&mut cmd, "mux")
|
||||
}
|
||||
|
||||
pub(crate) fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
|
||||
pub(crate) struct AudioSegment {
|
||||
pub path: PathBuf,
|
||||
pub sample_rate: u32,
|
||||
pub channels: u16,
|
||||
pub start_secs: f64,
|
||||
pub end_secs: f64,
|
||||
}
|
||||
|
||||
/// Align the audio takes to video time and fill gaps with whole sample frames.
|
||||
pub(crate) fn assemble_pcm(
|
||||
ffmpeg: &Path,
|
||||
segments: &[AudioSegment],
|
||||
output: &Path,
|
||||
duration_secs: f64,
|
||||
) -> Result<Option<(u32, u16)>> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
|
||||
let Some(first) = segments.first() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (sample_rate, channels) = (first.sample_rate, first.channels);
|
||||
let frame_bytes = u64::from(channels) * 4;
|
||||
let frame_at = |seconds: f64| round_u64(seconds * f64::from(sample_rate));
|
||||
let total_frames = frame_at(duration_secs);
|
||||
let mut out = std::fs::File::create(output).context("creating aligned audio file")?;
|
||||
let mut written = 0;
|
||||
let resampled = TempFileGuard(output.with_extension("resampled.pcm"));
|
||||
|
||||
for segment in segments {
|
||||
let start = frame_at(segment.start_secs);
|
||||
let end = frame_at(segment.end_secs).min(total_frames);
|
||||
let from = start.max(written);
|
||||
if end <= from || std::fs::metadata(&segment.path)?.len() == 0 {
|
||||
continue;
|
||||
}
|
||||
let path = if (segment.sample_rate, segment.channels) == (sample_rate, channels) {
|
||||
&segment.path
|
||||
} else {
|
||||
resample_pcm(ffmpeg, segment, &resampled.0, sample_rate, channels)?;
|
||||
&resampled.0
|
||||
};
|
||||
let mut input = std::fs::File::open(path)?;
|
||||
let skipped = from - start;
|
||||
let available = (input.metadata()?.len() / frame_bytes).saturating_sub(skipped);
|
||||
let frames = available.min(end - from);
|
||||
if frames == 0 {
|
||||
continue;
|
||||
}
|
||||
write_silence(&mut out, (from - written) * frame_bytes)?;
|
||||
input.seek(SeekFrom::Start(skipped * frame_bytes))?;
|
||||
let bytes = frames * frame_bytes;
|
||||
if std::io::copy(&mut input.take(bytes), &mut out)? != bytes {
|
||||
bail!("audio segment ended before its recorded length");
|
||||
}
|
||||
written = from + frames;
|
||||
}
|
||||
|
||||
if written == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
write_silence(&mut out, (total_frames - written) * frame_bytes)?;
|
||||
Ok(Some((sample_rate, channels)))
|
||||
}
|
||||
|
||||
fn write_silence(output: &mut std::fs::File, mut bytes: u64) -> Result<()> {
|
||||
use std::io::Write;
|
||||
if segments.is_empty() {
|
||||
bail!("no audio segments to concatenate");
|
||||
|
||||
const ZEROS: [u8; 8192] = [0; 8192];
|
||||
while bytes > 0 {
|
||||
let chunk = bytes.min(8192);
|
||||
let zeros = ZEROS
|
||||
.get(..usize::try_from(chunk)?)
|
||||
.context("audio padding exceeds its buffer")?;
|
||||
output.write_all(zeros)?;
|
||||
bytes -= chunk;
|
||||
}
|
||||
if let Some(parent) = output.parent() {
|
||||
std::fs::create_dir_all(parent).context("creating audio concat parent")?;
|
||||
}
|
||||
let mut out = std::fs::File::create(output).context("creating audio concat file")?;
|
||||
for seg in segments {
|
||||
let mut f =
|
||||
std::fs::File::open(seg).with_context(|| format!("opening {}", seg.display()))?;
|
||||
std::io::copy(&mut f, &mut out).context("copying audio segment")?;
|
||||
}
|
||||
out.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct TempFileGuard(PathBuf);
|
||||
fn resample_pcm(
|
||||
ffmpeg: &Path,
|
||||
segment: &AudioSegment,
|
||||
output: &Path,
|
||||
sample_rate: u32,
|
||||
channels: u16,
|
||||
) -> Result<()> {
|
||||
let mut cmd = Command::new(ffmpeg);
|
||||
cmd.args(["-y", "-hide_banner", "-f", "f32le"])
|
||||
.args(["-ar", &segment.sample_rate.to_string()])
|
||||
.args(["-ac", &segment.channels.to_string()])
|
||||
.arg("-i")
|
||||
.arg(&segment.path)
|
||||
.args(["-ar", &sample_rate.to_string()])
|
||||
.args(["-ac", &channels.to_string()])
|
||||
.args(["-f", "f32le"])
|
||||
.arg(output);
|
||||
run(&mut cmd, "audio resampling")
|
||||
}
|
||||
|
||||
pub(crate) struct TempFileGuard(pub(crate) PathBuf);
|
||||
|
||||
impl TempFileGuard {
|
||||
pub(crate) fn create_in(dir: &Path, purpose: &str, extension: &str) -> Result<Self> {
|
||||
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let path = dir.join(format!("{purpose}-{}-{sequence}.{extension}", std::process::id()));
|
||||
drop(std::fs::File::create_new(&path)?);
|
||||
Ok(Self(path))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempFileGuard {
|
||||
fn drop(&mut self) {
|
||||
drop(std::fs::remove_file(&self.0));
|
||||
if !self.0.as_os_str().is_empty() {
|
||||
drop(std::fs::remove_file(&self.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user