Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion exporter/integration_tests/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use anyhow::{anyhow, Context, Result};
use clap::Parser;
use exporter::{run_main, Opt};
use exporter::{cli::Opt, run_main};
use libtest_mimic::Trial;
use ruffle_fs_tests_runner::{FsTestsRunner, TestLoaderParams};
use serde::Deserialize;
Expand Down
115 changes: 115 additions & 0 deletions exporter/src/cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
use crate::player_ext::PlayerExporterExt;
use anyhow::Result;
use clap::Parser;
use ruffle_core::Player;
use ruffle_render_wgpu::clap::{GraphicsBackend, PowerPreference};
use std::num::NonZeroU32;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::{Arc, Mutex};

#[derive(Parser, Debug, Copy, Clone)]
pub struct SizeOpt {
/// The amount to scale the page size with
#[clap(long = "scale", default_value = "1.0")]
pub scale: f64,

/// Optionally override the output width
#[clap(long = "width")]
pub width: Option<u32>,

/// Optionally override the output height
#[clap(long = "height")]
pub height: Option<u32>,
}

#[derive(Debug, Clone, Copy)]
pub enum FrameSelection {
All,
Count(NonZeroU32),
}

impl FrameSelection {
pub fn is_single_frame(self) -> bool {
match self {
FrameSelection::All => false,
FrameSelection::Count(n) => n.get() == 1,
}
}

pub fn total_frames(self, player: &Arc<Mutex<Player>>, skipframes: u32) -> u32 {
match self {
// TODO Getting frame count from the header won't always work.
FrameSelection::All => player.header_frames() as u32,
FrameSelection::Count(n) => n.get() + skipframes,
}
}
}

impl FromStr for FrameSelection {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let s_lower = s.to_ascii_lowercase();
if s_lower == "all" {
Ok(FrameSelection::All)
} else if let Ok(n) = s.parse::<u32>() {
Copy link
Collaborator

@SuchAFuriousDeath SuchAFuriousDeath Oct 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might be intentional, but NonZero<u32> implements FromStr directly

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I'll fix that in a separate PR — I don't really want to include any changes here, just moving code around, it's easier to review

let non_zero = NonZeroU32::new(n)
.ok_or_else(|| "Frame count must be greater than 0".to_string())?;
Ok(FrameSelection::Count(non_zero))
} else {
Err(format!("Invalid value for --frames: {s}"))
}
}
}

#[derive(Parser, Debug)]
#[clap(name = "Ruffle Exporter", author, version)]
pub struct Opt {
/// The file or directory of files to export frames from
#[clap(name = "swf")]
pub swf: PathBuf,

/// The file or directory (if multiple frames/files) to store the capture in.
/// The default value will either be:
/// - If given one swf and one frame, the name of the swf + ".png"
/// - If given one swf and multiple frames, the name of the swf as a directory
/// - If given multiple swfs, this field is required.
#[clap(name = "output")]
pub output_path: Option<PathBuf>,

/// Number of frames to capture per file. Use 'all' to capture all frames.
#[clap(short = 'f', long = "frames", default_value = "1")]
pub frames: FrameSelection,

/// Number of frames to skip
#[clap(long = "skipframes", default_value = "0")]
pub skipframes: u32,

/// Don't show a progress bar
#[clap(short, long, action)]
pub silent: bool,

#[clap(flatten)]
pub size: SizeOpt,

/// Force the main timeline to play, bypassing "Click to Play" buttons and similar restrictions.
/// This can help automate playback in some SWFs, but may break or alter content that expects user interaction.
/// Use with caution: enabling this may cause some movies to behave incorrectly.
#[clap(long)]
pub force_play: bool,

/// Type of graphics backend to use. Not all options may be supported by your current system.
/// Default will attempt to pick the most supported graphics backend.
#[clap(long, short, default_value = "default")]
pub graphics: GraphicsBackend,

/// Power preference for the graphics device used. High power usage tends to prefer dedicated GPUs,
/// whereas a low power usage tends prefer integrated GPUs.
#[clap(long, short, default_value = "high")]
pub power: PowerPreference,

/// TODO Unused, remove after some time
#[clap(long, action, hide = true)]
pub skip_unsupported: bool,
}
131 changes: 131 additions & 0 deletions exporter/src/exporter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
use std::panic::catch_unwind;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;

