├── src ├── app │ ├── transforms │ │ ├── mod.rs │ │ └── icc.rs │ ├── ui │ │ ├── custom_widgets │ │ │ ├── mod.rs │ │ │ └── custom_image.rs │ │ ├── state_window.rs │ │ ├── bottom_panel.rs │ │ ├── mod.rs │ │ ├── message_window.rs │ │ ├── controls.rs │ │ ├── frame_props.rs │ │ ├── preferences.rs │ │ └── preview_image.rs │ ├── preview_filter_type.rs │ ├── eframe_app.rs │ ├── mod.rs │ └── vs_previewer.rs ├── vs_handler │ ├── vsnode.rs │ ├── vstransform.rs │ ├── zimg_map.rs │ ├── vsframe.rs │ └── mod.rs ├── main.rs └── utils.rs ├── assets ├── 00demo.jpg ├── 01gui.jpg ├── 04logs.jpg ├── 03prefs.jpg └── 02clipinfo.jpg ├── .gitignore ├── .github └── workflows │ ├── ci.yml │ └── artifacts.yml ├── Cargo.toml ├── README.md ├── UI.md └── LICENSE /src/app/transforms/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod icc; 2 | -------------------------------------------------------------------------------- /assets/00demo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quietvoid/vspreview-rs/HEAD/assets/00demo.jpg -------------------------------------------------------------------------------- /assets/01gui.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quietvoid/vspreview-rs/HEAD/assets/01gui.jpg -------------------------------------------------------------------------------- /assets/04logs.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quietvoid/vspreview-rs/HEAD/assets/04logs.jpg -------------------------------------------------------------------------------- /assets/03prefs.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quietvoid/vspreview-rs/HEAD/assets/03prefs.jpg -------------------------------------------------------------------------------- /src/app/ui/custom_widgets/mod.rs: -------------------------------------------------------------------------------- 1 | mod custom_image; 2 | 3 | pub use custom_image::CustomImage; 4 | -------------------------------------------------------------------------------- /assets/02clipinfo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quietvoid/vspreview-rs/HEAD/assets/02clipinfo.jpg -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # These are backup files generated by rustfmt 6 | **/*.rs.bk 7 | 8 | /*.vpy 9 | -------------------------------------------------------------------------------- /src/app/ui/state_window.rs: -------------------------------------------------------------------------------- 1 | use super::{UiControls, UiFrameProps, UiPreferences, VSPreviewer, egui}; 2 | 3 | pub struct UiStateWindow {} 4 | 5 | impl UiStateWindow { 6 | pub fn ui(pv: &mut VSPreviewer, ctx: &egui::Context) { 7 | let has_current_output = 8 | !pv.outputs.is_empty() && pv.outputs.contains_key(&pv.state.cur_output); 9 | 10 | egui::Window::new("State") 11 | .resizable(true) 12 | .collapsible(false) 13 | .show(ctx, |ui| { 14 | UiControls::ui(pv, ui); 15 | ui.separator(); 16 | 17 | if has_current_output { 18 | let res = UiFrameProps::ui(pv, ctx, ui); 19 | pv.add_error("preview", &res); 20 | } 21 | 22 | UiPreferences::ui(pv, ctx, ui); 23 | }); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | ci: 11 | name: Check, test, rustfmt and clippy 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Install dependencies 17 | run: sudo apt-get install -y libgtk-3-dev 18 | 19 | - name: Install Rust, clippy and rustfmt 20 | uses: dtolnay/rust-toolchain@stable 21 | with: 22 | components: clippy, rustfmt 23 | 24 | - name: Check 25 | run: | 26 | cargo check --workspace --all-features 27 | 28 | - name: Rustfmt 29 | run: | 30 | cargo fmt --all --check 31 | 32 | - name: Clippy 33 | run: | 34 | cargo clippy --workspace --all-features --all-targets --tests -- --deny warnings 35 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "vspreview-rs" 3 | version = "1.0.0" 4 | authors = ["quietvoid"] 5 | edition = "2024" 6 | rust-version = "1.85.0" 7 | license = "GPL-3.0" 8 | 9 | [dependencies] 10 | anyhow = "1.0.100" 11 | clap = { version = "4.5.51", features = ["derive", "wrap_help", "deprecated"] } 12 | eframe = { version = "0.33.0", features = ["persistence"] } 13 | fast_image_resize = "5.3.0" 14 | image = { version = "0.25.8", default-features = false, features = ["png"] } 15 | rgb = "0.8.52" 16 | itertools = "0.14.0" 17 | lcms2 = "6.1.1" 18 | num_enum = "0.7.5" 19 | tokio = { version = "1.48.0", default-features = false, features = ["rt-multi-thread", "macros", "sync"] } 20 | tokio-stream = { version = "*", default-features = false, features = ["net"] } 21 | parking_lot = "0.12.5" 22 | poll-promise = "0.3.0" 23 | rfd = "0.15.4" 24 | serde_derive = "1.0.228" 25 | serde = "1.0.228" 26 | vapoursynth = { version = "0.4.0", features = ["vapoursynth-api-36", "vapoursynth-functions", "vsscript-api-32", "vsscript-functions"] } 27 | 28 | [[bin]] 29 | name = "vspreview-rs" 30 | path = "src/main.rs" 31 | 32 | [profile.release] 33 | opt-level = 3 34 | strip = true 35 | -------------------------------------------------------------------------------- /.github/workflows/artifacts.yml: -------------------------------------------------------------------------------- 1 | on: 2 | workflow_dispatch: 3 | 4 | name: Windows Artifacts 5 | 6 | env: 7 | RELEASE_BIN: vspreview-rs 8 | RELEASE_DIR: artifacts 9 | WINDOWS_TARGET: x86_64-pc-windows-msvc 10 | 11 | jobs: 12 | build: 13 | name: Build artifacts 14 | runs-on: ${{ matrix.os }} 15 | 16 | strategy: 17 | fail-fast: false 18 | 19 | matrix: 20 | build: [Windows] 21 | include: 22 | - build: Windows 23 | os: windows-latest 24 | 25 | steps: 26 | - uses: actions/checkout@v4 27 | 28 | - name: Install Rust 29 | uses: dtolnay/rust-toolchain@stable 30 | 31 | - name: Get the version 32 | shell: bash 33 | run: | 34 | echo "RELEASE_PKG_VERSION=$(cargo pkgid | cut -d# -f2 | cut -d: -f2)" >> $GITHUB_ENV 35 | 36 | - name: Install VapourSynth (Windows) 37 | run: build/win64-vs-setup.ps1 38 | 39 | - name: Build (Windows) 40 | run: | 41 | $Env:Path += ";C:\Program Files\VapourSynth;" 42 | cargo build --release 43 | 44 | - name: Create artifact directory 45 | run: mkdir ${{ env.RELEASE_DIR }} 46 | 47 | - name: Create zipfile (Windows) 48 | if: matrix.build == 'Windows' 49 | shell: bash 50 | run: | 51 | mv ./target/release/${{ env.RELEASE_BIN }}.exe ./${{ env.RELEASE_BIN }}.exe 52 | 7z a ./${{ env.RELEASE_DIR }}/${{ env.RELEASE_BIN }}-${{ env.RELEASE_PKG_VERSION }}-${{ env.WINDOWS_TARGET }}.zip ./${{ env.RELEASE_BIN }}.exe 53 | 54 | - name: Upload Zip 55 | uses: actions/upload-artifact@v4 56 | with: 57 | name: ${{ matrix.build }} 58 | path: ./${{ env.RELEASE_DIR }} 59 | -------------------------------------------------------------------------------- /src/app/ui/custom_widgets/custom_image.rs: -------------------------------------------------------------------------------- 1 | /// Copied from `egui::widgets::Image` 2 | use eframe::egui::*; 3 | 4 | #[derive(Clone, Copy, Debug)] 5 | pub struct CustomImage { 6 | texture_id: TextureId, 7 | uv: Rect, 8 | size: Vec2, 9 | tint: Color32, 10 | sense: Sense, 11 | //translate: Vec2, 12 | } 13 | 14 | impl CustomImage { 15 | pub fn new(texture_id: impl Into, size: impl Into) -> Self { 16 | Self { 17 | texture_id: texture_id.into(), 18 | uv: Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), 19 | size: size.into(), 20 | tint: Color32::WHITE, 21 | sense: Sense::hover(), 22 | //translate: Vec2::ZERO, 23 | } 24 | } 25 | 26 | /*pub fn translate(mut self, translate: Vec2) -> Self { 27 | self.translate = translate; 28 | self 29 | }*/ 30 | } 31 | 32 | impl CustomImage { 33 | pub fn paint_at(&self, ui: &mut Ui, rect: Rect) { 34 | if ui.is_rect_visible(rect) { 35 | use epaint::*; 36 | let Self { 37 | texture_id, 38 | uv, 39 | tint, 40 | .. 41 | } = self; 42 | 43 | { 44 | // TODO: builder pattern for Mesh 45 | let mut mesh = Mesh::with_texture(*texture_id); 46 | mesh.add_rect_with_uv(rect, *uv, *tint); 47 | 48 | let shape = Shape::mesh(mesh); 49 | //shape.translate(*translate); 50 | 51 | ui.painter().add(shape); 52 | } 53 | } 54 | } 55 | } 56 | 57 | impl Widget for CustomImage { 58 | fn ui(self, ui: &mut Ui) -> Response { 59 | let (rect, response) = ui.allocate_exact_size(self.size, self.sense); 60 | self.paint_at(ui, rect); 61 | response 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/vs_handler/vsnode.rs: -------------------------------------------------------------------------------- 1 | use vapoursynth::{prelude::Property, video_info::VideoInfo}; 2 | 3 | #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize)] 4 | pub struct VSNode { 5 | pub num_frames: u32, 6 | pub width: u32, 7 | pub height: u32, 8 | pub fr_num: u32, 9 | pub fr_denom: u32, 10 | pub framerate: u32, 11 | pub format_name: String, 12 | } 13 | 14 | impl VSNode { 15 | pub fn from_videoinfo(info: VideoInfo) -> VSNode { 16 | let (width, height) = match info.resolution { 17 | Property::Constant(r) => (r.width as u32, r.height as u32), 18 | Property::Variable => panic!("Only supports constant resolution!"), 19 | }; 20 | let format = match info.format { 21 | Property::Constant(f) => f, 22 | Property::Variable => panic!("Unsupported format!"), 23 | }; 24 | 25 | let (fr_num, fr_denom) = match info.framerate { 26 | Property::Constant(fr) => (fr.numerator as u32, fr.denominator as u32), 27 | Property::Variable => panic!("Only supports constant framerate!"), 28 | }; 29 | 30 | VSNode { 31 | num_frames: info.num_frames as u32, 32 | width, 33 | height, 34 | fr_num, 35 | fr_denom, 36 | framerate: (fr_num as f64 / fr_denom as f64).ceil() as u32, 37 | format_name: String::from(format.name()), 38 | } 39 | } 40 | } 41 | 42 | impl std::fmt::Display for VSNode { 43 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 44 | write!( 45 | f, 46 | "Frames: {} | Size: {}x{} | FPS: {}/{} = {:.3} | Format: {}", 47 | self.num_frames, 48 | self.width, 49 | self.height, 50 | self.fr_num, 51 | self.fr_denom, 52 | (self.fr_num as f32 / self.fr_denom as f32), 53 | self.format_name, 54 | ) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/vs_handler/vstransform.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | #[derive(Default, Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)] 4 | pub struct VSTransformOptions { 5 | pub resizer: VSResizer, 6 | pub enable_dithering: bool, 7 | pub dither_algo: VSDitherAlgo, 8 | } 9 | 10 | #[derive(Default, Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)] 11 | pub enum VSResizer { 12 | Bilinear, 13 | Bicubic, 14 | Point, 15 | Lanczos, 16 | #[default] 17 | Spline16, 18 | Spline36, 19 | Spline64, 20 | } 21 | 22 | #[derive(Default, Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)] 23 | pub enum VSDitherAlgo { 24 | #[default] 25 | None, 26 | Ordered, 27 | Random, 28 | ErrorDiffusion, 29 | } 30 | 31 | impl VSResizer { 32 | pub const fn as_str(&self) -> &str { 33 | match self { 34 | Self::Bilinear => "Bilinear", 35 | Self::Bicubic => "Bicubic", 36 | Self::Point => "Point", 37 | Self::Lanczos => "Lanczos", 38 | Self::Spline16 => "Spline16", 39 | Self::Spline36 => "Spline36", 40 | Self::Spline64 => "Spline64", 41 | } 42 | } 43 | } 44 | 45 | impl VSDitherAlgo { 46 | pub const fn as_str(&self) -> &str { 47 | match self { 48 | Self::None => "none", 49 | Self::Ordered => "ordered", 50 | Self::Random => "random", 51 | Self::ErrorDiffusion => "error_diffusion", 52 | } 53 | } 54 | } 55 | 56 | impl Display for VSResizer { 57 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 58 | f.write_str(self.as_str()) 59 | } 60 | } 61 | 62 | impl Display for VSDitherAlgo { 63 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 64 | let v = match self { 65 | Self::None => "None", 66 | Self::Ordered => "Ordered", 67 | Self::Random => "Random", 68 | Self::ErrorDiffusion => "Error Diffusion", 69 | }; 70 | 71 | f.write_str(v) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vspreview-rs 2 | 3 | 4 | 5 | 6 | 7 |   8 | 9 | Minimal and functional VapourSynth script previewer 10 | Built on top of [egui](https://github.com/emilk/egui) and [vapoursynth-rs](https://github.com/YaLTeR/vapoursynth-rs) 11 | 12 |   13 | 14 | ### Dependencies 15 | Requires a VapourSynth installation with support for API 3.6 minimum. 16 | For the GUI, see [eframe](https://github.com/emilk/egui/tree/master/eframe) dependencies. 17 | 18 | ### Building 19 | The minimum Rust version to build `vspreview-rs` is 1.85.0. 20 | 21 | `RUSTFLAGS="-C target-cpu=native" cargo build --release` 22 | Targeting the CPU is highly recommended to get the most performance. 23 | 24 | ### Running 25 | `cargo run --release -- script.vpy` 26 | `vspreview-rs script.vpy` 27 | 28 | ### GUI 29 | 30 | The togglable GUI includes information about the clip as well as interactive controls. 31 | Also, frame props are easily accessible. 32 | 33 | Main parts of the UI: 34 | - A window with the current state, including access to frame props and settings. 35 | - A bottom panel with a slider to change frame quickly, as well as the clip info. 36 | - An error window for VapourSynth messages or errors while rendering. 37 | 38 | See more from the [UI documentation](UI.md). 39 | 40 | ### Config 41 | Using `egui`, the state is persisted across runs. 42 | Refer to [directories-next](https://docs.rs/directories-next/2.0.0/directories_next/struct.ProjectDirs.html#method.data_dir) docs. 43 | 44 | ### Keybindings 45 | 46 | **Moving around the image/clip**: 47 | - Seek 1 frame: `Right`, `Left` 48 | - Seek 1 second: `Down`, `Up` 49 | - Alternative seeking: `H`, `J`, `K`, `L` 50 | - Change outputs: `Num1` to `Num0` 51 | - Outputs must be from 0-9 52 | - Zoom: `Ctrl` + **Scroll wheel** 53 | - `Ctrl` + `Up`/`Down` for 0.1 zoom increments 54 | - Scroll horizontally: `Home`/`End` or `Shift` + **Scroll wheel** 55 | - Scroll vertically: `PageUp`/`PageDown`, **Scroll wheel** 56 | 57 | **Misc**: 58 | - Close: `Escape`, `Q` 59 | - Show GUI: `I` (toggle) 60 | - Reload script: `R` 61 | - Toggle the ICC profile color correction: `C` 62 | - Take a screenshot: `S` (saves to script directory) 63 | - Copy the current frame number to clipboard: `Ctrl` + `Shift` + `C` 64 | 65 | **Context menu** (right click): 66 | - Open a new script file 67 | -------------------------------------------------------------------------------- /src/app/ui/bottom_panel.rs: -------------------------------------------------------------------------------- 1 | use super::{VSPreviewer, egui, epaint::Color32, update_input_key_state}; 2 | use anyhow::{Result, anyhow}; 3 | use eframe::epaint::MarginF32; 4 | 5 | pub struct UiBottomPanel {} 6 | 7 | impl UiBottomPanel { 8 | pub fn ui(pv: &mut VSPreviewer, ctx: &egui::Context) -> Result<()> { 9 | let output = pv 10 | .outputs 11 | .get_mut(&pv.state.cur_output) 12 | .ok_or_else(|| anyhow!("UiBottomPanel::ui: Invalid current output key"))?; 13 | let node_info = &output.vsoutput.node_info; 14 | 15 | let transparent_frame = egui::Frame::default() 16 | .fill(Color32::from_black_alpha(96)) 17 | .inner_margin(MarginF32 { 18 | left: 20.0, 19 | right: 20.0, 20 | top: 10.0, 21 | bottom: 10.0, 22 | }); 23 | 24 | egui::TopBottomPanel::bottom("BottomInfo") 25 | .frame(transparent_frame) 26 | .show(ctx, |ui| { 27 | // Add slider 28 | ui.spacing_mut().slider_width = 600.0; 29 | 30 | let mut slider_frame_no = pv.state.cur_frame_no; 31 | 32 | // We want a bit more precision to within ~50 frames 33 | let frames_slider = 34 | egui::Slider::new(&mut slider_frame_no, 0..=(node_info.num_frames - 1)) 35 | .smart_aim(false) 36 | .integer(); 37 | 38 | let slider_res = ui.add(frames_slider); 39 | let in_use = slider_res.has_focus() || slider_res.drag_started(); 40 | let lost_focus = update_input_key_state( 41 | &mut pv.inputs_focused, 42 | "frame_slider", 43 | in_use, 44 | &slider_res, 45 | ); 46 | 47 | // Released/changed value 48 | if lost_focus { 49 | output.last_frame_no = pv.state.cur_frame_no; 50 | pv.state.cur_frame_no = slider_frame_no; 51 | 52 | pv.rerender = true; 53 | } else if slider_frame_no != pv.state.cur_frame_no { 54 | pv.state.cur_frame_no = slider_frame_no; 55 | } 56 | 57 | let output_info = format!("Output {} - {}", output.vsoutput.index, node_info); 58 | 59 | let node_info_label = egui::RichText::new(output_info) 60 | .color(Color32::from_gray(200)) 61 | .size(20.0); 62 | ui.label(node_info_label); 63 | }); 64 | 65 | Ok(()) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/app/preview_filter_type.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | use fast_image_resize as fir; 4 | 5 | /// Filter type to use with fast_image_resize 6 | #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, serde::Serialize)] 7 | pub enum PreviewFilterType { 8 | #[default] 9 | Gpu, 10 | Point, 11 | Bilinear, 12 | Hamming, 13 | CatmullRom, 14 | Mitchell, 15 | Lanczos3, 16 | } 17 | 18 | #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, serde::Serialize)] 19 | pub enum PreviewTextureFilterType { 20 | #[default] 21 | Linear, 22 | Nearest, 23 | } 24 | 25 | impl From<&PreviewFilterType> for fir::FilterType { 26 | fn from(f: &PreviewFilterType) -> Self { 27 | match f { 28 | // Placeholder but it wouldn't be used 29 | PreviewFilterType::Gpu => fir::FilterType::Box, 30 | PreviewFilterType::Point => fir::FilterType::Box, 31 | PreviewFilterType::Bilinear => fir::FilterType::Bilinear, 32 | PreviewFilterType::Hamming => fir::FilterType::Hamming, 33 | PreviewFilterType::CatmullRom => fir::FilterType::CatmullRom, 34 | PreviewFilterType::Mitchell => fir::FilterType::Mitchell, 35 | PreviewFilterType::Lanczos3 => fir::FilterType::Lanczos3, 36 | } 37 | } 38 | } 39 | 40 | impl From<&PreviewTextureFilterType> for eframe::egui::TextureFilter { 41 | fn from(f: &PreviewTextureFilterType) -> Self { 42 | match f { 43 | PreviewTextureFilterType::Linear => eframe::egui::TextureFilter::Linear, 44 | PreviewTextureFilterType::Nearest => eframe::egui::TextureFilter::Nearest, 45 | } 46 | } 47 | } 48 | 49 | impl Display for PreviewFilterType { 50 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 51 | let val = match self { 52 | PreviewFilterType::Gpu => "GPU", 53 | PreviewFilterType::Point => "Point", 54 | PreviewFilterType::Bilinear => "Bilinear", 55 | PreviewFilterType::Hamming => "Hamming", 56 | PreviewFilterType::CatmullRom => "CatmullRom", 57 | PreviewFilterType::Mitchell => "Mitchell", 58 | PreviewFilterType::Lanczos3 => "Lanczos3", 59 | }; 60 | 61 | f.write_str(val) 62 | } 63 | } 64 | 65 | impl Display for PreviewTextureFilterType { 66 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 67 | let val = match self { 68 | PreviewTextureFilterType::Linear => "Linear", 69 | PreviewTextureFilterType::Nearest => "Nearest", 70 | }; 71 | 72 | f.write_str(val) 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /UI.md: -------------------------------------------------------------------------------- 1 | The UI has two parts (currently). 2 | Both can be displayed by toggling with the `I` key. 3 | 4 | ## State Window 5 | 6 | ![State window](/assets/01gui.jpg?raw=true "State window") 7 | 8 | **Controls** 9 | 10 | The following controls are available in window: 11 | - **Output selector**: Change output by selecting from the list. 12 | - **Zoom factor**: Slider/input to adjust the zoom. 13 | - **Translate**: Adjust the image translation. 14 | - Can only be used when the image does not already fit in the window. 15 | 16 | **Frame props** 17 | 18 | The frame props default to the converted RGB24 clip for display. 19 | Original frame props require an extra frame request, so they can be obtained on demand. 20 | 21 | - **Supported frame props**: 22 | - **Frame type**, `_PictType`. 23 | - **Color range**, `_ColorRange`. 24 | - **Chroma location** (only in original props), `_ChromaLocation`. 25 | - **Primaries** (`_Primaries`), **Matrix** (`_Matrix`), **Transfer** (`_Transfer`). 26 | - If the frame is a scene cut, `_SceneChangePrev`. 27 | - **HDR10**/**ST2086** metadata, from `ffms2`. 28 | - Can be clicked to copy the corresponding `x265` CLI settings. 29 | - If the frame carries **Dolby Vision** RPU metadata, from `ffms2`. 30 | - **CAMBI** score, from [akarin.Cambi](https://github.com/AkarinVS/vapoursynth-plugin). 31 | 32 | **Preferences** 33 | 34 | ![Preferences](/assets/03prefs.jpg?raw=true "Preferences") 35 | 36 | - **Resizer**: The VapourSynth resizer used to convert to RGB24. 37 | - **Dithering**: whether to add additionnal dithering when converting. 38 | - **Upscale to the window**: can be used to upscale the frame to fit in the window. 39 | - Useful when the clip is lower resolution than the window. 40 | - **Fit image to the window**: Downscale the image to fit within the window width. 41 | - **Zoom multiplier**: Multiplies the zoom factor by this value instead of incrementing by 1.0. 42 | - **Scroll multiplier**: Mutliplies the pixels translated on wheel scroll. 43 | - Can be used to translate faster or slower. 44 | - **Canvas margin**: Padding to add around the image. 45 | - **Transforms**: Transformations applied to the image previewed: 46 | - **ICC Profile**: ICC profile to use for color correction of the rendered image. 47 | 48 |   49 | 50 | ## Bottom Panel 51 | 52 | ![Bottom panel](/assets/02clipinfo.jpg?raw=true "Bottom panel") 53 | 54 | Provides a slider to seek through frames, as well as an input box to enter a specific frame. 55 | Various informations about the clip. 56 | 57 |   58 | 59 | ## Error/message window 60 | 61 | ![Error window](/assets/04logs.jpg?raw=true "Error window") 62 | 63 | Provides info about the different messages from VapourSynth, and fatal errors. 64 | Cleared on reload or window close. 65 | -------------------------------------------------------------------------------- /src/app/ui/mod.rs: -------------------------------------------------------------------------------- 1 | use super::{MAX_ZOOM, MIN_ZOOM, PreviewFilterType, VSPreviewer, update_input_key_state}; 2 | use anyhow::Result; 3 | use eframe::{ 4 | egui::{self, Layout, RichText}, 5 | emath::{Align, Align2, Vec2}, 6 | epaint, 7 | }; 8 | 9 | mod bottom_panel; 10 | mod controls; 11 | mod frame_props; 12 | mod message_window; 13 | mod preferences; 14 | mod preview_image; 15 | mod state_window; 16 | 17 | mod custom_widgets; 18 | 19 | pub use bottom_panel::UiBottomPanel; 20 | use controls::UiControls; 21 | use frame_props::UiFrameProps; 22 | pub use message_window::MessageWindowUi; 23 | use preferences::UiPreferences; 24 | pub use preview_image::UiPreviewImage; 25 | pub use state_window::UiStateWindow; 26 | 27 | const STATE_LABEL_COLOR: epaint::Color32 = epaint::Color32::from_gray(160); 28 | 29 | pub struct PreviewerMainUi {} 30 | 31 | impl PreviewerMainUi { 32 | pub fn ui(pv: &mut VSPreviewer, ctx: &egui::Context, ui: &mut egui::Ui) -> Result<()> { 33 | let cur_output = pv.state.cur_output; 34 | let has_current_output = !pv.outputs.is_empty() && pv.outputs.contains_key(&cur_output); 35 | 36 | // Draw window on top 37 | if pv.state.show_gui { 38 | UiStateWindow::ui(pv, ctx); 39 | } 40 | 41 | // Centered image painted on 42 | let canvas_res = UiPreviewImage::ui(pv, ui)?; 43 | canvas_res.context_menu(|ui| { 44 | let change_script_text = RichText::new("Open script file") 45 | .size(18.0) 46 | .color(STATE_LABEL_COLOR); 47 | 48 | let about_text = RichText::new("About").size(18.0).color(STATE_LABEL_COLOR); 49 | 50 | if ui.button(change_script_text).clicked() { 51 | pv.change_script_file(ctx); 52 | ui.close(); 53 | } 54 | 55 | if ui.button(about_text).clicked() { 56 | pv.about_window_open = true; 57 | ui.close(); 58 | } 59 | }); 60 | 61 | // Bottom panel 62 | if pv.state.show_gui && has_current_output { 63 | UiBottomPanel::ui(pv, ctx)?; 64 | } 65 | 66 | // About window 67 | egui::Window::new("About") 68 | .open(&mut pv.about_window_open) 69 | .resizable(false) 70 | .anchor(Align2::CENTER_CENTER, Vec2::ZERO) 71 | .show(ctx, |ui| { 72 | ui.with_layout(Layout::top_down(Align::Center), |ui| { 73 | ui.heading("vspreview-rs"); 74 | ui.label("Minimal and functional VapourSynth script previewer"); 75 | 76 | ui.separator(); 77 | 78 | ui.horizontal(|ui| { 79 | ui.spacing_mut().item_spacing.x = 0.0; 80 | 81 | ui.label("Built on top of "); 82 | ui.hyperlink_to("egui", "https://github.com/emilk/egui"); 83 | ui.label(" and "); 84 | ui.hyperlink_to( 85 | "vapoursynth-rs", 86 | "https://github.com/YaLTeR/vapoursynth-rs", 87 | ); 88 | }); 89 | }); 90 | }); 91 | 92 | // Check at the end of frame for reprocessing 93 | pv.try_rerender(ctx)?; 94 | 95 | Ok(()) 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/app/ui/message_window.rs: -------------------------------------------------------------------------------- 1 | use super::{VSPreviewer, egui}; 2 | use eframe::egui::{RichText, Ui}; 3 | 4 | pub struct MessageWindowUi {} 5 | 6 | impl MessageWindowUi { 7 | pub fn ui(pv: &mut VSPreviewer, ctx: &egui::Context) { 8 | let mut vs_messages = None; 9 | 10 | if let Some(script_lock) = pv.script.try_lock() { 11 | if let Some(mut messages) = script_lock.vs_messages.try_lock() { 12 | if !messages.is_empty() { 13 | vs_messages = Some(messages.clone()); 14 | messages.clear(); 15 | } 16 | } 17 | } 18 | 19 | if let Some(messages) = &vs_messages { 20 | // Keep critical errors to avoid rendering image 21 | let mapped: Vec = messages 22 | .iter() 23 | .map(|e| format!("{:?}: {}", &e.message_type, &e.message)) 24 | .collect(); 25 | 26 | pv.add_errors("vapoursynth", &mapped); 27 | } 28 | 29 | if !pv.errors.is_empty() { 30 | egui::Window::new(RichText::new("Messages").size(20.0)) 31 | .resizable(true) 32 | .collapsible(false) 33 | .default_pos((pv.available_size.x / 2.0, pv.available_size.y / 2.0)) 34 | .show(ctx, |ui| { 35 | Self::draw_error_section(pv, ui, "vapoursynth", "VapourSynth messages"); 36 | 37 | Self::draw_error_section( 38 | pv, 39 | ui, 40 | "callbacks", 41 | "Error fetching frames or reloading", 42 | ); 43 | Self::draw_error_section( 44 | pv, 45 | ui, 46 | "preview", 47 | "Error rendering the preview or GUI", 48 | ); 49 | 50 | ui.separator(); 51 | ui.add_space(10.0); 52 | 53 | ui.vertical_centered(|ui| { 54 | if ui 55 | .button(RichText::new("Okay, clear messages").size(22.0)) 56 | .on_hover_text( 57 | RichText::new("The previewer may not end up in a useable state!") 58 | .size(18.0), 59 | ) 60 | .clicked() 61 | { 62 | pv.errors.clear(); 63 | } 64 | }); 65 | }); 66 | } 67 | } 68 | 69 | pub fn draw_error_section(pv: &mut VSPreviewer, ui: &mut Ui, key: &str, header: &str) { 70 | if let Some(errors) = pv.errors.get(key) { 71 | let header = RichText::new(header).size(20.0); 72 | egui::CollapsingHeader::new(header).show(ui, |ui| { 73 | for (i, e) in errors.iter().enumerate() { 74 | Self::draw_error_label(ui, format!("{}. {e}", i + 1)); 75 | } 76 | }); 77 | } 78 | } 79 | 80 | pub fn draw_error_label(ui: &mut Ui, value: String) { 81 | let max_size = value.len().min(75); 82 | 83 | let final_text = if value.len() > 75 { 84 | let trimmed = value[..max_size].replace('\n', " "); 85 | 86 | format!("{} ...", trimmed) 87 | } else { 88 | value.trim().to_string() 89 | }; 90 | 91 | let res = ui.label(RichText::new(final_text).size(18.0)); 92 | 93 | if value.len() > 75 { 94 | res.on_hover_text(RichText::new(value).size(16.0)); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/app/eframe_app.rs: -------------------------------------------------------------------------------- 1 | use eframe::egui::{self, Frame}; 2 | use eframe::epaint::{Color32, MarginF32, Shadow, Stroke}; 3 | 4 | use super::*; 5 | 6 | #[derive(Debug, Default, serde::Deserialize, serde::Serialize)] 7 | #[serde(default)] 8 | pub struct SavedState { 9 | preview_state: PreviewState, 10 | transforms: PreviewTransforms, 11 | } 12 | 13 | impl VSPreviewer { 14 | pub fn with_cc(mut self, cc: &eframe::CreationContext) -> Self { 15 | // Load existing or default state 16 | if let Some(storage) = cc.storage { 17 | let saved_state: SavedState = 18 | eframe::get_value(storage, eframe::APP_KEY).unwrap_or_default(); 19 | 20 | self.state = saved_state.preview_state; 21 | self.transforms = Arc::new(Mutex::new(saved_state.transforms)); 22 | } 23 | 24 | // Set the global theme, default to dark mode 25 | let mut global_visuals = egui::style::Visuals::dark(); 26 | global_visuals.window_shadow = Shadow { 27 | offset: [6, 10], 28 | blur: 8, 29 | spread: 0, 30 | color: Color32::from_black_alpha(25), 31 | }; 32 | cc.egui_ctx.set_visuals(global_visuals); 33 | 34 | cc.egui_ctx.options_mut(|opts| { 35 | opts.zoom_with_keyboard = false; 36 | }); 37 | 38 | // Fix invalid state options 39 | if self.state.scroll_multiplier <= 0.0 { 40 | self.state.scroll_multiplier = 1.0; 41 | } 42 | 43 | // Limit to 2.0 multiplier every zoom, should be plenty 44 | self.state.zoom_multiplier = self.state.zoom_multiplier.clamp(1.0, 2.0); 45 | 46 | self.init_transforms(); 47 | 48 | // Request initial outputs 49 | self.reload(cc.egui_ctx.clone()); 50 | 51 | self 52 | } 53 | } 54 | 55 | impl eframe::App for VSPreviewer { 56 | fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { 57 | if let Some(PreviewerResponse::Close) = self.exit_promise.as_ref().and_then(|p| p.ready()) { 58 | ctx.send_viewport_cmd(egui::ViewportCommand::Close); 59 | return; 60 | } 61 | 62 | let promise_res = self.check_promise_callbacks(ctx); 63 | self.add_error("callbacks", &promise_res); 64 | 65 | let panel_frame = Frame::default() 66 | .fill(Color32::from_gray(51)) 67 | .inner_margin(MarginF32::same(self.state.canvas_margin)) 68 | .stroke(Stroke::NONE); 69 | 70 | egui::CentralPanel::default() 71 | .frame(panel_frame) 72 | .show(ctx, |ui| { 73 | // Check for quit, GUI toggle, reload, etc. 74 | self.check_misc_keyboard_inputs(ctx, ui); 75 | 76 | // React on canvas resolution change 77 | if self.available_size != ui.available_size() { 78 | self.available_size = ui.available_size(); 79 | 80 | // If the win size changed and we were already translated 81 | let translate_changed = self.state.translate.length() > 0.0; 82 | 83 | self.reprocess_outputs(true, translate_changed); 84 | } 85 | 86 | let preview_res = PreviewerMainUi::ui(self, ctx, ui); 87 | self.add_error("preview", &preview_res); 88 | 89 | // Display errors if any 90 | if self.state.show_gui { 91 | MessageWindowUi::ui(self, ctx); 92 | } 93 | }); 94 | } 95 | 96 | fn save(&mut self, storage: &mut dyn eframe::Storage) { 97 | let saved_state = SavedState { 98 | preview_state: self.state, 99 | transforms: self.transforms.lock().clone(), 100 | }; 101 | 102 | eframe::set_value(storage, eframe::APP_KEY, &saved_state); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/app/transforms/icc.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | 3 | use lcms2::{CIExyY, CIExyYTRIPLE, Flags, Intent, PixelFormat, Profile, ToneCurve, Transform}; 4 | use rgb::RGB8; 5 | 6 | #[derive(Debug, serde::Deserialize, serde::Serialize)] 7 | pub struct IccProfile { 8 | pub icc_file: PathBuf, 9 | 10 | #[serde(skip)] 11 | pub target_profile: Option, 12 | 13 | #[serde(skip)] 14 | pub input_profile: Option, 15 | 16 | pub input_whitepoint: XyYCoords, 17 | pub input_primaries: XyYTriple, 18 | 19 | #[serde(skip)] 20 | pub transform: Option>, 21 | } 22 | 23 | #[derive(Debug, Copy, Clone, serde::Deserialize, serde::Serialize)] 24 | pub struct XyYCoords { 25 | x: f64, 26 | y: f64, 27 | y2: f64, 28 | } 29 | 30 | #[derive(Debug, Copy, Clone, serde::Deserialize, serde::Serialize)] 31 | pub struct XyYTriple { 32 | red: XyYCoords, 33 | green: XyYCoords, 34 | blue: XyYCoords, 35 | } 36 | 37 | // Correct image from BT.1886 Rec709 to the target profile 38 | impl IccProfile { 39 | pub fn srgb(icc_file: PathBuf) -> Self { 40 | Self { 41 | icc_file, 42 | target_profile: None, 43 | input_profile: None, 44 | input_whitepoint: XyYCoords::d65(), 45 | input_primaries: XyYTriple::rec709(), 46 | transform: None, 47 | } 48 | } 49 | 50 | pub fn setup(&mut self) { 51 | let target_profile = Profile::new_file(&self.icc_file).unwrap(); 52 | let intent = Intent::RelativeColorimetric; 53 | 54 | let bp = target_profile.detect_black_point(intent).unwrap(); 55 | 56 | // Target contract with profile black point 57 | let lw: f64 = 1.0; 58 | let lb: f64 = bp.Y; 59 | 60 | // Input assumed BT.1886 61 | let wp = CIExyY::from(&self.input_whitepoint); 62 | let prim = CIExyYTRIPLE::from(&self.input_primaries); 63 | 64 | let lwy = lw.powf(1.0 / 2.4); 65 | let lby = lb.powf(1.0 / 2.4); 66 | 67 | let tc = &ToneCurve::new_parametric(6, &[2.4, lwy - lby, lby, 0.0]).unwrap(); 68 | let curves = [tc, tc, tc]; 69 | 70 | let input_profile = Profile::new_rgb(&wp, &prim, &curves).unwrap(); 71 | 72 | let transform = Transform::new_flags( 73 | &input_profile, 74 | PixelFormat::RGB_8, 75 | &target_profile, 76 | PixelFormat::RGB_8, 77 | intent, 78 | Flags::default() | Flags::BLACKPOINT_COMPENSATION, 79 | ) 80 | .unwrap(); 81 | 82 | self.input_profile = Some(input_profile); 83 | self.target_profile = Some(target_profile); 84 | self.transform = Some(transform); 85 | } 86 | } 87 | 88 | impl XyYCoords { 89 | pub fn d65() -> Self { 90 | Self { 91 | x: 0.31271, 92 | y: 0.32902, 93 | y2: 1.0, 94 | } 95 | } 96 | } 97 | 98 | impl XyYTriple { 99 | pub fn rec709() -> Self { 100 | XyYTriple { 101 | red: XyYCoords { 102 | x: 0.64, 103 | y: 0.33, 104 | y2: 1.0, 105 | }, 106 | green: XyYCoords { 107 | x: 0.30, 108 | y: 0.60, 109 | y2: 1.0, 110 | }, 111 | blue: XyYCoords { 112 | x: 0.15, 113 | y: 0.06, 114 | y2: 1.0, 115 | }, 116 | } 117 | } 118 | } 119 | 120 | impl From<&XyYCoords> for CIExyY { 121 | fn from(xyy: &XyYCoords) -> Self { 122 | CIExyY { 123 | x: xyy.x, 124 | y: xyy.y, 125 | Y: xyy.y2, 126 | } 127 | } 128 | } 129 | 130 | impl From<&XyYTriple> for CIExyYTRIPLE { 131 | fn from(prim: &XyYTriple) -> Self { 132 | Self { 133 | Red: CIExyY::from(&prim.red), 134 | Green: CIExyY::from(&prim.green), 135 | Blue: CIExyY::from(&prim.blue), 136 | } 137 | } 138 | } 139 | 140 | impl Clone for IccProfile { 141 | fn clone(&self) -> Self { 142 | Self { 143 | icc_file: self.icc_file.clone(), 144 | target_profile: None, 145 | input_profile: None, 146 | input_whitepoint: self.input_whitepoint, 147 | input_primaries: self.input_primaries, 148 | transform: None, 149 | } 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/app/ui/controls.rs: -------------------------------------------------------------------------------- 1 | use super::{ 2 | MAX_ZOOM, MIN_ZOOM, STATE_LABEL_COLOR, VSPreviewer, egui, egui::RichText, 3 | update_input_key_state, 4 | }; 5 | use anyhow::{Result, anyhow}; 6 | use itertools::Itertools; 7 | 8 | pub struct UiControls {} 9 | 10 | impl UiControls { 11 | pub fn ui(pv: &mut VSPreviewer, ui: &mut egui::Ui) { 12 | egui::Grid::new("controls_grid") 13 | .num_columns(2) 14 | .spacing([8.0, 4.0]) 15 | .show(ui, |ui| { 16 | let mut res = Self::output_select_ui(pv, ui); 17 | pv.add_error("preview", &res); 18 | ui.end_row(); 19 | 20 | res = Self::zoom_slider_ui(pv, ui); 21 | pv.add_error("preview", &res); 22 | ui.end_row(); 23 | 24 | res = Self::translate_drag_ui(pv, ui); 25 | pv.add_error("preview", &res); 26 | ui.end_row(); 27 | }); 28 | } 29 | 30 | pub fn output_select_ui(pv: &mut VSPreviewer, ui: &mut egui::Ui) -> Result<()> { 31 | let old_output = pv.state.cur_output; 32 | let mut new_output = old_output; 33 | 34 | ui.label(RichText::new("Output").color(STATE_LABEL_COLOR)); 35 | 36 | egui::ComboBox::from_id_salt(egui::Id::new("output_select")) 37 | .selected_text(format!("Output {}", new_output)) 38 | .show_ui(ui, |ui| { 39 | for i in pv.outputs.keys().sorted() { 40 | ui.selectable_value(&mut new_output, *i, format!("Output {}", i)); 41 | } 42 | }); 43 | 44 | // Changed output 45 | if new_output != old_output { 46 | pv.state.cur_output = new_output; 47 | 48 | let out = pv 49 | .outputs 50 | .get_mut(&old_output) 51 | .ok_or_else(|| anyhow!("output_select_ui: Invalid old output key"))?; 52 | out.original_props = None; 53 | 54 | if pv.output_needs_rerender(old_output)? { 55 | pv.rerender = true; 56 | } 57 | } 58 | 59 | Ok(()) 60 | } 61 | 62 | pub fn zoom_slider_ui(pv: &mut VSPreviewer, ui: &mut egui::Ui) -> Result<()> { 63 | let old_zoom = pv.state.zoom_factor; 64 | let mut new_zoom = old_zoom; 65 | 66 | let zoom_range = MIN_ZOOM..=MAX_ZOOM; 67 | let frames_slider = egui::Slider::new(&mut new_zoom, zoom_range).max_decimals(3); 68 | 69 | ui.label(RichText::new("Zoom factor").color(STATE_LABEL_COLOR)); 70 | let res = ui.add(frames_slider); 71 | 72 | let in_use = res.has_focus() || res.drag_started(); 73 | update_input_key_state(&mut pv.inputs_focused, "zoom_factor_dragval", in_use, &res); 74 | 75 | if new_zoom != old_zoom { 76 | pv.state.zoom_factor = new_zoom; 77 | pv.rerender = true; 78 | 79 | pv.correct_translate_for_current_output(pv.state.translate, false)?; 80 | } 81 | 82 | Ok(()) 83 | } 84 | 85 | pub fn translate_drag_ui(pv: &mut VSPreviewer, ui: &mut egui::Ui) -> Result<()> { 86 | let old_translate = pv.state.translate_norm; 87 | let mut new_translate = old_translate; 88 | 89 | ui.label(RichText::new("Translate").color(STATE_LABEL_COLOR)); 90 | ui.horizontal(|ui| { 91 | let x_drag = egui::DragValue::new(&mut new_translate.x) 92 | .speed(0.01) 93 | .range(0.0..=1.0) 94 | .max_decimals(3); 95 | 96 | let y_drag = egui::DragValue::new(&mut new_translate.y) 97 | .speed(0.01) 98 | .range(0.0..=1.0) 99 | .max_decimals(3); 100 | 101 | ui.label(RichText::new("x").color(STATE_LABEL_COLOR)); 102 | let res = ui.add(x_drag); 103 | 104 | let in_use = res.has_focus() || res.drag_started(); 105 | update_input_key_state(&mut pv.inputs_focused, "translate_x_dragval", in_use, &res); 106 | 107 | ui.label(RichText::new("y").color(STATE_LABEL_COLOR)); 108 | let res = ui.add(y_drag); 109 | 110 | let in_use = res.has_focus() || res.drag_started(); 111 | update_input_key_state(&mut pv.inputs_focused, "translate_y_dragval", in_use, &res); 112 | }); 113 | 114 | if old_translate != new_translate { 115 | // Fix and update state 116 | pv.correct_translate_for_current_output(new_translate, true)?; 117 | } 118 | 119 | Ok(()) 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/app/mod.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::HashMap, sync::Arc}; 2 | 3 | use eframe::{ 4 | egui::{self, Context}, 5 | epaint::Vec2, 6 | }; 7 | use image::DynamicImage; 8 | use parking_lot::{Mutex, RwLock}; 9 | use poll_promise::{Promise, Sender}; 10 | 11 | mod eframe_app; 12 | mod preview_filter_type; 13 | mod transforms; 14 | mod ui; 15 | mod vs_previewer; 16 | 17 | use ui::*; 18 | 19 | use preview_filter_type::{PreviewFilterType, PreviewTextureFilterType}; 20 | pub use vs_previewer::VSPreviewer; 21 | 22 | use super::vs_handler::{VSFrame, VSFrameProps, VSOutput, vstransform}; 23 | use vstransform::VSTransformOptions; 24 | 25 | use crate::utils::{ 26 | dimensions_for_window, resize_fast, translate_norm_coeffs, update_input_key_state, 27 | }; 28 | 29 | pub use transforms::icc::IccProfile; 30 | 31 | pub const MIN_ZOOM: f32 = 0.125; 32 | pub const MAX_ZOOM: f32 = 64.0; 33 | 34 | type VSPreviewFrame = Arc>; 35 | type FrameResponse = Option; 36 | type PropsResponse = Option; 37 | type ReloadResponse = Option>; 38 | 39 | pub enum PreviewerResponse { 40 | Reload(ReloadResponse), 41 | Frame(FrameResponse), 42 | Props(PropsResponse), 43 | Misc(ReloadType), 44 | Close, 45 | } 46 | 47 | /// TODO: 48 | /// - Canvas background color 49 | /// - ? 50 | #[derive(Debug, Copy, Clone, serde::Deserialize, serde::Serialize)] 51 | #[serde(default)] 52 | pub struct PreviewState { 53 | pub show_gui: bool, 54 | 55 | pub cur_output: i32, 56 | pub cur_frame_no: u32, 57 | 58 | pub zoom_factor: f32, 59 | 60 | #[serde(skip)] 61 | pub translate_changed: bool, 62 | 63 | pub translate: Vec2, 64 | pub translate_norm: Vec2, 65 | 66 | pub frame_transform_opts: VSTransformOptions, 67 | 68 | /// Texture filter (for GPU scaling) 69 | pub texture_filter: PreviewTextureFilterType, 70 | // Only upscales 71 | pub upscale_to_window: bool, 72 | /// Defaults to Point for performance 73 | pub upsampling_filter: PreviewFilterType, 74 | /// Fit the texture before painting 75 | pub fit_to_window: bool, 76 | 77 | pub zoom_multiplier: f32, 78 | 79 | pub scroll_multiplier: f32, 80 | pub canvas_margin: f32, 81 | 82 | pub icc_enabled: bool, 83 | } 84 | 85 | #[derive(Default)] 86 | pub struct PreviewOutput { 87 | pub vsoutput: VSOutput, 88 | 89 | pub rendered_frame: Option, 90 | pub original_props: Option, 91 | 92 | pub force_reprocess: bool, 93 | pub last_frame_no: u32, 94 | } 95 | 96 | pub struct PreviewFrame { 97 | pub vsframe: VSFrame, 98 | 99 | /// Can't be moved out of `VSFrame` without a copy 100 | /// As an Option, we can check which image to use 101 | pub processed_image: Option, 102 | pub texture: Mutex>, 103 | } 104 | 105 | pub struct FetchImageState { 106 | frame_mutex: Arc>>>, 107 | state: PreviewState, 108 | pf: Option, 109 | reprocess: bool, 110 | win_size: Vec2, 111 | } 112 | 113 | pub struct FetchPropsState { 114 | pub frame_mutex: Arc>>>, 115 | pub state: PreviewState, 116 | } 117 | 118 | #[derive(Debug, Clone, Copy)] 119 | pub enum ReloadType { 120 | None, 121 | Reload, 122 | Reprocess, 123 | } 124 | 125 | #[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)] 126 | #[serde(default)] 127 | pub struct PreviewTransforms { 128 | pub icc: Option, 129 | } 130 | 131 | pub enum VSCommand { 132 | Frame(FetchImageState), 133 | FrameProps(FetchPropsState), 134 | ChangeScript, 135 | ChangeIcc(Arc>), 136 | Reload, 137 | Exit, 138 | } 139 | 140 | pub struct VSCommandMsg { 141 | pub res_sender: Sender, 142 | pub cmd: VSCommand, 143 | pub egui_ctx: Context, 144 | } 145 | 146 | impl Default for PreviewState { 147 | fn default() -> Self { 148 | Self { 149 | zoom_factor: 1.0, 150 | zoom_multiplier: 1.0, 151 | scroll_multiplier: 1.0, 152 | canvas_margin: 0.0, 153 | fit_to_window: true, 154 | show_gui: Default::default(), 155 | cur_output: Default::default(), 156 | cur_frame_no: Default::default(), 157 | translate_changed: Default::default(), 158 | translate: Default::default(), 159 | translate_norm: Default::default(), 160 | frame_transform_opts: Default::default(), 161 | upscale_to_window: Default::default(), 162 | upsampling_filter: Default::default(), 163 | icc_enabled: Default::default(), 164 | texture_filter: Default::default(), 165 | } 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /src/vs_handler/zimg_map.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_camel_case_types)] 2 | use std::fmt::Display; 3 | 4 | use num_enum::FromPrimitive; 5 | 6 | // Color range 7 | #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, num_enum::Default)] 8 | #[repr(u8)] 9 | pub enum VSColorRange { 10 | Full = 0, 11 | Limited, 12 | #[num_enum(default)] 13 | Unspecfied, 14 | } 15 | 16 | // Mapping zimg color matrices 17 | #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, num_enum::Default)] 18 | #[repr(u8)] 19 | pub enum VSMatrix { 20 | Rgb = 0, 21 | BT709, 22 | #[num_enum(default)] 23 | Unspecified, 24 | Reserved3, 25 | Fcc, 26 | BT470bg, 27 | ST170M, 28 | ST240M, 29 | YCgCo, 30 | BT2020Ncl, 31 | BT2020cl, 32 | ST2085, 33 | ChromaNcl, 34 | Chromacl, 35 | ICtCp, 36 | } 37 | 38 | // Mapping zimg transfer characteristics 39 | #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, num_enum::Default)] 40 | #[repr(u8)] 41 | pub enum VSTransferCharacteristics { 42 | Reserved0 = 0, 43 | BT709, 44 | #[num_enum(default)] 45 | Unspecified, 46 | Reserved3, 47 | BT470m, 48 | BT470bg, 49 | BT601, 50 | ST240M, 51 | Linear, 52 | Log100, 53 | Log316, 54 | xvYCC, 55 | BT1361, 56 | sRgb, 57 | BT2020_10, 58 | BT2020_12, 59 | ST2084, 60 | ST428, 61 | STD_B67, 62 | } 63 | 64 | // Primaries 65 | #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, num_enum::Default)] 66 | #[repr(u8)] 67 | pub enum VSPrimaries { 68 | Reserved0 = 0, 69 | BT709, 70 | #[num_enum(default)] 71 | Unspecified, 72 | Reserved3, 73 | BT470m, 74 | BT470bg, 75 | ST170M, 76 | ST240M, 77 | Film, 78 | BT2020, 79 | Xyz, 80 | DCIP3, 81 | DCIP3_D65, 82 | Reserved13, 83 | Reserved14, 84 | Reserved15, 85 | Reserved16, 86 | Reserved17, 87 | Reserved18, 88 | Reserved19, 89 | Reserved20, 90 | Reserved21, 91 | JEDEC_P22, // EBU3213 92 | } 93 | 94 | #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, num_enum::Default)] 95 | #[repr(u8)] 96 | pub enum VSChromaLocation { 97 | Left = 0, 98 | Center, 99 | TopLeft, 100 | Top, 101 | BottomLeft, 102 | Bottom, 103 | #[num_enum(default)] 104 | Unspecified, 105 | } 106 | 107 | impl Display for VSColorRange { 108 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 109 | let val = match self { 110 | Self::Limited => "Limited", 111 | Self::Full => "Full", 112 | Self::Unspecfied => "Unspecified", 113 | }; 114 | 115 | f.write_str(val) 116 | } 117 | } 118 | 119 | impl Display for VSChromaLocation { 120 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 121 | let val = match self { 122 | Self::Left => "Left", 123 | Self::Center => "Center", 124 | Self::TopLeft => "Top left", 125 | Self::Top => "Top", 126 | Self::BottomLeft => "Bottom left", 127 | Self::Bottom => "Bottom", 128 | Self::Unspecified => "Unspecified", 129 | }; 130 | 131 | f.write_str(val) 132 | } 133 | } 134 | 135 | impl Display for VSMatrix { 136 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 137 | let val = match self { 138 | Self::Rgb => "RGB", 139 | Self::BT709 => "BT.709", 140 | Self::Unspecified => "Unspecified", 141 | Self::Reserved3 => "Reserved", 142 | Self::Fcc => "FCC", 143 | Self::BT470bg => "BT.470bg", 144 | Self::ST170M => "ST 170M", 145 | Self::ST240M => "ST 240M", 146 | Self::YCgCo => "YCgCo", 147 | Self::BT2020Ncl => "BT.2020 non-constant luminance", 148 | Self::BT2020cl => "BT.2020 constant luminance", 149 | Self::ST2085 => "ST2085", 150 | Self::ChromaNcl => "Chromaticity derived non-constant luminance", 151 | Self::Chromacl => "Chromaticity derived constant luminance", 152 | Self::ICtCp => "ICtCp", 153 | }; 154 | 155 | f.write_str(val) 156 | } 157 | } 158 | 159 | impl Display for VSTransferCharacteristics { 160 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 161 | let val = match self { 162 | Self::Reserved0 | Self::Reserved3 => "Reserved", 163 | Self::BT709 => "BT.709", 164 | Self::Unspecified => "Unspecified", 165 | Self::BT470m => "BT.470m", 166 | Self::BT470bg => "BT.470bg", 167 | Self::BT601 => "BT.601", 168 | Self::ST240M => "ST 240M", 169 | Self::Linear => "Linear", 170 | Self::Log100 => "Log 1:100 contrast", 171 | Self::Log316 => "Log 1:316 contrast", 172 | Self::xvYCC => "xvYCC", 173 | Self::BT1361 => "BT.1361", 174 | Self::sRgb => "sRGB", 175 | Self::BT2020_10 => "BT.2020_10", 176 | Self::BT2020_12 => "BT.2020_12", 177 | Self::ST2084 => "ST 2084 (PQ)", 178 | Self::ST428 => "ST 428", 179 | Self::STD_B67 => "ARIB std-b67 (HLG)", 180 | }; 181 | 182 | f.write_str(val) 183 | } 184 | } 185 | 186 | impl Display for VSPrimaries { 187 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 188 | let val = match self { 189 | Self::Reserved0 190 | | Self::Reserved3 191 | | Self::Reserved13 192 | | Self::Reserved14 193 | | Self::Reserved15 194 | | Self::Reserved16 195 | | Self::Reserved17 196 | | Self::Reserved18 197 | | Self::Reserved19 198 | | Self::Reserved20 199 | | Self::Reserved21 => "Reserved", 200 | Self::BT709 => "BT.709", 201 | Self::Unspecified => "Unspecified", 202 | Self::BT470m => "BT.470m", 203 | Self::BT470bg => "BT.470bg", 204 | Self::ST170M => "ST 170M", 205 | Self::ST240M => "ST 240M", 206 | Self::Film => "Film", 207 | Self::BT2020 => "BT.2020", 208 | Self::Xyz => "XYZ", 209 | Self::DCIP3 => "DCI-P3, DCI white point", 210 | Self::DCIP3_D65 => "DCI-P3 D65 white point", 211 | Self::JEDEC_P22 => "JEDEC P22", 212 | }; 213 | 214 | f.write_str(val) 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /src/app/ui/frame_props.rs: -------------------------------------------------------------------------------- 1 | use super::{STATE_LABEL_COLOR, VSPreviewer, egui, egui::RichText}; 2 | use anyhow::{Result, anyhow}; 3 | 4 | pub struct UiFrameProps {} 5 | 6 | impl UiFrameProps { 7 | pub fn ui(pv: &mut VSPreviewer, ctx: &egui::Context, ui: &mut egui::Ui) -> Result<()> { 8 | let output = pv 9 | .outputs 10 | .get(&pv.state.cur_output) 11 | .ok_or_else(|| anyhow!("UiFrameProps::ui: Invalid current output key"))?; 12 | let mut props = None; 13 | 14 | if let Some(pf) = &output.rendered_frame { 15 | let pf = pf.read(); 16 | props = Some(pf.vsframe.props); 17 | } 18 | 19 | // Overwrite from original if available 20 | if let Some(original_props) = &output.original_props { 21 | props = Some(*original_props); 22 | } 23 | 24 | if let Some(props) = props { 25 | let header = RichText::new("Frame props").color(STATE_LABEL_COLOR); 26 | 27 | egui::CollapsingHeader::new(header).show(ui, |ui| { 28 | ui.spacing_mut().item_spacing.y = 0.0; 29 | 30 | egui::Grid::new("props_grid") 31 | .num_columns(2) 32 | .spacing([8.0, -2.0]) 33 | .show(ui, |ui| { 34 | ui.label(RichText::new("Frame type").color(STATE_LABEL_COLOR)); 35 | ui.label(props.frame_type.to_string()); 36 | ui.end_row(); 37 | 38 | ui.label(RichText::new("Color range").color(STATE_LABEL_COLOR)); 39 | ui.label(props.color_range.to_string()); 40 | ui.end_row(); 41 | 42 | ui.label(RichText::new("Chroma location").color(STATE_LABEL_COLOR)); 43 | ui.label(props.chroma_location.to_string()); 44 | ui.end_row(); 45 | 46 | ui.label(RichText::new("Primaries").color(STATE_LABEL_COLOR)); 47 | ui.label(props.primaries.to_string()); 48 | ui.end_row(); 49 | 50 | ui.label(RichText::new("Matrix").color(STATE_LABEL_COLOR)); 51 | ui.label(props.matrix.to_string()); 52 | ui.end_row(); 53 | 54 | ui.label(RichText::new("Transfer").color(STATE_LABEL_COLOR)); 55 | ui.label(props.transfer.to_string()); 56 | ui.end_row(); 57 | 58 | if let Some(sc) = props.is_scenecut { 59 | let (v, color) = crate::utils::icon_color_for_bool(sc); 60 | 61 | ui.label(RichText::new("Scene cut").color(STATE_LABEL_COLOR)); 62 | ui.label(RichText::new(v).size(20.0).color(color)); 63 | ui.end_row(); 64 | } 65 | 66 | if let Some(hdr10_meta) = props.hdr10_metadata { 67 | ui.label(RichText::new("Mastering display").color(STATE_LABEL_COLOR)); 68 | 69 | let prim_label = 70 | egui::Label::new(hdr10_meta.mastering_display.to_string()) 71 | .sense(egui::Sense::click()); 72 | let mdcv_res = ui.add(prim_label); 73 | 74 | if mdcv_res 75 | .on_hover_text("Click to copy x265 setting") 76 | .clicked() 77 | { 78 | let arg = format!( 79 | "--master-display \"{}\"", 80 | hdr10_meta.mastering_display.x265_string() 81 | ); 82 | println!("{}", arg); 83 | 84 | ctx.copy_text(arg); 85 | } 86 | ui.end_row(); 87 | 88 | if let (Some(maxcll), Some(maxfall)) = 89 | (hdr10_meta.maxcll, hdr10_meta.maxfall) 90 | { 91 | ui.label( 92 | RichText::new("Content light level").color(STATE_LABEL_COLOR), 93 | ); 94 | 95 | let cll_label = egui::Label::new(format!( 96 | "MaxCLL: {maxcll}, MaxFALL: {maxfall}" 97 | )) 98 | .sense(egui::Sense::click()); 99 | let cll_res = ui.add(cll_label); 100 | 101 | if cll_res 102 | .on_hover_text("Click to copy x265 setting") 103 | .clicked() 104 | { 105 | let arg = format!("--max-cll \"{},{}\"", maxcll, maxfall); 106 | println!("{}", arg); 107 | 108 | ctx.copy_text(arg); 109 | } 110 | ui.end_row(); 111 | } 112 | } 113 | 114 | let (v, color) = crate::utils::icon_color_for_bool(props.is_dolbyvision); 115 | ui.label(RichText::new("Dolby Vision").color(STATE_LABEL_COLOR)); 116 | ui.label(RichText::new(v).size(20.0).color(color)); 117 | ui.end_row(); 118 | 119 | if let Some(cambi) = props.cambi_score { 120 | let rounded = egui::emath::round_to_decimals(cambi, 4); 121 | ui.label(RichText::new("CAMBI score").color(STATE_LABEL_COLOR)); 122 | ui.label(rounded.to_string()); 123 | ui.end_row(); 124 | } 125 | 126 | ui.label(""); 127 | ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { 128 | let reload_btn = ui.button("Reload original props"); 129 | 130 | if reload_btn.clicked() { 131 | pv.fetch_original_props(ctx); 132 | } 133 | }); 134 | ui.end_row(); 135 | }); 136 | }); 137 | } 138 | 139 | Ok(()) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release 2 | 3 | use anyhow::{Result, bail}; 4 | use clap::{Parser, ValueHint}; 5 | use parking_lot::Mutex; 6 | use std::{path::PathBuf, sync::Arc}; 7 | use tokio::sync::mpsc::Receiver; 8 | 9 | mod app; 10 | mod utils; 11 | mod vs_handler; 12 | 13 | use app::{IccProfile, PreviewerResponse, ReloadType, VSCommand, VSCommandMsg, VSPreviewer}; 14 | use vs_handler::PreviewedScript; 15 | 16 | #[derive(Parser, Debug)] 17 | #[command(name = env!("CARGO_PKG_NAME"), about = "VapourSynth script previewer", author = "quietvoid", version = env!("CARGO_PKG_VERSION"))] 18 | struct Opt { 19 | #[arg(id = "input", value_hint = ValueHint::FilePath)] 20 | input: PathBuf, 21 | 22 | #[arg( 23 | id = "variable", 24 | visible_alias = "arg", 25 | short = 'v', 26 | visible_short_alias = 'a', 27 | help = "Variables to set in the script environment. Example: `-v key=value`", 28 | value_delimiter = ',' 29 | )] 30 | variables: Vec, 31 | } 32 | 33 | #[tokio::main(flavor = "multi_thread", worker_threads = 1)] 34 | async fn main() -> Result<()> { 35 | let opt = Opt::parse(); 36 | 37 | if !opt.input.is_file() { 38 | bail!("Input script file does not exist!"); 39 | } 40 | 41 | let script = Arc::new(Mutex::new(PreviewedScript::new(opt.input, opt.variables))); 42 | let (cmd_sender, cmd_receiver) = tokio::sync::mpsc::channel(1); 43 | 44 | { 45 | let script = script.clone(); 46 | tokio::spawn(async move { 47 | init_vs_command_loop(script, cmd_receiver).await; 48 | }); 49 | } 50 | 51 | let previewer = VSPreviewer::new(script, cmd_sender); 52 | let res = eframe::run_native( 53 | "vspreview-rs", 54 | eframe::NativeOptions::default(), 55 | Box::new(|cc| Ok(Box::new(previewer.with_cc(cc)))), 56 | ); 57 | 58 | if let Err(e) = res { 59 | bail!("Failed starting egui window: {}", e); 60 | } 61 | 62 | Ok(()) 63 | } 64 | 65 | pub async fn init_vs_command_loop( 66 | script: Arc>, 67 | mut cmd_receiver: Receiver, 68 | ) { 69 | while let Some(msg) = cmd_receiver.recv().await { 70 | let VSCommandMsg { 71 | res_sender, 72 | cmd, 73 | egui_ctx, 74 | } = msg; 75 | let script = script.clone(); 76 | 77 | match cmd { 78 | VSCommand::Reload => { 79 | let mut script_mutex = script.lock(); 80 | let res = script_mutex.reload(); 81 | script_mutex.add_vs_error(&res); 82 | 83 | let ret = if res.is_ok() { 84 | let outputs_res = script_mutex.get_outputs(); 85 | script_mutex.add_vs_error(&outputs_res); 86 | 87 | let outputs = if let Ok(outputs) = outputs_res { 88 | // No output case handled by vapoursynth-rs 89 | assert!(!outputs.is_empty()); 90 | Some(outputs) 91 | } else { 92 | None 93 | }; 94 | 95 | // Not ready but we need to get the checker going 96 | egui_ctx.request_repaint(); 97 | 98 | outputs 99 | } else { 100 | None 101 | }; 102 | 103 | res_sender.send(PreviewerResponse::Reload(ret)) 104 | } 105 | VSCommand::Frame(fetch_image_state) => { 106 | let ret = match VSPreviewer::get_preview_image(egui_ctx, script, fetch_image_state) 107 | { 108 | Ok(preview_frame) => preview_frame, 109 | Err(e) => { 110 | // Errors here are not recoverable 111 | panic!("{}", e) 112 | } 113 | }; 114 | 115 | res_sender.send(PreviewerResponse::Frame(ret)); 116 | } 117 | VSCommand::FrameProps(fetch_image_state) => { 118 | let ret = if let Some(mut script_mutex) = script.try_lock() { 119 | let cur_output = fetch_image_state.state.cur_output; 120 | let cur_frame_no = fetch_image_state.state.cur_frame_no; 121 | 122 | let _lock = fetch_image_state.frame_mutex.lock(); 123 | 124 | let props_res = script_mutex.get_original_props(cur_output, cur_frame_no); 125 | script_mutex.add_vs_error(&props_res); 126 | 127 | if let Ok(props) = props_res { 128 | egui_ctx.request_repaint(); 129 | 130 | Some(props) 131 | } else { 132 | None 133 | } 134 | } else { 135 | None 136 | }; 137 | 138 | res_sender.send(PreviewerResponse::Props(ret)); 139 | } 140 | VSCommand::ChangeScript => { 141 | let path = std::env::current_dir().unwrap(); 142 | 143 | let new_file = rfd::FileDialog::new() 144 | .set_title("Select a VapourSynth script file") 145 | .add_filter("VapourSynth", &["vpy"]) 146 | .set_directory(path) 147 | .pick_file(); 148 | 149 | let ret = if let Some(new_file) = new_file { 150 | let mut script_mutex = script.lock(); 151 | 152 | script_mutex.change_script_path(new_file); 153 | egui_ctx.request_repaint(); 154 | 155 | ReloadType::Reload 156 | } else { 157 | ReloadType::None 158 | }; 159 | 160 | res_sender.send(PreviewerResponse::Misc(ret)); 161 | } 162 | VSCommand::ChangeIcc(transforms) => { 163 | let new_file = rfd::FileDialog::new() 164 | .set_title("Select a ICC profile file") 165 | .add_filter("ICC", &["icc", "icm"]) 166 | .pick_file(); 167 | 168 | let ret = if let Some(new_file) = new_file { 169 | let mut transforms = transforms.lock(); 170 | 171 | let mut profile = IccProfile::srgb(new_file); 172 | profile.setup(); 173 | 174 | transforms.icc = Some(profile); 175 | 176 | egui_ctx.request_repaint(); 177 | 178 | ReloadType::Reprocess 179 | } else { 180 | ReloadType::None 181 | }; 182 | 183 | res_sender.send(PreviewerResponse::Misc(ret)); 184 | } 185 | VSCommand::Exit => { 186 | let script_mutex = script.lock(); 187 | script_mutex.exit(); 188 | 189 | res_sender.send(PreviewerResponse::Close); 190 | 191 | break; 192 | } 193 | } 194 | } 195 | 196 | cmd_receiver.close(); 197 | } 198 | -------------------------------------------------------------------------------- /src/vs_handler/vsframe.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | use image::DynamicImage; 4 | use vapoursynth::map::MapRef; 5 | 6 | use super::zimg_map::*; 7 | 8 | /// Reserved props 9 | const KEY_FRAME_TYPE: &str = "_PictType"; 10 | const KEY_COLOR_RANGE: &str = "_ColorRange"; 11 | const KEY_CHROMALOC: &str = "_ChromaLocation"; 12 | const KEY_PRIMARIES: &str = "_Primaries"; 13 | const KEY_MATRIX: &str = "_Matrix"; 14 | const KEY_TRANSFER: &str = "_Transfer"; 15 | const KEY_SCENE_CUT: &str = "_SceneChangePrev"; 16 | 17 | /// Potentially relevant props 18 | const KEY_CAMBI: &str = "CAMBI"; 19 | const KEY_DOVI_RPU: &str = "DolbyVisionRPU"; 20 | 21 | // HDR10 related 22 | const KEY_MDCV_PRIM_X: &str = "MasteringDisplayPrimariesX"; 23 | const KEY_MDCV_PRIM_Y: &str = "MasteringDisplayPrimariesY"; 24 | const KEY_MDCV_WP_X: &str = "MasteringDisplayWhitePointX"; 25 | const KEY_MDCV_WP_Y: &str = "MasteringDisplayWhitePointY"; 26 | const KEY_MDCV_LUM_MIN: &str = "MasteringDisplayMinLuminance"; 27 | const KEY_MDCV_LUM_MAX: &str = "MasteringDisplayMaxLuminance"; 28 | const KEY_HDR10_MAXCLL: &str = "ContentLightLevelMax"; 29 | const KEY_HDR10_MAXFALL: &str = "ContentLightLevelAverage"; 30 | 31 | #[derive(Default, Clone)] 32 | pub struct VSFrame { 33 | pub image: DynamicImage, 34 | pub props: VSFrameProps, 35 | } 36 | 37 | #[derive(Default, Debug, Clone, Copy, PartialEq)] 38 | pub struct VSFrameProps { 39 | pub frame_type: char, 40 | 41 | pub color_range: VSColorRange, 42 | pub chroma_location: VSChromaLocation, 43 | 44 | pub primaries: VSPrimaries, 45 | pub matrix: VSMatrix, 46 | pub transfer: VSTransferCharacteristics, 47 | 48 | pub is_scenecut: Option, 49 | pub cambi_score: Option, 50 | 51 | pub hdr10_metadata: Option, 52 | pub is_dolbyvision: bool, 53 | } 54 | 55 | #[derive(Default, Debug, Clone, Copy, PartialEq)] 56 | pub struct Hdr10Metadata { 57 | pub mastering_display: MdcvMetadata, 58 | pub maxcll: Option, 59 | pub maxfall: Option, 60 | } 61 | 62 | #[derive(Default, Debug, Clone, Copy, PartialEq)] 63 | pub struct MdcvMetadata { 64 | pub lum_min: f64, 65 | pub lum_max: f64, 66 | 67 | pub red: [f64; 2], 68 | pub green: [f64; 2], 69 | pub blue: [f64; 2], 70 | pub white_point: [f64; 2], 71 | } 72 | 73 | impl VSFrameProps { 74 | // Only reserved frame props 75 | pub fn from_mapref(map: MapRef) -> Self { 76 | let frame_type = if let Ok(frame_type) = map.get_data(KEY_FRAME_TYPE) { 77 | frame_type[0] as char 78 | } else { 79 | '?' 80 | }; 81 | 82 | let color_range = map 83 | .get_int(KEY_COLOR_RANGE) 84 | .map_or(VSColorRange::default(), |v| VSColorRange::from(v as u8)); 85 | 86 | let chroma_location = map 87 | .get_int(KEY_CHROMALOC) 88 | .map_or(VSChromaLocation::default(), |v| { 89 | VSChromaLocation::from(v as u8) 90 | }); 91 | 92 | let primaries = map 93 | .get_int(KEY_PRIMARIES) 94 | .map_or(VSPrimaries::default(), |v| VSPrimaries::from(v as u8)); 95 | 96 | let matrix = map 97 | .get_int(KEY_MATRIX) 98 | .map_or(VSMatrix::default(), |v| VSMatrix::from(v as u8)); 99 | 100 | let transfer = map.get_int(KEY_TRANSFER).map(|v| v as u8).map_or( 101 | VSTransferCharacteristics::default(), 102 | VSTransferCharacteristics::from, 103 | ); 104 | 105 | let is_scenecut = map.get_int(KEY_SCENE_CUT).map_or(None, |v| Some(v != 0)); 106 | let cambi_score = map.get_float(KEY_CAMBI).ok(); 107 | 108 | let hdr10_metadata = Hdr10Metadata::new(&map); 109 | let is_dolbyvision = map.value_count(KEY_DOVI_RPU).is_ok_and(|v| v > 0); 110 | 111 | VSFrameProps { 112 | frame_type, 113 | color_range, 114 | chroma_location, 115 | primaries, 116 | matrix, 117 | transfer, 118 | is_scenecut, 119 | cambi_score, 120 | is_dolbyvision, 121 | hdr10_metadata, 122 | } 123 | } 124 | } 125 | 126 | // Requires MDCV minimum 127 | impl Hdr10Metadata { 128 | fn new(map: &MapRef) -> Option { 129 | let mastering_display = MdcvMetadata::new(map)?; 130 | 131 | let maxcll = map.get_float(KEY_HDR10_MAXCLL).ok(); 132 | let maxfall = map.get_float(KEY_HDR10_MAXFALL).ok(); 133 | 134 | let meta = Hdr10Metadata { 135 | mastering_display, 136 | maxcll, 137 | maxfall, 138 | }; 139 | 140 | Some(meta) 141 | } 142 | } 143 | 144 | impl MdcvMetadata { 145 | fn new(map: &MapRef) -> Option { 146 | let lum_min = map.get_float(KEY_MDCV_LUM_MIN).ok()?; 147 | let lum_max = map.get_float(KEY_MDCV_LUM_MAX).ok()?; 148 | 149 | let primaries_x = map.get_float_array(KEY_MDCV_PRIM_X).ok()?; 150 | assert!(primaries_x.len() == 3); 151 | let primaries_y = map.get_float_array(KEY_MDCV_PRIM_Y).ok()?; 152 | assert!(primaries_x.len() == 3); 153 | 154 | let wp_x = map.get_float(KEY_MDCV_WP_X).ok()?; 155 | let wp_y = map.get_float(KEY_MDCV_WP_Y).ok()?; 156 | 157 | let meta = MdcvMetadata { 158 | lum_min, 159 | lum_max, 160 | red: [primaries_x[0], primaries_y[0]], 161 | green: [primaries_x[1], primaries_y[1]], 162 | blue: [primaries_x[2], primaries_y[2]], 163 | white_point: [wp_x, wp_y], 164 | }; 165 | 166 | Some(meta) 167 | } 168 | 169 | pub fn x265_string(&self) -> String { 170 | let Self { 171 | lum_min, 172 | lum_max, 173 | red, 174 | green, 175 | blue, 176 | white_point, 177 | } = self; 178 | let [rx, ry] = red.map(|v| (v * 50000.0).round() as u16); 179 | let [gx, gy] = green.map(|v| (v * 50000.0).round() as u16); 180 | let [bx, by] = blue.map(|v| (v * 50000.0).round() as u16); 181 | let [wx, wy] = white_point.map(|v| (v * 50000.0).round() as u16); 182 | let (max, min) = ( 183 | (*lum_max * 10000.0).round() as usize, 184 | (*lum_min * 10000.0).round() as usize, 185 | ); 186 | 187 | format!( 188 | "\ 189 | G({gx},{gy})\ 190 | B({bx},{by})\ 191 | R({rx},{ry})\ 192 | WP({wx},{wy})\ 193 | L({max},{min})\ 194 | " 195 | ) 196 | } 197 | } 198 | 199 | impl Display for MdcvMetadata { 200 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 201 | let Self { 202 | lum_min, 203 | lum_max, 204 | red, 205 | green, 206 | blue, 207 | white_point, 208 | } = self; 209 | let [rx, ry] = red.map(|v| (v * 50000.0).round() as u16); 210 | let [gx, gy] = green.map(|v| (v * 50000.0).round() as u16); 211 | let [bx, by] = blue.map(|v| (v * 50000.0).round() as u16); 212 | let [wx, wy] = white_point; 213 | 214 | let primaries_str = match (rx, ry, gx, gy, bx, by) { 215 | (35400, 14600, 8500, 39850, 6550, 2300) => Some("BT.2020"), 216 | (34000, 16000, 13250, 34500, 7500, 3000) => Some("Display P3"), 217 | (32000, 16500, 15000, 30000, 7500, 3000) => Some("BT.709"), 218 | _ => None, 219 | }; 220 | 221 | if let Some(prim) = primaries_str { 222 | f.write_str(prim) 223 | } else { 224 | f.write_str(&format!( 225 | "\ 226 | G({gx:.03},{gy:.03})\ 227 | B({bx:.03},{by:.03})\ 228 | R({rx:.03},{ry:.03})\ 229 | WP({wx:.04},{wy:.04})\ 230 | L({lum_max:.0},{lum_min:.4})\ 231 | " 232 | )) 233 | } 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use anyhow::{Result, anyhow}; 4 | use eframe::epaint::{Color32, ColorImage, Vec2}; 5 | use fast_image_resize::{self as fr, ResizeAlg, ResizeOptions}; 6 | use fr::images::Image as FrImage; 7 | use image::{DynamicImage, ImageBuffer}; 8 | use rgb::{AsPixels, ComponentSlice}; 9 | use vapoursynth::prelude::{ColorFamily, FrameRef}; 10 | 11 | use crate::app::{PreviewState, PreviewTransforms}; 12 | 13 | /// `DynamicImage` from `VS::FrameRef` 14 | /// `ColorFamily::Gray` => `DynamicImage::ImageLuma8` 15 | /// `ColorFamily::RGB` => `DynamicImage::ImageRgb8` 16 | pub fn frame_to_dynimage(frame: &FrameRef) -> DynamicImage { 17 | let format = frame.format(); 18 | 19 | // Gray or RGB 20 | assert!(matches!( 21 | format.color_family(), 22 | ColorFamily::Gray | ColorFamily::RGB 23 | )); 24 | 25 | let plane_count = frame.format().plane_count(); 26 | assert!(plane_count == 1 || plane_count == 3); 27 | 28 | // Assumes all planes are the same resolution 29 | let (w, h) = (frame.width(0), frame.height(0)); 30 | 31 | if plane_count == 1 { 32 | let mut buf = ImageBuffer::new(w as u32, h as u32); 33 | 34 | buf.enumerate_rows_mut().for_each(|(row, pixels)| { 35 | let y = frame.plane_row(0, row as usize); 36 | pixels.for_each(|(x, _, p)| *p = image::Luma([y[x as usize]])); 37 | }); 38 | 39 | DynamicImage::ImageLuma8(buf) 40 | } else { 41 | let mut buf = ImageBuffer::new(w as u32, h as u32); 42 | 43 | buf.enumerate_rows_mut().for_each(|(row, pixels)| { 44 | let row = row as usize; 45 | let r = frame.plane_row(0, row); 46 | let g = frame.plane_row(1, row); 47 | let b = frame.plane_row(2, row); 48 | 49 | pixels.for_each(|(x, _, p)| { 50 | let x = x as usize; 51 | *p = image::Rgb([r[x], g[x], b[x]]) 52 | }); 53 | }); 54 | 55 | DynamicImage::ImageRgb8(buf) 56 | } 57 | } 58 | 59 | // Based on fast_image_resize example doc 60 | pub fn resize_fast( 61 | img: DynamicImage, 62 | dst_width: u32, 63 | dst_height: u32, 64 | filter_type: fr::FilterType, 65 | ) -> Result { 66 | let width = img.width(); 67 | let height = img.height(); 68 | 69 | let src_image = match img { 70 | DynamicImage::ImageLuma8(luma) => { 71 | FrImage::from_vec_u8(width, height, luma.into_raw(), fr::PixelType::U8)? 72 | } 73 | DynamicImage::ImageRgb8(rgb) => { 74 | FrImage::from_vec_u8(width, height, rgb.into_raw(), fr::PixelType::U8x3)? 75 | } 76 | _ => unreachable!(), 77 | }; 78 | 79 | let mut dst_image = FrImage::new(dst_width, dst_height, src_image.pixel_type()); 80 | 81 | let mut resizer = fr::Resizer::new(); 82 | resizer.resize( 83 | &src_image, 84 | &mut dst_image, 85 | &ResizeOptions::new().resize_alg(ResizeAlg::Convolution(filter_type)), 86 | )?; 87 | 88 | let resized_img = match dst_image.pixel_type() { 89 | fr::PixelType::U8 => DynamicImage::ImageLuma8( 90 | image::ImageBuffer::from_raw(dst_width, dst_height, dst_image.buffer().to_vec()) 91 | .ok_or_else(|| anyhow!("Failed resizing luma"))?, 92 | ), 93 | fr::PixelType::U8x3 => DynamicImage::ImageRgb8( 94 | image::ImageBuffer::from_raw(dst_width, dst_height, dst_image.buffer().to_vec()) 95 | .ok_or_else(|| anyhow!("Failed resizing RGB"))?, 96 | ), 97 | _ => unreachable!(), 98 | }; 99 | 100 | Ok(resized_img) 101 | } 102 | 103 | pub fn dimensions_for_window(win_size: &Vec2, orig_size: &Vec2) -> Vec2 { 104 | let mut size = *orig_size; 105 | 106 | // Fit to width 107 | if orig_size.x != win_size.x { 108 | size.x = win_size.x; 109 | size.y = (size.x * orig_size.y) / orig_size.x; 110 | } 111 | 112 | // Fit to height 113 | if size.y > win_size.y { 114 | size.y = win_size.y; 115 | size.x = (size.y * orig_size.x) / orig_size.y; 116 | } 117 | 118 | size 119 | } 120 | 121 | pub fn image_to_colorimage( 122 | img: &DynamicImage, 123 | state: &PreviewState, 124 | transforms: &PreviewTransforms, 125 | ) -> ColorImage { 126 | let size = [img.width() as usize, img.height() as usize]; 127 | 128 | let icc = if state.icc_enabled { 129 | transforms.icc.as_ref() 130 | } else { 131 | None 132 | }; 133 | 134 | let pixels = match img { 135 | DynamicImage::ImageLuma8(luma) => luma.iter().copied().map(Color32::from_gray).collect(), 136 | DynamicImage::ImageRgb8(rgb) => { 137 | if let Some(icc) = icc { 138 | let t = icc.transform.as_ref().unwrap(); 139 | let mut transformed = rgb.as_pixels().to_vec(); 140 | 141 | t.transform_in_place(&mut transformed); 142 | 143 | transformed 144 | .iter() 145 | .map(|p| { 146 | let p = p.as_slice(); 147 | Color32::from_rgb(p[0], p[1], p[2]) 148 | }) 149 | .collect() 150 | } else { 151 | rgb.as_raw() 152 | .chunks_exact(3) 153 | .map(|p| Color32::from_rgb(p[0], p[1], p[2])) 154 | .collect() 155 | } 156 | } 157 | _ => unreachable!(), 158 | }; 159 | 160 | ColorImage { 161 | size, 162 | source_size: Vec2::from(size.map(|e| e as f32)), 163 | pixels, 164 | } 165 | } 166 | 167 | // Normalize from max translate value to float with range [-1, 1] 168 | pub fn translate_norm_coeffs(size: &Vec2, win_size: &Vec2, zoom_factor: f32) -> Vec2 { 169 | // Clips left and right 170 | let max_tx = if zoom_factor > 1.0 { 171 | // When zooming, the image is cropped to smallest bound 172 | size.x - (win_size.x.min(size.x) / zoom_factor) 173 | } else if zoom_factor < 1.0 { 174 | // When unzooming, we want reduce the image size 175 | // That way it might fit within the window 176 | (size.x * zoom_factor) - win_size.x 177 | } else { 178 | size.x - win_size.x 179 | }; 180 | 181 | // Clips vertically at the bottom only 182 | let max_ty = if zoom_factor > 1.0 { 183 | size.y - (win_size.y.min(size.y) / zoom_factor) 184 | } else if zoom_factor < 1.0 { 185 | (size.y * zoom_factor) - win_size.y 186 | } else { 187 | size.y - win_size.y 188 | }; 189 | 190 | Vec2::from([max_tx, max_ty]) 191 | } 192 | 193 | pub fn translate_norm_to_pixels( 194 | translate_norm: &Vec2, 195 | size: &Vec2, 196 | win_size: &Vec2, 197 | zoom_factor: f32, 198 | ) -> Vec2 { 199 | let coeffs = translate_norm_coeffs(size, win_size, zoom_factor); 200 | 201 | Vec2::from([ 202 | (translate_norm.x * coeffs.x).round(), 203 | (translate_norm.y * coeffs.y).round(), 204 | ]) 205 | } 206 | 207 | pub const fn icon_color_for_bool(value: bool) -> (&'static str, Color32) { 208 | if value { 209 | ("✅", Color32::from_rgb(0, 128, 0)) 210 | } else { 211 | ("✖", Color32::from_rgb(200, 0, 0)) 212 | } 213 | } 214 | 215 | pub fn update_input_key_state<'a>( 216 | map: &mut HashMap<&'a str, bool>, 217 | key: &'a str, 218 | val: bool, 219 | res: &eframe::egui::Response, 220 | ) -> bool { 221 | if let Some(current) = map.get_mut(key) { 222 | *current |= val; 223 | } else { 224 | map.insert(key, val); 225 | } 226 | 227 | release_on_focus_lost(map, key, res) 228 | } 229 | 230 | fn release_on_focus_lost<'a>( 231 | map: &mut HashMap<&'a str, bool>, 232 | key: &'a str, 233 | res: &eframe::egui::Response, 234 | ) -> bool { 235 | if !res.has_focus() && (res.drag_stopped() || res.lost_focus()) { 236 | map.insert(key, false); 237 | 238 | true 239 | } else { 240 | false 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /src/vs_handler/mod.rs: -------------------------------------------------------------------------------- 1 | use itertools::Itertools; 2 | use parking_lot::Mutex; 3 | use std::collections::HashMap; 4 | use std::path::PathBuf; 5 | use std::sync::Arc; 6 | 7 | use anyhow::{Result, anyhow, bail}; 8 | use vapoursynth::api::MessageHandlerId; 9 | use vapoursynth::prelude::*; 10 | 11 | use crate::utils::frame_to_dynimage; 12 | 13 | pub mod vsframe; 14 | pub mod vsnode; 15 | pub mod vstransform; 16 | pub mod zimg_map; 17 | 18 | pub use vsframe::{VSFrame, VSFrameProps}; 19 | pub use vsnode::VSNode; 20 | pub use vstransform::*; 21 | 22 | #[derive(serde::Deserialize, serde::Serialize)] 23 | pub struct PreviewedScript { 24 | script_file: String, 25 | script_dir: PathBuf, 26 | variables: Vec, 27 | 28 | #[serde(skip)] 29 | env: Option, 30 | #[serde(skip)] 31 | message_handler_id: Option, 32 | 33 | #[serde(skip)] 34 | pub vs_messages: Arc>>, 35 | } 36 | 37 | #[derive(Default, Clone, Debug)] 38 | pub struct VSOutput { 39 | pub index: i32, 40 | pub node_info: VSNode, 41 | } 42 | 43 | #[derive(Clone, Debug)] 44 | pub struct VSMessage { 45 | pub message_type: MessageType, 46 | pub message: String, 47 | } 48 | 49 | impl PreviewedScript { 50 | pub fn new(script_path: PathBuf, variables: Vec) -> Self { 51 | let mut script_dir = script_path.clone(); 52 | script_dir.pop(); 53 | 54 | let script_file: String = script_path 55 | .into_os_string() 56 | .into_string() 57 | .expect("Invalid script file path!"); 58 | 59 | Self { 60 | script_file, 61 | script_dir, 62 | variables, 63 | env: None, 64 | message_handler_id: None, 65 | vs_messages: Arc::new(Mutex::new(Vec::new())), 66 | } 67 | } 68 | 69 | pub fn reload(&mut self) -> Result<()> { 70 | let env = if let Some(env) = self.env.as_mut() { 71 | env.clear(); 72 | 73 | env 74 | } else { 75 | self.env.get_or_insert(Environment::new()?) 76 | }; 77 | 78 | if self.message_handler_id.is_none() { 79 | let api = API::get().ok_or_else(|| anyhow!("Couldn't retrieve API object"))?; 80 | 81 | let vserrors = self.vs_messages.clone(); 82 | let id = api.add_message_handler(move |message_type, message| { 83 | let message = message.to_str().unwrap().to_string(); 84 | 85 | let mut errors = vserrors.lock(); 86 | errors.push(VSMessage { 87 | message_type, 88 | message, 89 | }); 90 | }); 91 | 92 | self.message_handler_id = Some(id); 93 | } 94 | 95 | if !self.variables.is_empty() { 96 | let mut variables = OwnedMap::new(API::get().unwrap()); 97 | let kv_map = self 98 | .variables 99 | .iter() 100 | .filter_map(|s| s.split('=').collect_tuple()); 101 | for (name, value) in kv_map { 102 | variables 103 | .append_data(name, value.as_bytes()) 104 | .expect("Couldn't append an argument value"); 105 | } 106 | 107 | env.set_variables(&variables) 108 | .expect("Couldn't set arguments"); 109 | } 110 | 111 | env.eval_file(&self.script_file, EvalFlags::SetWorkingDir)?; 112 | 113 | Ok(()) 114 | } 115 | 116 | pub fn get_outputs(&mut self) -> Result> { 117 | let env = self.env.get_or_insert(Environment::new()?); 118 | 119 | let outputs: HashMap = (0..9) 120 | .map(|i| { 121 | env.get_output(i).map(|(node, _alpha)| { 122 | let out = VSOutput { 123 | index: i, 124 | node_info: VSNode::from_videoinfo(node.info()), 125 | }; 126 | 127 | (i, out) 128 | }) 129 | }) 130 | .filter_map(Result::ok) 131 | .collect(); 132 | 133 | if !outputs.is_empty() { 134 | Ok(outputs) 135 | } else { 136 | bail!("VapourSynth script has not set any output node!"); 137 | } 138 | } 139 | 140 | pub fn get_frame( 141 | &mut self, 142 | output: i32, 143 | frame_no: u32, 144 | opts: &VSTransformOptions, 145 | ) -> Result { 146 | let env = self 147 | .env 148 | .as_ref() 149 | .ok_or_else(|| anyhow!("Cannot request VS frame without environment"))?; 150 | 151 | let (mut node, _alpha) = env.get_output(output)?; 152 | 153 | // std plugin, should always exist 154 | let resize_plugin = env 155 | .get_core()? 156 | .get_plugin_by_id("com.vapoursynth.resize")? 157 | .unwrap(); 158 | 159 | let mut args = 160 | OwnedMap::new(API::get().ok_or_else(|| anyhow!("Couldn't initialize VS API"))?); 161 | args.set_node("clip", &node)?; 162 | 163 | if let Property::Constant(f) = node.info().format { 164 | let id = i32::from(f.id()); 165 | let is_rgb24 = id == PresetFormat::RGB24 as i32; 166 | 167 | // Disable dither for RGB24 src 168 | // Always dither for GRAY/YUV src 169 | if opts.enable_dithering && !is_rgb24 && f.bitsPerSample >= 8 { 170 | args.set_data("dither_type", opts.dither_algo.as_str().as_bytes())?; 171 | } 172 | 173 | let modified = match f.color_family() { 174 | ColorFamily::Gray => { 175 | if id != PresetFormat::Gray8 as i32 { 176 | args.set_int("format", PresetFormat::Gray8 as i64)?; 177 | true 178 | } else { 179 | false 180 | } 181 | } 182 | ColorFamily::YUV => { 183 | args.set_int("format", PresetFormat::RGB24 as i64)?; 184 | args.set_int("matrix_in", 1)?; 185 | 186 | true 187 | } 188 | ColorFamily::RGB => { 189 | if !is_rgb24 { 190 | args.set_int("format", PresetFormat::RGB24 as i64)?; 191 | true 192 | } else { 193 | false 194 | } 195 | } 196 | _ => panic!("Invalid frame color family for preview!"), 197 | }; 198 | 199 | if modified { 200 | let rgb = resize_plugin.invoke(opts.resizer.as_str(), &args)?; 201 | node = rgb.get_node("clip")?; 202 | } 203 | } else { 204 | panic!("Invalid format: must be constant"); 205 | } 206 | 207 | let frame = node.get_frame(frame_no as usize)?; 208 | let props = VSFrameProps::from_mapref(frame.props()); 209 | let image = frame_to_dynimage(&frame); 210 | 211 | Ok(VSFrame { image, props }) 212 | } 213 | 214 | pub fn get_original_props(&mut self, output: i32, frame_no: u32) -> Result { 215 | let env = self 216 | .env 217 | .as_ref() 218 | .ok_or_else(|| anyhow!("Cannot request VS frame without environment"))?; 219 | 220 | let (node, _alpha) = env.get_output(output)?; 221 | let frame = node.get_frame(frame_no as usize)?; 222 | 223 | Ok(VSFrameProps::from_mapref(frame.props())) 224 | } 225 | 226 | pub fn get_script_dir(&self) -> PathBuf { 227 | self.script_dir.clone() 228 | } 229 | 230 | pub fn add_vs_error(&mut self, res: &Result) { 231 | if let Err(e) = res { 232 | let mut messages = self.vs_messages.lock(); 233 | 234 | messages.push(VSMessage { 235 | message_type: MessageType::Fatal, 236 | message: format!("{:?}", e), 237 | }); 238 | } 239 | } 240 | 241 | pub fn change_script_path(&mut self, new_script: PathBuf) { 242 | let mut script_dir = new_script.clone(); 243 | script_dir.pop(); 244 | 245 | let script_file: String = new_script 246 | .into_os_string() 247 | .into_string() 248 | .expect("Invalid script file path!"); 249 | 250 | self.script_dir = script_dir; 251 | self.script_file = script_file; 252 | } 253 | 254 | pub fn send_debug_message(&self, message: String) -> Result<()> { 255 | let api = API::get().unwrap(); 256 | api.log(MessageType::Debug, &message)?; 257 | 258 | Ok(()) 259 | } 260 | 261 | pub fn exit(&self) { 262 | if let Some(env) = self.env.as_ref() { 263 | env.clear(); 264 | } 265 | } 266 | } 267 | 268 | impl Drop for PreviewedScript { 269 | fn drop(&mut self) { 270 | if let Some(handler_id) = self.message_handler_id { 271 | let api = API::get().unwrap(); 272 | api.remove_message_handler(handler_id); 273 | } 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /src/app/ui/preferences.rs: -------------------------------------------------------------------------------- 1 | use super::{ 2 | PreviewFilterType, STATE_LABEL_COLOR, VSPreviewer, egui, egui::RichText, update_input_key_state, 3 | }; 4 | 5 | use crate::{ 6 | app::preview_filter_type::PreviewTextureFilterType, 7 | vs_handler::{VSDitherAlgo, VSResizer}, 8 | }; 9 | 10 | pub struct UiPreferences {} 11 | 12 | impl UiPreferences { 13 | pub fn ui(pv: &mut VSPreviewer, ctx: &egui::Context, ui: &mut egui::Ui) { 14 | let header = RichText::new("Preferences").color(STATE_LABEL_COLOR); 15 | 16 | egui::CollapsingHeader::new(header).show(ui, |ui| { 17 | Self::pref_grid(pv, ui); 18 | Self::transforms_ui(pv, ui, ctx); 19 | }); 20 | } 21 | 22 | fn pref_grid(pv: &mut VSPreviewer, ui: &mut egui::Ui) { 23 | let old_vs_resizer = pv.state.frame_transform_opts.resizer; 24 | let old_enable_dithering = pv.state.frame_transform_opts.enable_dithering; 25 | let old_dither_algo = pv.state.frame_transform_opts.dither_algo; 26 | 27 | let old_texture_filter = pv.state.texture_filter; 28 | let old_upscale_flag = pv.state.upscale_to_window; 29 | let old_upsampling_filter = pv.state.upsampling_filter; 30 | let old_fit_window_flag = pv.state.fit_to_window; 31 | 32 | egui::Grid::new("prefs_grid") 33 | .num_columns(2) 34 | .spacing([8.0, 4.0]) 35 | .show(ui, |ui| { 36 | let new_vs_resizer = &mut pv.state.frame_transform_opts.resizer; 37 | 38 | ui.label(RichText::new("Resizer (chroma)").color(STATE_LABEL_COLOR)); 39 | egui::ComboBox::from_id_salt(egui::Id::new("vs_resizer_select")) 40 | .selected_text(new_vs_resizer.to_string()) 41 | .show_ui(ui, |ui| { 42 | ui.selectable_value(new_vs_resizer, VSResizer::Bilinear, "Bilinear"); 43 | ui.selectable_value(new_vs_resizer, VSResizer::Bicubic, "Bicubic"); 44 | ui.selectable_value(new_vs_resizer, VSResizer::Point, "Point"); 45 | ui.selectable_value(new_vs_resizer, VSResizer::Lanczos, "Lanczos"); 46 | ui.selectable_value(new_vs_resizer, VSResizer::Spline16, "Spline16"); 47 | ui.selectable_value(new_vs_resizer, VSResizer::Spline36, "Spline36"); 48 | ui.selectable_value(new_vs_resizer, VSResizer::Spline64, "Spline64"); 49 | }); 50 | ui.end_row(); 51 | 52 | let new_enable_dithering = &mut pv.state.frame_transform_opts.enable_dithering; 53 | 54 | ui.checkbox(new_enable_dithering, "Enable dithering"); 55 | if *new_enable_dithering { 56 | let new_dither_algo = &mut pv.state.frame_transform_opts.dither_algo; 57 | 58 | egui::ComboBox::from_id_salt(egui::Id::new("vs_dither_algo_select")) 59 | .selected_text(new_dither_algo.to_string()) 60 | .show_ui(ui, |ui| { 61 | ui.selectable_value(new_dither_algo, VSDitherAlgo::None, "None"); 62 | ui.selectable_value(new_dither_algo, VSDitherAlgo::Ordered, "Ordered"); 63 | ui.selectable_value(new_dither_algo, VSDitherAlgo::Random, "Random"); 64 | ui.selectable_value( 65 | new_dither_algo, 66 | VSDitherAlgo::ErrorDiffusion, 67 | "Error Diffusion", 68 | ); 69 | }); 70 | } 71 | ui.end_row(); 72 | 73 | ui.checkbox(&mut pv.state.upscale_to_window, "Upscale image to window"); 74 | ui.checkbox(&mut pv.state.fit_to_window, "Fit image to window"); 75 | ui.end_row(); 76 | 77 | if pv.state.upscale_to_window || pv.state.fit_to_window { 78 | let new_texture_filter = &mut pv.state.texture_filter; 79 | 80 | ui.label(RichText::new("Texture filter").color(STATE_LABEL_COLOR)) 81 | .on_hover_text("Filter to use when scaling the texture (GPU)"); 82 | 83 | egui::ComboBox::from_id_salt(egui::Id::new("texture_filter_select")) 84 | .selected_text(new_texture_filter.to_string()) 85 | .show_ui(ui, |ui| { 86 | ui.selectable_value( 87 | new_texture_filter, 88 | PreviewTextureFilterType::Linear, 89 | PreviewTextureFilterType::Linear.to_string(), 90 | ); 91 | ui.selectable_value( 92 | new_texture_filter, 93 | PreviewTextureFilterType::Nearest, 94 | PreviewTextureFilterType::Nearest.to_string(), 95 | ); 96 | }); 97 | ui.end_row(); 98 | } 99 | 100 | if pv.state.upscale_to_window { 101 | let new_upsampling_filter = &mut pv.state.upsampling_filter; 102 | 103 | ui.label(RichText::new("Upsampling filter").color(STATE_LABEL_COLOR)); 104 | egui::ComboBox::from_id_salt(egui::Id::new("upsampling_filter_select")) 105 | .selected_text(new_upsampling_filter.to_string()) 106 | .show_ui(ui, |ui| { 107 | ui.selectable_value( 108 | new_upsampling_filter, 109 | PreviewFilterType::Gpu, 110 | PreviewFilterType::Gpu.to_string(), 111 | ); 112 | ui.selectable_value( 113 | new_upsampling_filter, 114 | PreviewFilterType::Point, 115 | PreviewFilterType::Point.to_string(), 116 | ); 117 | ui.selectable_value( 118 | new_upsampling_filter, 119 | PreviewFilterType::Bilinear, 120 | PreviewFilterType::Bilinear.to_string(), 121 | ); 122 | ui.selectable_value( 123 | new_upsampling_filter, 124 | PreviewFilterType::Hamming, 125 | PreviewFilterType::Hamming.to_string(), 126 | ); 127 | ui.selectable_value( 128 | new_upsampling_filter, 129 | PreviewFilterType::CatmullRom, 130 | PreviewFilterType::CatmullRom.to_string(), 131 | ); 132 | ui.selectable_value( 133 | new_upsampling_filter, 134 | PreviewFilterType::Mitchell, 135 | PreviewFilterType::Mitchell.to_string(), 136 | ); 137 | ui.selectable_value( 138 | new_upsampling_filter, 139 | PreviewFilterType::Lanczos3, 140 | PreviewFilterType::Lanczos3.to_string(), 141 | ); 142 | }); 143 | ui.end_row(); 144 | } 145 | 146 | let zoom_mult_dragval = egui::DragValue::new(&mut pv.state.zoom_multiplier) 147 | .speed(0.01) 148 | .range(1.0..=2.0) 149 | .max_decimals(2); 150 | ui.label(RichText::new("Zoom multiplier").color(STATE_LABEL_COLOR)); 151 | let res = ui.add(zoom_mult_dragval); 152 | ui.end_row(); 153 | 154 | let in_use = res.has_focus() || res.drag_started(); 155 | update_input_key_state(&mut pv.inputs_focused, "zoom_mult_dragval", in_use, &res); 156 | 157 | let scroll_mult_dragval = egui::DragValue::new(&mut pv.state.scroll_multiplier) 158 | .speed(0.01) 159 | .range(0.5..=4.0) 160 | .max_decimals(2); 161 | ui.label(RichText::new("Scroll multiplier").color(STATE_LABEL_COLOR)); 162 | let res = ui.add(scroll_mult_dragval); 163 | ui.end_row(); 164 | 165 | let in_use = res.has_focus() || res.drag_started(); 166 | update_input_key_state(&mut pv.inputs_focused, "scroll_mult_dragval", in_use, &res); 167 | 168 | let canvas_margin_dragval = egui::DragValue::new(&mut pv.state.canvas_margin) 169 | .speed(1) 170 | .range(0.0..=100.0) 171 | .max_decimals(0); 172 | ui.label(RichText::new("Canvas margin").color(STATE_LABEL_COLOR)); 173 | let res = ui.add(canvas_margin_dragval); 174 | ui.end_row(); 175 | 176 | let in_use = res.has_focus() || res.drag_started(); 177 | let lost_focus = update_input_key_state( 178 | &mut pv.inputs_focused, 179 | "canvas_margin_dragval", 180 | in_use, 181 | &res, 182 | ); 183 | 184 | if lost_focus { 185 | pv.reprocess_outputs(true, false); 186 | } 187 | }); 188 | 189 | let ft = pv.state.frame_transform_opts; 190 | 191 | // VS Processing setting changed 192 | if ft.resizer != old_vs_resizer 193 | || ft.enable_dithering != old_enable_dithering 194 | || ft.dither_algo != old_dither_algo 195 | { 196 | pv.rerender = true; 197 | } else if pv.state.upscale_to_window != old_upscale_flag 198 | || pv.state.upsampling_filter != old_upsampling_filter 199 | || pv.state.fit_to_window != old_fit_window_flag 200 | || pv.state.texture_filter != old_texture_filter 201 | { 202 | pv.reprocess_outputs(true, false); 203 | } 204 | } 205 | 206 | fn transforms_ui(pv: &mut VSPreviewer, ui: &mut egui::Ui, ctx: &egui::Context) { 207 | let mut profile_name = String::from("None"); 208 | if let Some(t) = pv.transforms.try_lock() { 209 | if let Some(icc) = &t.icc { 210 | if let Some(name) = icc.icc_file.file_name() { 211 | profile_name = name.to_str().unwrap().to_string(); 212 | } 213 | } 214 | } 215 | 216 | let max_name_size = profile_name.len().min(50); 217 | let header = RichText::new("Transforms").color(STATE_LABEL_COLOR); 218 | 219 | let old_icc_flag = pv.state.icc_enabled; 220 | 221 | egui::CollapsingHeader::new(header).show(ui, |ui| { 222 | egui::Grid::new("prefs_grid") 223 | .num_columns(2) 224 | .spacing([8.0, 4.0]) 225 | .show(ui, |ui| { 226 | ui.checkbox(&mut pv.state.icc_enabled, "Enable ICC profile"); 227 | 228 | let icc_name = 229 | ui.label(format!("Loaded ICC: {}", &profile_name[..max_name_size])); 230 | ui.end_row(); 231 | 232 | let change_icc_text = 233 | RichText::new("Open ICC profile").color(STATE_LABEL_COLOR); 234 | let icc_button = ui.button(change_icc_text); 235 | ui.end_row(); 236 | 237 | if icc_button.clicked() { 238 | pv.change_icc_profile(ctx); 239 | } 240 | 241 | if profile_name.len() > 50 { 242 | icc_name.on_hover_text(profile_name); 243 | } 244 | }); 245 | }); 246 | 247 | if pv.state.icc_enabled != old_icc_flag { 248 | pv.reprocess_outputs(true, false); 249 | } 250 | } 251 | } 252 | -------------------------------------------------------------------------------- /src/app/ui/preview_image.rs: -------------------------------------------------------------------------------- 1 | use super::{ 2 | MAX_ZOOM, MIN_ZOOM, PreviewFilterType, VSPreviewer, custom_widgets::CustomImage, egui, 3 | egui::Key, epaint::Vec2, 4 | }; 5 | use anyhow::{Result, anyhow}; 6 | use eframe::egui::{Response, Sense, UiBuilder}; 7 | 8 | pub struct UiPreviewImage {} 9 | 10 | impl UiPreviewImage { 11 | pub fn ui(pv: &mut VSPreviewer, ui: &mut egui::Ui) -> Result { 12 | let cur_output = pv.state.cur_output; 13 | let has_current_output = !pv.outputs.is_empty() && pv.outputs.contains_key(&cur_output); 14 | 15 | // If the outputs differ in frame index, we should wait for the render 16 | // instead of rendering the old frame 17 | let output_diff_frame = if has_current_output { 18 | let cur_output = pv 19 | .outputs 20 | .get(&cur_output) 21 | .ok_or_else(|| anyhow!("UiPreviewImage::ui: Invalid current output key"))?; 22 | let last_output = pv 23 | .outputs 24 | .get(&pv.last_output_key) 25 | .ok_or_else(|| anyhow!("UiPreviewImage::ui: Invalid last output key"))?; 26 | 27 | last_output.last_frame_no != cur_output.last_frame_no 28 | } else { 29 | false 30 | }; 31 | 32 | let mut zoom_delta = ui.input(|i| i.zoom_delta()); 33 | if (1.0 - zoom_delta).abs() < 0.025 { 34 | zoom_delta = 1.0; 35 | } 36 | 37 | let scroll_delta = ui.input(|i| i.raw_scroll_delta); 38 | 39 | // Acquire frame texture to render now 40 | let preview_frame = if has_current_output { 41 | let output = pv.outputs.get(&cur_output).ok_or_else(|| { 42 | anyhow!("UiPreviewImage::ui preview_frame: Invalid current output key") 43 | })?; 44 | 45 | if output_diff_frame { 46 | None 47 | } else { 48 | output.rendered_frame.as_ref().map(Clone::clone) 49 | } 50 | } else { 51 | None 52 | }; 53 | 54 | let mut painted_image = false; 55 | let mut image_size = Vec2::ZERO; 56 | 57 | // We want the image size for alignment 58 | if let Some(pf) = &preview_frame { 59 | let pf = pf.read(); 60 | 61 | let image = &pf.vsframe.image; 62 | image_size = Vec2::from([image.width() as f32, image.height() as f32]); 63 | } 64 | 65 | let win_size = pv.available_size; 66 | let unzoomed_image_size = image_size * pv.state.zoom_factor.min(1.0); 67 | 68 | // We want to move the far left side of the image to avoid clipping 69 | let cross_align = if unzoomed_image_size.x > win_size.x { 70 | egui::Align::Min 71 | } else { 72 | egui::Align::Center 73 | }; 74 | 75 | let canvas_layout = egui::Layout::centered_and_justified(egui::Direction::TopDown) 76 | .with_cross_align(cross_align); 77 | 78 | let canvas_res = ui.scope_builder(UiBuilder::new().sense(Sense::click()), |ui| { 79 | ui.with_layout(canvas_layout, |ui| { 80 | if let Some(pf) = preview_frame { 81 | let pf = pf.read(); 82 | if let Some(tex_mutex) = pf.texture.try_lock() { 83 | if let Some(tex) = &*tex_mutex { 84 | painted_image = true; 85 | 86 | let mut tex_size = tex.size_vec2(); 87 | 88 | if (tex_size.x > win_size.x || tex_size.y > win_size.y) 89 | && pv.state.fit_to_window 90 | { 91 | // Image larger than window, downscaling 92 | tex_size *= (win_size.x / tex_size.x).min(1.0); 93 | tex_size *= (win_size.y / tex_size.y).min(1.0); 94 | } else if (tex_size.x < win_size.x || tex_size.y < win_size.y) 95 | && pv.state.upscale_to_window 96 | && pv.state.upsampling_filter == PreviewFilterType::Gpu 97 | { 98 | let target_size = 99 | crate::utils::dimensions_for_window(&win_size, &tex_size); 100 | // Image smaller than window, upscale 101 | tex_size = target_size; 102 | } 103 | 104 | let custom_image = CustomImage::new(tex.id(), tex_size); 105 | 106 | ui.add(custom_image); 107 | 108 | if !pv.any_input_focused() && !pv.frame_promise.is_locked() { 109 | let mut res = Self::handle_move_inputs( 110 | pv, 111 | ui, 112 | &image_size, 113 | zoom_delta, 114 | scroll_delta, 115 | ); 116 | pv.add_error("preview", &res); 117 | 118 | res = Self::handle_keypresses(pv, ui); 119 | pv.add_error("preview", &res); 120 | } 121 | } 122 | }; 123 | } 124 | 125 | // Show loading when reloading or when no image and errors cleared 126 | if pv.reload_data.is_some() || (!painted_image && pv.errors.is_empty()) { 127 | ui.add(egui::Spinner::new().size(200.0)); 128 | } 129 | }) 130 | }); 131 | 132 | Ok(canvas_res.response) 133 | } 134 | 135 | pub fn handle_keypresses(pv: &mut VSPreviewer, ui: &mut egui::Ui) -> Result<()> { 136 | let mut rerender = Self::check_update_seek(pv, ui)?; 137 | rerender |= Self::check_update_output(pv, ui)?; 138 | rerender |= Self::check_icc_toggle(pv, ui)?; 139 | 140 | if ui.input(|i| i.key_pressed(Key::S)) { 141 | pv.save_screenshot()?; 142 | } 143 | 144 | pv.rerender |= rerender; 145 | 146 | Ok(()) 147 | } 148 | 149 | /// Returns whether to rerender 150 | pub fn check_update_seek(pv: &mut VSPreviewer, ui: &mut egui::Ui) -> Result { 151 | // Must not have modifiers 152 | if !ui.input(|i| i.modifiers.is_none()) { 153 | return Ok(false); 154 | } 155 | 156 | let output = pv 157 | .outputs 158 | .get_mut(&pv.state.cur_output) 159 | .ok_or_else(|| anyhow!("check_update_seek: Invalid current output key"))?; 160 | let node_info = &output.vsoutput.node_info; 161 | 162 | let current = pv.state.cur_frame_no; 163 | 164 | let res = if ui.input(|i| i.key_pressed(Key::ArrowLeft) || i.key_pressed(Key::H)) { 165 | if current > 0 { 166 | pv.state.cur_frame_no -= 1; 167 | true 168 | } else { 169 | false 170 | } 171 | } else if ui.input(|i| i.key_pressed(Key::ArrowRight) || i.key_pressed(Key::L)) { 172 | if current < node_info.num_frames - 1 { 173 | pv.state.cur_frame_no += 1; 174 | true 175 | } else { 176 | false 177 | } 178 | } else if ui.input(|i| i.key_pressed(Key::ArrowUp) || i.key_pressed(Key::K)) { 179 | if current >= node_info.framerate { 180 | pv.state.cur_frame_no -= node_info.framerate; 181 | true 182 | } else if current < node_info.framerate { 183 | pv.state.cur_frame_no = 0; 184 | true 185 | } else { 186 | false 187 | } 188 | } else if ui.input(|i| i.key_pressed(Key::ArrowDown) || i.key_pressed(Key::J)) { 189 | pv.state.cur_frame_no += node_info.framerate; 190 | 191 | pv.state.cur_frame_no < node_info.num_frames - 1 192 | } else { 193 | false 194 | }; 195 | 196 | // Update frame once it's loaded 197 | output.last_frame_no = current; 198 | 199 | pv.state.cur_frame_no = pv.state.cur_frame_no.clamp(0, node_info.num_frames - 1); 200 | 201 | Ok(res) 202 | } 203 | 204 | pub fn check_update_output(pv: &mut VSPreviewer, ui: &mut egui::Ui) -> Result { 205 | // Must not have modifiers 206 | if !ui.input(|i| i.modifiers.is_none()) { 207 | return Ok(false); 208 | } 209 | 210 | let old_output = pv.state.cur_output; 211 | 212 | let new_output: i32 = if ui.input(|i| i.key_pressed(Key::Num1)) { 213 | 0 214 | } else if ui.input(|i| i.key_pressed(Key::Num2)) { 215 | 1 216 | } else if ui.input(|i| i.key_pressed(Key::Num3)) { 217 | 2 218 | } else if ui.input(|i| i.key_pressed(Key::Num4)) { 219 | 3 220 | } else if ui.input(|i| i.key_pressed(Key::Num5)) { 221 | 4 222 | } else if ui.input(|i| i.key_pressed(Key::Num6)) { 223 | 5 224 | } else if ui.input(|i| i.key_pressed(Key::Num7)) { 225 | 6 226 | } else if ui.input(|i| i.key_pressed(Key::Num8)) { 227 | 7 228 | } else if ui.input(|i| i.key_pressed(Key::Num9)) { 229 | 8 230 | } else if ui.input(|i| i.key_pressed(Key::Num0)) { 231 | 9 232 | } else { 233 | -1 234 | }; 235 | 236 | if new_output >= 0 && pv.outputs.contains_key(&new_output) { 237 | pv.state.cur_output = new_output; 238 | 239 | // Changed output 240 | pv.output_needs_rerender(old_output) 241 | } else { 242 | Ok(false) 243 | } 244 | } 245 | 246 | /// Size of the image to scroll/zoom, not the final texture 247 | pub fn handle_move_inputs( 248 | pv: &mut VSPreviewer, 249 | ui: &mut egui::Ui, 250 | size: &Vec2, 251 | zoom_delta: f32, 252 | scroll_delta: Vec2, 253 | ) -> Result<()> { 254 | // Update zoom delta to take into consideration small step keyboard input 255 | let mut delta = zoom_delta; 256 | let small_step = delta == 1.0 257 | && ui.input(|i| { 258 | i.modifiers.ctrl && (i.key_pressed(Key::ArrowDown) || i.key_pressed(Key::ArrowUp)) 259 | }); 260 | 261 | if small_step { 262 | if ui.input(|i| i.key_pressed(Key::ArrowDown)) { 263 | delta = 0.0; 264 | } else { 265 | delta = 2.0; 266 | } 267 | } 268 | 269 | let mut scroll_delta = scroll_delta; 270 | 271 | // Keyboard based scrolling 272 | if ui.input(|i| i.key_pressed(Key::End)) { 273 | scroll_delta.x = -50.0; 274 | } else if ui.input(|i| i.key_pressed(Key::Home)) { 275 | scroll_delta.x = 50.0; 276 | } else if ui.input(|i| i.key_pressed(Key::PageDown)) { 277 | scroll_delta.y = -50.0; 278 | } else if ui.input(|i| i.key_pressed(Key::PageUp)) { 279 | scroll_delta.y = 50.0; 280 | } 281 | 282 | let win_size = pv.available_size; 283 | 284 | // Calculate zoom factor 285 | let res_zoom = if delta != 1.0 { 286 | // Zoom 287 | let mut new_factor = pv.state.zoom_factor; 288 | let zoom_modifier = if small_step { 0.1 } else { 1.0 }; 289 | 290 | // Ignore 1.0 delta, means no zoom done 291 | if delta < 1.0 { 292 | // Smaller unzooming when below 1.0 293 | if new_factor <= 1.0 { 294 | new_factor -= 0.125; 295 | } else if !small_step && pv.state.zoom_multiplier > 1.0 { 296 | new_factor /= pv.state.zoom_multiplier; 297 | } else { 298 | new_factor -= zoom_modifier; 299 | } 300 | } else if delta > 1.0 { 301 | if new_factor < 1.0 { 302 | // Zoom back from a unzoomed state 303 | // Go back to no zoom 304 | new_factor += 0.125; 305 | } else if !small_step && pv.state.zoom_multiplier > 1.0 { 306 | new_factor *= pv.state.zoom_multiplier; 307 | } else { 308 | new_factor += zoom_modifier; 309 | } 310 | } 311 | 312 | let min = if pv.state.upscale_to_window { 313 | 1.0 314 | } else { 315 | MIN_ZOOM 316 | }; 317 | 318 | new_factor = new_factor.clamp(min, MAX_ZOOM); 319 | 320 | if new_factor != pv.state.zoom_factor { 321 | let trunc_factor = if new_factor < 1.0 { 1000.0 } else { 10.0 }; 322 | pv.state.zoom_factor = (new_factor * trunc_factor).round() / trunc_factor; 323 | 324 | true 325 | } else { 326 | false 327 | } 328 | } else { 329 | false 330 | }; 331 | 332 | let mut new_translate = pv.state.translate; 333 | 334 | // Calculate new translates 335 | let res_scroll = if scroll_delta.length() > 0.0 { 336 | let res_multiplier = *size / win_size; 337 | let final_delta = scroll_delta * res_multiplier * pv.state.scroll_multiplier; 338 | 339 | new_translate -= final_delta; 340 | 341 | true 342 | } else { 343 | false 344 | }; 345 | 346 | // NOTE: We are outside the scroll_delta condition 347 | // Because we want to modify the translations on zoom as well 348 | let reprocess_translate = pv.correct_translate_for_current_output(new_translate, false)?; 349 | 350 | let res = res_zoom || (res_scroll && reprocess_translate); 351 | 352 | // Set other outputs to reprocess if we're modifying the image 353 | if res { 354 | pv.reprocess_outputs(true, reprocess_translate); 355 | } 356 | 357 | pv.rerender |= res; 358 | 359 | Ok(()) 360 | } 361 | 362 | pub fn check_icc_toggle(pv: &mut VSPreviewer, ui: &mut egui::Ui) -> Result { 363 | // Must not have modifiers 364 | if !ui.input(|i| i.modifiers.is_none()) { 365 | return Ok(false); 366 | } 367 | 368 | let mut res = false; 369 | 370 | // Toggle is always a rerender 371 | if ui.input(|i| i.key_pressed(Key::C)) { 372 | pv.state.icc_enabled = !pv.state.icc_enabled; 373 | 374 | pv.reprocess_outputs(true, false); 375 | res = true; 376 | } 377 | 378 | Ok(res) 379 | } 380 | } 381 | -------------------------------------------------------------------------------- /src/app/vs_previewer.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::sync::Arc; 3 | 4 | use anyhow::{Result, anyhow, bail}; 5 | use eframe::egui::Key; 6 | use eframe::egui::{self, TextureOptions}; 7 | use fast_image_resize as fir; 8 | use image::DynamicImage; 9 | use parking_lot::{Mutex, RwLock}; 10 | use tokio::sync::mpsc::Sender; 11 | 12 | use crate::utils::image_to_colorimage; 13 | use crate::vs_handler::PreviewedScript; 14 | 15 | use super::*; 16 | 17 | pub struct VSPreviewer { 18 | pub script: Arc>, 19 | cmd_sender: Sender, 20 | 21 | pub state: PreviewState, 22 | pub errors: HashMap<&'static str, Vec>, 23 | pub about_window_open: bool, 24 | 25 | /// Promise returning the newly reloaded outputs 26 | pub reload_data: Option>, 27 | /// Outputs available from the script 28 | pub outputs: HashMap, 29 | /// Last output used 30 | pub last_output_key: i32, 31 | 32 | /// Canvas drawing available size 33 | pub available_size: Vec2, 34 | /// Map of the currently active inputs 35 | pub inputs_focused: HashMap<&'static str, bool>, 36 | 37 | /// Force rerender/reprocess 38 | pub rerender: bool, 39 | /// Override to only reprocess without requesting a new VS frame 40 | pub reprocess: bool, 41 | 42 | /// Promise returning a new requested frame 43 | pub frame_promise: Arc>>>, 44 | /// Promise returning the original props of the current frame 45 | pub original_props_promise: Arc>>>, 46 | 47 | /// Promise returning a bool, whether to rerender or not 48 | pub misc_promise: Arc>>>, 49 | 50 | pub transforms: Arc>, 51 | pub exit_promise: Option>, 52 | } 53 | 54 | impl VSPreviewer { 55 | pub fn new(script: Arc>, cmd_sender: Sender) -> Self { 56 | Self { 57 | script, 58 | cmd_sender, 59 | state: Default::default(), 60 | errors: Default::default(), 61 | about_window_open: Default::default(), 62 | reload_data: Default::default(), 63 | outputs: Default::default(), 64 | last_output_key: Default::default(), 65 | available_size: Default::default(), 66 | inputs_focused: Default::default(), 67 | rerender: Default::default(), 68 | reprocess: Default::default(), 69 | frame_promise: Default::default(), 70 | original_props_promise: Default::default(), 71 | misc_promise: Default::default(), 72 | transforms: Default::default(), 73 | exit_promise: Default::default(), 74 | } 75 | } 76 | 77 | pub fn process_image( 78 | orig: &DynamicImage, 79 | state: &PreviewState, 80 | win_size: &eframe::epaint::Vec2, 81 | ) -> Result { 82 | // Rounded up 83 | let win_size = win_size.round(); 84 | let src_size = Vec2::from([orig.width() as f32, orig.height() as f32]); 85 | 86 | let (src_w, src_h) = (src_size.x, src_size.y); 87 | 88 | let mut img = orig.clone(); 89 | 90 | let zoom_factor = state.zoom_factor; 91 | let (mut w, mut h) = (src_w, src_h); 92 | 93 | // Unzoom first and foremost 94 | if zoom_factor < 1.0 && !state.upscale_to_window { 95 | w *= zoom_factor; 96 | h *= zoom_factor; 97 | 98 | img = resize_fast( 99 | img, 100 | w.round() as u32, 101 | h.round() as u32, 102 | fir::FilterType::Box, 103 | )?; 104 | } 105 | 106 | if w > win_size.x || h > win_size.y || zoom_factor > 1.0 { 107 | // Factors for translations relative to the image resolution 108 | // -1 means no translation, 1 means translated to the bound 109 | let (tx_norm, ty_norm) = (state.translate_norm.x, state.translate_norm.y); 110 | 111 | let translate_pixel = crate::utils::translate_norm_to_pixels( 112 | &state.translate_norm, 113 | &src_size, 114 | &win_size, 115 | zoom_factor, 116 | ); 117 | 118 | // Scale [-1, 1] coords back to pixels 119 | let (tx, ty) = (translate_pixel.x, translate_pixel.y); 120 | 121 | // Positive = crop right part 122 | let x = if tx_norm.is_sign_negative() { 0.0 } else { tx }; 123 | let y = if ty_norm.is_sign_negative() { 0.0 } else { ty }; 124 | 125 | if (tx > 0.0 || ty > 0.0) && zoom_factor <= 1.0 { 126 | w -= tx; 127 | h -= ty; 128 | } 129 | 130 | // Limit to window size if not scaling down 131 | // Also when zooming in 132 | if state.zoom_factor > 1.0 || !state.fit_to_window { 133 | w = w.min(win_size.x); 134 | h = h.min(win_size.y); 135 | } 136 | 137 | img = img.crop_imm(x as u32, y as u32, w as u32, h as u32); 138 | } 139 | 140 | // Zoom after translate 141 | if zoom_factor > 1.0 { 142 | // Cropped size of the zoomed zone 143 | let cw = (w / zoom_factor).round(); 144 | let ch = (h / zoom_factor).round(); 145 | 146 | // Crop for performance, we only want the visible zoomed part 147 | img = img.crop_imm(0, 0, cw as u32, ch as u32); 148 | 149 | // Size for nearest resize, same as current image size 150 | // But since we cropped, it creates the zoom effect. 151 | let new_size = Vec2::new(w, h).round(); 152 | 153 | let target_size = if state.upscale_to_window { 154 | // Resize up to max size of window 155 | dimensions_for_window(&win_size, &new_size).round() 156 | } else { 157 | new_size 158 | }; 159 | 160 | img = resize_fast( 161 | img, 162 | target_size.x.round() as u32, 163 | target_size.y.round() as u32, 164 | fir::FilterType::Box, 165 | )?; 166 | } 167 | 168 | // Upscale small images 169 | if state.upscale_to_window && state.upsampling_filter != PreviewFilterType::Gpu { 170 | // Image size after crop 171 | let orig_size = Vec2::new(img.width() as f32, img.height() as f32); 172 | 173 | // Scaled size to window bounds 174 | let target_size = dimensions_for_window(&win_size, &orig_size).round(); 175 | 176 | if orig_size != target_size { 177 | let fr_filter = fir::FilterType::from(&state.upsampling_filter); 178 | img = resize_fast(img, target_size.x as u32, target_size.y as u32, fr_filter)?; 179 | } 180 | } 181 | 182 | Ok(img) 183 | } 184 | 185 | // Always reloads the script 186 | pub fn reload(&mut self, ctx: egui::Context) { 187 | if self.reload_data.is_some() { 188 | return; 189 | } 190 | 191 | if !self.errors.is_empty() { 192 | self.errors.clear(); 193 | } 194 | 195 | let (res_sender, promise) = Promise::new(); 196 | self.reload_data = Some(promise); 197 | self.cmd_sender 198 | .try_send(VSCommandMsg { 199 | res_sender, 200 | cmd: VSCommand::Reload, 201 | egui_ctx: ctx.clone(), 202 | }) 203 | .ok(); 204 | } 205 | 206 | pub fn check_reload_finish(&mut self) -> Result<()> { 207 | if let Some(promise) = &self.reload_data { 208 | if let Some(PreviewerResponse::Reload(promise_res)) = promise.ready() { 209 | self.outputs.clear(); 210 | 211 | if let Some(outputs) = promise_res { 212 | self.outputs = outputs 213 | .iter() 214 | .map(|(key, o)| { 215 | let new = PreviewOutput { 216 | vsoutput: o.clone(), 217 | ..Default::default() 218 | }; 219 | 220 | (*key, new) 221 | }) 222 | .collect(); 223 | 224 | if !self.outputs.contains_key(&self.state.cur_output) { 225 | // Fallback to first output in order 226 | let mut keys: Vec<&i32> = self.outputs.keys().collect(); 227 | keys.sort(); 228 | 229 | self.state.cur_output = **keys 230 | .first() 231 | .ok_or_else(|| anyhow!("No outputs available"))?; 232 | } 233 | 234 | let output = self 235 | .outputs 236 | .get_mut(&self.state.cur_output) 237 | .ok_or_else(|| anyhow!("outputs reload: Invalid current output key"))?; 238 | let node_info = &output.vsoutput.node_info; 239 | 240 | self.reload_data = None; 241 | self.last_output_key = self.state.cur_output; 242 | 243 | if self.state.cur_frame_no >= node_info.num_frames { 244 | self.state.cur_frame_no = node_info.num_frames - 1; 245 | } 246 | 247 | // Fetch a frame for new current output 248 | self.rerender = true; 249 | } 250 | 251 | // Done reloading, remove promise 252 | if let Some(mut mutex) = self.misc_promise.try_lock() { 253 | if (*mutex).is_some() { 254 | *mutex = None; 255 | }; 256 | } 257 | 258 | // Reset reload data even if errored 259 | self.reload_data = None; 260 | } 261 | } 262 | 263 | Ok(()) 264 | } 265 | 266 | pub fn try_rerender(&mut self, ctx: &egui::Context) -> Result<()> { 267 | if let Some(mut promise) = self.frame_promise.try_lock() { 268 | let misc_in_progress = if let Some(p) = self.misc_promise.try_lock() { 269 | p.is_some() 270 | } else { 271 | true 272 | }; 273 | 274 | // Still rendering, reloading or changing 275 | if promise.is_some() || misc_in_progress || self.reload_data.is_some() { 276 | return Ok(()); 277 | } 278 | 279 | if !self.outputs.is_empty() { 280 | let output = self 281 | .outputs 282 | .get_mut(&self.state.cur_output) 283 | .ok_or_else(|| anyhow!("rerender: Invalid current output key"))?; 284 | 285 | if output.force_reprocess { 286 | self.rerender = true; 287 | 288 | // Reprocess only if the output is already the correct frame 289 | self.reprocess = output.last_frame_no == self.state.cur_frame_no; 290 | 291 | output.force_reprocess = false; 292 | } 293 | 294 | if self.rerender && !self.reprocess { 295 | // Remove original frame props when a VS render is requested 296 | output.original_props = None; 297 | } 298 | } 299 | 300 | if self.rerender { 301 | self.rerender = false; 302 | 303 | let mut reprocess = self.reprocess; 304 | self.reprocess = false; 305 | 306 | // Still reloading, can't reprocess 307 | if self.reload_data.is_some() && reprocess { 308 | reprocess = false; 309 | } 310 | 311 | // Get current state at the moment the frame is requested 312 | let state = self.state; 313 | 314 | // Reset current changed flag 315 | self.state.translate_changed = false; 316 | 317 | let win_size = self.available_size; 318 | 319 | let pf = self.get_current_frame()?; 320 | 321 | let frame_mutex = self.frame_promise.clone(); 322 | 323 | let fetch_image_state = FetchImageState { 324 | frame_mutex, 325 | state, 326 | pf, 327 | reprocess, 328 | win_size, 329 | }; 330 | 331 | let (res_sender, new_promise) = Promise::new(); 332 | *promise = Some(new_promise); 333 | self.cmd_sender 334 | .try_send(VSCommandMsg { 335 | res_sender, 336 | cmd: VSCommand::Frame(fetch_image_state), 337 | egui_ctx: ctx.clone(), 338 | }) 339 | .ok(); 340 | } 341 | } 342 | 343 | Ok(()) 344 | } 345 | 346 | pub fn check_rerender_finish(&mut self, ctx: &egui::Context) -> Result<()> { 347 | if let Some(mut promise_mutex) = self.frame_promise.try_lock() { 348 | let mut updated_tex = false; 349 | 350 | if let Some(promise) = &*promise_mutex { 351 | if let Some(PreviewerResponse::Frame(Some(rendered_frame))) = promise.ready() { 352 | // Block as it's supposed to be ready 353 | let pf = rendered_frame.read(); 354 | 355 | if let Some(mut tex_mutex) = pf.texture.try_lock() { 356 | let output = 357 | self.outputs 358 | .get_mut(&self.state.cur_output) 359 | .ok_or_else(|| { 360 | anyhow!("current_output_mut: Invalid current output key") 361 | })?; 362 | 363 | // Set PreviewFrame from what the promise returned 364 | output.rendered_frame = Some(rendered_frame.clone()); 365 | 366 | // Processed if available, otherwise original 367 | let final_image = if let Some(image) = &pf.processed_image { 368 | image 369 | } else { 370 | &pf.vsframe.image 371 | }; 372 | 373 | let transforms = self.transforms.lock(); 374 | 375 | // Convert to ColorImage on texture change 376 | let colorimage = image_to_colorimage(final_image, &self.state, &transforms); 377 | 378 | let tex_filter = egui::TextureFilter::from(&self.state.texture_filter); 379 | let tex_opts = TextureOptions { 380 | magnification: tex_filter, 381 | minification: tex_filter, 382 | ..Default::default() 383 | }; 384 | // Update texture on render done 385 | if let Some(ref mut tex) = *tex_mutex { 386 | tex.set(colorimage, tex_opts); 387 | } else { 388 | *tex_mutex = Some(ctx.load_texture("frame", colorimage, tex_opts)); 389 | } 390 | 391 | // Update last output once the new frame is rendered 392 | self.last_output_key = output.vsoutput.index; 393 | 394 | updated_tex = true; 395 | }; 396 | } 397 | } 398 | 399 | if updated_tex { 400 | *promise_mutex = None; 401 | } 402 | } 403 | 404 | Ok(()) 405 | } 406 | 407 | pub fn get_current_frame(&self) -> Result> { 408 | if !self.outputs.is_empty() { 409 | let output = self 410 | .outputs 411 | .get(&self.state.cur_output) 412 | .ok_or_else(|| anyhow!("get_current_Frame: Invalid current output key"))?; 413 | Ok(output.rendered_frame.clone()) 414 | } else { 415 | Ok(None) 416 | } 417 | } 418 | 419 | pub fn get_preview_image( 420 | ctx: Context, 421 | script: Arc>, 422 | fetch_image_state: FetchImageState, 423 | ) -> Result> { 424 | let FetchImageState { 425 | frame_mutex, 426 | state, 427 | pf, 428 | reprocess, 429 | win_size, 430 | } = fetch_image_state; 431 | 432 | // This is fine because only one promise may be executing at a time 433 | let mut script_mutex = script.lock(); 434 | 435 | let have_existing_frame = pf.is_some(); 436 | 437 | let _lock = frame_mutex.lock(); 438 | 439 | // Reuse existing image, process and recreate texture 440 | let pf = if reprocess && have_existing_frame { 441 | // Verified above, cannot panic 442 | let pf = pf.unwrap(); 443 | 444 | // Force blocking as we need to reprocess the image 445 | let mut existing_frame = pf.write(); 446 | let image = &existing_frame.vsframe.image; 447 | let image_size = Vec2::from([image.width() as f32, image.height() as f32]); 448 | 449 | if Self::state_needs_processing(&state, &image_size, &win_size) { 450 | // Reprocess and update image for painting 451 | existing_frame.processed_image = 452 | Some(Self::process_image(image, &state, &win_size)?); 453 | } else { 454 | existing_frame.processed_image = None; 455 | } 456 | 457 | Some(pf.clone()) 458 | } else { 459 | // Request new frame, process and recreate image for painting 460 | let vsframe_res = script_mutex.get_frame( 461 | state.cur_output, 462 | state.cur_frame_no, 463 | &state.frame_transform_opts, 464 | ); 465 | script_mutex.add_vs_error(&vsframe_res); 466 | 467 | if let Ok(vsframe) = vsframe_res { 468 | let image_size = 469 | Vec2::from([vsframe.image.width() as f32, vsframe.image.height() as f32]); 470 | 471 | let processed_image = 472 | if Self::state_needs_processing(&state, &image_size, &win_size) { 473 | Some(Self::process_image(&vsframe.image, &state, &win_size)?) 474 | } else { 475 | None 476 | }; 477 | 478 | let new_pf = if let Some(existing_frame) = pf { 479 | let mut pf = existing_frame.write(); 480 | pf.vsframe = vsframe; 481 | pf.processed_image = processed_image; 482 | 483 | existing_frame.clone() 484 | } else { 485 | Arc::new(RwLock::new(PreviewFrame { 486 | vsframe, 487 | processed_image, 488 | texture: Mutex::new(None), 489 | })) 490 | }; 491 | 492 | Some(new_pf) 493 | } else { 494 | pf 495 | } 496 | }; 497 | 498 | // Once frame is ready 499 | ctx.request_repaint(); 500 | 501 | Ok(pf) 502 | } 503 | 504 | pub fn save_screenshot(&self) -> Result<()> { 505 | if let Some(script) = self.script.try_lock() { 506 | let mut save_path = script.get_script_dir(); 507 | 508 | let screen_file = format!( 509 | "vspreview-rs_out{}_{}.png", 510 | self.state.cur_output, self.state.cur_frame_no 511 | ); 512 | save_path.push(screen_file); 513 | 514 | let output = self 515 | .outputs 516 | .get(&self.state.cur_output) 517 | .ok_or_else(|| anyhow!("save_screenshot: Invalid current output key"))?; 518 | if let Some(pf) = &output.rendered_frame { 519 | let pf = pf.read(); 520 | 521 | // Shouldn't fail at this point 522 | pf.vsframe 523 | .image 524 | .save_with_format(&save_path, image::ImageFormat::Png)?; 525 | } else { 526 | bail!("There is no rendered frame for the current output"); 527 | } 528 | 529 | let path_str = save_path 530 | .to_str() 531 | .ok_or_else(|| anyhow!("Invalid UTF-8 save path"))?; 532 | 533 | script.send_debug_message(format!("Screenshot saved to {}", path_str))?; 534 | } else { 535 | bail!("The script is busy rendering a frame, try again later"); 536 | } 537 | 538 | Ok(()) 539 | } 540 | 541 | // Returns fixed pixel based and normalized translation vectors 542 | pub fn fix_translation_bounds(&self, image_size: &Vec2, new_translate: &Vec2) -> (Vec2, Vec2) { 543 | let win_size = self.available_size; 544 | 545 | // Updated zoom factor 546 | // We need the new zoom factor to be able to correct invalid translations 547 | // Reduce (unzoom) or increase max translate (zooming) 548 | let zoom_factor = self.state.zoom_factor; 549 | 550 | let mut fixed_translate = *new_translate; 551 | 552 | let coeffs = translate_norm_coeffs(image_size, &win_size, zoom_factor); 553 | 554 | // Clamp to valid translates 555 | // Min has to be negative to be able to detect when there's no translate 556 | fixed_translate.x = if coeffs.x.is_sign_positive() { 557 | new_translate.x.clamp(0.0, coeffs.x) 558 | } else { 559 | // Negative means the image isn't clipped by the window rect 560 | new_translate.x.clamp(0.0, 0.0) 561 | }; 562 | 563 | fixed_translate.y = if coeffs.y.is_sign_positive() { 564 | new_translate.y.clamp(0.0, coeffs.y) 565 | } else { 566 | // Negative means the image isn't clipped by the window rect 567 | new_translate.y.clamp(0.0, 0.0) 568 | }; 569 | 570 | // Normalize to [0, 1] 571 | let normalized_translate = Vec2::new( 572 | (fixed_translate.x / coeffs.x).clamp(0.0, 1.0), 573 | (fixed_translate.y / coeffs.y).clamp(0.0, 1.0), 574 | ); 575 | 576 | (fixed_translate, normalized_translate) 577 | } 578 | 579 | // Only called when the output changes 580 | // Update zoom/translate for the new output 581 | // Returns if we need to rerender 582 | pub fn output_needs_rerender(&mut self, old_output: i32) -> Result { 583 | let old = self 584 | .outputs 585 | .get(&old_output) 586 | .ok_or_else(|| anyhow!("output_needs_rerender: Invalid new output key"))?; 587 | let new = self 588 | .outputs 589 | .get(&self.state.cur_output) 590 | .ok_or_else(|| anyhow!("output_needs_rerender: Invalid current output key"))?; 591 | 592 | // Update translate values 593 | let new_node = &new.vsoutput.node_info; 594 | let new_size = Vec2::from([new_node.width as f32, new_node.height as f32]); 595 | 596 | // Scale normalized coords back to pixels 597 | self.state.translate_changed = true; 598 | self.state.translate = crate::utils::translate_norm_to_pixels( 599 | &self.state.translate_norm, 600 | &new_size, 601 | &self.available_size, 602 | self.state.zoom_factor, 603 | ); 604 | 605 | // Different frame or output not rendered yet 606 | Ok(old.last_frame_no != new.last_frame_no || new.rendered_frame.is_none()) 607 | } 608 | 609 | // Returns if the translate changed and we need to reprocess 610 | pub fn correct_translate_for_current_output( 611 | &mut self, 612 | new_translate: Vec2, 613 | normalized: bool, 614 | ) -> Result { 615 | if self.outputs.is_empty() { 616 | return Ok(false); 617 | } 618 | 619 | let info = { 620 | let output = self.outputs.get(&self.state.cur_output).ok_or_else(|| { 621 | anyhow!("correct_translate_for_current_output: Invalid current output key") 622 | })?; 623 | output.vsoutput.node_info.clone() 624 | }; 625 | 626 | let image_size = Vec2::from([info.width as f32, info.height as f32]); 627 | let old_translate = self.state.translate; 628 | 629 | let new_translate = if normalized { 630 | crate::utils::translate_norm_to_pixels( 631 | &new_translate, 632 | &image_size, 633 | &self.available_size, 634 | self.state.zoom_factor, 635 | ) 636 | } else { 637 | new_translate 638 | }; 639 | 640 | let (fix_pixel, fix_norm) = self.fix_translation_bounds(&image_size, &new_translate); 641 | 642 | let useless_translate = self.state.fit_to_window && self.state.zoom_factor <= 1.0; 643 | 644 | // Update if necessary 645 | if fix_pixel != old_translate { 646 | if !useless_translate { 647 | self.state.translate = fix_pixel; 648 | self.state.translate_norm = fix_norm; 649 | } else { 650 | self.state.translate = Vec2::ZERO; 651 | self.state.translate_norm = Vec2::ZERO; 652 | } 653 | 654 | self.reprocess_outputs(true, true); 655 | 656 | Ok(true) 657 | } else { 658 | Ok(false) 659 | } 660 | } 661 | 662 | pub fn any_input_focused(&self) -> bool { 663 | self.inputs_focused.values().any(|e| *e) 664 | } 665 | 666 | pub fn reprocess_outputs(&mut self, flag: bool, translate_changed: bool) { 667 | if translate_changed { 668 | self.state.translate_changed |= translate_changed; 669 | } 670 | 671 | self.outputs.values_mut().for_each(|o| { 672 | o.force_reprocess = flag; 673 | }); 674 | } 675 | 676 | // Can only be called when an output is selected 677 | pub fn fetch_original_props(&mut self, ctx: &egui::Context) { 678 | if let Some(mut promise_mutex) = self.original_props_promise.try_lock() { 679 | let fetch_props_state = FetchPropsState { 680 | frame_mutex: self.frame_promise.clone(), 681 | state: self.state, 682 | }; 683 | 684 | let (res_sender, new_promise) = Promise::new(); 685 | *promise_mutex = Some(new_promise); 686 | self.cmd_sender 687 | .try_send(VSCommandMsg { 688 | res_sender, 689 | cmd: VSCommand::FrameProps(fetch_props_state), 690 | egui_ctx: ctx.clone(), 691 | }) 692 | .ok(); 693 | } 694 | } 695 | 696 | pub fn check_original_props_finish(&mut self) -> Result<()> { 697 | if let Some(mut mutex) = self.original_props_promise.try_lock() { 698 | if let Some(PreviewerResponse::Props(props)) = mutex.as_ref().and_then(|p| p.ready()) { 699 | let output = self 700 | .outputs 701 | .get_mut(&self.state.cur_output) 702 | .ok_or_else(|| { 703 | anyhow!("check_original_props_finish: Invalid current output key") 704 | })?; 705 | output.original_props = *props; 706 | 707 | *mutex = None; 708 | }; 709 | } 710 | 711 | Ok(()) 712 | } 713 | 714 | pub fn check_misc_keyboard_inputs(&mut self, ctx: &egui::Context, ui: &mut egui::Ui) { 715 | // Don't allow quit when inputs are still focused 716 | if !self.any_input_focused() { 717 | if ui.input(|i| i.key_pressed(Key::Q) || i.key_pressed(Key::Escape)) { 718 | if self.exit_promise.is_none() { 719 | let (res_sender, new_promise) = Promise::new(); 720 | 721 | self.exit_promise = Some(new_promise); 722 | self.cmd_sender 723 | .try_send(VSCommandMsg { 724 | res_sender, 725 | cmd: VSCommand::Exit, 726 | egui_ctx: ctx.clone(), 727 | }) 728 | .ok(); 729 | } 730 | } else if ui.input(|i| i.key_pressed(Key::I)) { 731 | self.state.show_gui = !self.state.show_gui; 732 | 733 | // Clear if the GUI is hidden 734 | if !self.state.show_gui { 735 | self.inputs_focused.clear(); 736 | } 737 | } else if ui.input(|i| i.key_pressed(Key::R)) { 738 | self.reload(ctx.clone()) 739 | } else if ui.input(|i| i.modifiers.ctrl && i.modifiers.shift && i.key_pressed(Key::C)) { 740 | ctx.copy_text(self.state.cur_frame_no.to_string()); 741 | } 742 | } 743 | } 744 | 745 | pub fn state_needs_processing( 746 | state: &PreviewState, 747 | image_size: &Vec2, 748 | win_size: &Vec2, 749 | ) -> bool { 750 | if state.upscale_to_window 751 | && state.zoom_factor == 1.0 752 | && !state.translate_changed 753 | && state.translate_norm.length() <= 0.0 754 | { 755 | // Pure upscale 756 | // Scaled size to window bounds 757 | let target_size = dimensions_for_window(win_size, image_size).round(); 758 | 759 | // Needs to be scaled up 760 | // Only go into processing if not using egui to scale the texture 761 | image_size.length() < target_size.length() 762 | && state.upsampling_filter != PreviewFilterType::Gpu 763 | } else if state.fit_to_window { 764 | // Downscaling image 765 | 766 | // Allow upscaling if enabled 767 | state.upscale_to_window || state.zoom_factor != 1.0 768 | } else { 769 | // Any other processing needed 770 | state.zoom_factor != 1.0 771 | || state.translate_norm.length() > 0.0 772 | || state.translate_changed 773 | } 774 | } 775 | 776 | pub fn check_promise_callbacks(&mut self, ctx: &egui::Context) -> Result<()> { 777 | // Initial callback 778 | self.check_reload_finish()?; 779 | 780 | // Poll new requested frame, replace old if ready 781 | self.check_rerender_finish(ctx)?; 782 | 783 | // Check for original props if requested 784 | self.check_original_props_finish()?; 785 | 786 | self.check_misc_finish(ctx); 787 | 788 | // We want a new frame 789 | // Previously rendering frames must have completed to request a new one 790 | self.try_rerender(ctx)?; 791 | 792 | Ok(()) 793 | } 794 | 795 | pub fn add_error(&mut self, key: &'static str, res: &Result) { 796 | if let Err(e) = res { 797 | if let Some(list) = self.errors.get_mut(key) { 798 | list.push(format!("{:?}", e)); 799 | } else { 800 | self.errors.insert(key, vec![format!("{:?}", e)]); 801 | } 802 | } 803 | } 804 | 805 | pub fn add_errors(&mut self, key: &'static str, errors: &[String]) { 806 | if !errors.is_empty() { 807 | if let Some(list) = self.errors.get_mut(key) { 808 | list.extend(errors.iter().cloned()); 809 | } else { 810 | self.errors.insert(key, errors.to_owned()); 811 | } 812 | } 813 | } 814 | 815 | pub fn change_script_file(&mut self, ctx: &egui::Context) { 816 | if let Some(mut promise_mutex) = self.misc_promise.try_lock() { 817 | let (res_sender, new_promise) = Promise::new(); 818 | *promise_mutex = Some(new_promise); 819 | self.cmd_sender 820 | .try_send(VSCommandMsg { 821 | res_sender, 822 | cmd: VSCommand::ChangeScript, 823 | egui_ctx: ctx.clone(), 824 | }) 825 | .ok(); 826 | } 827 | } 828 | 829 | pub fn check_misc_finish(&mut self, ctx: &egui::Context) { 830 | let mut reload_type = None; 831 | 832 | if let Some(mutex) = self.misc_promise.try_lock() { 833 | if let Some(PreviewerResponse::Misc(rt)) = mutex.as_ref().and_then(|p| p.ready()) { 834 | reload_type = Some(*rt); 835 | }; 836 | } 837 | 838 | // Reload handles the promise reset, to avoid rendering other frames 839 | if let Some(reload_type) = reload_type { 840 | match reload_type { 841 | ReloadType::Reload => self.reload(ctx.clone()), 842 | ReloadType::Reprocess => { 843 | self.reprocess_outputs(true, false); 844 | *self.misc_promise.lock() = None; 845 | } 846 | ReloadType::None => *self.misc_promise.lock() = None, 847 | } 848 | } 849 | } 850 | 851 | pub fn init_transforms(&mut self) { 852 | let mut transforms = self.transforms.lock(); 853 | 854 | if let Some(icc) = transforms.icc.as_mut() { 855 | icc.setup(); 856 | } 857 | } 858 | 859 | pub fn change_icc_profile(&mut self, ctx: &egui::Context) { 860 | if let Some(mut promise_mutex) = self.misc_promise.try_lock() { 861 | let (res_sender, new_promise) = Promise::new(); 862 | *promise_mutex = Some(new_promise); 863 | self.cmd_sender 864 | .try_send(VSCommandMsg { 865 | res_sender, 866 | cmd: VSCommand::ChangeIcc(self.transforms.clone()), 867 | egui_ctx: ctx.clone(), 868 | }) 869 | .ok(); 870 | } 871 | } 872 | } 873 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------