use std::cell::RefCell;
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
use std::sync::mpsc::{channel, sync_channel, Receiver, RecvError, SendError, Sender, SyncSender};
use clap::{Parser, Subcommand, ValueEnum};
use image::{ImageFormat, ImageReader};
use insta360_stitch::math::{apply, cross, dot, mul, norm, normalize, transpose, Mat3, IDENTITY};
#[cfg(feature = "gpu")]
use insta360_stitch::GpuStitcher;
use insta360_stitch::{
band_offset, check_different_files, check_photo_layout, frame_times_us, gps_track,
merge_bracket, preview_rgb, read_imu, read_preview, read_trailer, stitch_photo_band_with,
uses_recorded_frame_times, video_sample_times, write_spherical_mp4_file, DenoiseSettings,
Denoiser, FrameFlow, FrameFusion, FrameRotation, GpuMode, Image, Imu, LensModel, PhotoSeam,
Stabilization, Stitcher, Trailer, MAX_VIDEO_WIDTH,
};
use jpeg_encoder::{rgb_to_ycbcr, Encoder, ImageBuffer, JpegColorType};
mod bullet_time_cut;
use bullet_time_cut::bullet_time_cut;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Parser)]
#[command(version)]
struct Cli {
#[arg(long, global = true, value_parser = clap::value_parser!(u16).range(1..))]
threads: Option<u16>,
#[arg(long, global = true, value_enum, default_value_t = GpuArg::Auto)]
gpu: GpuArg,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
enum Commands {
Gpx {
input: PathBuf,
output: PathBuf,
#[arg(long)]
raw: bool,
},
Info { file: PathBuf },
Photo {
input: PathBuf,
output: PathBuf,
#[arg(long, default_value_t = 95, value_parser = clap::value_parser!(u8).range(1..=100))]
quality: u8,
#[arg(long, value_name = "PHOTO")]
level_from: Option<PathBuf>,
#[arg(long = "bracket", value_name = "PHOTO")]
bracket: Vec<PathBuf>,
},
Preview { input: PathBuf, output: PathBuf },
Video {
input: PathBuf,
output: PathBuf,
#[command(flatten)]
options: VideoOptions,
},
}
#[derive(clap::Args)]
struct VideoOptions {
#[arg(long, value_parser = parse_width)]
width: Option<usize>,
#[arg(long, value_enum)]
stabilization: Option<StabilizationArg>,
#[arg(long, conflicts_with = "stabilization")]
bullet_time_view: bool,
#[arg(long, num_args = 0..=1, default_missing_value = "libx265", conflicts_with_all = ["encoder", "crf"])]
studio_encode: Option<StudioEncoder>,
#[arg(long, default_value = "libx264")]
encoder: String,
#[arg(long, default_value_t = 20, value_parser = clap::value_parser!(u8).range(0..=51))]
crf: u8,
#[arg(long, default_value = "medium")]
preset: String,
#[arg(long = "encoder-arg", allow_hyphen_values = true)]
encoder_args: Vec<String>,
#[arg(long)]
hwaccel: Option<String>,
#[arg(long, default_value_t = 2, value_parser = clap::value_parser!(u16).range(1..))]
decoder_threads: u16,
#[arg(long = "decoder-arg", allow_hyphen_values = true)]
decoder_args: Vec<String>,
#[arg(long)]
no_rolling_shutter: bool,
#[arg(long)]
no_seam_flow: bool,
#[arg(long)]
no_color_fusion: bool,
#[arg(long, value_parser = parse_seconds)]
start: Option<f64>,
#[arg(long, value_parser = parse_seconds)]
end: Option<f64>,
#[arg(long)]
no_camera_trim: bool,
#[arg(long)]
denoise: bool,
#[arg(long, requires = "denoise", value_parser = parse_strength)]
denoise_strength: Option<f32>,
#[arg(long, default_value = "ffmpeg")]
ffmpeg: String,
#[arg(long, default_value = "ffprobe")]
ffprobe: String,
}
#[derive(Clone, Copy, Debug, PartialEq, ValueEnum)]
enum StudioEncoder {
#[value(name = "libx265")]
Libx265,
#[value(name = "hevc_nvenc")]
HevcNvenc,
}
#[derive(Clone, Copy, ValueEnum)]
enum GpuArg {
Auto,
Off,
}
impl From<GpuArg> for GpuMode {
fn from(value: GpuArg) -> Self {
match value {
GpuArg::Auto => GpuMode::Auto,
GpuArg::Off => GpuMode::Off,
}
}
}
#[derive(Clone, Copy, ValueEnum)]
enum StabilizationArg {
Lock,
Follow,
Off,
}
impl From<StabilizationArg> for Stabilization {
fn from(value: StabilizationArg) -> Self {
match value {
StabilizationArg::Lock => Stabilization::Lock,
StabilizationArg::Follow => Stabilization::Follow,
StabilizationArg::Off => Stabilization::Off,
}
}
}
fn split_threads(threads: Option<u16>, side_work: bool) -> (Option<usize>, usize) {
match (threads.map(usize::from), side_work) {
(Some(n), true) => {
let flow = (n / 2).clamp(1, 2);
(Some((n - flow).max(1)), flow)
}
(threads, _) => (threads, 2),
}
}
fn main() -> ExitCode {
let cli = Cli::parse();
let side_work = matches!(
&cli.command,
Commands::Video { options, .. } if !options.no_seam_flow || !options.no_color_fusion
);
let (threads, flow_threads) = split_threads(cli.threads, side_work);
if let Some(threads) = threads {
rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build_global()
.expect("the thread pool is not in use yet");
}
let gpu = GpuMode::from(cli.gpu);
let result = match cli.command {
Commands::Gpx { input, output, raw } => gpx(&input, &output, !raw),
Commands::Info { file } => info(&file),
Commands::Photo {
input,
output,
quality,
level_from,
bracket,
} => photo(
&input,
&output,
quality,
level_from.as_deref(),
&bracket,
gpu,
),
Commands::Preview { input, output } => preview(&input, &output),
Commands::Video {
input,
output,
options,
} => video(&input, &output, &options, flow_threads, gpu),
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("insta360-stitch: {error}");
ExitCode::FAILURE
}
}
}
fn trailer_of(path: &Path) -> Result<Trailer> {
Ok(read_trailer(&mut BufReader::new(File::open(path)?))?)
}
fn gpx(input: &Path, output: &Path, smooth: bool) -> Result<()> {
check_output(input, output)?;
let trailer = trailer_of(input)?;
let fixes = trailer.gps.ok_or("the file has no GPS data")?;
let track = gps_track(&fixes, trailer.gps_start_ms, smooth);
if track.is_empty() {
return Err("the file has no GPS position after the start of the recording".into());
}
let gpx = insta360_stitch::gpx(&track);
write_atomically(output, |out| Ok(out.write_all(gpx.as_bytes())?))
}
fn info(path: &Path) -> Result<()> {
let stitcher = Stitcher::new(trailer_of(path)?);
let trailer = &stitcher.trailer;
let offset = &trailer.offset;
let json = serde_json::json!({
"stitchable": stitcher.unsupported_reason().is_none(),
"reason": stitcher.unsupported_reason(),
"lensType": offset[15] as u32 & 0xff,
"offsetState": u64::from(trailer.offset_state),
"subMediaType": trailer.sub_media_type.map(u64::from),
"iso": trailer.iso,
"calibration": { "width": offset[13], "height": offset[14] },
"localTime": trailer.local_time,
"firstFrameUs": trailer.first_frame_us,
"imuSamples": trailer.imu.as_ref().map_or(0, |imu| imu.len()),
"flickerSpansMs": trailer.flicker_spans_ms(),
"preview": trailer.preview_size().map(|(width, height)| serde_json::json!({ "width": width, "height": height })),
});
println!("{}", serde_json::to_string_pretty(&json)?);
Ok(())
}
const BAND_ROWS: usize = 64;
#[cfg(feature = "gpu")]
const GPU_BAND_ROWS: usize = 256;
enum Rows<'a> {
Plain {
rgb: &'a [u8],
width: usize,
height: usize,
},
Stitched {
width: usize,
height: usize,
bands: Receiver<insta360_stitch::Result<(usize, Vec<u8>)>>,
used: Sender<Vec<u8>>,
band: RefCell<(usize, Vec<u8>)>,
error: RefCell<Option<Box<dyn std::error::Error>>>,
},
}
impl<'a> Rows<'a> {
fn size(&self) -> (usize, usize) {
match self {
Rows::Plain { width, height, .. } | Rows::Stitched { width, height, .. } => {
(*width, *height)
}
}
}
fn stitched<'scope>(
scope: &'scope std::thread::Scope<'scope, 'a>,
source: Image<'a>,
model: &'a LensModel,
seam: &'a PhotoSeam,
) -> Self {
Rows::bands(
scope,
source.width,
source.height,
BAND_ROWS,
move |first, band| stitch_photo_band_with(&source, model, seam, first, band),
)
}
fn bands<'scope>(
scope: &'scope std::thread::Scope<'scope, 'a>,
width: usize,
height: usize,
band_rows: usize,
stitch: impl Fn(usize, &mut [u8]) -> insta360_stitch::Result<()> + Send + 'scope,
) -> Self {
let (send, bands) = sync_channel(1);
let (used, free) = channel::<Vec<u8>>();
scope.spawn(move || {
let row_len = width * 3;
for first in (0..height).step_by(band_rows) {
let mut band = free.try_recv().unwrap_or_default();
band.resize(band_rows.min(height - first) * row_len, 0);
let result = stitch(first, &mut band);
let failed = result.is_err();
if send.send(result.map(|()| (first, band))).is_err() || failed {
return;
}
}
});
Rows::Stitched {
width,
height,
bands,
used,
band: RefCell::new((0, Vec::new())),
error: RefCell::new(None),
}
}
fn check(&self) -> Result<()> {
match self {
Rows::Stitched { error, .. } => error.take().map_or(Ok(()), Err),
Rows::Plain { .. } => Ok(()),
}
}
}
impl ImageBuffer for &Rows<'_> {
fn get_jpeg_color_type(&self) -> JpegColorType {
JpegColorType::Ycbcr
}
fn width(&self) -> u16 {
self.size().0 as u16
}
fn height(&self) -> u16 {
self.size().1 as u16
}
fn fill_buffers(&self, y: u16, buffers: &mut [Vec<u8>; 4]) {
let width = self.size().0;
let (y, row_len) = (usize::from(y), width * 3);
let mut push = |row: &[u8]| {
for pixel in row.as_chunks::<3>().0 {
let (luma, cb, cr) = rgb_to_ycbcr(pixel[0], pixel[1], pixel[2]);
buffers[0].push(luma);
buffers[1].push(cb);
buffers[2].push(cr);
}
};
match self {
Rows::Plain { rgb, .. } => push(&rgb[y * row_len..][..row_len]),
Rows::Stitched {
bands,
used,
band,
error,
..
} => {
let mut band = band.borrow_mut();
while y >= band.0 + band.1.len() / row_len && error.borrow().is_none() {
match bands.recv() {
Ok(Ok(next)) => {
used.send(std::mem::replace(&mut *band, next).1).ok();
}
Ok(Err(stitch)) => *error.borrow_mut() = Some(stitch.into()),
Err(RecvError) => {
*error.borrow_mut() = Some("the stitch stopped before the end".into())
}
}
}
if error.borrow().is_some() {
push(&vec![0; row_len]);
} else {
push(&band.1[(y - band.0) * row_len..][..row_len]);
}
}
}
}
}
fn write_panorama_jpeg(
output: &Path,
rows: Rows,
quality: u8,
exif: Option<Vec<u8>>,
) -> Result<()> {
let (width, height) = rows.size();
if width > usize::from(u16::MAX) || height > usize::from(u16::MAX) {
return Err(format!(
"a JPEG cannot be larger than 65535 pixels, the image is {width}x{height}"
)
.into());
}
write_atomically(output, |out| encode_panorama(out, &rows, quality, exif))
}
fn encode_panorama(out: impl Write, rows: &Rows, quality: u8, exif: Option<Vec<u8>>) -> Result<()> {
let (width, height) = rows.size();
let xmp = format!(
concat!(
"http://ns.adobe.com/xap/1.0/\0",
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">"#,
r#"<rdf:Description rdf:about="" xmlns:GPano="http://ns.google.com/photos/1.0/panorama/" "#,
r#"GPano:ProjectionType="equirectangular" GPano:UsePanoramaViewer="True" "#,
r#"GPano:FullPanoWidthPixels="{w}" GPano:FullPanoHeightPixels="{h}" "#,
r#"GPano:CroppedAreaImageWidthPixels="{w}" GPano:CroppedAreaImageHeightPixels="{h}" "#,
r#"GPano:CroppedAreaLeftPixels="0" GPano:CroppedAreaTopPixels="0" "#,
r#"GPano:InitialViewVerticalFOVDegrees="95" GPano:InitialHorizontalFOVDegrees="100" "#,
r#"GPano:StitchingSoftware="insta360-stitch"/></rdf:RDF></x:xmpmeta>"#
),
w = width,
h = height
);
let mut encoder = Encoder::new(out, quality);
if let Some(exif) = exif {
encoder.add_app_segment(1, exif)?;
}
encoder.add_app_segment(1, xmp.into_bytes())?;
let encoded = encoder.encode_image(rows);
rows.check()?;
Ok(encoded?)
}
fn write_atomically(
output: &Path,
write: impl FnOnce(&mut BufWriter<File>) -> Result<()>,
) -> Result<()> {
if output.exists() && !output.is_file() {
let mut out = BufWriter::new(std::fs::OpenOptions::new().write(true).open(output)?);
write(&mut out)?;
return Ok(out.flush()?);
}
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let mut part = output.as_os_str().to_owned();
part.push(format!(
".{}-{}.part",
std::process::id(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
let file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&part)?;
let result = (|| -> Result<()> {
let mut out = BufWriter::new(file);
write(&mut out)?;
out.into_inner().map_err(|e| e.into_error())?.sync_all()?;
Ok(std::fs::rename(&part, output)?)
})();
if result.is_err() {
std::fs::remove_file(&part).ok();
}
result
}
fn exif_segment(jpeg: impl Read) -> Option<Vec<u8>> {
let mut jpeg = BufReader::new(jpeg);
let mut two = [0u8; 2];
jpeg.read_exact(&mut two).ok()?;
if two != [0xff, 0xd8] {
return None;
}
loop {
let mut marker = [0u8; 2];
jpeg.read_exact(&mut marker).ok()?;
if marker[0] != 0xff || marker[1] == 0xda {
return None;
}
jpeg.read_exact(&mut two).ok()?;
let len = usize::from(u16::from_be_bytes(two)).checked_sub(2)?;
let mut data = vec![0u8; len];
jpeg.read_exact(&mut data).ok()?;
if marker[1] == 0xe1 && data.starts_with(b"Exif\0\0") {
return Some(data);
}
}
}
fn decode_photo(path: &Path) -> Result<image::RgbImage> {
let decoded = ImageReader::with_format(BufReader::new(File::open(path)?), ImageFormat::Jpeg)
.decode()?
.into_rgb8();
check_photo_layout(decoded.width() as usize, decoded.height() as usize)?;
Ok(decoded)
}
fn check_output(input: &Path, output: &Path) -> Result<()> {
check_different_files(input, output)?;
let extension = output.extension().and_then(|e| e.to_str()).unwrap_or("");
if ["insv", "insp", "lrv"]
.iter()
.any(|e| extension.eq_ignore_ascii_case(e))
{
return Err(format!(
"the output {} has the extension of a camera file; give another output file",
output.display()
)
.into());
}
Ok(())
}
fn photo(
input: &Path,
output: &Path,
quality: u8,
level_from: Option<&Path>,
bracket: &[PathBuf],
gpu: GpuMode,
) -> Result<()> {
check_output(input, output)?;
#[cfg(feature = "gpu")]
let gpu = (gpu == GpuMode::Auto).then(|| std::thread::spawn(GpuStitcher::new));
#[cfg(not(feature = "gpu"))]
let _ = gpu;
for other in bracket {
check_different_files(other, output)
.map_err(|_| "the output must be a different file than the --bracket photos")?;
}
let level = match level_from {
Some(reference) => {
check_different_files(reference, output)
.map_err(|_| "the output must be a different file than the --level-from photo")?;
let reference = Stitcher::new(trailer_of(reference)?);
if let Some(why) = reference.unsupported_reason() {
return Err(format!("the photo for --level-from cannot be used: {why}").into());
}
Some(reference.trailer)
}
None => None,
};
let mut decoded = decode_photo(input)?;
let mut trailer = trailer_of(input)?;
let level = if bracket.is_empty() {
level
} else {
Some(level.unwrap_or_else(|| trailer.clone()))
};
if !bracket.is_empty() {
let mut photos = vec![(decoded, trailer)];
for other in bracket {
photos.push((decode_photo(other)?, trailer_of(other)?));
}
let size = (photos[0].0.width(), photos[0].0.height());
if photos.iter().any(|(p, _)| (p.width(), p.height()) != size) {
return Err("the photos of the bracket must have the same size".into());
}
let images: Vec<Image> = photos
.iter()
.map(|(p, _)| Image {
width: size.0 as usize,
height: size.1 as usize,
channels: 3,
data: p.as_raw(),
})
.collect();
let lens = LensModel::new(&photos[0].1, size.1 as usize, IDENTITY)?;
let merged = merge_bracket(&images, Some(&lens))?;
drop(images);
let (_, reference) = photos.swap_remove(merged.reference);
trailer = reference;
decoded = image::RgbImage::from_raw(size.0, size.1, merged.data)
.ok_or("the merged photo has a wrong size")?;
}
let mut stitcher = Stitcher::new(trailer);
if let Some(level) = &level {
stitcher = stitcher.with_level_of(level);
}
let (width, height) = (decoded.width() as usize, decoded.height() as usize);
let model = stitcher.model(height)?;
let source = Image {
width,
height,
channels: 3,
data: decoded.as_raw(),
};
let seam = PhotoSeam::new(&source, &model)?;
let exif = exif_segment(File::open(input)?);
#[cfg(feature = "gpu")]
{
let gpu = match gpu {
Some(setup) => setup.join().map_err(|_| "the setup of the GPU stopped")?,
None => Err(insta360_stitch::Error::Unsupported("--gpu off".into())),
};
let on_gpu = gpu.as_ref().map_err(reason).and_then(|gpu| {
Ok((
gpu,
gpu.upload(&source, &model, &seam).map_err(|e| reason(&e))?,
))
});
match on_gpu {
Ok((gpu, photo)) => {
eprintln!("insta360-stitch: photo stitch on the GPU ({})", gpu.name());
drop(decoded);
return std::thread::scope(|scope| {
let rows = Rows::bands(scope, width, height, GPU_BAND_ROWS, |first, band| {
photo.stitch_band(first, band)
});
write_panorama_jpeg(output, rows, quality, exif)
});
}
Err(reason) => eprintln!("insta360-stitch: photo stitch on the processor ({reason})"),
}
}
std::thread::scope(|scope| {
let rows = Rows::stitched(scope, source, &model, &seam);
write_panorama_jpeg(output, rows, quality, exif)
})
}
#[cfg(feature = "gpu")]
fn reason(error: &insta360_stitch::Error) -> String {
match error {
insta360_stitch::Error::Unsupported(reason) => reason.clone(),
other => other.to_string(),
}
.replace(['\r', '\n'], " ")
}
fn preview(input: &Path, output: &Path) -> Result<()> {
check_output(input, output)?;
let mut reader = BufReader::new(File::open(input)?);
let trailer = read_trailer(&mut reader)?;
let preview = read_preview(&mut reader, &trailer)?;
let rgb = preview_rgb(&preview);
let rows = Rows::Plain {
rgb: &rgb,
width: preview.width as usize,
height: preview.height as usize,
};
write_panorama_jpeg(output, rows, 92, None)
}
fn new_temp_folder(parent: &Path) -> Result<PathBuf> {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |time| time.as_nanos());
for attempt in 0..100 {
let name = format!("insta360-stitch-{}-{nanos}-{attempt}", std::process::id());
let folder = parent.join(name);
match std::fs::create_dir(&folder) {
Ok(()) => return Ok(folder),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error.into()),
}
}
Err("cannot make a temporary folder".into())
}
fn parse_width(text: &str) -> std::result::Result<usize, String> {
let width: usize = text
.parse()
.map_err(|_| format!("{text} is not a number"))?;
if width < 16 || !width.is_multiple_of(4) || width > MAX_VIDEO_WIDTH {
return Err(format!(
"the width must be a multiple of 4 from 16 to {MAX_VIDEO_WIDTH}, not {width}"
));
}
Ok(width)
}
#[derive(Debug, PartialEq)]
struct Probe {
lens_size: usize,
lens_height: usize,
rate: String,
fps: f64,
frame_count: usize,
colour_args: Vec<String>,
full_range: bool,
file_bitrate: u64,
duration_us: Option<u64>,
}
fn parse_seconds(text: &str) -> std::result::Result<f64, String> {
match text.parse::<f64>() {
Ok(seconds) if seconds.is_finite() && seconds >= 0.0 => Ok(seconds),
_ => Err(format!("`{text}` is not a time in seconds (0 or more)")),
}
}
fn parse_strength(text: &str) -> std::result::Result<f32, String> {
match text.parse::<f32>() {
Ok(strength) if strength > 0.0 && strength <= 16.0 => Ok(strength),
_ => Err(format!(
"`{text}` is not a strength (more than 0, at most 16)"
)),
}
}
fn denoise_settings_for(
requested: Option<f32>,
trailer: &Trailer,
lens_size: usize,
fps: f64,
) -> DenoiseSettings {
trailer
.denoise_settings(lens_size, fps)
.scaled(requested.unwrap_or(1.0))
}
fn first_unmatched_frame(
video_s: &[f64],
camera_us: &[f64],
fps: f64,
end: usize,
) -> Option<usize> {
let half = 0.5e6 / fps;
(1..video_s.len().min(camera_us.len()).min(end)).find(|&n| {
let video = (video_s[n] - video_s[n - 1]) * 1e6;
((camera_us[n] - camera_us[n - 1]) - video).abs() > half
})
}
const RANGE_TOLERANCE: f64 = 0.001;
fn frame_range(
fps: f64,
frame_count: usize,
start: Option<f64>,
end: Option<f64>,
) -> Result<(usize, usize)> {
let first = start.map_or(0.0, |start| {
((start - RANGE_TOLERANCE) * fps).ceil().max(0.0)
}) as usize;
let last = end.map_or(f64::INFINITY, |end| ((end + RANGE_TOLERANCE) * fps).floor());
let last = last.min(frame_count as f64 - 1.0);
if first as f64 > last {
return Err(format!(
"the time range has no frame: the video has {frame_count} frames at {fps:.3} fps ({:.3} s)",
frame_count as f64 / fps
)
.into());
}
Ok((first, last as usize - first + 1))
}
fn plan_range(
probe: &Probe,
(start, end): (Option<f64>, Option<f64>),
trimmed: bool,
cut: Option<(usize, usize)>,
) -> Result<FrameRange> {
let (start, end) = match cut {
Some((first, last)) => (
start.or(Some(first as f64 / probe.fps)),
end.or(Some(last as f64 / probe.fps)),
),
None => (start, end),
};
let (first, count) =
frame_range(probe.fps, probe.frame_count, start, end).map_err(|error| match trimmed {
true => format!(
"{error}. The camera trim of the file applies (--no-camera-trim keeps all frames)"
)
.into(),
false => error,
})?;
let repeat_last = match end {
None => studio_frame_count(probe)
.saturating_sub(probe.frame_count)
.min(1),
Some(_) => 0,
};
Ok(FrameRange {
first,
count,
repeat_last,
})
}
fn camera_trim(
fps: f64,
frame_count: usize,
trim_ms: [u64; 2],
start: Option<f64>,
end: Option<f64>,
) -> (Option<f64>, Option<f64>) {
let frame = |ms: f64| (ms * fps / 1000.0) as usize;
let duration_ms = frame_count as f64 * 1000.0 / fps;
let first = frame(trim_ms[0] as f64);
let last = frame((duration_ms - trim_ms[1] as f64).max(0.0)).min(frame_count - 1);
if first > last {
return (start, end);
}
(
start.or((trim_ms[0] > 0).then(|| first as f64 / fps)),
end.or((trim_ms[1] > 0).then(|| last as f64 / fps)),
)
}
fn studio_frame_count(probe: &Probe) -> usize {
let Some(duration_us) = probe.duration_us else {
return probe.frame_count;
};
let ticks = match probe.rate.split_once('/') {
Some((n, d)) => match (n.parse::<u128>(), d.parse::<u128>()) {
(Ok(n), Ok(d)) if d > 0 => (duration_us as u128 * n / (d * 1_000_000)) as usize,
_ => (duration_us as f64 * probe.fps / 1e6) as usize,
},
None => (duration_us as f64 * probe.fps / 1e6) as usize,
};
ticks + 1
}
fn gyro_span(trailer: &Trailer) -> Option<(f64, f64)> {
let (imu, first_frame) = (trailer.imu.as_ref()?, trailer.first_frame_us?);
let first = imu.ts.iter().find(|&&t| t >= first_frame)?;
Some((
(first - first_frame) / 1e6,
(imu.ts.last()? - first_frame) / 1e6,
))
}
#[derive(Clone, Copy, Debug)]
struct FrameRange {
first: usize,
count: usize,
repeat_last: usize,
}
impl FrameRange {
#[cfg(test)]
fn whole(probe: &Probe) -> FrameRange {
FrameRange {
first: 0,
count: probe.frame_count,
repeat_last: 0,
}
}
fn is_part_of(&self, probe: &Probe) -> bool {
self.first > 0 || self.count < probe.frame_count
}
}
fn is_video_filter(option: &str) -> bool {
option == "-vf"
|| option.starts_with("-vf:")
|| option == "-filter"
|| option.starts_with("-filter:v")
|| option == "-filter:0"
|| option.starts_with("-filter:0:")
}
fn ffmpeg_file(path: &Path) -> std::ffi::OsString {
let mut file = std::ffi::OsString::from("file:");
file.push(path);
file
}
fn probe(ffprobe: &str, input: &Path) -> Result<Probe> {
let out = Command::new(ffprobe)
.args(["-v", "error", "-select_streams", "v", "-show_entries"])
.arg("stream=width,height,r_frame_rate,nb_frames,color_space,color_primaries,color_transfer,color_range:format=duration")
.args(["-of", "compact=p=0"])
.arg("-i")
.arg(ffmpeg_file(input))
.output()
.map_err(|e| format!("cannot start {ffprobe}: {e}"))?;
if !out.status.success() {
return Err(format!(
"ffprobe failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
)
.into());
}
let text = String::from_utf8_lossy(&out.stdout);
let mut probe = parse_probe(&text)?;
probe.duration_us = text
.lines()
.filter_map(|line| line.trim().strip_prefix("duration="))
.find_map(|seconds| seconds.parse::<f64>().ok())
.map(|seconds| (seconds * 1e6).round() as u64);
probe.file_bitrate = file_bitrate(
std::fs::metadata(input)?.len(),
probe.frame_count,
probe.fps,
);
Ok(probe)
}
fn file_bitrate(bytes: u64, frame_count: usize, fps: f64) -> u64 {
(bytes as f64 * 8.0 / (frame_count as f64 / fps)) as u64
}
fn parse_probe(text: &str) -> Result<Probe> {
let streams: Vec<std::collections::HashMap<&str, &str>> = text
.lines()
.filter(|line| line.contains("width="))
.map(|line| {
line.trim()
.split('|')
.filter_map(|kv| kv.split_once('='))
.collect()
})
.collect();
let [first, second, ..] = streams.as_slice() else {
return Err("expected one video stream per lens".into());
};
let number = |s: &std::collections::HashMap<&str, &str>, key: &str| -> Option<usize> {
s.get(key).and_then(|v| v.parse().ok())
};
let size = |s| -> Result<(usize, usize)> {
Ok((
number(s, "width").ok_or("no stream width")?,
number(s, "height").ok_or("no stream height")?,
))
};
let (width, height) = size(first)?;
let other = size(second)?;
if other != (width, height) || height > width {
return Err(format!(
"unsupported lens streams {width}x{height} and {}x{}",
other.0, other.1
)
.into());
}
let rate = first.get("r_frame_rate").copied().unwrap_or("").to_string();
let fps = match rate.split_once('/') {
Some((n, d)) => n.parse::<f64>()? / d.parse::<f64>()?,
None => rate.parse()?,
};
if !fps.is_finite() || fps <= 0.0 {
return Err(format!("invalid frame rate {rate}").into());
}
let frame_count = match (number(first, "nb_frames"), number(second, "nb_frames")) {
(Some(a), Some(b)) => a.min(b),
_ => return Err("ffprobe gives no frame count for the lens streams".into()),
};
if frame_count == 0 {
return Err("the lens streams have no frames".into());
}
let mut colour_args = Vec::new();
for (key, option) in [
("color_space", "-colorspace"),
("color_primaries", "-color_primaries"),
("color_transfer", "-color_trc"),
("color_range", "-color_range"),
] {
if let Some(value) = first.get(key).filter(|v| !v.is_empty() && **v != "unknown") {
colour_args.extend([option.to_string(), value.to_string()]);
}
}
Ok(Probe {
lens_size: width,
lens_height: height,
rate,
fps,
frame_count,
colour_args,
full_range: first.get("color_range") == Some(&"pc"),
file_bitrate: 0,
duration_us: None,
})
}
fn encoder_args(options: &VideoOptions, probe: &Probe) -> Vec<String> {
let mut args = Vec::new();
let gop = probe.fps.round().max(1.0);
if options.studio_encode == Some(StudioEncoder::HevcNvenc) {
args.extend([
"-c:v".into(),
"hevc_nvenc".into(),
"-b:v".into(),
probe.file_bitrate.to_string(),
"-bf".into(),
"0".into(),
"-g".into(),
gop.to_string(),
"-pix_fmt".into(),
"yuv420p".into(),
"-tag:v".into(),
"hvc1".into(),
]);
} else if options.studio_encode.is_some() {
args.extend([
"-c:v".into(),
"libx265".into(),
"-preset".into(),
options.preset.clone(),
"-b:v".into(),
probe.file_bitrate.to_string(),
"-x265-params".into(),
format!("keyint={gop}:min-keyint={gop}:scenecut=0:bframes=0"),
"-pix_fmt".into(),
"yuv420p".into(),
"-tag:v".into(),
"hvc1".into(),
]);
} else {
args.extend(["-c:v".to_string(), options.encoder.clone()]);
if matches!(options.encoder.as_str(), "libx264" | "libx265") {
args.extend([
"-preset".into(),
options.preset.clone(),
"-crf".into(),
options.crf.to_string(),
]);
args.extend(["-pix_fmt".into(), "yuv420p".into()]);
}
}
args.extend(options.encoder_args.iter().cloned());
args
}
fn read_frames(
mut source: impl Read,
bytes: usize,
limit: usize,
free: Receiver<Vec<u8>>,
full: SyncSender<Vec<u8>>,
) -> std::io::Result<usize> {
let mut count = 0;
while count < limit {
let Ok(mut buffer) = free.recv() else { break };
buffer.resize(bytes, 0);
match source.read_exact(&mut buffer) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => break,
Err(error) => return Err(error),
}
if full.send(buffer).is_err() {
break;
}
count += 1;
}
Ok(count)
}
const FLOW_RADIUS: usize = 2;
struct Prepared {
flow: Option<FrameFlow>,
fusion: Option<FrameFusion>,
}
struct DenoiseWriter<W: Write> {
inner: W,
denoiser: Denoiser,
pending: Vec<u8>,
filtered: Vec<u8>,
}
impl<W: Write> DenoiseWriter<W> {
fn new(inner: W, denoiser: Denoiser) -> Self {
DenoiseWriter {
inner,
denoiser,
pending: Vec::new(),
filtered: Vec::new(),
}
}
}
impl<W: Write> DenoiseWriter<W> {
fn push(&mut self, frame: &[u8]) -> std::io::Result<()> {
if self
.denoiser
.push(frame, &mut self.filtered)
.map_err(std::io::Error::other)?
{
self.inner.write_all(&self.filtered)?;
}
Ok(())
}
}
impl<W: Write> Write for DenoiseWriter<W> {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
let size = self.denoiser.frame_bytes();
let mut rest = bytes;
if self.pending.is_empty() {
while rest.len() >= size {
self.push(&rest[..size])?;
rest = &rest[size..];
}
}
self.pending.extend_from_slice(rest);
let mut pending = std::mem::take(&mut self.pending);
let full = pending.len() / size * size;
for frame in pending[..full].chunks_exact(size) {
self.push(frame)?;
}
pending.drain(..full);
self.pending = pending;
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
while self
.denoiser
.finish(&mut self.filtered)
.map_err(std::io::Error::other)?
{
self.inner.write_all(&self.filtered)?;
}
self.inner.flush()
}
}
#[allow(clippy::too_many_arguments)]
fn pipeline<P: Send>(
decoded: impl Read + Send,
mut encoded: impl Write + Send,
(in_bytes, out_bytes): (usize, usize),
limit: usize,
(radius, lag): (usize, usize),
prepare: impl Fn(&[u8]) -> insta360_stitch::Result<P> + Sync,
stitch: impl Fn(usize, &[u8], &[&P], Vec<u8>) -> Result<Option<Vec<u8>>>,
finish: impl FnOnce() -> Result<Option<Vec<u8>>>,
) -> Result<usize> {
let lookahead = if radius == 0 { 0 } else { radius + 1 };
let (free_in_tx, free_in) = sync_channel(2 + lookahead);
let (full_tx, full) = sync_channel(2);
let (free_out_tx, free_out) = sync_channel(2 + lag);
let (done_tx, done) = sync_channel::<Vec<u8>>(2 + lag);
for _ in 0..2 + lookahead {
free_in_tx.send(Vec::new())?;
}
for _ in 0..2 + lag {
free_out_tx.send(vec![0u8; out_bytes])?;
}
let started = std::time::Instant::now();
std::thread::scope(|scope| -> Result<usize> {
let free_in_tx = free_in_tx;
let reader = scope.spawn(move || read_frames(decoded, in_bytes, limit, free_in, full_tx));
let writer = scope.spawn(move || -> std::io::Result<()> {
for buffer in done {
encoded.write_all(&buffer)?;
if free_out_tx.send(buffer).is_err() {
break;
}
}
encoded.flush()
});
let mut held = std::collections::VecDeque::new();
let mut data = std::collections::VecDeque::new();
let (mut index, mut first) = (0, 0);
fn window<P>(
data: &std::collections::VecDeque<P>,
first: usize,
n: usize,
radius: usize,
) -> Vec<&P> {
(n.saturating_sub(radius)..=n + radius)
.filter_map(|i| i.checked_sub(first).and_then(|i| data.get(i)))
.collect()
}
let send = |frame: Vec<u8>, out: Option<Vec<u8>>, index: usize| -> Result<()> {
free_in_tx.send(frame).ok();
if let Some(out) = out {
done_tx.send(out)?;
}
if (index + 1).is_multiple_of(30) {
let fps = (index + 1) as f64 / started.elapsed().as_secs_f64();
eprint!("\rframe {}/{limit} ({fps:.1} fps)", index + 1);
}
Ok(())
};
for frame in full {
held.push_back(frame);
let newest = held.back().ok_or("no frame")?;
let next = if lookahead > 0 && held.len() > lookahead {
let out = free_out.recv()?;
let near = window(&data, first, index, radius);
let (next, stitched) = std::thread::scope(|threads| {
let next = threads.spawn(|| prepare(newest));
let stitched = stitch(index, &held[0], &near, out);
(next.join(), stitched)
});
let out = stitched?;
send(held.pop_front().ok_or("no frame")?, out, index)?;
index += 1;
next.map_err(|_| "the seam flow thread panicked")??
} else {
prepare(newest)?
};
data.push_back(next);
if lookahead == 0 {
let out = free_out.recv()?;
let out = stitch(index, &held[0], &window(&data, first, index, radius), out)?;
send(held.pop_front().ok_or("no frame")?, out, index)?;
index += 1;
}
while first + radius < index {
data.pop_front();
first += 1;
}
}
while let Some(frame) = held.pop_front() {
let out = free_out.recv()?;
let out = stitch(index, &frame, &window(&data, first, index, radius), out)?;
send(frame, out, index)?;
index += 1;
}
if let Some(out) = finish()? {
done_tx.send(out)?;
}
drop(done_tx);
let read = reader.join().map_err(|_| "the decoder thread panicked")??;
writer.join().map_err(|_| "the encoder thread panicked")??;
Ok(read.min(index))
})
}
fn frame_itself<'a, P>(near: &[&'a P], index: usize, radius: usize) -> Option<&'a P> {
near.get(index.min(radius)).copied()
}
fn encoder_stopped(error: &(dyn std::error::Error + 'static)) -> bool {
error.is::<RecvError>()
|| error.is::<SendError<Vec<u8>>>()
|| (error.downcast_ref::<std::io::Error>())
.is_some_and(|e| e.kind() == std::io::ErrorKind::BrokenPipe)
}
fn stabilization_for(requested: Option<StabilizationArg>, time_shift: bool) -> Stabilization {
match requested {
Some(mode) => mode.into(),
None if time_shift => Stabilization::Follow,
None => Stabilization::Lock,
}
}
fn imu_or_empty(imu: insta360_stitch::Result<Imu>) -> Result<Imu> {
match imu {
Err(insta360_stitch::Error::Unsupported(_)) => Ok(Imu::default()),
imu => Ok(imu?),
}
}
fn stabilize<T>(
mode: Stabilization,
rotations: impl Fn(Stabilization) -> insta360_stitch::Result<Vec<T>>,
) -> Result<(Stabilization, Vec<T>)> {
match rotations(mode) {
Err(insta360_stitch::Error::Unsupported(why)) if mode != Stabilization::Off => {
eprintln!("insta360-stitch: {why}. The video is not stabilized");
Ok((Stabilization::Off, rotations(Stabilization::Off)?))
}
rotations => Ok((mode, rotations?)),
}
}
fn decoder_command(
options: &VideoOptions,
probe: &Probe,
lens_size: usize,
band: Option<usize>,
input: &Path,
range: FrameRange,
) -> Command {
let format = if probe.full_range {
"yuvj420p"
} else {
"yuv420p"
};
let scale = if lens_size < probe.lens_size {
format!("scale={lens_size}:{}:flags=area,", 2 * lens_size)
} else {
String::new()
};
let lenses = match band {
Some(row) => {
let size = probe.lens_size;
format!("[0:v:1]pad={size}:{size}:0:{row}[l0];[0:v:0]pad={size}:{size}:0:{row}[l1];[l0][l1]")
}
None => "[0:v:1][0:v:0]".to_string(),
};
let mut command = Command::new(&options.ffmpeg);
command.args(["-v", "error", "-nostdin"]);
if let Some(hwaccel) = &options.hwaccel {
command.args(["-hwaccel", hwaccel]);
}
let threads = options.decoder_threads.to_string();
command.args(["-threads", &threads, "-filter_complex_threads", "1"]);
if range.first > 0 {
let seek = (range.first as f64 - 0.5) / probe.fps;
command.args(["-ss", &format!("{seek:.6}")]);
}
command
.args(&options.decoder_args)
.arg("-i")
.arg(ffmpeg_file(input))
.arg("-filter_complex")
.arg(format!("{lenses}vstack=inputs=2,{scale}format={format}[v]"))
.args(["-map", "[v]", "-fps_mode", "passthrough"]);
if range.is_part_of(probe) {
command.args(["-frames:v", &range.count.to_string()]);
}
command.args(["-f", "rawvideo", "-pix_fmt", format, "pipe:1"]);
command
}
fn encoder_command(
options: &VideoOptions,
probe: &Probe,
(width, height): (usize, usize),
flat: Option<(usize, usize)>,
input: &Path,
stitched: &Path,
range: FrameRange,
) -> Command {
let rate = if flat.is_some() {
BULLET_TIME_RATE
} else {
&probe.rate
};
let mut command = Command::new(&options.ffmpeg);
command
.args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
.args(["-s", &format!("{width}x{height}"), "-framerate", rate])
.args(&probe.colour_args)
.args(["-i", "pipe:0"]);
if range.is_part_of(probe) {
command.args([
"-ss",
&format!("{:.6}", range.first as f64 / probe.fps),
"-t",
&format!("{:.6}", range.count as f64 / probe.fps),
]);
}
command
.arg("-i")
.arg(ffmpeg_file(input))
.args(["-map", "0:v:0"]);
let mut filters = Vec::new();
if let Some((w, h)) = flat {
filters.push(format!(
"v360=e:sg:h_fov={BULLET_TIME_H_FOV}:v_fov={:.2}:w={w}:h={h}",
bullet_time_v_fov(w, h)
));
}
if range.repeat_last > 0 {
filters.push(format!("tpad=stop={}:stop_mode=clone", range.repeat_last));
}
let mut args = encoder_args(options, probe);
let user = args
.iter()
.rposition(|a| is_video_filter(a))
.filter(|&at| at + 1 < args.len());
match user {
_ if filters.is_empty() => {}
Some(at) => args[at + 1] = format!("{},{}", filters.join(","), args[at + 1]),
None => {
command.args(["-vf", &filters.join(",")]);
}
}
match flat {
Some(_) => command.arg("-an"),
None => command.args(["-map", "1:a?", "-c:a", "copy"]),
};
command
.args(["-map_metadata", "1"])
.args(args)
.arg(ffmpeg_file(stitched));
command
}
fn video(
input: &Path,
output: &Path,
options: &VideoOptions,
flow_threads: usize,
gpu: GpuMode,
) -> Result<()> {
check_output(input, output)?;
let mut reader = BufReader::new(File::open(input)?);
let trailer = read_trailer(&mut reader)?;
let probe = probe(&options.ffprobe, input)?;
let trim_ms = if options.no_camera_trim {
[0, 0]
} else {
trailer.trim_ms
};
let (start, end) = camera_trim(
probe.fps,
probe.frame_count,
trim_ms,
options.start,
options.end,
);
let stitcher = Stitcher::new(trailer);
let cut_bullet_time = !options.no_camera_trim
&& stitcher.trailer.is_bullet_time()
&& (start.is_none() || end.is_none());
let flat = options.bullet_time_view.then(|| {
let w = options.width.unwrap_or(2 * probe.lens_size);
(w, (w * 9 / 16) & !1)
});
let width = match flat {
Some(_) => 2 * probe.lens_size,
None => options.width.unwrap_or(2 * probe.lens_size),
};
let lens_size = probe.lens_size.min(width / 2);
let frames = stitcher.frame_stitcher(lens_size, Some(width))?;
let band = band_offset(&stitcher.trailer, probe.lens_size, probe.lens_height)?;
if options.bullet_time_view && !stitcher.trailer.is_bullet_time() {
return Err("--bullet-time-view is only for a Bullet Time clip".into());
}
let mode = match options.bullet_time_view {
true => Stabilization::Off,
false => stabilization_for(options.stabilization, stitcher.trailer.is_time_shift()),
};
let rolling = !options.no_rolling_shutter;
let imu = match (mode, rolling) {
_ if options.bullet_time_view => read_imu(&mut reader, &stitcher.trailer)?,
(Stabilization::Off, false) if !cut_bullet_time => Imu::default(),
_ => imu_or_empty(read_imu(&mut reader, &stitcher.trailer))?,
};
let (mode, mut rotations) = stabilize(mode, |mode| {
stitcher.frame_motions(&imu, probe.frame_count, probe.fps, mode, rolling)
})?;
let levels = match flat.is_some() || cut_bullet_time {
true => {
match stitcher.frame_rotations(&imu, probe.frame_count, probe.fps, Stabilization::Lock)
{
Err(insta360_stitch::Error::Unsupported(why)) if flat.is_none() => {
eprintln!("insta360-stitch: {why}. The Bullet Time clip is not cut");
Vec::new()
}
levels => levels?,
}
}
false => Vec::new(),
};
if flat.is_some() {
bullet_time_rotations(&mut rotations, &levels, probe.fps);
}
let cut = cut_bullet_time
.then(|| gyro_span(&stitcher.trailer))
.flatten()
.and_then(|span| bullet_time_cut(&levels, probe.fps, span));
if let Some((first, last)) = cut {
eprintln!("insta360-stitch: Bullet Time cut as Insta360 Studio: frames {first} to {last} (--no-camera-trim keeps all frames)");
}
let trimmed = (start, end) != (options.start, options.end);
let range = plan_range(&probe, (start, end), trimmed, cut)?;
let rotations = rotations_of_range(rotations, range);
drop(levels);
if mode != Stabilization::Off
&& !uses_recorded_frame_times(&stitcher.trailer, probe.frame_count)
{
eprintln!("insta360-stitch: the file does not have the time of all frames, the frame times use the frame rate");
}
if mode != Stabilization::Off && stitcher.trailer.frame_times.is_none() {
let video_times = File::open(input)
.ok()
.and_then(|file| video_sample_times(&mut BufReader::new(file)).ok().flatten());
let camera_times = frame_times_us(&stitcher.trailer, probe.frame_count, probe.fps);
if let Some(frame) = video_times.and_then(|video| {
first_unmatched_frame(&video, &camera_times, probe.fps, range.first + range.count)
}) {
eprintln!("insta360-stitch: the time step before frame {frame} of the video is not in the camera frame times (a dropped frame?). The stabilization from this frame can be one frame early or late");
}
}
drop(imu);
let denoise = denoise_settings_for(
options.denoise_strength,
&stitcher.trailer,
probe.lens_size,
probe.fps,
);
let denoise_on = options.denoise && stitcher.trailer.studio_denoises();
if options.denoise && !denoise_on {
eprintln!("insta360-stitch: no denoise: the camera already filtered this video in time (mctf_process_type 2), and Studio does not denoise it");
}
if denoise_on {
eprintln!(
"insta360-stitch: denoise as Studio: knee {:.1} levels, limit {} levels",
denoise.knee, denoise.limit
);
}
let parent = output
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let folder = new_temp_folder(parent)?;
let stitched = folder.join("stitched.mp4");
let result = (|| -> Result<()> {
let denoiser = denoise_on
.then(|| Denoiser::with_gpu(frames.width(), frames.height(), 1.0, Some(denoise), gpu))
.transpose()?;
if let Some(denoiser) = &denoiser {
match denoiser.gpu() {
Some(name) => eprintln!("insta360-stitch: denoise on the GPU ({name})"),
None => eprintln!(
"insta360-stitch: denoise on the processor ({})",
denoiser
.gpu_reason()
.unwrap_or("no GPU")
.replace(['\r', '\n'], " ")
),
}
}
#[cfg(feature = "gpu")]
let on_gpu = match gpu {
GpuMode::Auto => frames.gpu_video().map_err(|e| reason(&e)),
GpuMode::Off => Err("--gpu off".to_string()),
};
#[cfg(feature = "gpu")]
let on_gpu = match on_gpu {
Ok(on_gpu) => {
eprintln!(
"insta360-stitch: video stitch on the GPU ({})",
on_gpu.name()
);
Some(on_gpu)
}
Err(reason) => {
eprintln!("insta360-stitch: video stitch on the processor ({reason})");
None
}
};
#[cfg(feature = "gpu")]
let lag = usize::from(on_gpu.is_some());
#[cfg(not(feature = "gpu"))]
let lag = 0;
let flow_pool = rayon::ThreadPoolBuilder::new()
.num_threads(flow_threads)
.build()?;
let mut decoder = decoder_command(options, &probe, lens_size, band, input, range)
.stdout(Stdio::piped())
.spawn()
.map_err(|e| format!("cannot start {}: {e}", options.ffmpeg))?;
let mut encoder = encoder_command(
options,
&probe,
(frames.width(), frames.height()),
flat,
input,
&stitched,
range,
)
.stdin(Stdio::piped())
.spawn()
.map_err(|e| format!("cannot start {}: {e}", options.ffmpeg))?;
let decoded = decoder.stdout.take().ok_or("no decoder output")?;
let encoded = BufWriter::new(encoder.stdin.take().ok_or("no encoder input")?);
let encoded: Box<dyn Write + Send> = match denoiser {
Some(denoiser) => Box::new(DenoiseWriter::new(encoded, denoiser)),
None => Box::new(encoded),
};
let color_fusion = !options.no_color_fusion && probe.full_range;
if !options.no_color_fusion && !probe.full_range {
eprintln!(
"insta360-stitch: the source is not full range. The video has no colour fusion"
);
}
let no_seam_flow = options.no_seam_flow || options.bullet_time_view;
let radius = if no_seam_flow { 0 } else { FLOW_RADIUS };
let fusion_history = std::sync::Mutex::new(insta360_stitch::FusionHistory::default());
let started = std::time::Instant::now();
let count = pipeline(
decoded,
encoded,
(frames.input_frame_bytes(), frames.output_frame_bytes()),
range.count,
(radius, lag),
|frame| {
flow_pool.install(|| {
Ok(Prepared {
flow: match no_seam_flow {
true => None,
false => frames.frame_flow(frame)?,
},
fusion: match color_fusion {
true => Some(
frames.frame_fusion_after(
frame,
&mut fusion_history
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
)?,
),
false => None,
},
})
})
},
|index, frame, near, mut out| {
let flows: Vec<&FrameFlow> = near.iter().filter_map(|p| p.flow.as_ref()).collect();
let flow = (!flows.is_empty()).then(|| FrameFlow::mean(&flows));
let fusion = frame_itself(near, index, radius).and_then(|p| p.fusion.as_ref());
#[cfg(feature = "gpu")]
if let Some(gpu) = &on_gpu {
return Ok(frames.stitch_yuv420_gpu(
gpu,
&rotations[index],
flow.as_ref(),
fusion,
frame,
out,
)?);
}
frames.stitch_yuv420_full(
&rotations[index],
flow.as_ref(),
fusion,
frame,
&mut out,
)?;
Ok(Some(out))
},
|| {
#[cfg(feature = "gpu")]
if let Some(gpu) = &on_gpu {
return Ok(frames.finish_gpu(gpu)?);
}
Ok(None)
},
);
let count = match count {
Ok(count) => count,
Err(error) => {
decoder.kill().ok();
decoder.wait().ok();
let status = encoder.wait()?;
if !status.success() {
return Err(format!("the ffmpeg encoder exited with {status}").into());
}
if encoder_stopped(&*error) {
return Err("the ffmpeg encoder stopped before the last frame".into());
}
return Err(error);
}
};
let decoder_status = if count < range.count {
Some(decoder.wait()?)
} else {
decoder.kill().ok();
decoder.wait().ok();
None
};
let encoder_status = encoder.wait()?;
eprintln!(
"\rframe {count}/{} in {:.1} s",
range.count,
started.elapsed().as_secs_f64()
);
if let Some(status) = decoder_status.filter(|status| !status.success()) {
return Err(format!("the ffmpeg decoder exited with {status}").into());
}
if !encoder_status.success() {
return Err(format!("the ffmpeg encoder exited with {encoder_status}").into());
}
if count == 0 {
return Err("the decoder gave no frames".into());
}
if count < range.count {
eprintln!(
"insta360-stitch: the decoder gave {count} of {} frames",
range.count
);
}
match flat {
Some(_) => Ok(std::fs::rename(&stitched, output)?),
None => finish_video(&stitched, output),
}
})();
std::fs::remove_dir_all(&folder).ok();
result
}
const BULLET_TIME_VIEW: Mat3 = [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0]];
const BULLET_TIME_H_FOV: f64 = 143.0;
const BULLET_TIME_RATE: &str = "30000/1001";
const BULLET_TIME_SMOOTHING_S: f64 = 0.11;
fn bullet_time_v_fov(width: usize, height: usize) -> f64 {
let half = (BULLET_TIME_H_FOV / 4.0).to_radians().tan() * height as f64 / width as f64;
4.0 * half.atan().to_degrees()
}
fn bullet_time_view(level: &Mat3, forward: &[f64; 3]) -> Mat3 {
let world_up = apply(level, &[0.0, 1.0, 0.0]);
let along = dot(&world_up, forward);
let up = std::array::from_fn(|i| world_up[i] - along * forward[i]);
if norm(&up) < 1e-6 {
return BULLET_TIME_VIEW;
}
let up = normalize(&up);
let right = cross(forward, &up);
std::array::from_fn(|i| [right[i], up[i], -forward[i]])
}
fn bullet_time_forwards(levels: &[Mat3], sigma: f64) -> Vec<[f64; 3]> {
let stick: Vec<[f64; 3]> = levels
.iter()
.map(|level| apply(&transpose(level), &[0.0, -1.0, 0.0]))
.collect();
let reach = (4.0 * sigma).ceil() as isize;
let last = stick.len() as isize - 1;
levels
.iter()
.enumerate()
.map(|(k, level)| {
let mut sum = [0.0; 3];
for d in -reach..=reach {
let w = (-0.5 * (d as f64 / sigma.max(1e-9)).powi(2)).exp();
let s = stick[(k as isize + d).clamp(0, last) as usize];
(0..3).for_each(|i| sum[i] += w * s[i]);
}
apply(level, &normalize(&sum))
})
.collect()
}
fn rotations_of_range<T>(mut rotations: Vec<T>, range: FrameRange) -> Vec<T> {
rotations.truncate(range.first + range.count);
rotations.drain(..range.first.min(rotations.len()));
rotations.shrink_to_fit();
rotations
}
fn bullet_time_rotations(rotations: &mut [FrameRotation], levels: &[Mat3], fps: f64) {
let forwards = bullet_time_forwards(levels, BULLET_TIME_SMOOTHING_S * fps);
for ((rotation, level), forward) in rotations.iter_mut().zip(levels).zip(&forwards) {
let view = bullet_time_view(level, forward);
let fix = mul(&transpose(&rotation.centre), &view);
rotation.centre = view;
for rows in &mut rotation.rows {
for row in rows.iter_mut() {
*row = mul(row, &fix);
}
}
}
}
fn finish_video(stitched: &Path, output: &Path) -> Result<()> {
if let Err(error) = write_spherical_mp4_file(stitched, output) {
eprintln!("insta360-stitch: the output has no 360 video metadata: {error}");
std::fs::rename(stitched, output)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use insta360_stitch::math::IDENTITY;
use insta360_stitch::{stitch_photo, Lens};
fn pipeline_at_once<P: Send>(
decoded: impl Read + Send,
encoded: impl Write + Send,
bytes: (usize, usize),
limit: usize,
radius: usize,
prepare: impl Fn(&[u8]) -> insta360_stitch::Result<P> + Sync,
stitch: impl Fn(usize, &[u8], &[&P], &mut [u8]) -> Result<()>,
) -> Result<usize> {
pipeline(
decoded,
encoded,
bytes,
limit,
(radius, 0),
prepare,
|index, frame, near, mut out| {
stitch(index, frame, near, &mut out)?;
Ok(Some(out))
},
|| Ok(None),
)
}
fn test_photo(width: usize, height: usize) -> (LensModel, Vec<u8>) {
let pixels: Vec<u8> = (0..width * height * 3)
.map(|i| (i * 7 % 251) as u8)
.collect();
let lens = Lens {
rotation: IDENTITY,
cx: 64.0,
cy: 64.0,
radius: 64.0,
mei: None,
};
let model = LensModel {
lenses: [lens, lens],
coefficients: [0.0, 0.03159, -8.415e-5, 2.201e-6, -1.284e-8],
half_fov: 100.0,
level: IDENTITY,
blend: None,
};
(model, pixels)
}
#[test]
fn only_the_rotations_of_the_range_stay() {
let range = |first, count| FrameRange {
first,
count,
repeat_last: 1,
};
let kept = rotations_of_range((0..10).collect::<Vec<u32>>(), range(3, 4));
assert_eq!(
(kept.as_slice(), kept.capacity()),
([3, 4, 5, 6].as_slice(), 4)
);
assert_eq!(
rotations_of_range((0..10).collect::<Vec<u32>>(), range(0, 10)),
(0..10).collect::<Vec<_>>()
);
}
#[test]
fn rows_give_the_encoder_the_stitched_rows_across_bands() {
let (width, height) = (300, 150);
let (model, pixels) = test_photo(width, height);
let source = Image {
width,
height,
channels: 3,
data: &pixels,
};
let expected = stitch_photo(&source, &model).unwrap();
let seam = PhotoSeam::new(&source, &model).unwrap();
std::thread::scope(|scope| {
let rows = Rows::stitched(scope, source, &model, &seam);
for y in (0..height).chain([height - 1, height - 1]) {
let mut buffers: [Vec<u8>; 4] = Default::default();
(&rows).fill_buffers(y as u16, &mut buffers);
let want: Vec<u8> = expected[y * width * 3..][..width * 3]
.as_chunks::<3>()
.0
.iter()
.map(|p| rgb_to_ycbcr(p[0], p[1], p[2]).0)
.collect();
assert_eq!(buffers[0], want, "row {y}");
}
rows.check().unwrap();
});
}
#[test]
fn a_stitch_error_stops_the_photo_and_leaves_no_file() {
let (width, height) = (256, 128);
let (model, pixels) = test_photo(width, height);
let good = Image {
width,
height,
channels: 3,
data: &pixels,
};
let seam = PhotoSeam::new(&good, &model).unwrap();
let bad = Image {
data: &pixels[1..],
..good
};
let folder = new_temp_folder(&std::env::temp_dir()).unwrap();
let output = folder.join("pano.jpg");
let result = std::thread::scope(|scope| {
write_panorama_jpeg(&output, Rows::stitched(scope, bad, &model, &seam), 90, None)
});
let error = result.unwrap_err().to_string();
assert!(error.contains("image data does not match"), "{error}");
assert_eq!(std::fs::read_dir(&folder).unwrap().count(), 0);
std::fs::remove_dir_all(&folder).ok();
}
#[test]
fn a_stitch_error_comes_before_the_write_error_that_follows_it() {
struct FailsInTheScan(Vec<u8>);
impl Write for FailsInTheScan {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
match self.0.windows(2).position(|w| w == [0xff, 0xda]) {
Some(sos) if self.0.len() >= sos + 14 => {
Err(std::io::Error::other("disk full"))
}
_ => {
self.0.extend_from_slice(bytes);
Ok(bytes.len())
}
}
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let (width, height) = (256, 128);
let (model, pixels) = test_photo(width, height);
let good = Image {
width,
height,
channels: 3,
data: &pixels,
};
let seam = PhotoSeam::new(&good, &model).unwrap();
let encode = |source| {
std::thread::scope(|scope| {
let rows = Rows::stitched(scope, source, &model, &seam);
encode_panorama(FailsInTheScan(Vec::new()), &rows, 90, None)
.unwrap_err()
.to_string()
})
};
let error = encode(good);
assert!(error.contains("disk full"), "{error}");
let error = encode(Image {
data: &pixels[1..],
..good
});
assert!(error.contains("image data does not match"), "{error}");
}
#[test]
fn the_stitch_thread_stops_when_the_encoder_stops_early() {
let (width, height) = (512, 256);
let (model, pixels) = test_photo(width, height);
let source = Image {
width,
height,
channels: 3,
data: &pixels,
};
let seam = PhotoSeam::new(&source, &model).unwrap();
std::thread::scope(|scope| {
let rows = Rows::stitched(scope, source, &model, &seam);
(&rows).fill_buffers(0, &mut Default::default());
});
}
fn test_folder(name: &str) -> PathBuf {
let folder =
std::env::temp_dir().join(format!("insta360-cli-{name}-{}", std::process::id()));
std::fs::remove_dir_all(&folder).ok();
std::fs::create_dir_all(&folder).unwrap();
folder
}
fn make_box(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
[&((8 + body.len()) as u32).to_be_bytes()[..], kind, body].concat()
}
fn minimal_mp4() -> Vec<u8> {
let full = |kind: &[u8; 4], body: &[u8]| make_box(kind, &[&[0u8; 4][..], body].concat());
let ftyp = make_box(b"ftyp", b"isom\0\0\x02\0isomiso2");
let mdat = make_box(b"mdat", b"VIDEO-ONE");
let entry = make_box(b"avc1", &[0u8; 78]);
let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &entry].concat());
let offset = (ftyp.len() as u32 + 8).to_be_bytes();
let stco = full(b"stco", &[&1u32.to_be_bytes()[..], &offset].concat());
let hdlr = full(b"hdlr", &[&[0u8; 4][..], b"vide", &[0u8; 13]].concat());
let minf = make_box(b"minf", &make_box(b"stbl", &[stsd, stco].concat()));
let trak = make_box(b"trak", &make_box(b"mdia", &[hdlr, minf].concat()));
[ftyp, mdat, make_box(b"moov", &trak)].concat()
}
#[test]
fn finish_video_keeps_the_encode_when_the_metadata_step_fails() {
let folder = test_folder("finish");
let (stitched, output) = (folder.join("stitched.mp4"), folder.join("out.mp4"));
std::fs::write(&stitched, minimal_mp4()).unwrap();
finish_video(&stitched, &output).unwrap();
let out = std::fs::read(&output).unwrap();
assert!(out.windows(4).any(|w| w == b"sv3d"));
std::fs::write(&stitched, b"an encode that is not a usual MP4 file").unwrap();
finish_video(&stitched, &output).unwrap();
assert_eq!(
std::fs::read(&output).unwrap(),
b"an encode that is not a usual MP4 file"
);
assert!(!stitched.exists());
std::fs::remove_dir_all(&folder).unwrap();
}
#[test]
fn a_bracket_of_three_photos_is_merged_and_a_bracket_of_two_is_refused() {
let folder = test_folder("bracket");
let photo_file = folder.join("IMG_1.insp");
std::fs::write(
&photo_file,
include_bytes!("../../../tests/fixtures/synthetic_x5.insp"),
)
.unwrap();
let out = folder.join("merged.jpg");
let others = [photo_file.clone(), photo_file.clone()];
photo(&photo_file, &out, 95, None, &others, GpuMode::Auto).unwrap();
assert!(std::fs::metadata(&out).unwrap().len() > 0);
let two = folder.join("two.jpg");
let error = photo(&photo_file, &two, 95, None, &others[..1], GpuMode::Auto).unwrap_err();
assert!(error.to_string().contains("2 exposures"), "{error}");
assert!(!two.exists());
let error = photo(
&photo_file,
&out,
95,
None,
&[out.clone(), photo_file.clone()],
GpuMode::Auto,
)
.unwrap_err();
assert!(error.to_string().contains("--bracket"), "{error}");
std::fs::remove_dir_all(&folder).unwrap();
}
#[test]
fn the_level_from_photo_gives_the_level_and_must_be_a_usable_other_file() {
let folder = test_folder("level-from");
let photo_file = folder.join("IMG_1.insp");
std::fs::write(
&photo_file,
include_bytes!("../../../tests/fixtures/synthetic_x5.insp"),
)
.unwrap();
let (plain, same) = (folder.join("plain.jpg"), folder.join("same.jpg"));
photo(&photo_file, &plain, 95, None, &[], GpuMode::Auto).unwrap();
photo(
&photo_file,
&same,
95,
Some(&photo_file),
&[],
GpuMode::Auto,
)
.unwrap();
assert_eq!(
std::fs::read(&plain).unwrap(),
std::fs::read(&same).unwrap()
);
let not_a_photo = folder.join("note.txt");
std::fs::write(¬_a_photo, b"not an Insta360 file").unwrap();
let out = folder.join("out.jpg");
assert!(photo(
&photo_file,
&out,
95,
Some(¬_a_photo),
&[],
GpuMode::Auto
)
.is_err());
assert!(!out.exists());
let error = photo(&photo_file, &out, 95, Some(&out), &[], GpuMode::Auto)
.unwrap_err()
.to_string();
assert!(error.contains("--level-from"), "{error}");
std::fs::remove_dir_all(&folder).unwrap();
}
#[test]
fn a_band_stream_is_padded_to_a_square_at_its_row() {
let line =
|w: u32, h: u32| format!("width={w}|height={h}|r_frame_rate=120/1|nb_frames=9\n");
let probe = parse_probe(&line(2880, 1440).repeat(2)).unwrap();
assert_eq!((probe.lens_size, probe.lens_height), (2880, 1440));
let args: Vec<String> = decoder_command(
&test_video_options(),
&probe,
2880,
Some(1440),
Path::new("in.insv"),
FrameRange::whole(&probe),
)
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
let filter = &args[args.iter().position(|a| a == "-filter_complex").unwrap() + 1];
let pads = "[0:v:1]pad=2880:2880:0:1440[l0];[0:v:0]pad=2880:2880:0:1440[l1];[l0][l1]vstack";
assert!(filter.starts_with(pads), "{filter}");
assert!(parse_probe(&line(1440, 2880).repeat(2)).is_err());
}
#[test]
fn the_bullet_time_view_looks_along_the_stick_with_the_world_up_on_top() {
use insta360_stitch::math::{apply, axis_rotation, IDENTITY};
let close = |x: &[f64], y: &[f64]| x.iter().zip(y).all(|(p, q)| (p - q).abs() < 1e-12);
let level_z = axis_rotation('x', -90.0);
assert!(close(&apply(&level_z, &[0.0, 1.0, 0.0]), &[0.0, 0.0, -1.0]));
assert!(close(
bullet_time_view(&level_z, &[0.0, -1.0, 0.0]).as_flattened(),
BULLET_TIME_VIEW.as_flattened()
));
let level = mul(&axis_rotation('y', 10.0), &level_z);
let view = bullet_time_view(&level, &[0.0, -1.0, 0.0]);
let world_up = apply(&level, &[0.0, 1.0, 0.0]);
assert!(close(&apply(&view, &[0.0, 0.0, -1.0]), &[0.0, -1.0, 0.0]));
assert!(close(&apply(&view, &[0.0, 1.0, 0.0]), &world_up));
assert!(close(
bullet_time_view(&IDENTITY, &[0.0, -1.0, 0.0]).as_flattened(),
BULLET_TIME_VIEW.as_flattened()
));
let f = axis_rotation('x', 30.0);
let a = axis_rotation('z', 2.0);
let mut rotations = [FrameRotation {
centre: f,
rows: [vec![f, mul(&a, &f)], vec![]],
}];
bullet_time_rotations(&mut rotations, &[level], 120.0);
assert!(close(
rotations[0].centre.as_flattened(),
view.as_flattened()
));
assert!(close(
rotations[0].rows[0][0].as_flattened(),
view.as_flattened()
));
assert!(close(
rotations[0].rows[0][1].as_flattened(),
mul(&a, &view).as_flattened()
));
assert!(rotations[0].rows[1].is_empty());
}
#[test]
fn the_bullet_time_view_follows_a_smoothed_stick() {
use insta360_stitch::math::{apply, axis_rotation};
let level_z = axis_rotation('x', -90.0);
let levels: Vec<Mat3> = (0..41)
.map(|k| {
mul(
&level_z,
&axis_rotation('y', if k % 2 == 0 { 1.0 } else { -1.0 }),
)
})
.collect();
let forwards = bullet_time_forwards(&levels, 5.0);
let middle = apply(&transpose(&levels[20]), &forwards[20]);
let stick = apply(&transpose(&levels[20]), &[0.0, -1.0, 0.0]);
let level_stick = apply(&transpose(&level_z), &[0.0, -1.0, 0.0]);
let angle = |a: &[f64; 3], b: &[f64; 3]| dot(a, b).clamp(-1.0, 1.0).acos().to_degrees();
assert!((angle(&stick, &level_stick) - 1.0).abs() < 1e-9);
assert!(
angle(&middle, &level_stick) < 0.01,
"{}",
angle(&middle, &level_stick)
);
let still = bullet_time_forwards(&[level_z; 3], 5.0);
assert!(still.iter().all(|f| angle(f, &[0.0, -1.0, 0.0]) < 1e-6));
}
#[test]
fn a_bullet_time_view_is_flat_at_29_97_fps_without_audio() {
let probe = parse_probe(
&"width=64|height=32|r_frame_rate=120000/1001|nb_frames=9
"
.repeat(2),
)
.unwrap();
let args: Vec<String> = encoder_command(
&test_video_options(),
&probe,
(128, 64),
Some((1920, 1080)),
Path::new("in.insv"),
Path::new("out.mp4"),
FrameRange::whole(&probe),
)
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
let after = |key: &str| &args[args.iter().position(|a| a == key).unwrap() + 1];
assert_eq!(after("-framerate"), "30000/1001");
assert!(
after("-vf").starts_with("v360=e:sg:h_fov=143:v_fov=88."),
"{args:?}"
);
assert!(after("-vf").ends_with(":w=1920:h=1080"), "{args:?}");
assert!(args.contains(&"-an".to_string()) && !args.contains(&"1:a?".to_string()));
assert!((bullet_time_v_fov(1920, 1080) - 88.17).abs() < 0.05);
}
#[test]
fn each_command_refuses_to_write_over_its_input() {
let folder = test_folder("same");
let file = folder.join("VID_1.insv");
std::fs::write(&file, b"original footage").unwrap();
let results = [
photo(&file, &file, 95, None, &[], GpuMode::Auto),
preview(&file, &file),
video(&file, &file, &test_video_options(), 2, GpuMode::Auto),
];
for result in results {
let error = result.unwrap_err().to_string();
assert!(error.contains("different file"), "{error}");
}
assert_eq!(std::fs::read(&file).unwrap(), b"original footage");
std::fs::remove_dir_all(&folder).unwrap();
}
fn test_video_options() -> VideoOptions {
VideoOptions {
width: None,
stabilization: None,
studio_encode: None,
encoder: "libx264".into(),
crf: 20,
preset: "medium".into(),
encoder_args: vec!["-tune".into(), "film".into()],
hwaccel: None,
decoder_threads: 2,
decoder_args: Vec::new(),
no_rolling_shutter: false,
no_seam_flow: false,
no_color_fusion: false,
bullet_time_view: false,
denoise: false,
denoise_strength: None,
start: None,
end: None,
no_camera_trim: false,
ffmpeg: "ffmpeg".into(),
ffprobe: "ffprobe".into(),
}
}
#[test]
fn probe_reads_square_lens_streams_the_smaller_frame_count_and_the_colour_tags() {
let line = |frames: &str| {
format!("width=3840|height=3840|r_frame_rate=24/1|nb_frames={frames}|color_range=tv|color_space=bt709|color_transfer=bt709|color_primaries=unknown\n")
};
let probe = parse_probe(&(line("80") + &line("81"))).unwrap();
assert_eq!(
probe,
Probe {
lens_size: 3840,
lens_height: 3840,
rate: "24/1".into(),
fps: 24.0,
frame_count: 80,
colour_args: [
"-colorspace",
"bt709",
"-color_trc",
"bt709",
"-color_range",
"tv"
]
.map(String::from)
.to_vec(),
full_range: false,
file_bitrate: 0,
duration_us: None,
}
);
let ntsc = "width=2880|height=2880|r_frame_rate=60000/1001|nb_frames=233\n".repeat(2);
assert!((parse_probe(&ntsc).unwrap().fps - 59.94).abs() < 0.01);
for bad in [
line("80"),
"width=1920|height=3840|r_frame_rate=24/1|nb_frames=80\n".repeat(2),
"width=64|height=64|r_frame_rate=0/1|nb_frames=5\n".repeat(2),
"width=64|height=64|r_frame_rate=24/1|nb_frames=N/A\n".repeat(2),
"width=64|height=64|r_frame_rate=24/1|nb_frames=0\n".repeat(2),
] {
assert!(parse_probe(&bad).is_err(), "{bad}");
}
}
fn probe_of(fps_rate: &str) -> Probe {
let line = format!(
"width=64|height=64|r_frame_rate={fps_rate}|nb_frames=5|color_range=pc
"
);
parse_probe(&line.repeat(2)).unwrap()
}
#[test]
fn studio_exports_one_frame_more_when_the_duration_is_a_whole_number_of_frames() {
for (frames, duration_us, studio) in [
(90, 3_003_000, 91),
(8, 266_933, 8),
(198, 6_606_600, 199),
(113, 3_770_433, 113),
] {
let mut probe = probe_of("30000/1001");
probe.frame_count = frames;
probe.duration_us = Some(duration_us);
assert_eq!(studio_frame_count(&probe), studio, "{frames} frames");
}
assert_eq!(studio_frame_count(&probe_of("30000/1001")), 5);
}
#[test]
fn the_range_takes_the_cut_only_at_the_ends_without_a_time_and_repeats_only_to_the_end() {
let mut probe = probe_of("30/1");
(probe.frame_count, probe.duration_us) = (90, Some(3_000_000));
let plan = |range, cut| plan_range(&probe, range, false, cut).unwrap();
let of = |r: FrameRange| (r.first, r.count, r.repeat_last);
assert_eq!(of(plan((None, None), None)), (0, 90, 1));
assert_eq!(of(plan((Some(1.0), None), Some((10, 59)))), (30, 30, 0));
assert_eq!(of(plan((None, Some(2.0)), None)), (0, 61, 0));
probe.duration_us = Some(3_066_667);
assert_eq!(
of(plan_range(&probe, (None, None), false, None).unwrap()),
(0, 90, 1)
);
probe.duration_us = Some(3_000_000);
let error = plan_range(&probe, (Some(2.5), Some(0.5)), true, None).unwrap_err();
assert!(error.to_string().contains("--no-camera-trim"), "{error}");
let error = plan_range(&probe, (Some(2.5), Some(0.5)), false, None).unwrap_err();
assert!(!error.to_string().contains("--no-camera-trim"), "{error}");
}
#[test]
fn encoder_args_add_quality_only_for_x264_and_x265() {
let probe = probe_of("24/1");
let mut options = test_video_options();
assert_eq!(
encoder_args(&options, &probe),
[
"-c:v", "libx264", "-preset", "medium", "-crf", "20", "-pix_fmt", "yuv420p",
"-tune", "film"
]
);
options.encoder = "hevc_vaapi".into();
options.encoder_args = vec!["-vf".into(), "format=nv12,hwupload".into()];
assert_eq!(
encoder_args(&options, &probe),
["-c:v", "hevc_vaapi", "-vf", "format=nv12,hwupload"]
);
}
#[test]
fn studio_encode_gives_hevc_at_the_file_bitrate_with_a_key_frame_each_second() {
let mut probe = probe_of("30000/1001");
probe.file_bitrate = 153_314_373;
let mut options = test_video_options();
options.studio_encode = Some(StudioEncoder::Libx265);
options.encoder_args = vec!["-threads".into(), "4".into()];
assert_eq!(
encoder_args(&options, &probe),
[
"-c:v",
"libx265",
"-preset",
"medium",
"-b:v",
"153314373",
"-x265-params",
"keyint=30:min-keyint=30:scenecut=0:bframes=0",
"-pix_fmt",
"yuv420p",
"-tag:v",
"hvc1",
"-threads",
"4"
]
);
}
#[test]
fn the_file_bitrate_is_the_size_over_the_video_duration() {
let bitrate = file_bitrate(1_335_808_342, 2089, 30000.0 / 1001.0);
assert!(bitrate.abs_diff(153_314_373) < 1000, "{bitrate}");
}
#[test]
fn studio_encode_does_not_go_with_an_encoder_or_a_crf() {
use clap::Parser;
let parse = |extra: &[&str]| {
let mut args = vec!["insta360-stitch", "video", "in.insv", "out.mp4"];
args.extend(extra);
Cli::try_parse_from(args)
};
assert!(parse(&["--studio-encode", "--preset", "fast"]).is_ok());
assert!(parse(&["--studio-encode=hevc_nvenc"]).is_ok());
assert!(parse(&["--studio-encode=libx264"]).is_err());
assert!(parse(&["--studio-encode", "--encoder", "libx264"]).is_err());
assert!(parse(&["--studio-encode", "--crf", "18"]).is_err());
}
#[test]
fn studio_encode_with_nvenc_has_the_encoder_settings_of_studio() {
let mut probe = probe_of("30000/1001");
probe.file_bitrate = 153_314_373;
let mut options = test_video_options();
options.studio_encode = Some(StudioEncoder::HevcNvenc);
assert_eq!(
encoder_args(&options, &probe),
[
"-c:v",
"hevc_nvenc",
"-b:v",
"153314373",
"-bf",
"0",
"-g",
"30",
"-pix_fmt",
"yuv420p",
"-tag:v",
"hvc1",
"-tune",
"film"
]
);
}
#[test]
fn a_file_at_the_temporary_name_is_not_written_over() {
let folder = std::env::temp_dir().join(format!("insta360-cli-part-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
let output = folder.join("out.gpx");
let parts: Vec<PathBuf> = (0..64)
.map(|n| {
let mut part = output.as_os_str().to_owned();
part.push(format!(".{}-{n}.part", std::process::id()));
std::fs::write(&part, b"keep").unwrap();
part.into()
})
.collect();
assert!(write_atomically(&output, |out| Ok(out.write_all(b"gpx")?)).is_err());
assert!(!output.exists());
for part in &parts {
assert_eq!(std::fs::read(part).unwrap(), b"keep");
}
std::fs::remove_dir_all(&folder).unwrap();
}
#[test]
fn a_program_that_does_not_start_is_named_in_the_error() {
let error = probe("no-such-ffprobe-program", Path::new("in.insv")).unwrap_err();
assert!(
error.to_string().contains("no-such-ffprobe-program"),
"{error}"
);
}
#[test]
fn only_the_video_filter_options_get_our_filters() {
for option in [
"-vf",
"-vf:0",
"-filter",
"-filter:v",
"-filter:v:0",
"-filter:0",
] {
assert!(is_video_filter(option), "{option}");
}
for option in [
"-filter:a",
"-filter:1",
"-filter_complex",
"-filter_script:v",
"-af",
"-vframes",
] {
assert!(!is_video_filter(option), "{option}");
}
}
#[cfg(unix)]
#[test]
fn an_output_that_is_a_device_gets_the_data_directly() {
let result = write_atomically(Path::new("/dev/null"), |out| Ok(out.write_all(b"gpx")?));
assert!(result.is_ok(), "{result:?}");
}
#[test]
fn a_step_of_the_video_that_the_camera_times_do_not_have_is_found() {
let fps = 30.0;
let video: Vec<f64> = [0, 1, 2, 4, 5].iter().map(|&n| n as f64 / fps).collect();
let camera = [0.0, 33_400.0, 66_600.0, 133_300.0, 166_700.0];
assert_eq!(first_unmatched_frame(&video, &camera, fps, 5), None);
let camera = [0.0, 33_333.0, 66_667.0, 100_000.0, 133_333.0];
assert_eq!(first_unmatched_frame(&video, &camera, fps, 5), Some(3));
let video = [0.0, 1.0 / fps, 2.0 / fps];
assert_eq!(
first_unmatched_frame(&video, &[0.0, 66_667.0, 100_000.0], fps, 3),
Some(1)
);
let video = [0.0, 1.0 / fps, 2.0 / fps, 4.0 / fps];
let camera = [0.0, 33_333.0, 66_667.0, 100_000.0];
assert_eq!(first_unmatched_frame(&video, &camera, fps, 3), None);
assert_eq!(first_unmatched_frame(&video, &camera, fps, 4), Some(3));
}
#[test]
fn the_denoise_strength_needs_the_denoise_and_is_more_than_0_and_at_most_16() {
use clap::Parser;
let parse = |extra: &[&str]| {
let mut args = vec!["insta360-stitch", "video", "in.insv", "out.mp4"];
args.extend(extra);
Cli::try_parse_from(args)
};
assert!(parse(&["--denoise", "--denoise-strength", "1.5"]).is_ok());
assert!(parse(&["--denoise", "--denoise-strength", "16"]).is_ok());
assert!(parse(&["--denoise-strength", "1.5"]).is_err());
for bad in ["0", "-1", "16.5", "nan", "inf", "much"] {
assert!(
parse(&["--denoise", "--denoise-strength", bad]).is_err(),
"{bad}"
);
}
}
#[test]
fn the_encoder_copies_the_metadata_and_the_colour_tags_and_keeps_all_frames() {
let line = "width=64|height=64|r_frame_rate=24/1|nb_frames=5|color_range=pc\n";
let probe = parse_probe(&line.repeat(2)).unwrap();
let command = encoder_command(
&test_video_options(),
&probe,
(128, 64),
None,
Path::new("in.insv"),
Path::new("out.mp4"),
FrameRange::whole(&probe),
);
let args: Vec<_> = command.get_args().map(|a| a.to_string_lossy()).collect();
let at = |value: &str| args.iter().position(|a| a == value).unwrap();
assert!(!args.iter().any(|a| a == "-ss" || a == "-t"), "{args:?}");
assert_eq!(args[at("file:in.insv") - 1], "-i");
assert_eq!(args[at("-map_metadata") + 1], "1");
assert!(at("-map_metadata") > at("file:in.insv"), "{args:?}");
assert!(at("-color_range") < at("pipe:0"), "{args:?}");
assert_eq!(args.iter().filter(|a| *a == "-color_range").count(), 1);
assert!(!args.iter().any(|a| a == "-shortest"), "{args:?}");
assert_eq!(args.last().unwrap(), "file:out.mp4");
}
#[test]
fn the_output_must_not_be_the_input_or_a_camera_file() {
let dir = std::env::temp_dir();
let input = dir.join("VID_1_00_001.insv");
assert!(check_output(&input, &dir.join("out.mp4")).is_ok());
assert!(check_output(&input, &input).is_err());
for other in ["VID_2_00_002.insv", "IMG_1.INSP", "LRV_1_01_001.lrv"] {
assert!(check_output(&input, &dir.join(other)).is_err(), "{other}");
}
}
#[test]
fn the_time_range_keeps_the_frames_that_studio_keeps() {
let ntsc = 30000.0 / 1001.0;
assert_eq!(
frame_range(ntsc, 2089, Some(2.96963), Some(66.7)).unwrap(),
(89, 1911)
);
assert_eq!(
frame_range(ntsc, 446, Some(2.96963), Some(11.8785)).unwrap(),
(89, 268)
);
assert_eq!(
frame_range(60000.0 / 1001.0, 233, Some(0.0), Some(3.88722)).unwrap(),
(0, 233)
);
assert_eq!(
frame_range(120000.0 / 1001.0, 392, None, Some(3.26159)).unwrap(),
(0, 392)
);
assert_eq!(frame_range(24.0, 80, None, None).unwrap(), (0, 80));
assert_eq!(frame_range(24.0, 80, Some(1.0), None).unwrap(), (24, 56));
assert!(frame_range(24.0, 80, Some(10.0), None).is_err());
assert!(frame_range(24.0, 80, Some(2.0), Some(1.0)).is_err());
assert_eq!(
frame_range(24.0, 80, Some(1.0004), Some(1.0)).unwrap(),
(24, 1)
);
}
#[test]
fn the_camera_trim_cuts_the_frames_that_studio_cuts_by_default() {
let range = |fps: f64, n: usize, trim: [u64; 2], start: Option<f64>, end: Option<f64>| {
let (start, end) = camera_trim(fps, n, trim, start, end);
frame_range(fps, n, start, end).unwrap()
};
let ntsc = 30000.0 / 1001.0;
assert_eq!(range(25.0, 451, [3000, 3000], None, None), (75, 302));
assert_eq!(range(ntsc, 732, [3000, 3000], None, None), (89, 554));
assert_eq!(range(ntsc, 446, [3000, 3000], None, None), (89, 268));
assert_eq!(range(25.0, 750, [3000, 0], None, None), (75, 675));
assert_eq!(range(25.0, 750, [0, 0], None, None), (0, 750));
assert_eq!(range(25.0, 750, [3000, 3000], Some(1.0), None), (25, 651));
assert_eq!(range(25.0, 750, [3000, 3000], None, Some(20.0)), (75, 426));
assert_eq!(range(25.0, 100, [3000, 3000], None, None), (0, 100));
}
#[test]
fn a_time_range_seeks_the_decoder_and_cuts_the_audio_to_the_same_frames() {
let line = "width=64|height=64|r_frame_rate=24/1|nb_frames=240|color_range=pc
";
let probe = parse_probe(&line.repeat(2)).unwrap();
let range = FrameRange {
first: 48,
count: 24,
repeat_last: 0,
};
let strings = |command: Command| -> Vec<String> {
command
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect()
};
let decoder = strings(decoder_command(
&test_video_options(),
&probe,
64,
None,
Path::new("in.insv"),
range,
));
let seek = decoder.iter().position(|a| a == "-ss").expect("no seek");
let frames = decoder
.iter()
.position(|a| a == "-frames:v")
.expect("no frame limit");
assert_eq!(decoder[frames + 1], "24");
assert_eq!(decoder[seek + 1], "1.979167");
assert!(
seek < decoder.iter().position(|a| a == "file:in.insv").unwrap(),
"{decoder:?}"
);
let encoder = strings(encoder_command(
&test_video_options(),
&probe,
(128, 64),
None,
Path::new("in.insv"),
Path::new("out.mp4"),
range,
));
let at = |value: &str| encoder.iter().position(|a| a == value).unwrap();
assert_eq!(encoder[at("-ss") + 1], "2.000000");
assert_eq!(encoder[at("-t") + 1], "1.000000");
assert!(
at("pipe:0") < at("-ss") && at("-ss") < at("file:in.insv"),
"{encoder:?}"
);
assert!(!encoder.iter().any(|a| a == "-vf"), "{encoder:?}");
let repeat = FrameRange {
repeat_last: 1,
..range
};
let encoder = strings(encoder_command(
&test_video_options(),
&probe,
(128, 64),
None,
Path::new("in.insv"),
Path::new("out.mp4"),
repeat,
));
let at = |value: &str| encoder.iter().position(|a| a == value).unwrap();
assert_eq!(encoder[at("-vf") + 1], "tpad=stop=1:stop_mode=clone");
let mut options = test_video_options();
options.encoder_args = vec!["-vf".into(), "hwupload".into()];
let encoder = strings(encoder_command(
&options,
&probe,
(128, 64),
None,
Path::new("in.insv"),
Path::new("out.mp4"),
repeat,
));
assert_eq!(
encoder.iter().filter(|a| *a == "-vf").count(),
1,
"{encoder:?}"
);
let at = |value: &str| encoder.iter().position(|a| a == value).unwrap();
assert_eq!(
encoder[at("-vf") + 1],
"tpad=stop=1:stop_mode=clone,hwupload"
);
let tpad = "tpad=stop=1:stop_mode=clone";
for (user, expected) in [
(
vec!["-vf", "a", "-filter:v:0", "b"],
vec![vec![
"-vf",
"a",
"-filter:v:0",
"tpad=stop=1:stop_mode=clone,b",
]],
),
(
vec!["-vf", "a", "-vf"],
vec![vec!["-vf", tpad], vec!["-vf", "a", "-vf"]],
),
] {
let mut options = test_video_options();
options.encoder_args = user.iter().map(|a| a.to_string()).collect();
let encoder = strings(encoder_command(
&options,
&probe,
(128, 64),
None,
Path::new("in.insv"),
Path::new("out.mp4"),
repeat,
));
for args in expected {
assert!(
encoder.windows(args.len()).any(|w| w == args),
"{encoder:?}"
);
}
}
let whole = strings(decoder_command(
&test_video_options(),
&probe,
64,
None,
Path::new("in.insv"),
FrameRange::whole(&probe),
));
assert!(
!whole.iter().any(|a| a == "-ss" || a == "-frames:v"),
"{whole:?}"
);
}
#[test]
fn the_range_options_are_times_of_0_seconds_or_more() {
let parse = |args: &[&str]| {
Cli::try_parse_from([&["insta360-stitch", "video", "a", "b"], args].concat())
};
let options = |cli: Cli| match cli.command {
Commands::Video { options, .. } => options,
_ => panic!("not the video command"),
};
let cli = options(parse(&["--start", "2.5", "--end", "10"]).unwrap());
assert_eq!((cli.start, cli.end), (Some(2.5), Some(10.0)));
let cli = options(parse(&[]).unwrap());
assert_eq!((cli.start, cli.end), (None, None));
assert!(parse(&["--start", "-1"]).is_err());
assert!(parse(&["--end", "nan"]).is_err());
assert!(parse(&["--start", "abc"]).is_err());
}
#[test]
fn the_gpu_is_a_global_option_auto_or_off() {
let gpu = |args: &[&str]| {
Cli::try_parse_from([&["insta360-stitch"], args].concat())
.map(|cli| GpuMode::from(cli.gpu))
};
assert_eq!(gpu(&["photo", "a", "b"]).unwrap(), GpuMode::Auto);
assert_eq!(
gpu(&["photo", "a", "b", "--gpu", "off"]).unwrap(),
GpuMode::Off
);
assert_eq!(
gpu(&["--gpu", "off", "video", "a", "b"]).unwrap(),
GpuMode::Off
);
assert!(gpu(&["photo", "a", "b", "--gpu", "on"]).is_err());
}
#[test]
fn a_photo_with_the_gpu_off_is_the_same_as_with_the_gpu() {
let folder = test_folder("gpu-off");
let photo_file = folder.join("IMG_1.insp");
std::fs::write(
&photo_file,
include_bytes!("../../../tests/fixtures/synthetic_x5.insp"),
)
.unwrap();
let (auto, off) = (folder.join("auto.jpg"), folder.join("off.jpg"));
photo(&photo_file, &auto, 95, None, &[], GpuMode::Auto).unwrap();
photo(&photo_file, &off, 95, None, &[], GpuMode::Off).unwrap();
let decode = |path: &Path| image::open(path).unwrap().to_rgb8().into_raw();
let (auto, off) = (decode(&auto), decode(&off));
assert_eq!(auto.len(), off.len());
assert!(auto.iter().zip(&off).all(|(a, b)| a.abs_diff(*b) <= 8));
}
#[test]
fn threads_are_a_global_option_of_at_least_1() {
let parse = |args: &[&str]| Cli::try_parse_from([&["insta360-stitch"], args].concat());
let cli = parse(&["video", "in.insv", "out.mp4", "--threads", "4"]).unwrap();
assert_eq!(cli.threads, Some(4));
assert_eq!(
parse(&["--threads", "2", "photo", "a", "b"])
.unwrap()
.threads,
Some(2)
);
assert!(parse(&["photo", "a", "b", "--threads", "0"]).is_err());
let Commands::Video { options, .. } = parse(&["video", "a", "b"]).unwrap().command else {
panic!("not the video command")
};
assert_eq!(options.decoder_threads, 2);
assert!(!options.no_rolling_shutter);
let Commands::Video { options, .. } = parse(&["video", "a", "b", "--no-rolling-shutter"])
.unwrap()
.command
else {
panic!("not the video command")
};
assert!(options.no_rolling_shutter);
}
#[test]
fn width_must_be_a_multiple_of_4_from_16() {
for good in ["16", "3840", "16384"] {
assert!(parse_width(good).is_ok(), "{good}");
}
for bad in ["3002", "12", "0", "16388", "wide"] {
assert!(parse_width(bad).is_err(), "{bad}");
}
}
struct StoppingWriter(usize);
impl Write for StoppingWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
std::thread::sleep(std::time::Duration::from_millis(20));
if self.0 == 0 {
return Err(std::io::ErrorKind::BrokenPipe.into());
}
self.0 -= 1;
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn in_time<T: Send + 'static>(run: impl FnOnce() -> T + Send + 'static) -> T {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || tx.send(run()).ok());
match rx.recv_timeout(std::time::Duration::from_secs(10)) {
Ok(value) => value,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
panic!("the pipeline waits without end")
}
Err(_) => panic!("the pipeline thread panicked"),
}
}
#[test]
fn a_frame_is_at_position_index_or_radius_in_its_window() {
for radius in [0, 2] {
let seen = in_time(move || {
let input: Vec<u8> = (0..7u8).collect();
let mut output = Vec::new();
pipeline_at_once(
&input[..],
&mut output,
(1, 1),
10,
radius,
|frame| Ok(frame[0]),
|index, frame, near, out| {
let own = frame_itself(near, index, radius).copied();
out[0] = u8::from(own == Some(frame[0]));
Ok(())
},
)
.map_err(|e| e.to_string())
.map(|_| output)
});
assert_eq!(seen, Ok(vec![1; 7]), "radius {radius}");
}
}
#[test]
fn the_denoise_writer_gives_the_bytes_of_the_denoiser_for_all_write_sizes() {
let (w, h) = (64usize, 64usize);
let size = w * h * 3 / 2;
let count = 9;
let stream: Vec<u8> = (0..count * size)
.map(|i| (i * 7 + i / size * 31) as u8)
.collect();
let mut expected = Vec::new();
let mut denoiser = Denoiser::new(w, h, 1.0).unwrap();
let mut out = Vec::new();
for frame in stream.chunks(size) {
if denoiser.push(frame, &mut out).unwrap() {
expected.extend_from_slice(&out);
}
}
while denoiser.finish(&mut out).unwrap() {
expected.extend_from_slice(&out);
}
assert_eq!(expected.len(), count * size);
let odd = [
size / 2,
size * 5 / 2,
size + 1,
size - 1,
1,
size * 2,
0,
size * 2 - 1,
];
let ways: [&[usize]; 3] = [&[size], &[1000], &odd];
for sizes in ways {
let mut sink = Vec::new();
let mut writer = DenoiseWriter::new(&mut sink, Denoiser::new(w, h, 1.0).unwrap());
let mut rest = &stream[..];
for &n in sizes.iter().cycle() {
if rest.is_empty() {
break;
}
let (part, next) = rest.split_at(n.min(rest.len()));
assert_eq!(writer.write(part).unwrap(), part.len());
assert!(writer.pending.len() < size);
if sizes == [size] {
assert_eq!(writer.pending.capacity(), 0);
}
rest = next;
}
writer.flush().unwrap();
drop(writer);
assert!(sink == expected, "{sizes:?}");
}
}
#[test]
fn pipeline_stitches_each_frame_in_order_and_stops_when_the_encoder_stops() {
let (count, output) = in_time(|| {
let input: Vec<u8> = (0..5u8).flat_map(|i| [i; 4]).collect();
let mut output = Vec::new();
let count = pipeline_at_once(
&input[..],
&mut output,
(4, 2),
10,
0,
|_| Ok(()),
|index, frame, _, out| {
out.copy_from_slice(&[frame[0], index as u8]);
Ok(())
},
);
(count.map_err(|e| e.to_string()), output)
});
assert_eq!(count, Ok(5));
assert_eq!(output, [0, 0, 1, 1, 2, 2, 3, 3, 4, 4]);
let stops = |writes: usize, stitch_error_at: usize| {
in_time(move || {
pipeline_at_once(
std::io::repeat(1),
StoppingWriter(writes),
(16, 16),
1000,
0,
|_| Ok(()),
|index, _, _, _| match index == stitch_error_at {
true => Err("stitch error".into()),
false => Ok(()),
},
)
.map_err(|e| (encoder_stopped(&*e), e.to_string()))
})
};
assert!(matches!(stops(3, usize::MAX), Err((true, _))));
assert_eq!(stops(usize::MAX, 5), Err((false, "stitch error".into())));
let at_end = in_time(|| {
let input = [7u8; 5 * 16];
pipeline_at_once(
&input[..],
StoppingWriter(4),
(16, 16),
5,
0,
|_| Ok(()),
|_, _, _, _| Ok(()),
)
.map_err(|e| encoder_stopped(&*e))
});
assert_eq!(at_end, Err(true));
}
#[test]
fn lagged_pipeline_writes_the_late_outputs_in_order() {
for radius in [0, 2] {
let output = in_time(move || {
let input: Vec<u8> = (0..6u8).collect();
let mut output = Vec::new();
let late = std::sync::Mutex::new(None::<Vec<u8>>);
let count = pipeline(
&input[..],
&mut output,
(1, 1),
10,
(radius, 1),
|_| Ok(()),
|_, frame, _, mut out| {
out[0] = frame[0];
Ok(late.lock().unwrap().replace(out))
},
|| Ok(late.lock().unwrap().take()),
);
(count.map_err(|e| e.to_string()), output)
});
assert_eq!(output, (Ok(6), vec![0, 1, 2, 3, 4, 5]), "radius {radius}");
}
}
#[test]
fn pipeline_gives_each_frame_the_data_of_its_neighbours() {
let output = in_time(|| {
let input: Vec<u8> = (0..7u8).collect();
let mut output = Vec::new();
let count = pipeline_at_once(
&input[..],
&mut output,
(1, 6),
10,
2,
|frame| Ok(frame[0]),
|index, frame, near, out| {
let mut ids = [255u8; 5];
for (id, &&n) in ids.iter_mut().zip(near) {
*id = n;
}
out[0] = frame[0];
out[1..].copy_from_slice(&ids);
assert_eq!(index, frame[0] as usize);
Ok(())
},
);
(count.map_err(|e| e.to_string()), output)
});
let want: Vec<u8> = (0..7i32)
.flat_map(|n| {
let near: Vec<u8> = ((n - 2).max(0)..=(n + 2).min(6)).map(|i| i as u8).collect();
let mut row = vec![n as u8];
row.extend(near.iter().copied().chain(std::iter::repeat(255)).take(5));
row
})
.collect();
assert_eq!(output, (Ok(7), want));
}
fn jpeg_head(segments: &[(u8, &[u8])]) -> Vec<u8> {
let mut out = vec![0xff, 0xd8];
for (marker, data) in segments {
out.extend([0xff, *marker]);
out.extend(((data.len() + 2) as u16).to_be_bytes());
out.extend(*data);
}
out.extend([0xff, 0xda, 0, 2, 0xff, 0xe1, 0, 8]);
out.extend(b"Exif\0\0");
out
}
#[test]
fn the_seam_flow_threads_come_out_of_the_thread_budget() {
assert_eq!(split_threads(None, true), (None, 2));
assert_eq!(split_threads(Some(6), false), (Some(6), 2));
assert_eq!(split_threads(Some(6), true), (Some(4), 2));
assert_eq!(split_threads(Some(3), true), (Some(2), 1));
assert_eq!(split_threads(Some(2), true), (Some(1), 1));
assert_eq!(split_threads(Some(1), true), (Some(1), 1));
}
#[test]
fn exif_segment_finds_the_exif_app1_before_the_image_data() {
let jfif: &[u8] = b"JFIF\0\x01\x01";
let xmp: &[u8] = b"http://ns.adobe.com/xap/1.0/\0<x/>";
let exif: &[u8] = b"Exif\0\0MM\0*";
let file = jpeg_head(&[(0xe0, jfif), (0xe1, xmp), (0xe1, exif)]);
assert_eq!(exif_segment(&file[..]), Some(exif.to_vec()));
assert_eq!(
exif_segment(&jpeg_head(&[(0xe0, jfif), (0xe1, xmp)])[..]),
None
);
assert_eq!(exif_segment(&b"GIF89a"[..]), None);
assert_eq!(exif_segment(&file[..12]), None);
}
#[test]
fn the_panorama_jpeg_decodes_near_its_pixels_with_and_without_avx2() {
let (width, height) = (64, 32);
let rgb: Vec<u8> = (0..width * height)
.flat_map(|i| {
let (x, y) = (i % width, i / width);
[(x * 4) as u8, (y * 8) as u8, ((x + y) * 3) as u8]
})
.collect();
let rows = Rows::Plain {
rgb: &rgb,
width,
height,
};
let mut jpeg = Vec::new();
encode_panorama(&mut jpeg, &rows, 95, None).unwrap();
let decoded = image::load_from_memory(&jpeg).unwrap().to_rgb8();
assert_eq!(decoded.dimensions(), (width as u32, height as u32));
let diffs: Vec<u32> = rgb
.iter()
.zip(decoded.as_raw())
.map(|(&a, &b)| u32::from(a.abs_diff(b)))
.collect();
let mean = diffs.iter().sum::<u32>() as f64 / diffs.len() as f64;
let max = *diffs.iter().max().unwrap();
assert!(mean < 2.0 && max <= 32, "mean {mean:.2}, max {max}");
}
#[test]
fn the_no_avx2_step_runs_without_avx2() {
if std::env::var_os("INSTA360_EXPECT_NO_AVX2").is_some() {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
assert!(
!std::is_x86_feature_detected!("avx2"),
"the processor has AVX2"
);
}
}
#[test]
fn the_panorama_jpeg_has_the_exif_then_the_360_metadata_and_no_temporary_file() {
let folder = new_temp_folder(&std::env::temp_dir()).unwrap();
let output = folder.join("pano.jpg");
let rgb = vec![128u8; 8 * 4 * 3];
let rows = Rows::Plain {
rgb: &rgb,
width: 8,
height: 4,
};
let exif = b"Exif\0\0MM\0*".to_vec();
write_panorama_jpeg(&output, rows, 90, Some(exif.clone())).unwrap();
let bytes = std::fs::read(&output).unwrap();
let at = |needle: &[u8]| bytes.windows(needle.len()).position(|w| w == needle);
let (e, x) = (at(&exif).unwrap(), at(b"GPano:ProjectionType").unwrap());
assert!(e < x);
for field in [
&b"GPano:InitialViewVerticalFOVDegrees=\"95\""[..],
b"GPano:InitialHorizontalFOVDegrees=\"100\"",
b"GPano:StitchingSoftware=\"insta360-stitch\"",
] {
assert!(at(field).is_some());
}
assert_eq!(exif_segment(&bytes[..]), Some(exif));
let names: Vec<_> = std::fs::read_dir(&folder)
.unwrap()
.map(|e| e.unwrap().file_name())
.collect();
assert_eq!(names, ["pano.jpg"]);
std::fs::remove_dir_all(&folder).ok();
}
#[test]
fn the_decoder_keeps_the_lens_order_and_the_full_range() {
let line = |range: &str| {
format!(
"width=64|height=64|r_frame_rate=24/1|nb_frames=5|color_range={range}
"
)
};
let args = |range: &str, lens_size: usize| -> Vec<String> {
let probe = parse_probe(&line(range).repeat(2)).unwrap();
decoder_command(
&test_video_options(),
&probe,
lens_size,
None,
Path::new("in.insv"),
FrameRange::whole(&probe),
)
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect()
};
let full = args("pc", 64);
assert!(
full.contains(&"[0:v:1][0:v:0]vstack=inputs=2,format=yuvj420p[v]".to_string()),
"{full:?}"
);
assert!(
full.windows(2).any(|w| w == ["-pix_fmt", "yuvj420p"]),
"{full:?}"
);
let mut options = test_video_options();
options.decoder_threads = 3;
options.decoder_args = ["-threads", "8"].map(String::from).to_vec();
let probe = parse_probe(&line("pc").repeat(2)).unwrap();
let tuned: Vec<_> = decoder_command(
&options,
&probe,
64,
None,
Path::new("in.insv"),
FrameRange::whole(&probe),
)
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
let input = tuned.iter().position(|a| a == "file:in.insv").unwrap();
let threads: Vec<_> = (0..input)
.filter(|&i| tuned[i] == "-threads")
.map(|i| &tuned[i + 1])
.collect();
assert_eq!(threads, ["3", "8"], "{tuned:?}");
assert!(
tuned[..input]
.windows(2)
.any(|w| w == ["-filter_complex_threads", "1"]),
"{tuned:?}"
);
let limited = args("tv", 32);
let filter = "[0:v:1][0:v:0]vstack=inputs=2,scale=32:64:flags=area,format=yuv420p[v]";
assert!(limited.contains(&filter.to_string()), "{limited:?}");
assert!(
limited.windows(2).any(|w| w == ["-pix_fmt", "yuv420p"]),
"{limited:?}"
);
}
#[test]
fn the_stabilization_is_the_requested_one_else_follow_for_a_time_shift_else_lock() {
assert_eq!(stabilization_for(None, false), Stabilization::Lock);
assert_eq!(stabilization_for(None, true), Stabilization::Follow);
for time_shift in [false, true] {
let off = stabilization_for(Some(StabilizationArg::Off), time_shift);
assert_eq!(off, Stabilization::Off);
let lock = stabilization_for(Some(StabilizationArg::Lock), time_shift);
assert_eq!(lock, Stabilization::Lock);
}
}
#[test]
fn lock_without_orientations_uses_off_and_other_errors_stop() {
let rotations = |error: fn() -> insta360_stitch::Error| {
move |mode| match mode {
Stabilization::Off => Ok(vec![IDENTITY]),
_ => Err(error()),
}
};
let unsupported = || insta360_stitch::Error::Unsupported("too short".into());
let invalid = || insta360_stitch::Error::InvalidArgument("bad".into());
assert_eq!(
stabilize(Stabilization::Lock, rotations(unsupported)).unwrap(),
(Stabilization::Off, vec![IDENTITY])
);
assert!(stabilize(Stabilization::Follow, rotations(invalid)).is_err());
let lock = stabilize(Stabilization::Lock, |_| Ok(vec![IDENTITY; 2])).unwrap();
assert_eq!(lock.0, Stabilization::Lock);
}
#[test]
fn a_file_without_imu_data_gives_no_imu_data_and_other_errors_stop() {
let none = imu_or_empty(Err(insta360_stitch::Error::Unsupported(
"no IMU record in trailer".into(),
)))
.unwrap();
assert!(none.is_empty());
let io = std::io::Error::other("disk");
assert!(imu_or_empty(Err(insta360_stitch::Error::Io(io))).is_err());
}
#[test]
fn read_frames_gives_full_frames_and_stops_at_the_end_or_the_limit() {
let data: Vec<u8> = (0..10).collect();
let run = |limit: usize| {
let (free_tx, free) = sync_channel(4);
let (full_tx, full) = sync_channel(4);
for _ in 0..4 {
free_tx.send(Vec::new()).unwrap();
}
let n = read_frames(&data[..], 4, limit, free, full_tx).unwrap();
(n, full.iter().collect::<Vec<_>>())
};
assert_eq!(run(10), (2, vec![vec![0, 1, 2, 3], vec![4, 5, 6, 7]]));
assert_eq!(run(1), (1, vec![vec![0, 1, 2, 3]]));
}
}