Skip to content

🎥 Make videos programmatically with React

handle videos with rotation on offthreadvideo

Jonny Burgerf0bdc8f1f04d
diff --git a/packages/compositor-darwin-arm64/compositor b/packages/compositor-darwin-arm64/compositor
index bf6f527c0a..d54104c342 100755
Binary files a/packages/compositor-darwin-arm64/compositor and b/packages/compositor-darwin-arm64/compositor differ
diff --git a/packages/renderer/rust/main.rs b/packages/renderer/rust/main.rs
index 8169ef321f..d2392152fa 100644
--- a/packages/renderer/rust/main.rs
+++ b/packages/renderer/rust/main.rs
@@ -10,6 +10,7 @@ mod opened_stream;
mod opened_video;
mod opened_video_manager;
mod payloads;
+mod rotation;
mod scalable_frame;
use commands::execute_command;
use errors::{error_to_json, ErrorWithBacktrace};
diff --git a/packages/renderer/rust/opened_stream.rs b/packages/renderer/rust/opened_stream.rs
index 5031492e26..fc6af1f77a 100644
--- a/packages/renderer/rust/opened_stream.rs
+++ b/packages/renderer/rust/opened_stream.rs
@@ -13,7 +13,8 @@ use crate::{
errors::ErrorWithBacktrace,
frame_cache::{get_frame_cache_id, FrameCache, FrameCacheItem},
global_printer::_print_verbose,
- scalable_frame::{NotRgbFrame, ScalableFrame},
+ rotation,
+ scalable_frame::{NotRgbFrame, Rotate, ScalableFrame},
};
pub struct OpenedStream {
@@ -30,6 +31,7 @@ pub struct OpenedStream {
pub duration_or_zero: i64,
pub reached_eof: bool,
pub transparent: bool,
+ pub rotation: Rotate,
}
pub fn calc_position(time: f64, time_base: Rational) -> i64 {
@@ -98,6 +100,7 @@ impl OpenedStream {
original_height: self.original_height,
scaled_height: self.scaled_height,
scaled_width: self.scaled_width,
+ rotate: self.rotation,
};
offset = offset + one_frame_in_time_base;
@@ -198,6 +201,7 @@ impl OpenedStream {
if stream.parameters().medium() != Type::Video {
continue;
}
+
_print_verbose(&format!(
"Got packet dts = {} pts ={} key = {}",
packet.dts().unwrap(),
@@ -251,6 +255,7 @@ impl OpenedStream {
original_width: self.original_width,
scaled_height: self.scaled_height,
scaled_width: self.scaled_width,
+ rotate: self.rotation,
};
self.last_position = video.pts().expect("expected pts");
@@ -345,6 +350,31 @@ pub fn open_stream(
let time_base = mut_stream.time_base();
let parameters = mut_stream.parameters();
+ let side_data = mut_stream.side_data();
+
+ let mut rotate = Rotate::Rotate0;
+
+ for data in side_data {
+ if data.kind() == remotionffmpeg::codec::packet::side_data::Type::DisplayMatrix {
+ let value = data.data();
+ let rotate_value = rotation::get_from_side_data(value)?;
+ if rotate_value != 0.0 {
+ _print_verbose(&format!("Detected rotation in {}: {}", src, rotate_value))?;
+ if rotate_value == 90.0 {
+ rotate = Rotate::Rotate90;
+ } else if rotate_value == 180.0 {
+ rotate = Rotate::Rotate180;
+ } else if rotate_value == 270.0 || rotate_value == -90.0 {
+ rotate = Rotate::Rotate270;
+ } else {
+ return Err(ErrorWithBacktrace::from(format!(
+ "Unsupported rotation value {}",
+ rotate_value
+ )));
+ }
+ }
+ }
+ }
let mut parameters_cloned = parameters.clone();
let is_vp8_or_vp9_and_transparent = match transparent {
@@ -407,6 +437,7 @@ pub fn open_stream(
duration_or_zero,
reached_eof: false,
transparent,
+ rotation: rotate.into(),
};
Ok((opened_stream, fps, time_base))
diff --git a/packages/renderer/rust/rotation.rs b/packages/renderer/rust/rotation.rs
new file mode 100644
index 0000000000..3e6c47f42e
--- /dev/null
+++ b/packages/renderer/rust/rotation.rs
@@ -0,0 +1,45 @@
+use std::{f64::consts::PI, io::ErrorKind};
+
+use crate::errors::ErrorWithBacktrace;
+
+pub fn get_from_side_data(value: &[u8]) -> Result<f64, ErrorWithBacktrace> {
+ let mut i32_values: Vec<i32> = Vec::new();
+
+ for bytes in value.chunks(4) {
+ let i32_value = ((bytes[0] as i32) << 24)
+ + ((bytes[1] as i32) << 16)
+ + ((bytes[2] as i32) << 8)
+ + (bytes[3] as i32);
+ i32_values.push(i32_value);
+ }
+
+ if i32_values.len() != 9 {
+ Err(std::io::Error::new(ErrorKind::Other, "Invalid side data"))?;
+ }
+ return get_rotation(&i32_values);
+}
+
+pub fn get_rotation(displaymatrix: &[i32]) -> Result<f64, ErrorWithBacktrace> {
+ let mut theta = -(rotation_get(displaymatrix))?.round();
+
+ theta -= 360.0 * (theta / 360.0 + 0.9 / 360.0).floor();
+
+ if (theta - 90.0 * (theta / 90.0).round()).abs() > 2.0 {
+ Err(std::io::Error::new(ErrorKind::Other, "Odd rotation angle"))?;
+ }
+
+ return Ok(theta);
+}
+
+pub fn rotation_get(matrix: &[i32]) -> Result<f64, ErrorWithBacktrace> {
+ let scale0 = (matrix[0] as f64).hypot(matrix[3] as f64);
+ let scale1 = (matrix[1] as f64).hypot(matrix[4] as f64);
+
+ if scale0 == 0.0 || scale1 == 0.0 {
+ Err(std::io::Error::new(ErrorKind::Other, "Invalid matrix"))?;
+ }
+
+ let rotation = (((matrix[1] as f64) / scale1).atan2((matrix[0] as f64) / scale0)) * 180.0 / PI;
+
+ return Ok(-rotation);
+}
diff --git a/packages/renderer/rust/scalable_frame.rs b/packages/renderer/rust/scalable_frame.rs
index 3f85f718c9..29e29b2ce6 100644
--- a/packages/renderer/rust/scalable_frame.rs
+++ b/packages/renderer/rust/scalable_frame.rs
@@ -6,6 +6,14 @@ use ffmpeg_next::{
use crate::{errors::ErrorWithBacktrace, image::get_png_data};
+#[derive(Clone, Copy)]
+pub enum Rotate {
+ Rotate0,
+ Rotate90,
+ Rotate180,
+ Rotate270,
+}
+
pub struct NotRgbFrame {
pub planes: Vec<Vec<u8>>,
pub linesizes: [i32; 8],
@@ -14,6 +22,7 @@ pub struct NotRgbFrame {
pub original_height: u32,
pub scaled_width: u32,
pub scaled_height: u32,
+ pub rotate: Rotate,
}
pub struct RgbFrame {
@@ -65,14 +74,16 @@ impl ScalableFrame {
}
}
-fn create_bmp_image_from_frame(rgb_frame: &mut Video) -> Vec<u8> {
- let width = rgb_frame.width() as u32;
- let height = rgb_frame.height() as u32;
+fn create_bmp_image_from_frame(
+ rgb_frame: &[u8],
+ width: u32,
+ height: u32,
+ stride: usize,
+) -> Vec<u8> {
let row_size = (width * 3 + 3) & !3;
let row_padding = row_size - width * 3;
let image_size = row_size * height;
let header_size = 54;
- let stride = rgb_frame.stride(0);
let mut bmp_data = Vec::with_capacity(header_size as usize + image_size as usize);
@@ -97,7 +108,7 @@ fn create_bmp_image_from_frame(rgb_frame: &mut Video) -> Vec<u8> {
for y in (0..height).rev() {
let row_start = (y as usize) * stride;
let row_end = row_start + (width * 3) as usize;
- bmp_data.extend_from_slice(&rgb_frame.data(0)[row_start..row_end]);
+ bmp_data.extend_from_slice(&rgb_frame[row_start..row_end]);
for _ in 0..row_padding {
bmp_data.push(0);
}
@@ -149,13 +160,85 @@ pub fn scale_and_make_bitmap(
std::mem::drop(inner);
}
- if transparent {
- return get_png_data(
+ let (rotated, rotated_width, rotated_height) = match native_frame.rotate {
+ Rotate::Rotate90 => rotate_90(
+ scaled.data(0),
+ native_frame.scaled_width,
+ native_frame.scaled_height,
+ ),
+ Rotate::Rotate180 => rotate_180(
+ scaled.data(0),
+ native_frame.scaled_width,
+ native_frame.scaled_height,
+ ),
+ Rotate::Rotate270 => rotate_270(
scaled.data(0),
native_frame.scaled_width,
native_frame.scaled_height,
- );
+ ),
+ Rotate::Rotate0 => (
+ scaled.data(0).to_vec(),
+ native_frame.scaled_width,
+ native_frame.scaled_height,
+ ),
+ };
+
+ if transparent {
+ return get_png_data(&rotated, rotated_width, rotated_height);
+ }
+
+ Ok(create_bmp_image_from_frame(
+ &rotated,
+ rotated_width,
+ rotated_height,
+ (rotated_width * 3) as usize,
+ ))
+}
+
+pub fn rotate_270(data: &[u8], width: u32, height: u32) -> (Vec<u8>, u32, u32) {
+ let mut new_data: Vec<u8> = vec![0; data.len()];
+
+ for y in 0..height {
+ for x in 0..width {
+ let new_x = y;
+ let new_y = width - x - 1;
+ let new_index = (new_y * height + new_x) as usize * 3;
+ let old_index = (y * width + x) as usize * 3;
+ new_data[new_index..new_index + 3].copy_from_slice(&data[old_index..old_index + 3]);
+ }
+ }
+
+ (new_data, height, width)
+}
+
+pub fn rotate_180(data: &[u8], width: u32, height: u32) -> (Vec<u8>, u32, u32) {
+ let mut new_data: Vec<u8> = vec![0; data.len()];
+
+ for y in 0..height {
+ for x in 0..width {
+ let new_x = width - x - 1;
+ let new_y = height - y - 1;
+ let new_index = (new_y * width + new_x) as usize * 3;
+ let old_index = (y * width + x) as usize * 3;
+ new_data[new_index..new_index + 3].copy_from_slice(&data[old_index..old_index + 3]);
+ }
+ }
+
+ (new_data, width, height)
+}
+
+pub fn rotate_90(data: &[u8], width: u32, height: u32) -> (Vec<u8>, u32, u32) {
+ let mut new_data: Vec<u8> = vec![0; data.len()];
+
+ for y in 0..height {
+ for x in 0..width {
+ let new_x = height - y - 1;
+ let new_y = x;
+ let new_index = (new_y * height + new_x) as usize * 3;
+ let old_index = (y * width + x) as usize * 3;
+ new_data[new_index..new_index + 3].copy_from_slice(&data[old_index..old_index + 3]);
+ }
}
- Ok(create_bmp_image_from_frame(&mut scaled))
+ (new_data, height, width)
}
diff --git a/packages/renderer/src/test/extract-frame-rust.test.ts b/packages/renderer/src/test/extract-frame-rust.test.ts
index 43fbc6b511..e965c40c97 100644
--- a/packages/renderer/src/test/extract-frame-rust.test.ts
+++ b/packages/renderer/src/test/extract-frame-rust.test.ts
@@ -369,7 +369,7 @@ test('Should get from video with no fps', async () => {
test('Should get from broken webcam video', async () => {
const compositor = startLongRunningCompositor(
getIdealMaximumFrameCacheItems(),
- 'verbose',
+ 'info',
false
);
@@ -385,6 +385,25 @@ test('Should get from broken webcam video', async () => {
await compositor.waitForDone();
});
+test('Should get from iPhone video', async () => {
+ const compositor = startLongRunningCompositor(
+ getIdealMaximumFrameCacheItems(),
+ 'info',
+ false
+ );
+
+ const data = await compositor.executeCommand('ExtractFrame', {
+ input: exampleVideos.iphonevideo,
+ time: 3,
+ transparent: false,
+ });
+
+ expect(data.length).toBe(24883254);
+
+ compositor.finishCommands();
+ await compositor.waitForDone();
+});
+
test('Two different starting times should not result in big seeking', async () => {
const compositor = startLongRunningCompositor(300, 'info', false);