🎥 Make videos programmatically with React
only tonemap once needed
Jonny Burger5bc5f581d6b0
diff --git a/packages/renderer/rust/opened_stream.rs b/packages/renderer/rust/opened_stream.rsindex b627baa30c..9906971ea1 100644--- a/packages/renderer/rust/opened_stream.rs+++ b/packages/renderer/rust/opened_stream.rs@@ -1,12 +1,7 @@use std::{io::ErrorKind, time::SystemTime};use ffmpeg_next::Rational;-use remotionffmpeg::{- codec::Id,- frame::{self, Video},- media::Type,- Dictionary, StreamMut,-};+use remotionffmpeg::{codec::Id, frame::Video, media::Type, Dictionary, StreamMut};extern crate ffmpeg_next as remotionffmpeg;use std::time::UNIX_EPOCH;@@ -18,7 +13,7 @@ use crate::{global_printer::_print_verbose,rotation,scalable_frame::{NotRgbFrame, Rotate, ScalableFrame},- tone_map::make_tone_map_filtergraph,+ tone_map::FilterGraph,};pub struct OpenedStream {@@ -28,8 +23,6 @@ pub struct OpenedStream {pub scaled_width: u32,pub scaled_height: u32,pub video: remotionffmpeg::codec::decoder::Video,- pub filter: remotionffmpeg::filter::Graph,- pub should_filter: bool,pub src: String,pub original_src: String,pub input: remotionffmpeg::format::context::Input,@@ -38,6 +31,7 @@ pub struct OpenedStream {pub reached_eof: bool,pub transparent: bool,pub rotation: Rotate,+ pub filter_graph: FilterGraph,}#[derive(Clone, Copy)]@@ -97,27 +91,27 @@ impl OpenedStream {let result = self.receive_frame();match result {- Ok(Some(video)) => unsafe {- let linesize = (*video.as_ptr()).linesize;-+ Ok(Some(video)) => {let frame_cache_id = get_frame_cache_id();+ let mut size: u128 = 0;+let amount_of_planes = video.planes();- let mut planes = Vec::with_capacity(amount_of_planes);for i in 0..amount_of_planes {- planes.push(video.data(i).to_vec());+ size += video.data(i).len() as u128;}let frame = NotRgbFrame {- linesizes: linesize,- planes,- format: video.format(),original_width: self.original_width,original_height: self.original_height,scaled_height: self.scaled_height,scaled_width: self.scaled_width,rotate: self.rotation,original_src: self.original_src.clone(),+ size,+ unscaled_frame: video.clone(),+ tone_mapped,+ filter_graph: self.filter_graph,};offset = offset + one_frame_in_time_base;@@ -145,7 +139,7 @@ impl OpenedStream {index: frame_cache_id,pts: video.pts().expect("pts"),});- },+ }Ok(None) => {if self.reached_eof {break;@@ -288,40 +282,33 @@ impl OpenedStream {let result = self.receive_frame();match result {- Ok(Some(unfiltered)) => unsafe {- let mut video: Video;+ Ok(Some(unfiltered)) => {_print_verbose(&format!("received frame {}", tone_mapped))?;- if tone_mapped && self.should_filter {- video = frame::Video::empty();- self.filter.get("in").unwrap().source().add(&unfiltered)?;- self.filter.get("out").unwrap().sink().frame(&mut video)?;- } else {- video = unfiltered;- }- let linesize = (*video.as_ptr()).linesize;let frame_cache_id = get_frame_cache_id();- let amount_of_planes = video.planes();- let mut planes = Vec::with_capacity(amount_of_planes);+ let mut size: u128 = 0;++ let amount_of_planes = unfiltered.planes();for i in 0..amount_of_planes {- planes.push(video.data(i).to_vec());+ size += unfiltered.data(i).len() as u128;}let frame = NotRgbFrame {- linesizes: linesize,- planes,- format: video.format(),original_height: self.original_height,original_width: self.original_width,scaled_height: self.scaled_height,scaled_width: self.scaled_width,rotate: self.rotation,original_src: self.original_src.clone(),+ size,+ unscaled_frame: unfiltered.clone(),+ tone_mapped,+ filter_graph: self.filter_graph,};let item = FrameCacheItem {- resolved_pts: video.pts().expect("expected pts"),+ resolved_pts: unfiltered.pts().expect("expected pts"),frame: ScalableFrame::new(frame, self.transparent),id: frame_cache_id,asked_time: position,@@ -332,7 +319,7 @@ impl OpenedStream {},};- self.last_position = Some(video.pts().expect("expected pts"));+ self.last_position = Some(unfiltered.pts().expect("expected pts"));freshly_seeked = false;FrameCacheManager::get_instance().get_frame_cache(@@ -359,7 +346,8 @@ impl OpenedStream {Some(stop) => match last_frame_received {Some(last_frame) => {let prev_difference = (last_frame.pts - position).abs();- let new_difference = (video.pts().expect("pts") - position).abs();+ let new_difference =+ (unfiltered.pts().expect("pts") - position).abs();if new_difference > prev_difference {stop_after_n_diverging_pts = Some(stop - 1);@@ -376,9 +364,9 @@ impl OpenedStream {last_frame_received = Some(LastFrameInfo {index: frame_cache_id,- pts: video.pts().expect("pts"),+ pts: unfiltered.pts().expect("pts"),});- },+ }Ok(None) => {}Err(err) => {return Err(err);@@ -515,17 +503,17 @@ pub fn open_stream(original_height,);- let (filter, should_filter) = make_tone_map_filtergraph(+ let filter_graph = FilterGraph {original_width,original_height,- &format!("{:?}", decoder.format()).to_lowercase(),+ format: decoder.format(),time_base,- decoder.color_primaries(),- decoder.color_transfer_characteristic(),- decoder.color_space(),- decoder.color_range(),- decoder.aspect_ratio(),- )?;+ video_primaries: decoder.color_primaries(),+ transfer_characteristic: decoder.color_transfer_characteristic(),+ color_space: decoder.color_space(),+ color_range: decoder.color_range(),+ aspect_ratio: decoder.aspect_ratio(),+ };let opened_stream = OpenedStream {stream_index,@@ -542,8 +530,7 @@ pub fn open_stream(transparent,rotation: rotate,original_src: original_src.to_string(),- filter,- should_filter,+ filter_graph,};Ok((opened_stream, fps, time_base))diff --git a/packages/renderer/rust/scalable_frame.rs b/packages/renderer/rust/scalable_frame.rsindex bbee2708ce..6d224c07d3 100644--- a/packages/renderer/rust/scalable_frame.rs+++ b/packages/renderer/rust/scalable_frame.rs@@ -2,11 +2,16 @@ use std::usize;use ffmpeg_next::{format::Pixel,- frame::Video,+ frame::{self, Video},software::scaling::{Context, Flags},};-use crate::{errors::ErrorWithBacktrace, global_printer::_print_verbose, image::get_png_data};+use crate::{+ errors::ErrorWithBacktrace,+ global_printer::_print_verbose,+ image::get_png_data,+ tone_map::{make_tone_map_filtergraph, FilterGraph},+};#[derive(Clone, Copy)]pub enum Rotate {@@ -17,15 +22,16 @@ pub enum Rotate {}pub struct NotRgbFrame {- pub planes: Vec<Vec<u8>>,- pub linesizes: [i32; 8],- pub format: Pixel,pub original_width: u32,pub original_height: u32,pub scaled_width: u32,pub scaled_height: u32,pub rotate: Rotate,pub original_src: String,+ pub unscaled_frame: Video,+ pub size: u128,+ pub tone_mapped: bool,+ pub filter_graph: FilterGraph,}pub struct RgbFrame {@@ -58,7 +64,46 @@ impl ScalableFrame {"has neither native nor rgb frame",))),Some(frame) => {- let bitmap = scale_and_make_bitmap(&frame, self.transparent)?;+ let mut video;+ let mut planes: Vec<Vec<u8>>;+ let format: Pixel;+ let linesize: [i32; 8];+ let (mut filter, should_filter) = make_tone_map_filtergraph(frame.filter_graph)?;+ if frame.tone_mapped && should_filter {+ video = frame::Video::empty();+ filter+ .get("in")+ .unwrap()+ .source()+ .add(&frame.unscaled_frame)?;+ filter.get("out").unwrap().sink().frame(&mut video)?;++ let amount_of_planes = video.planes();++ planes = Vec::with_capacity(amount_of_planes);+ for i in 0..amount_of_planes {+ let d = &video.data(i).to_vec();+ let data = d.clone();+ planes.push(data);+ }+ format = video.format();++ linesize = unsafe { (*video.as_ptr()).linesize };+ } else {+ let amount_of_planes = frame.unscaled_frame.planes();++ planes = Vec::with_capacity(amount_of_planes);+ for i in 0..amount_of_planes {+ let d = &frame.unscaled_frame.data(i).to_vec();+ let data = d.clone();+ planes.push(data);+ }+ format = frame.unscaled_frame.format();+ linesize = unsafe { (*frame.unscaled_frame.as_ptr()).linesize };+ }++ let bitmap =+ scale_and_make_bitmap(&frame, planes, format, linesize, self.transparent)?;self.rgb_frame = Some(RgbFrame { data: bitmap });self.native_frame = None;Ok(())@@ -86,11 +131,7 @@ impl ScalableFrame {}match self.native_frame {None => {}- Some(ref frame) => {- for plane in &frame.planes {- size += plane.len() as u128;- }- }+ Some(ref frame) => size = frame.size,}size@@ -142,27 +183,30 @@ fn create_bmp_image_from_frame(pub fn scale_and_make_bitmap(native_frame: &NotRgbFrame,+ planes: Vec<Vec<u8>>,+ src_format: Pixel,+ linesize: [i32; 8],transparent: bool,) -> Result<Vec<u8>, ErrorWithBacktrace> {- let format: Pixel = match transparent {+ let dst_format: Pixel = match transparent {true => Pixel::RGBA,false => Pixel::BGR24,};let mut scaler = Context::get(- native_frame.format,+ src_format,native_frame.original_width,native_frame.original_height,- format,+ dst_format,native_frame.scaled_width,native_frame.scaled_height,Flags::BILINEAR,)?;- let mut data: Vec<*const u8> = Vec::with_capacity(native_frame.planes.len());+ let mut data: Vec<*const u8> = Vec::with_capacity(planes.len());- for i in 0..native_frame.planes.len() {- let ptr: *const u8 = native_frame.planes[i].as_ptr();+ for i in 0..planes.len() {+ let ptr: *const u8 = planes[i].as_ptr();data.push(ptr);}@@ -170,11 +214,11 @@ pub fn scale_and_make_bitmap(let mut scaled = Video::empty();scaler.run(- native_frame.format,+ src_format,native_frame.original_width,native_frame.original_height,ptr,- native_frame.linesizes.as_ptr(),+ linesize.as_ptr(),&mut scaled,)?;@@ -206,9 +250,9 @@ pub fn scale_and_make_bitmap(};if transparent {- let is_transparent_pixel_format = native_frame.format == Pixel::YUVA420P- || native_frame.format == Pixel::YUVA444P10LE- || native_frame.format == Pixel::YUVA444P12LE;+ let is_transparent_pixel_format = src_format == Pixel::YUVA420P+ || src_format == Pixel::YUVA444P10LE+ || src_format == Pixel::YUVA444P12LE;if is_transparent_pixel_format {return get_png_data(&rotated, rotated_width, rotated_height);@@ -216,7 +260,7 @@ pub fn scale_and_make_bitmap(_print_verbose(&format!("Requested transparent image, but the video {} is not transparent (pixel format {:?}). Returning BMP.",native_frame.original_src,- native_frame.format+ src_format))?;return Ok(create_bmp_image_from_frame(&rotated,diff --git a/packages/renderer/rust/tone_map.rs b/packages/renderer/rust/tone_map.rsindex b7cf82255c..2b7341afcf 100644--- a/packages/renderer/rust/tone_map.rs+++ b/packages/renderer/rust/tone_map.rs@@ -1,28 +1,43 @@use ffmpeg_next::{color::{self, transfer_characteristic, Primaries, TransferCharacteristic},filter::{self, Graph},+ util::format,Rational,};use crate::global_printer::_print_verbose;-pub fn make_tone_map_filtergraph(- original_width: u32,- original_height: u32,- format: &str,- time_base: Rational,- video_primaries: Primaries,- transfer_characteristic: transfer_characteristic::TransferCharacteristic,- space: color::Space,- color_range: color::Range,- aspect_ratio: Rational,-) -> Result<(Graph, bool), ffmpeg_next::Error> {+#[derive(Clone, Copy)]+pub struct FilterGraph {+ pub original_width: u32,+ pub original_height: u32,+ pub format: format::Pixel,+ pub time_base: Rational,+ pub video_primaries: Primaries,+ pub transfer_characteristic: transfer_characteristic::TransferCharacteristic,+ pub color_space: color::Space,+ pub color_range: color::Range,+ pub aspect_ratio: Rational,+}++pub fn make_tone_map_filtergraph(graph: FilterGraph) -> Result<(Graph, bool), ffmpeg_next::Error> {let mut filter = filter::Graph::new();++ let original_width = graph.original_width;+ let original_height = graph.original_height;+ let pixel_format = graph.format;+ let time_base = graph.time_base;+ let aspect_ratio = graph.aspect_ratio;+ let video_primaries = graph.video_primaries;+ let transfer_characteristic = graph.transfer_characteristic;+ let color_range = graph.color_range;+ let color_space = graph.color_space;+let args = format!("width={}:height={}:pix_fmt={}:time_base={}/{}:sar={}/{}",original_width,original_height,- format,+ format!("{:?}", pixel_format).to_lowercase(),time_base.0,time_base.1,aspect_ratio.0,@@ -49,7 +64,7 @@ pub fn make_tone_map_filtergraph(_ => "input",};- let matrix_in = match space {+ let matrix_in = match color_space {color::Space::BT2020NCL => "2020_ncl",color::Space::BT2020CL => "2020_cl",color::Space::BT470BG => "470bg",@@ -65,7 +80,8 @@ pub fn make_tone_map_filtergraph(_ => "input",};- let matrix_is_target = matrix_in == "input" || matrix_in == "470bg" || matrix_in == "709" || matrix_in == "170m";+ let matrix_is_target =+ matrix_in == "input" || matrix_in == "470bg" || matrix_in == "709" || matrix_in == "170m";let transfer_is_target = transfer_in == "input" || transfer_in == "709";let primaries_is_target = primaries == "input" || primaries == "709" || primaries == "170m";