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