use image::RgbaImage;
use ruffle_core::limits::ExecutionLimit;
use ruffle_core::tag_utils::SwfMovie;
use ruffle_core::Player;
use ruffle_core::PlayerBuilder;
use ruffle_render_wgpu::backend::WgpuRenderBackend;
use ruffle_render_wgpu::descriptors::Descriptors;

use anyhow::anyhow;
use anyhow::Result;
use ruffle_render_wgpu::backend::request_adapter_and_device;
use ruffle_render_wgpu::target::TextureTarget;
use ruffle_render_wgpu::wgpu;

use crate::cli::FrameSelection;
use crate::cli::Opt;
use crate::cli::SizeOpt;
use crate::player_ext::PlayerExporterExt;

pub struct Exporter {
descriptors: Arc<Descriptors>,
size: SizeOpt,
skipframes: u32,
frames: FrameSelection,
force_play: bool,
}

impl Exporter {
pub fn new(opt: &Opt) -> Result<Self> {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: opt.graphics.into(),
..Default::default()
});
let (adapter, device, queue) = futures::executor::block_on(request_adapter_and_device(
opt.graphics.into(),
&instance,
None,
opt.power.into(),
))
.map_err(|e| anyhow!(e.to_string()))?;

let descriptors = Arc::new(Descriptors::new(instance, adapter, device, queue));

Ok(Self {
descriptors,
size: opt.size,
skipframes: opt.skipframes,
frames: opt.frames,
force_play: opt.force_play,
})
}

pub fn start_exporting_movie(&self, swf_path: &Path) -> Result<MovieExport> {
let movie = SwfMovie::from_path(swf_path, None).map_err(|e| anyhow!(e.to_string()))?;

let width = self
.size
.width
.map(f64::from)
.unwrap_or_else(|| movie.width().to_pixels());
let width = (width * self.size.scale).round() as u32;

let height = self
.size
.height
.map(f64::from)
.unwrap_or_else(|| movie.height().to_pixels());
let height = (height * self.size.scale).round() as u32;

let target = TextureTarget::new(&self.descriptors.device, (width, height))
.map_err(|e| anyhow!(e.to_string()))?;
let player = PlayerBuilder::new()
.with_renderer(
WgpuRenderBackend::new(self.descriptors.clone(), target)
.map_err(|e| anyhow!(e.to_string()))?,
)
.with_movie(movie)
.with_viewport_dimensions(width, height, self.size.scale)
.build();

Ok(MovieExport {
player,
skipframes: self.skipframes,
frames: self.frames,
force_play: self.force_play,
})
}
}

pub struct MovieExport {
player: Arc<Mutex<Player>>,
skipframes: u32,
frames: FrameSelection,
force_play: bool,
}

impl MovieExport {
pub fn total_frames(&self) -> u32 {
self.frames.total_frames(&self.player, self.skipframes)
}

pub fn run_frame(&self) {
if self.force_play {
self.player.force_root_clip_play();
}

self.player
.lock()
.unwrap()
.preload(&mut ExecutionLimit::none());

self.player.lock().unwrap().run_frame();
}

pub fn capture_frame(&self) -> Result<RgbaImage> {
let image = || {
self.player.lock().unwrap().render();
self.player.capture_frame()
};
match catch_unwind(image) {
Ok(Some(image)) => Ok(image),
Ok(None) => Err(anyhow!("No frame captured")),
Err(e) => Err(anyhow!("{e:?}")),
}
}
}
Loading
Loading