spacebox/src/Recorder.cpp

90 lines
2.5 KiB
C++

#include "Recorder.hpp"
Recorder::Recorder(Node* parent) : Node(parent)
{
get_delegate().subscribe(&Recorder::respond, this);
}
void Recorder::respond(SDL_Event& event)
{
if (get_delegate().compare(event, "screenshot"))
{
capture_screen();
}
else if (get_delegate().compare(event, "record"))
{
if (animation.playing)
{
end_recording();
}
else
{
start_recording();
}
}
}
void Recorder::capture_screen()
{
nlohmann::json config = get_configuration();
SDL_Surface* surface = get_display().get_screen_surface();
fs::path directory = config["path"]["screenshots"];
fs::create_directories(directory);
std::string prefix = config["display"]["screenshot-prefix"].
get<std::string>();
std::string extension = config["display"]["screenshot-extension"].
get<std::string>();
int zfill = config["display"]["screenshot-zfill"].get<int>();
fs::path path = sfw::get_next_file_name(directory, zfill, prefix, extension);
IMG_SavePNG(surface, path.c_str());
SDL_FreeSurface(surface);
std::cout << "Saved screenshot to " << path.string() << std::endl;
}
void Recorder::start_recording()
{
std::cout << "Starting recording..." << std::endl;
animation.play();
}
void Recorder::add_frame_to_video()
{
frames.push_back(get_display().get_screen_surface());
}
void Recorder::end_recording()
{
std::cout << "Ending recording..." << std::endl;
animation.reset();
nlohmann::json config = get_configuration();
fs::path root = config["path"]["video"];
fs::create_directories(root);
fs::path directory = sfw::get_next_file_name(root, 5, "video-");
fs::create_directories(directory);
std::function<void(fs::path)> f = std::bind(&Recorder::write_video_frames, this, std::placeholders::_1);
std::thread writing(f, directory);
writing.detach();
}
void Recorder::write_video_frames(fs::path directory)
{
std::cout << "Writing recording to " << directory << "..." << std::endl;
SDL_Surface* frame;
for (int ii = 0; not frames.empty(); ii++)
{
frame = frames.front();
std::stringstream name;
name << sfw::pad(ii, 5) << ".png";
fs::path path = directory / name.str();
IMG_SavePNG(frame, path.string().c_str());
frames.erase(frames.begin());
SDL_FreeSurface(frame);
}
std::cout << "Wrote " << directory << std::endl;
}
void Recorder::update()
{
animation.update();
}