1mod audio_mode;
29mod audio_view;
30mod decoration;
31mod image_mode;
32mod live_mode;
33mod overlay;
34mod timeline;
35mod training_source;
36mod video_mode;
37mod workspace;
38
39#[cfg(test)]
40#[path = "../../../test/rs/render/viewer_canvas_unit.rs"]
41mod canvas_tests;
42
43pub use config::{ViewerAudioView, ViewerCanvasBackground, ViewerMode};
44pub use live_source::ViewerLiveSource;
45pub use training_source::{TrainingPreviewFrame, TrainingViewerSource};
46pub use types::{TrainingViewerConfig, ViewerConfig, ViewerLiveCapabilities};
47pub use workspace::{SharedItem, Workspace, WorkspaceItem, WorkspaceNode};
48
49mod config;
50mod live_source;
51#[path = "viewer/type.gen.rs"]
52mod types;
53
54use std::time::Instant;
55
56use crate::input::{
57 InputEventKind, Key, Navigation,
58 sdl_events::{convert_sdl_event, window_pixel_scale},
59};
60use crate::runtime::{Presenter, SdlWindow};
61use crate::ui::{Ui, types::PixelRect};
62use crate::{Engine, Error, Result, Texture, render::Renderer};
63
64pub struct Viewer<'src> {
68 config: ViewerConfig,
69 live_source: Option<&'src mut dyn ViewerLiveSource>,
70}
71
72impl<'src> Viewer<'src> {
73 pub fn new(config: ViewerConfig) -> Self {
74 Self {
75 config,
76 live_source: None,
77 }
78 }
79
80 pub fn new_with_path(path: impl Into<String>) -> Self {
81 Self::new(ViewerConfig {
82 path: path.into(),
83 ..ViewerConfig::default()
84 })
85 }
86
87 pub fn set_live_source(&mut self, source: &'src mut dyn ViewerLiveSource) {
88 self.live_source = Some(source);
89 self.config.mode = ViewerMode::Live;
90 }
91
92 pub fn set_workspace(&mut self, workspace: &'src mut Workspace) {
95 self.live_source = Some(workspace);
96 self.config.mode = ViewerMode::Workspace;
97 }
98
99 pub fn preview(path: &str) -> Result<()> {
103 Self::preview_with_config(path, ViewerConfig::default())
104 }
105
106 pub fn preview_with_config(path: &str, config: ViewerConfig) -> Result<()> {
107 if path.is_empty() {
108 return Err(Error::invalid_argument(
109 "Viewer::preview requires a non-empty path",
110 ));
111 }
112 let full_config = ViewerConfig {
113 path: path.to_owned(),
114 ..config
115 };
116 Viewer::new(full_config).run_owned()
117 }
118
119 pub fn preview_with_engine(engine: &Engine, path: &str) -> Result<()> {
121 Self::preview_with_engine_and_config(engine, path, ViewerConfig::default())
122 }
123
124 pub fn preview_with_engine_and_config(
125 engine: &Engine,
126 path: &str,
127 config: ViewerConfig,
128 ) -> Result<()> {
129 if path.is_empty() {
130 return Err(Error::invalid_argument(
131 "Viewer::preview requires a non-empty path",
132 ));
133 }
134 let full_config = ViewerConfig {
135 path: path.to_owned(),
136 ..config
137 };
138 Viewer::new(full_config).run_borrowed(engine)
139 }
140
141 pub fn show(engine: &Engine, texture: &Texture) -> Result<()> {
143 Self::show_with_config(engine, texture, ViewerConfig::default())
144 }
145
146 pub fn show_with_config(engine: &Engine, texture: &Texture, config: ViewerConfig) -> Result<()> {
147 if !texture.engine_handle().same_as(&engine.handle()) {
148 return Err(Error::invalid_argument(
149 "Viewer::show: Texture does not belong to this Engine",
150 ));
151 }
152 let app_config = ViewerConfig {
153 mode: ViewerMode::Image,
154 path: String::new(),
155 ..config
156 };
157 Viewer::new(app_config).run_with_texture(engine, texture)
158 }
159
160 pub fn show_render_frame(
169 engine: &Engine,
170 renderer: &Renderer<'_>,
171 frame: crate::render::RenderFrame,
172 config: ViewerConfig,
173 ) -> Result<()> {
174 if !renderer.owns_frame(&frame) {
175 return Err(Error::invalid_argument(
176 "Viewer::show_render_frame requires a frame produced by the supplied Renderer and Engine",
177 ));
178 }
179 frame.producer().wait()?;
181 let texture = frame.color().clone();
182 let app_config = ViewerConfig {
183 mode: ViewerMode::Image,
184 path: String::new(),
185 ..config
186 };
187 let result = Viewer::new(app_config).run_with_texture(engine, &texture);
190 drop(texture);
191 drop(frame);
192 let collect_result = renderer.collect().map(|_| ());
193 match (result, collect_result) {
194 (Err(error), _) | (Ok(()), Err(error)) => Err(error),
195 (Ok(()), Ok(())) => Ok(()),
196 }
197 }
198
199 pub fn run(self, engine: &Engine) -> Result<()> {
201 self.run_borrowed(engine)
202 }
203
204 pub fn run_standalone(self) -> Result<()> {
212 self.run_owned()
213 }
214
215 fn run_owned(mut self) -> Result<()> {
216 let window = SdlWindow::with_client_frame(
219 &self.config.title,
220 self.config.width,
221 self.config.height,
222 true,
223 )?;
224 let extensions = window.required_instance_extensions()?;
225 let engine = Engine::builder()
226 .requirements(crate::EngineRequirements::default().presentation())
227 .instance_extensions(extensions)
228 .build()?;
229 self.application_loop(&engine, window, None)
230 }
231
232 fn run_borrowed(mut self, engine: &Engine) -> Result<()> {
234 let window = SdlWindow::with_client_frame(
235 &self.config.title,
236 self.config.width,
237 self.config.height,
238 true,
239 )?;
240 self.application_loop(engine, window, None)
241 }
242
243 fn run_with_texture(mut self, engine: &Engine, texture: &Texture) -> Result<()> {
245 let window = SdlWindow::with_client_frame(
246 &self.config.title,
247 self.config.width,
248 self.config.height,
249 texture.render_target_image().is_none(),
250 )?;
251 self.application_loop(engine, window, Some(texture))
252 }
253
254 fn application_loop(
256 &mut self,
257 engine: &Engine,
258 window: SdlWindow,
259 borrowed_texture: Option<&Texture>,
260 ) -> Result<()> {
261 if self.config.show_help {
262 engine.log(crate::LogLevel::Info, crate::LogComponent::UI, "Viewer: wheel/drag pan, Ctrl+wheel or right-drag zoom, +/- zoom, 0 fit, 9 actual size, 1–5 channels, B background, G grid, Ctrl+O open file, F11 fullscreen, Space play/pause, arrows seek, W/S/M audio views, Q/Esc close")?;
263 }
264 let [w, h] = window.drawable_extent();
266 if w == 0 || h == 0 {
267 return Err(Error::invalid_argument(
268 "Viewer window has zero drawable extent",
269 ));
270 }
271
272 let mut presenter = Presenter::new(engine, &window)?;
274 if !presenter.supports_swapchain() {
275 return Err(Error::missing_capability(
276 "Viewer requires a swapchain-capable device (VK_KHR_swapchain)",
277 ));
278 }
279 if !presenter.has_present() {
280 return Err(Error::missing_capability(
281 "Viewer requires a queue family that can present to the window surface",
282 ));
283 }
284 presenter.init_swapchain(&window)?;
285
286 let style = self.config.style.clone();
288 let mut ui = Ui::init_with_style(engine, w, h, style)?;
289
290 let mut media = MediaState::open(engine, &self.config, borrowed_texture)?;
292
293 let mut nav = Navigation::new();
295 if let Some((cw, ch)) = media.content_size() {
296 nav.set_content_size(cw as f32, ch as f32)?;
297 }
298 nav.set_viewport_size(w as f32, h as f32)?;
299 nav.fit_to_window()?;
300
301 let mut source_opened = false;
302 let mut run_result = (|| -> Result<()> {
303 if let Some(source) = self.live_source.as_deref_mut() {
304 source.open(engine)?;
305 source_opened = true;
306 }
307
308 let mut event_pump = window
310 .event_pump()
311 .map_err(|e| Error::backend_failure("SDL3", "Viewer event pump", e))?;
312
313 let mut running = true;
314 let mut timeline_state = timeline::TransportState::default();
315 let (mut open_files, open_rx) = OpenFileRequest::new();
316 let mut gamepads: Vec<sdl3::gamepad::Gamepad> = window
318 .connected_gamepads()
319 .into_iter()
320 .filter_map(|id| window.open_gamepad(id).ok())
321 .collect();
322 let mut pointer_inside = true;
323 let mut ime_active = false;
324 let mut controls_idle_ms = 0.0_f32;
325 let mut last_instant = Instant::now();
326 let (mut sx, mut sy) = window_pixel_scale(&window.window);
327
328 while running {
329 let now = Instant::now();
330 let delta_ms = now.duration_since(last_instant).as_secs_f32() * 1000.0;
331 last_instant = now;
332 controls_idle_ms += delta_ms;
333
334 for sdl_ev in event_pump.poll_iter() {
336 match &sdl_ev {
337 sdl3::event::Event::Quit { .. } => {
338 running = false;
339 }
340 sdl3::event::Event::Window {
341 win_event: sdl3::event::WindowEvent::PixelSizeChanged(pw, ph),
342 ..
343 } => {
344 let pw = *pw as u32;
345 let ph = *ph as u32;
346 if pw > 0 && ph > 0 {
347 presenter.notify_pixel_size_changed(pw, ph);
348 ui.resize(pw, ph)?;
349 nav.set_viewport_size(pw as f32, ph as f32)?;
350 (sx, sy) = window_pixel_scale(&window.window);
351 }
352 }
353 sdl3::event::Event::Window {
354 win_event: sdl3::event::WindowEvent::MouseEnter,
355 ..
356 } => {
357 pointer_inside = true;
358 controls_idle_ms = 0.0;
359 }
360 sdl3::event::Event::Window {
361 win_event: sdl3::event::WindowEvent::MouseLeave,
362 ..
363 } => {
364 pointer_inside = false;
365 }
366 sdl3::event::Event::GamepadAdded { which, .. } => {
367 if let Ok(pad) = window.open_gamepad(which.raw()) {
368 gamepads.push(pad);
369 }
370 }
371 sdl3::event::Event::GamepadRemoved { which, .. } => {
372 gamepads.retain(|pad| pad.id().is_ok_and(|id| id != *which));
373 }
374 _ => {}
375 }
376 if let Some(ui_ev) = convert_sdl_event(&sdl_ev, sx, sy) {
377 controls_idle_ms = 0.0;
378 if ui_ev.kind == InputEventKind::KeyDown
380 && (ui_ev.key == self.config.key_quit || ui_ev.key == self.config.key_quit_q)
381 {
382 running = false;
383 continue;
384 }
385
386 if ui_ev.kind == InputEventKind::KeyDown && !ui_ev.key_repeat {
388 if ui_ev.key == Key::F11 {
389 window.toggle_fullscreen()?;
390 continue;
391 }
392 if ui_ev.key == Key::O && ui_ev.ctrl() && self.live_source.is_none() {
393 open_files.request(&window)?;
394 continue;
395 }
396 }
397
398 if ui_ev.kind == InputEventKind::KeyDown
400 && media.has_timeline()
401 && matches!(ui_ev.key, Key::Left | Key::Right | Key::Up | Key::Down)
402 {
403 let steps = match ui_ev.key {
404 Key::Left => -1,
405 Key::Right => 1,
406 Key::Up => 5,
407 _ => -5,
408 };
409 media.step_temporal(steps)?;
410 continue;
411 }
412
413 if ui_ev.kind == InputEventKind::KeyDown && !ui_ev.key_repeat {
414 if matches!(media, MediaState::Audio { .. }) {
415 match ui_ev.key {
416 Key::W => self.config.audio_view = ViewerAudioView::Waveform,
417 Key::S => self.config.audio_view = ViewerAudioView::Spectrum,
418 Key::M => self.config.audio_view = ViewerAudioView::Mel,
419 _ => {}
420 }
421 }
422
423 if ui_ev.key == Key::L && media.has_timeline() {
424 self.config.loop_media = !self.config.loop_media;
425 match &mut media {
426 MediaState::Audio { player, .. } => {
427 if let Some(player) = player.as_ref() {
428 player.set_loop(self.config.loop_media);
429 }
430 }
431 MediaState::Video { player } => {
432 if let Some(player) = player.as_mut() {
433 player.set_looping(self.config.loop_media);
434 }
435 }
436 _ => {}
437 }
438 continue;
439 }
440 if ui_ev.key == self.config.key_canvas_background {
441 self.config.canvas_background = match self.config.canvas_background {
442 ViewerCanvasBackground::Dark => ViewerCanvasBackground::Gradient,
443 ViewerCanvasBackground::Gradient => ViewerCanvasBackground::Dark,
444 };
445 continue;
446 }
447 if ui_ev.key == self.config.key_canvas_grid {
448 self.config.show_canvas_grid = !self.config.show_canvas_grid;
449 continue;
450 }
451 }
452
453 if let Some(source) = self.live_source.as_deref_mut()
455 && source.capabilities().receives_events
456 {
457 source.on_event(&ui_ev)?;
458 }
459
460 let pointer_event = matches!(
463 ui_ev.kind,
464 InputEventKind::MouseDown | InputEventKind::MouseScroll
465 );
466 let chrome_pointer = pointer_event
467 && (ui_ev.mouse_y < 43.0 * sy
468 || (self.config.show_timeline && media.has_timeline() && {
469 let [cw, ch] = ui.compose_extent().unwrap_or([w, h]);
470 let scale = (sx + sy) * 0.5;
471 timeline::owns_pointer(PixelRect::new(0, 0, cw, ch), scale, ui_ev.mouse_y)
472 }) || ui.is_popup_open("viewer-window-menu"));
473 let source_controls = pointer_event
474 && self.live_source.as_deref().is_some_and(|source| {
475 let [cw, ch] = ui.compose_extent().unwrap_or([w, h]);
476 source
477 .canvas_controls_rect(cw, ch, (sx + sy) * 0.5)
478 .is_some_and(|rect| rect.contains(ui_ev.mouse_x, ui_ev.mouse_y))
479 });
480 let nav_consumed = !chrome_pointer && !source_controls && nav.handle_event(&ui_ev);
481
482 if !nav_consumed {
484 media.handle_event(&ui_ev, &self.config)?;
485 }
486
487 ui.route_event(&ui_ev);
489 }
490 }
491
492 while let Ok(result) = open_rx.try_recv() {
494 open_files.active = false;
495 match result {
496 Ok(paths) => {
497 if let Some(path) = paths.into_iter().next() {
498 self.open_media_path(engine, &mut media, &mut nav, &mut timeline_state, &path)?;
499 }
500 }
501 Err(sdl3::dialog::DialogError::Canceled) => {}
502 Err(error) => {
503 engine.log(
504 crate::LogLevel::Warn,
505 crate::LogComponent::UI,
506 format!("Viewer: open file dialog failed: {error}"),
507 )?;
508 }
509 }
510 }
511
512 if presenter.needs_swapchain_recreate() {
514 presenter.wait_presentation_idle()?;
515 presenter.recreate_swapchain(&window)?;
516 }
517
518 nav.set_motion_speed(self.config.motion_speed);
520 nav.update(delta_ms);
521 media.update()?;
522 if let Some(source) = self.live_source.as_deref_mut() {
523 source.update(delta_ms)?;
524 media.update_live_texture(source.canvas_texture(), &mut nav)?;
525 }
526
527 let [compose_w, compose_h] = ui.compose_extent().unwrap_or([w, h]);
529 ui.set_content_scale((sx + sy) * 0.5)?;
530 ui.set_motion_speed(self.config.motion_speed)?;
531 ui.begin_frame(delta_ms);
532 let chrome_visible = !media.has_timeline()
533 || !self.config.auto_hide_controls
534 || !media.is_playing()
535 || (pointer_inside && controls_idle_ms < self.config.controls_hide_delay_ms as f32)
536 || ui.is_popup_open("viewer-window-menu");
537 render_frame(
538 &mut ui,
539 &mut media,
540 &mut nav,
541 &self.config,
542 compose_w,
543 compose_h,
544 (sx + sy) * 0.5,
545 chrome_visible,
546 &mut timeline_state,
547 )?;
548 if matches!(media, MediaState::Live { .. } | MediaState::Workspace)
549 && let Some(source) = self.live_source.as_deref_mut()
550 {
551 source.render(&mut ui, compose_w, compose_h)?;
552 }
553 if chrome_visible {
554 running &= decoration::render(
555 &mut ui,
556 &window,
557 &mut media,
558 &mut nav,
559 &mut self.config,
560 [compose_w, compose_h],
561 [sx, sy],
562 &mut open_files,
563 )?;
564 }
565 if window.client_frame
566 && presenter.has_transparent_composition()
567 && !window.window.is_maximized()
568 && window.window.fullscreen_state() == sdl3::video::FullscreenType::Off
569 {
570 ui.rect_outline_rounded_at(
574 PixelRect::new(0, 0, compose_w, compose_h),
575 crate::Color {
576 a: 1.0,
577 ..self.config.style.surface
578 },
579 (1.0 * (sx + sy) * 0.5).round().max(1.0) as u32,
580 PixelRect::new(0, 0, compose_w, compose_h),
581 crate::runtime::window_decoration::CORNER_RADIUS * (sx + sy) * 0.5,
582 );
583 ui.mask_rounded_rect(
584 PixelRect::new(0, 0, compose_w, compose_h),
585 crate::runtime::window_decoration::CORNER_RADIUS * (sx + sy) * 0.5,
586 crate::Color::new(0.0, 0.0, 0.0, 0.0),
587 )?;
588 }
589 ui.end_frame();
590
591 match ui.text_input_rect() {
594 Some(rect) => {
595 if !ime_active {
596 window.set_text_input_active(true);
597 ime_active = true;
598 }
599 window.set_text_input_area(rect.x, rect.y, rect.w, rect.h, 0);
600 }
601 None if ime_active => {
602 window.set_text_input_active(false);
603 ime_active = false;
604 }
605 None => {}
606 }
607
608 if presenter.has_swapchain() {
611 let suboptimal = if let Some(texture) = borrowed_texture
612 && texture.render_target_image().is_some()
613 {
614 presenter.present_texture(texture)?
615 } else {
616 ui.present_to(&mut presenter)?
617 };
618 if suboptimal {
619 let [dw, dh] = window.drawable_extent();
620 presenter.notify_pixel_size_changed(dw, dh);
621 }
622 }
623 }
624 Ok(())
625 })();
626
627 preserve_first(&mut run_result, presenter.wait_presentation_idle());
630 if source_opened && let Some(source) = self.live_source.as_deref_mut() {
631 preserve_first(&mut run_result, source.close());
632 }
633 preserve_first(&mut run_result, media.close());
634 preserve_first(&mut run_result, ui.close());
635 run_result
636 }
637
638 fn open_media_path(
642 &mut self,
643 engine: &Engine,
644 media: &mut MediaState,
645 nav: &mut Navigation,
646 timeline_state: &mut timeline::TransportState,
647 path: &std::path::Path,
648 ) -> Result<()> {
649 let config = ViewerConfig {
650 path: path.to_string_lossy().into_owned(),
651 ..self.config.clone()
652 };
653 let new_media = match MediaState::open(engine, &config, None) {
654 Ok(media) => media,
655 Err(error) => {
656 engine.log(
657 crate::LogLevel::Warn,
658 crate::LogComponent::UI,
659 format!("Viewer: could not open {}: {error}", path.display()),
660 )?;
661 return Ok(());
662 }
663 };
664 let mut previous = std::mem::replace(media, new_media);
665 previous.close()?;
666 self.config = config;
667 let (cw, ch) = media.content_size().unwrap_or((0, 0));
668 nav.set_content_size(cw as f32, ch as f32)?;
669 nav.fit_to_window()?;
670 *timeline_state = timeline::TransportState::default();
671 Ok(())
672 }
673}
674
675fn preserve_first(result: &mut Result<()>, next: Result<()>) {
676 if result.is_ok() {
677 *result = next;
678 }
679}
680
681type OpenFileResult = std::result::Result<Vec<std::path::PathBuf>, sdl3::dialog::DialogError>;
684
685pub(super) struct OpenFileRequest {
688 tx: std::sync::mpsc::Sender<OpenFileResult>,
689 active: bool,
690}
691
692impl OpenFileRequest {
693 fn new() -> (Self, std::sync::mpsc::Receiver<OpenFileResult>) {
694 let (tx, rx) = std::sync::mpsc::channel();
695 (Self { tx, active: false }, rx)
696 }
697
698 pub(super) fn request(&mut self, window: &SdlWindow) -> Result<()> {
700 if self.active {
701 return Ok(());
702 }
703 const FILTERS: &[sdl3::dialog::DialogFileFilter<'_>] = &[
704 sdl3::dialog::DialogFileFilter {
705 name: "Media",
706 pattern: "png;jpg;jpeg;bmp;tga;gif;webp;mp4;mkv;webm;avi;mov;mpg;mpeg;mp3;wav;flac;ogg;opus;m4a",
707 },
708 sdl3::dialog::DialogFileFilter {
709 name: "All files",
710 pattern: "*",
711 },
712 ];
713 let tx = self.tx.clone();
714 sdl3::dialog::show_open_file_dialog(
715 FILTERS,
716 None::<&std::path::Path>,
717 false,
718 &window.window,
719 Box::new(move |result, _filter| {
720 let _ = tx.send(result);
721 }),
722 )
723 .map_err(|e| {
724 Error::backend_failure(
725 "SDL3",
726 "open file dialog",
727 std::io::Error::other(e.to_string()),
728 )
729 })?;
730 self.active = true;
731 Ok(())
732 }
733}
734
735#[allow(clippy::too_many_arguments)]
738fn render_frame(
739 ui: &mut Ui<'_>,
740 media: &mut MediaState,
741 nav: &mut Navigation,
742 config: &ViewerConfig,
743 w: u32,
744 h: u32,
745 content_scale: f32,
746 chrome_visible: bool,
747 timeline_state: &mut timeline::TransportState,
748) -> Result<()> {
749 let full_rect = PixelRect::new(0, 0, w, h);
750
751 if media.has_visual_content() || matches!(media, MediaState::Audio { .. }) {
753 let (cw, ch) = media.content_size().unwrap_or((w, h));
754 let destination = PixelRect::new(
755 nav.pan_x() as i32,
756 nav.pan_y() as i32,
757 (cw as f32 * nav.zoom()).max(1.0) as u32,
758 (ch as f32 * nav.zoom()).max(1.0) as u32,
759 );
760 overlay::draw_canvas_background(
761 ui,
762 full_rect,
763 destination,
764 nav,
765 content_scale,
766 media.has_visual_content(),
767 config,
768 )?;
769 }
770
771 match media {
773 MediaState::Image {
774 texture,
775 channel_mode,
776 } => {
777 let tex_ref: Option<&Texture> = texture.as_ref().as_ref();
778 image_mode::render(ui, tex_ref, nav, channel_mode, full_rect, config)?;
779 }
780 MediaState::Video { player } => {
781 video_mode::render(ui, player.as_mut().as_mut(), nav)?;
782 }
783 MediaState::Audio { player, analysis } => {
784 let p: Option<&mut crate::AudioPlayer> = player.as_mut().as_mut();
785 let a: Option<&audio_view::AudioAnalysis> = analysis.as_ref();
786 audio_mode::render(ui, p, a, full_rect, config)?;
787 }
788 MediaState::Live {
789 texture,
790 channel_mode,
791 } => {
792 image_mode::render(
793 ui,
794 texture.as_ref().as_ref(),
795 nav,
796 channel_mode,
797 full_rect,
798 config,
799 )?;
800 }
801 MediaState::Workspace => {}
802 MediaState::Empty => {}
803 }
804
805 let mut hud_inset = 0.0;
807 if chrome_visible && config.show_timeline && media.has_timeline() {
808 timeline::render(ui, media, config, full_rect, timeline_state)?;
809 let bar = timeline::geometry(full_rect, ui.content_scale());
811 let title_top = bar.y - (34.0 * ui.content_scale()).round().max(1.0) as i32;
812 hud_inset = (full_rect.h as i32 - title_top).max(0) as f32;
813 }
814 overlay::draw_hud(ui, full_rect, nav, media.mode_name(), hud_inset, config)?;
815
816 Ok(())
817}
818
819#[allow(dead_code)]
822pub(crate) enum MediaState {
823 Image {
824 texture: Box<Option<Texture>>,
825 channel_mode: image_mode::ChannelMode,
826 },
827 Video {
828 player: Box<Option<crate::MediaPlayer>>,
829 },
830 Audio {
831 player: Box<Option<crate::AudioPlayer>>,
832 analysis: Option<audio_view::AudioAnalysis>,
833 },
834 Live {
835 texture: Box<Option<Texture>>,
836 channel_mode: image_mode::ChannelMode,
837 },
838 Workspace,
839 Empty,
840}
841
842impl MediaState {
843 fn open(engine: &Engine, config: &ViewerConfig, borrowed: Option<&Texture>) -> Result<Self> {
844 match config.mode {
845 ViewerMode::Image => {
846 let texture = if let Some(t) = borrowed {
847 Some(t.clone())
848 } else if !config.path.is_empty() {
849 Some(image_mode::load_texture(engine, &config.path)?)
850 } else {
851 None
852 };
853 Ok(Self::Image {
854 texture: Box::new(texture),
855 channel_mode: image_mode::ChannelMode::Rgb,
856 })
857 }
858 ViewerMode::Video => {
859 let player = if !config.path.is_empty() {
860 Some(video_mode::open(engine, config)?)
861 } else {
862 None
863 };
864 Ok(Self::Video {
865 player: Box::new(player),
866 })
867 }
868 ViewerMode::Audio => {
869 let (player, analysis) = if !config.path.is_empty() {
870 let a = audio_view::analyze(engine, &config.path, config)?;
871 let p = audio_mode::open(engine, config)?;
872 (Some(p), a)
873 } else {
874 (None, None)
875 };
876 Ok(Self::Audio {
877 player: Box::new(player),
878 analysis,
879 })
880 }
881 ViewerMode::Live => Ok(Self::Live {
882 texture: Box::new(None),
883 channel_mode: image_mode::ChannelMode::Rgb,
884 }),
885 ViewerMode::Workspace => Ok(Self::Workspace),
886 ViewerMode::Auto => {
887 if let Ok(texture) = image_mode::load_texture(engine, &config.path) {
889 return Ok(Self::Image {
890 texture: Box::new(Some(texture)),
891 channel_mode: image_mode::ChannelMode::Rgb,
892 });
893 }
894 let video_error = match video_mode::open(engine, config) {
895 Ok(player) => {
896 return Ok(Self::Video {
897 player: Box::new(Some(player)),
898 });
899 }
900 Err(error) => error,
901 };
902 let audio_error = match audio_mode::open(engine, config) {
903 Ok(mut player) => {
904 let analysis = match audio_view::analyze(engine, &config.path, config) {
905 Ok(analysis) => analysis,
906 Err(error) => {
907 let _ = player.close();
908 return Err(error);
909 }
910 };
911 return Ok(Self::Audio {
912 player: Box::new(Some(player)),
913 analysis,
914 });
915 }
916 Err(error) => error,
917 };
918 Err(Error::with_kind(
919 video_error.kind(),
920 format!("Viewer could not open media (video: {video_error}, audio: {audio_error})"),
921 ))
922 }
923 }
924 }
925
926 fn has_visual_content(&self) -> bool {
927 matches!(
928 self,
929 Self::Image { .. } | Self::Video { .. } | Self::Live { .. } | Self::Workspace
930 )
931 }
932
933 fn mode_name(&self) -> &'static str {
934 match self {
935 Self::Image { .. } => "Image",
936 Self::Video { .. } => "Video",
937 Self::Audio { .. } => "Audio",
938 Self::Live { .. } => "Live",
939 Self::Workspace => "Workspace",
940 Self::Empty => "Empty",
941 }
942 }
943
944 fn has_timeline(&self) -> bool {
945 matches!(self, Self::Video { .. } | Self::Audio { .. })
946 }
947
948 fn content_size(&self) -> Option<(u32, u32)> {
949 match self {
950 Self::Image { texture, .. } | Self::Live { texture, .. } => texture
951 .as_ref()
952 .as_ref()
953 .map(|t| (t.width() as u32, t.height() as u32)),
954 Self::Video { player } => player
955 .as_ref()
956 .as_ref()
957 .and_then(|p| p.info().map(|info| (info.width(), info.height()))),
958 _ => None,
959 }
960 }
961
962 fn update(&mut self) -> Result<()> {
963 match self {
964 Self::Video { player } => {
965 if let Some(player) = player.as_mut() {
966 player.tick(4)?;
968 }
969 }
970 Self::Audio { player, .. } => {
971 if let Some(player) = player.as_ref() {
972 player.check_playback()?;
973 }
974 }
975 _ => {}
976 }
977 Ok(())
978 }
979
980 fn update_live_texture(&mut self, source: Option<&Texture>, nav: &mut Navigation) -> Result<()> {
981 let previous = self.content_size();
982 if let Self::Live { texture, .. } = self {
983 **texture = source.cloned();
984 if let Some((width, height)) = self.content_size()
985 && previous != Some((width, height))
986 {
987 nav.set_content_size(width as f32, height as f32)?;
988 nav.fit_to_window()?;
989 }
990 }
991 Ok(())
992 }
993
994 fn handle_event(
995 &mut self,
996 ev: &crate::input::types::InputEvent,
997 config: &ViewerConfig,
998 ) -> Result<()> {
999 if ev.kind != InputEventKind::KeyDown || ev.key_repeat {
1000 return Ok(());
1001 }
1002 match self {
1003 Self::Image { channel_mode, .. } | Self::Live { channel_mode, .. } => {
1004 image_mode::handle_event(ev, channel_mode, config);
1005 }
1006 Self::Video { .. } | Self::Audio { .. } if ev.key == Key::Space => {
1007 self.toggle_play()?;
1008 }
1009 _ => {}
1010 }
1011 Ok(())
1012 }
1013
1014 fn close(&mut self) -> Result<()> {
1015 match self {
1016 Self::Video { player } => player
1017 .as_mut()
1018 .as_mut()
1019 .map_or(Ok(()), |player| player.close()),
1020 Self::Audio { player, .. } => {
1021 if let Some(player) = player.as_mut().as_mut() {
1022 player.close()?;
1023 }
1024 Ok(())
1025 }
1026 Self::Image { .. } | Self::Live { .. } | Self::Workspace | Self::Empty => Ok(()),
1027 }
1028 }
1029
1030 fn audio_player(&self) -> Option<&crate::AudioPlayer> {
1031 match self {
1032 Self::Video { player } => player.as_ref().as_ref().and_then(|player| player.audio()),
1033 Self::Audio { player, .. } => player.as_ref().as_ref(),
1034 _ => None,
1035 }
1036 }
1037
1038 fn pause_playback(&mut self) -> Result<()> {
1039 match self {
1040 Self::Video { player } => player
1041 .as_mut()
1042 .as_mut()
1043 .map_or(Ok(()), |player| player.pause()),
1044 Self::Audio { player, .. } => {
1045 if let Some(player) = player.as_ref() {
1046 player.pause();
1047 }
1048 Ok(())
1049 }
1050 _ => Ok(()),
1051 }
1052 }
1053
1054 pub(crate) fn position_us(&self) -> u64 {
1055 match self {
1056 Self::Video { player } => player
1057 .as_ref()
1058 .as_ref()
1059 .and_then(|player| player.position_us().ok())
1060 .unwrap_or(0),
1061 Self::Audio { player, .. } => player.as_ref().as_ref().map_or(0, |p| p.position_us()),
1062 _ => 0,
1063 }
1064 }
1065
1066 pub(crate) fn duration_us(&self) -> u64 {
1067 match self {
1068 Self::Video { player } => player.as_ref().as_ref().map_or(0, |p| p.duration_us()),
1069 Self::Audio { player, .. } => player.as_ref().as_ref().map_or(0, |p| p.duration_us()),
1070 _ => 0,
1071 }
1072 }
1073
1074 #[allow(dead_code)]
1075 pub(crate) fn is_playing(&self) -> bool {
1076 match self {
1077 Self::Video { player } => player.as_ref().as_ref().is_some_and(|p| p.is_playing()),
1078 Self::Audio { player, .. } => player.as_ref().as_ref().is_some_and(|p| p.is_playing()),
1079 _ => false,
1080 }
1081 }
1082
1083 #[allow(dead_code)]
1084 pub(crate) fn toggle_play(&mut self) -> Result<()> {
1085 match self {
1086 Self::Video { player } => {
1087 if let Some(p) = player.as_mut().as_mut() {
1088 if p.is_playing() { p.pause() } else { p.play() }
1089 } else {
1090 Ok(())
1091 }
1092 }
1093 Self::Audio { player, .. } => {
1094 if let Some(p) = player.as_mut().as_mut() {
1095 if p.is_playing() {
1096 p.pause();
1097 Ok(())
1098 } else {
1099 p.play()
1100 }
1101 } else {
1102 Ok(())
1103 }
1104 }
1105 _ => Ok(()),
1106 }
1107 }
1108
1109 pub(crate) fn step_temporal(&mut self, steps: i32) -> Result<()> {
1111 match self {
1112 Self::Video { player } => {
1113 if let Some(player) = player.as_mut() {
1114 player.step_frames(steps)?;
1115 }
1116 }
1117 Self::Audio { player, .. } => {
1118 if let Some(player) = player.as_mut() {
1119 player.pause();
1120 let target = (i128::from(player.position_us()) + i128::from(steps) * 5_000_000)
1121 .clamp(0, i128::from(player.duration_us())) as u64;
1122 player.seek(target)?;
1123 }
1124 }
1125 _ => {}
1126 }
1127 Ok(())
1128 }
1129
1130 pub(crate) fn seek_fraction(&mut self, fraction: f32) -> Result<()> {
1131 let fraction = fraction.clamp(0.0, 1.0);
1132 let dur = self.duration_us();
1133 if dur == 0 {
1134 return Ok(());
1135 }
1136 let target = (dur as f64 * fraction as f64) as u64;
1137 match self {
1138 Self::Video { player } => {
1139 player
1140 .as_mut()
1141 .as_mut()
1142 .map_or(Ok(()), |p| match p.seek_us(target) {
1143 Err(error) if p.current_frame().is_ok() => {
1144 crate::log_warn!(crate::LogComponent::VIDEO, "Viewer seek failed: {error}");
1145 Ok(())
1146 }
1147 result => result,
1148 })
1149 }
1150 Self::Audio { player, .. } => {
1151 if let Some(p) = player.as_mut().as_mut() {
1152 p.seek(target)
1153 } else {
1154 Ok(())
1155 }
1156 }
1157 _ => Ok(()),
1158 }
1159 }
1160}