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::{sync_channel, Receiver, RecvError, SendError, SyncSender};
use clap::{Parser, Subcommand, ValueEnum};
use image::{ImageFormat, ImageReader};
use insta360_stitch::{
check_different_files, check_photo_layout, preview_rgb, read_imu, read_preview, read_trailer,
stitch_photo_band_with, uses_exposure_table, write_spherical_mp4_file, FrameFlow, Image, Imu,
LensModel, PhotoSeam, Stabilization, Stitcher, Trailer, MAX_VIDEO_WIDTH,
};
use jpeg_encoder::{rgb_to_ycbcr, Encoder, ImageBuffer, JpegColorType};
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>,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
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,
},
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, default_value_t = StabilizationArg::Lock)]
stabilization: StabilizationArg,
#[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, default_value = "ffmpeg")]
ffmpeg: String,
#[arg(long, default_value = "ffprobe")]
ffprobe: String,
}
#[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>, seam_flow: bool) -> (Option<usize>, usize) {
match (threads.map(usize::from), seam_flow) {
(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 seam_flow =
matches!(&cli.command, Commands::Video { options, .. } if !options.no_seam_flow);
let (threads, flow_threads) = split_threads(cli.threads, seam_flow);
if let Some(threads) = threads {
rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build_global()
.expect("the thread pool is not in use yet");
}
let result = match cli.command {
Commands::Info { file } => info(&file),
Commands::Photo {
input,
output,
quality,
} => photo(&input, &output, quality),
Commands::Preview { input, output } => preview(&input, &output),
Commands::Video {
input,
output,
options,
} => video(&input, &output, &options, flow_threads),
};
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 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": trailer.offset_state,
"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()),
"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;
enum Rows<'a> {
Plain {
rgb: &'a [u8],
width: usize,
height: usize,
},
Stitched {
source: Image<'a>,
model: &'a LensModel,
seam: PhotoSeam,
band: RefCell<(usize, Vec<u8>)>,
},
}
impl Rows<'_> {
fn size(&self) -> (usize, usize) {
match self {
Rows::Plain { width, height, .. } => (*width, *height),
Rows::Stitched { source, .. } => (source.width, source.height),
}
}
}
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, height) = self.size();
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 {
source,
model,
seam,
band,
} => {
let mut band = band.borrow_mut();
let (first, rows) = (band.0, band.1.len() / row_len);
if y < first || y >= first + rows {
let rows = BAND_ROWS.min(height - y);
band.0 = y;
band.1.resize(rows * row_len, 0);
stitch_photo_band_with(source, model, seam, y, &mut band.1)
.expect("a valid source");
}
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());
}
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"/></rdf:RDF></x:xmpmeta>"#
),
w = width,
h = height
);
let mut part = output.as_os_str().to_owned();
part.push(format!(".{}.part", std::process::id()));
let result = (|| -> Result<()> {
let mut out = BufWriter::new(File::create(&part)?);
let mut encoder = Encoder::new(&mut out, quality);
if let Some(exif) = exif {
encoder.add_app_segment(1, exif)?;
}
encoder.add_app_segment(1, xmp.into_bytes())?;
encoder.encode_image(rows)?;
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 photo(input: &Path, output: &Path, quality: u8) -> Result<()> {
check_different_files(input, output)?;
let stitcher = Stitcher::new(trailer_of(input)?);
let decoded = ImageReader::with_format(BufReader::new(File::open(input)?), ImageFormat::Jpeg)
.decode()?
.into_rgb8();
let (width, height) = (decoded.width() as usize, decoded.height() as usize);
check_photo_layout(width, height)?;
let model = stitcher.model(height)?;
let source = Image {
width,
height,
channels: 3,
data: decoded.as_raw(),
};
let rows = Rows::Stitched {
seam: PhotoSeam::new(&source, &model)?,
source,
model: &model,
band: RefCell::new((0, Vec::new())),
};
let exif = exif_segment(File::open(input)?);
write_panorama_jpeg(output, rows, quality, exif)
}
fn preview(input: &Path, output: &Path) -> Result<()> {
check_different_files(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,
rate: String,
fps: f64,
frame_count: usize,
colour_args: Vec<String>,
full_range: bool,
}
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")
.args(["-of", "compact=p=0"])
.arg(input)
.output()?;
if !out.status.success() {
return Err(format!(
"ffprobe failed: {}",
String::from_utf8_lossy(&out.stderr).trim()
)
.into());
}
parse_probe(&String::from_utf8_lossy(&out.stdout))
}
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) || width != height {
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()),
};
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,
rate,
fps,
frame_count,
colour_args,
full_range: first.get("color_range") == Some(&"pc"),
})
}
fn encoder_args(options: &VideoOptions) -> Vec<String> {
let mut args = vec!["-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;
fn pipeline<P: Send>(
decoded: impl Read + Send,
mut encoded: impl Write + Send,
(in_bytes, out_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> {
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);
let (done_tx, done) = sync_channel::<Vec<u8>>(2);
for _ in 0..2 + lookahead {
free_in_tx.send(Vec::new())?;
}
for _ in 0..2 {
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: Vec<u8>, index: usize| -> Result<()> {
free_in_tx.send(frame).ok();
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 mut 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, &mut out);
(next.join(), stitched)
});
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 mut out = free_out.recv()?;
stitch(
index,
&held[0],
&window(&data, first, index, radius),
&mut 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 mut out = free_out.recv()?;
stitch(
index,
&frame,
&window(&data, first, index, radius),
&mut out,
)?;
send(frame, out, index)?;
index += 1;
}
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 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 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,
input: &Path,
) -> 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 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"])
.args(&options.decoder_args)
.arg("-i")
.arg(input)
.arg("-filter_complex")
.arg(format!(
"[0:v:1][0:v:0]vstack=inputs=2,{scale}format={format}[v]"
))
.args(["-map", "[v]", "-fps_mode", "passthrough", "-f", "rawvideo"])
.args(["-pix_fmt", format, "pipe:1"]);
command
}
fn encoder_command(
options: &VideoOptions,
probe: &Probe,
(width, height): (usize, usize),
input: &Path,
stitched: &Path,
) -> Command {
let mut command = Command::new(&options.ffmpeg);
command
.args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
.args([
"-s",
&format!("{width}x{height}"),
"-framerate",
&probe.rate,
])
.args(&probe.colour_args)
.args(["-i", "pipe:0", "-i"])
.arg(input)
.args(["-map", "0:v:0", "-map", "1:a?", "-c:a", "copy"])
.args(["-map_metadata", "1"])
.args(encoder_args(options))
.arg(stitched);
command
}
fn video(input: &Path, output: &Path, options: &VideoOptions, flow_threads: usize) -> Result<()> {
check_different_files(input, output)?;
let mut reader = BufReader::new(File::open(input)?);
let stitcher = Stitcher::new(read_trailer(&mut reader)?);
let probe = probe(&options.ffprobe, input)?;
let width = 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 mode = Stabilization::from(options.stabilization);
let rolling = !options.no_rolling_shutter;
let imu = match (mode, rolling) {
(Stabilization::Off, false) => Imu::default(),
(Stabilization::Off, true) => match read_imu(&mut reader, &stitcher.trailer) {
Err(insta360_stitch::Error::Unsupported(_)) => Imu::default(),
imu => imu?,
},
_ => read_imu(&mut reader, &stitcher.trailer)?,
};
let (mode, rotations) = stabilize(mode, |mode| {
stitcher.frame_motions(&imu, probe.frame_count, probe.fps, mode, rolling)
})?;
if mode != Stabilization::Off && !uses_exposure_table(&stitcher.trailer, probe.frame_count) {
eprintln!("insta360-stitch: the exposure table does not have all frames, the frame times use the frame rate");
}
drop(imu);
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 mut decoder = decoder_command(options, &probe, lens_size, input)
.stdout(Stdio::piped())
.spawn()?;
let mut encoder = encoder_command(
options,
&probe,
(frames.width(), frames.height()),
input,
&stitched,
)
.stdin(Stdio::piped())
.spawn()?;
let decoded = decoder.stdout.take().ok_or("no decoder output")?;
let encoded = BufWriter::new(encoder.stdin.take().ok_or("no encoder input")?);
let flow_pool = rayon::ThreadPoolBuilder::new()
.num_threads(flow_threads)
.build()?;
let started = std::time::Instant::now();
let count = pipeline(
decoded,
encoded,
(frames.input_frame_bytes(), frames.output_frame_bytes()),
probe.frame_count,
if options.no_seam_flow { 0 } else { FLOW_RADIUS },
|frame| match options.no_seam_flow {
true => Ok(None),
false => flow_pool.install(|| frames.frame_flow(frame)),
},
|index, frame, near, out| {
let near: Vec<&FrameFlow> = near.iter().filter_map(|f| f.as_ref()).collect();
let flow = (!near.is_empty()).then(|| FrameFlow::mean(&near));
Ok(frames.stitch_yuv420_flow(&rotations[index], flow.as_ref(), frame, out)?)
},
);
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 < probe.frame_count {
Some(decoder.wait()?)
} else {
decoder.kill().ok();
decoder.wait().ok();
None
};
let encoder_status = encoder.wait()?;
eprintln!(
"\rframe {count}/{} in {:.1} s",
probe.frame_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 < probe.frame_count {
eprintln!(
"insta360-stitch: the decoder gave {count} of {} frames",
probe.frame_count
);
}
finish_video(&stitched, output)
})();
std::fs::remove_dir_all(&folder).ok();
result
}
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};
#[test]
fn rows_give_the_encoder_the_stitched_rows_across_bands() {
let (width, height) = (256, 128);
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,
};
let source = Image {
width,
height,
channels: 3,
data: &pixels,
};
let expected = stitch_photo(&source, &model).unwrap();
let rows = Rows::Stitched {
seam: PhotoSeam::new(&source, &model).unwrap(),
source,
model: &model,
band: RefCell::new((0, Vec::new())),
};
let requests = (0..height).chain([height - 1, height - 1, 5]);
for y in requests {
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}");
}
}
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 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),
preview(&file, &file),
video(&file, &file, &test_video_options(), 2),
];
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: StabilizationArg::Lock,
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,
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,
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,
}
);
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=3840|height=1920|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),
] {
assert!(parse_probe(&bad).is_err(), "{bad}");
}
}
#[test]
fn encoder_args_add_quality_only_for_x264_and_x265() {
let mut options = test_video_options();
assert_eq!(
encoder_args(&options),
[
"-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),
["-c:v", "hevc_vaapi", "-vf", "format=nv12,hwupload"]
);
}
#[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),
Path::new("in.insv"),
Path::new("out.mp4"),
);
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_eq!(args[at("in.insv") - 1], "-i");
assert_eq!(args[at("-map_metadata") + 1], "1");
assert!(at("-map_metadata") > at("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:?}");
}
#[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 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(
&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(
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(
&input[..],
StoppingWriter(4),
(16, 16),
5,
0,
|_| Ok(()),
|_, _, _, _| Ok(()),
)
.map_err(|e| encoder_stopped(&*e))
});
assert_eq!(at_end, Err(true));
}
#[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(
&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_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);
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,
Path::new("in.insv"),
)
.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, Path::new("in.insv"))
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
let input = tuned.iter().position(|a| a == "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 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 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]]));
}
}