diff --git a/CMakeLists.txt b/CMakeLists.txt index b258c31..dfb90c8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,10 +34,13 @@ add_executable(videoframevr src/xbvr_server.cpp src/video_player.cpp src/decoder_holders.cpp + src/deletion.cpp + src/passthrough.cpp src/gl_util.cpp src/autofocus.cpp src/bluray.cpp src/bluray_disc.cpp + src/button_jobs.cpp src/cairo_canvas.cpp src/colour_balance.cpp src/controller_guide.cpp @@ -62,6 +65,7 @@ add_executable(videoframevr src/foveation.cpp src/frame_reuse.cpp src/frame_grabber.cpp + src/frame_scaler.cpp src/funscript.cpp src/gl_interop.cpp src/gpu_context.cpp @@ -142,6 +146,7 @@ add_executable(videoframevr src/removable_drives.cpp src/room_light.cpp src/run_log.cpp + src/running_video.cpp src/scene_renderer.cpp src/screen_control.cpp src/script_player.cpp @@ -154,8 +159,10 @@ add_executable(videoframevr src/setup_places.cpp src/sftp.cpp src/smb.cpp + src/sqlite_util.cpp src/stash.cpp src/stash_catalog.cpp + src/stash_diagnostic.cpp src/stash_similarity.cpp src/stash_client.cpp src/stash_server.cpp @@ -163,6 +170,7 @@ add_executable(videoframevr src/stash_folders.cpp src/stash_http.cpp src/stash_images.cpp + src/stash_outbox.cpp src/stash_preview.cpp src/stash_query.cpp src/stash_settings.cpp @@ -172,6 +180,7 @@ add_executable(videoframevr src/stash_text.cpp src/stash_write_back.cpp src/stereo_correction.cpp + src/stick_seek.cpp src/strings.cpp src/strings_de.cpp src/strings_es.cpp diff --git a/src/button_jobs.cpp b/src/button_jobs.cpp new file mode 100644 index 0000000..f27e31e --- /dev/null +++ b/src/button_jobs.cpp @@ -0,0 +1,273 @@ +#include "button_jobs.h" + +#include "controls.h" +#include "focus_settings.h" +#include "library.h" +#include "menu.h" +#include "playback_state.h" +#include "running_video.h" +#include "see_through.h" +#include "strings.h" +#include "video_player.h" + +#include +#include +#include +#include + +namespace { + +// The buttons' Zoom in and out: a press steps the Zoom (180°/360°) setting +// as the menu's slider does; held past kZoomDelay, it goes on at kZoomRate +// until let go. +constexpr double kZoomDelay = 0.4; // seconds +constexpr double kZoomRate = 40; // percent a second + +template +std::string printed(const char* format, Args... args) { + std::string text(std::max(std::snprintf(nullptr, 0, format, args...), 0), '\0'); + std::snprintf(text.data(), text.size() + 1, format, args...); + return text; +} + +} // namespace + +std::string ButtonJobs::seeThroughKey() const { + const VideoRecord r = library.record(running.currentFile); + return r.known() ? "#" + std::to_string(r.id) : running.currentFile; +} + +JobAction ButtonJobs::press(Job job, int hand, const Context& context) { + JobAction action; + const auto say = [&](std::string text) { action.said = std::move(text); }; + const auto sayf = [&](const char* format, auto... args) { say(printed(format, args...)); }; + // A switch whose change doesn't show by itself: as it will be. Mute and + // Passthrough change later (mpv's, and where the settings are). + const auto switching = [&](const char* name, bool on) { + sayf(strings().jobs.switched, name, on ? strings().on : strings().off); + }; + const JobInfo& info = jobInfo(job); + const JobStrings& said = strings().jobs; + const bool photo = context.photo, passthroughAvailable = context.passthroughAvailable; + const double now = context.now; + MenuCommand& c = action.command; + c = info.command; + if (info.length != JobLength::None) + c.value *= info.length == JobLength::Skip ? settings.skipSeconds : settings.bigSkipSeconds; + const PlaybackState& p = player.playback(); + switch (job) { + case Job::PlayPause: + // A photo's is the slideshow's: it stops one running. + if (photo) { + c = {}; + if (context.slideshow) c = {MenuCommand::SetSlideshow, 0.0}; + else say(said.notForPhotos); + } + break; + case Job::PreviousChapter: + case Job::NextChapter: { + if (player.loading()) break; + if (p.chapters.empty()) { + say(said.noChapters); + break; + } + // Back: to the start of this chapter first, more than 5 s into it. + const bool into = job == Job::PreviousChapter && p.chapter >= 0 && + p.chapter < static_cast(p.chapters.size()) && + p.position - p.chapters[p.chapter].time > 5; + const int to = p.chapter + (job == Job::NextChapter ? 1 : into ? 0 : -1); + if (to >= 0 && to < static_cast(p.chapters.size())) + c = {MenuCommand::SeekTo, p.chapters[to].time}; + else + say(to < 0 ? said.firstChapter : said.lastChapter); + break; + } + case Job::AfterVideo: + // As the strip's list, the next choice. + c = {MenuCommand::SetAfterVideo, static_cast((static_cast(context.afterVideo) + 1) % 4)}; + break; + case Job::VolumeUp: + case Job::VolumeDown: { + // As + and - do, within the volume gesture's 0..100. + const long volume = std::lround(p.volume); + const long to = job == Job::VolumeUp ? std::max(volume, std::min(volume + 5, 100L)) + : std::max(volume - 5, 0L); + c = {MenuCommand::SetVolume, static_cast(to)}; + sayf(said.volume, static_cast(to)); + break; + } + case Job::NextAudioTrack: + case Job::Subtitles: { + if (player.loading()) break; // the last file's tracks until it opens + const char* type = job == Job::Subtitles ? "sub" : "audio"; + std::vector tracks; + int chosen = -1; + for (const Track& t : p.tracks) + if (t.type == type) { + if (t.selected) chosen = static_cast(tracks.size()); + tracks.push_back(&t); + } + const Strings& words = strings(); + if (job == Job::NextAudioTrack) { + if (tracks.size() > 1) { + const Track& next = *tracks[(chosen + 1) % tracks.size()]; + c = {MenuCommand::SelectAudio, static_cast(next.id)}; + sayf(said.audioTrack, trackName(next, words).c_str()); + } else { + say(said.noOtherAudio); + } + } else if (chosen >= 0) { + lastSubtitle = tracks[chosen]->id; + c = {MenuCommand::SelectSubtitle, 0}; + sayf(said.switched, words.subtitles, words.off); + } else if (!tracks.empty()) { + const Track* on = tracks[0]; + for (const Track* t : tracks) + if (t->id == lastSubtitle) on = t; + c = {MenuCommand::SelectSubtitle, static_cast(on->id)}; + sayf(said.switched, words.subtitles, trackName(*on, words).c_str()); + } else { + say(said.noSubtitles); + } + break; + } + case Job::Mute: switching(said.sound, p.muted); break; + case Job::Passthrough: + if (!passthroughAvailable) { + say(said.noRoom); + c = {}; + } else { + switching(said.passthrough, !running.video.passthrough); + } + break; + case Job::PeekRoom: + if (!context.alphaBlend) say(said.noRoom); + break; + case Job::SeeThrough: + // Solid, and back to the see-through it had. + if (!context.alphaBlend) { + say(said.noRoom); + break; + } + if (running.video.opacity < 100) { + c = {MenuCommand::SetOpacity, 100.0}; + } else { + // (stored before the library knew it: by where it is) + auto last = lastSeeThrough.find(seeThroughKey()); + if (last == lastSeeThrough.end()) last = lastSeeThrough.find(running.currentFile); + c = {MenuCommand::SetOpacity, last != lastSeeThrough.end() ? last->second : 50.0}; + } + action.showOpacity = true; + break; + case Job::MatchRoom: + // Where the menu shows its switch: where the room's light is read. + if (!context.roomReadable) { + say(said.notOnHeadset); + c = {}; + } else if (!context.roomShown) { + say(said.needsPassthrough); + } else { + switching(strings().colourBalance.matchRoom, !context.roomMatched); + } + break; + case Job::ResetScreen: + // As Video settings' Screen group: a flat screen's only. + if (running.format.projection != Projection::Flat) { + say(said.flatOnly); + c = {}; + } + break; + case Job::RemoveBackground: + // Where its switch shows: passthrough on, without the video's own mask. + if (!passthroughAvailable) + say(said.noRoom); + else if (!running.video.passthrough) + say(said.needsPassthrough); + else if (packedMask(running.currentFile, running.video) && maskFormat(running.format)) + say(said.ownMask); + else { + c = {MenuCommand::ToggleGreenScreen}; + switching(strings().greenScreenOn, !running.video.greenScreen.on); + } + break; + case Job::ResetPicture: say(said.pictureReset); break; + case Job::ZoomIn: + case Job::ZoomOut: + if (running.format.projection == Projection::Flat) { + say(said.notForFlat); + break; + } + zoomHold = {job, hand, now, now, running.currentFile}; + running.zoomBy(job == Job::ZoomIn ? VideoSettings::kZoomStepPercent : -VideoSettings::kZoomStepPercent); + action.showRing = GestureValue::Zoom; + break; + case Job::StereoFocus: + case Job::ShowFocusTarget: { + const bool stereo = job == Job::StereoFocus; + if (!stereo && !settings.focusPrefs.enabled) { // its switch is greyed out + say(said.needsFocus); + break; + } + c = {MenuCommand::SetFocus, + (stereo ? settings.focusPrefs.enabled : settings.focusPrefs.showTarget) ? 0.0 : 1.0}; + c.option = static_cast(stereo ? FocusControl::Enabled : FocusControl::ShowTarget); + break; + } + default: break; + } + return action; +} + +std::string ButtonJobs::saidAfter(Job job, AfterVideo afterVideo) const { + std::string said; + const Strings& words = strings(); + const auto say = [&](const char* text) { said = text; }; + const auto switched = [&](const char* name, bool on) { + said = printed(words.jobs.switched, name, on ? words.on : words.off); + }; + switch (job) { + case Job::AfterVideo: say(words.afterVideo.choices[static_cast(afterVideo)]); break; + case Job::Scripts: switched(words.scripts.group, settings.scripts.enabled); break; + case Job::Motion: switched(words.focus.motion, settings.motionEmulation); break; + case Job::ToneLook: switched(words.toneLook, settings.toneLook); break; + case Job::TvGamma: switched(words.tvGamma, settings.tvGamma); break; + case Job::StereoFocus: switched(words.focus.enabled, settings.focusPrefs.enabled); break; + default: break; + } + return said; +} + +void ButtonJobs::keepSeeThrough() { + if (running.video.opacity < 100 && !running.currentFile.empty() && + (running.video.opacity != seeThroughSeen || running.currentFile != seeThroughFile)) + lastSeeThrough[seeThroughKey()] = running.video.opacity; + seeThroughFile = running.currentFile; + seeThroughSeen = running.video.opacity; +} + +bool ButtonJobs::holdZoom(const JobInput& jobs, double now) { + if (zoomHold.hand >= 0) { + if (running.currentFile != zoomHold.file) { + zoomHold.hand = -1; // stored as the video changed + } else if (const int other = 1 - zoomHold.hand; + running.format.projection != Projection::Flat && !jobs.isHeld(zoomHold.job, zoomHold.hand) && + (jobs.isHeld(Job::ZoomIn, other) || jobs.isHeld(Job::ZoomOut, other))) { + // Let go while the other hand holds a zoom too: it goes on with that. + zoomHold.job = jobs.isHeld(Job::ZoomIn, other) ? Job::ZoomIn : Job::ZoomOut; + zoomHold.hand = other; + zoomHold.at = now; + } else if (running.format.projection == Projection::Flat || !jobs.isHeld(zoomHold.job, zoomHold.hand)) { + // In whole percents, as the slider sets it. + running.video.zoom = std::round(running.video.zoom * 100) / 100; + running.screen.zoom = running.video.zoom; + running.storeVideoSoon(VideoSettings::kZoom); + zoomHold.hand = -1; + } else if (now > zoomHold.start + kZoomDelay) { + const double from = std::max(zoomHold.at, zoomHold.start + kZoomDelay); + running.zoomBy((zoomHold.job == Job::ZoomIn ? kZoomRate : -kZoomRate) * (now - from)); + zoomHold.at = now; + return true; + } + } + return false; +} diff --git a/src/button_jobs.h b/src/button_jobs.h new file mode 100644 index 0000000..6ffd4ff --- /dev/null +++ b/src/button_jobs.h @@ -0,0 +1,85 @@ +#pragma once + +#include "control_map.h" +#include "menu_command.h" +#include "settings.h" + +#include +#include +#include + +class Library; +class RunningVideo; +class VideoPlayer; +struct JobInput; + +// What a press of a button's job does, in this order: what it says, then the +// command, as if the menu sent it. +struct JobAction { + std::string said; // empty: nothing + bool showOpacity = false; // See-through: the opacity's value shows + GestureValue showRing = GestureValue::Count; // this value's ring shows (Zoom in and out) + MenuCommand command; // None: nothing +}; + +// The buttons' other jobs (controls.h), as the menu's or the strip's +// controls do them, and what they turn back on. Main thread only. +class ButtonJobs { + public: + // What else is going on at the press. + struct Context { + double now = 0; + bool photo = false; + bool slideshow = false; // a photo's slideshow runs + bool passthroughAvailable = false; + bool alphaBlend = false; // the room can show (XrContext::alphaBlendSupported()) + bool roomReadable = false; // Passthrough::roomReadable + bool roomShown = false; // Passthrough::roomShown() + bool roomMatched = false; // Passthrough::matched() + AfterVideo afterVideo = AfterVideo::Stop; + }; + + ButtonJobs(const VideoPlayer& player, RunningVideo& running, const Settings& settings, + const Library& library) + : player(player), running(running), settings(settings), library(library) {} + + // A press of a job that has what it needs (JobInfo::needs), by that hand. + // Frame back and forward, Rating up and down and Delete get only their + // command: the caller does them. + JobAction press(Job job, int hand, const Context& context); + // After the press's command: the switches whose change doesn't show by + // itself, as they are now; empty for the rest. + std::string saidAfter(Job job, AfterVideo afterVideo) const; + // Each frame, before the presses: the running video's see-through, for + // See-through to go back to. + void keepSeeThrough(); + // Each frame, after the presses: a held Zoom in or out goes on. True if + // the zoom changed (its ring shows). + bool holdZoom(const JobInput& jobs, double now); + // A zoom is held: it is stored once let go. + bool zoomHeld() const { return zoomHold.hand >= 0; } + + private: + const VideoPlayer& player; + RunningVideo& running; + const Settings& settings; + const Library& library; + + std::string seeThroughKey() const; + + // The buttons' Subtitles and Opacity jobs: what they turn back on; the + // opacity, each video's last see-through value however it was set, for + // this run (by its library id, else where it is). + int64_t lastSubtitle = 0; + std::unordered_map lastSeeThrough; + std::string seeThroughFile; + int seeThroughSeen = 100; + // Zoom in or out held: by which hand (-1 none), since when, and how far + // it has gone, on which file. It is stored once, when let go. + struct ZoomHold { + Job job = Job::None; + int hand = -1; + double start = 0, at = 0; + std::string file; + } zoomHold; +}; diff --git a/src/controller_guide.cpp b/src/controller_guide.cpp index 408394c..c80ea77 100644 --- a/src/controller_guide.cpp +++ b/src/controller_guide.cpp @@ -1,6 +1,7 @@ #include "controller_guide.h" #include "platform.h" +#include "server_json.h" #include "strings.h" #include @@ -21,6 +22,7 @@ namespace { namespace fs = std::filesystem; using json = nlohmann::json; using Source = ControllerBindings::Source; +using server_json::text; const char* const kFrameProfile = "/interaction_profiles/valve/frame_controller_valve"; // SteamVR's profile for each interaction profile the app suggests bindings @@ -50,11 +52,6 @@ std::string readFile(const fs::path& path) { // Discarded (not an object) if missing or not JSON; SteamVR's may have comments. json readJson(const fs::path& path) { return json::parse(readFile(path), nullptr, false, true); } -std::string text(const json& j, const char* key) { - const auto it = j.is_object() ? j.find(key) : j.end(); - return j.is_object() && it != j.end() && it->is_string() ? it->get() : std::string(); -} - // SteamVR's folder, as it registers itself in OpenVR's paths file, else the // Steam Frame's. fs::path steamvrPath() { diff --git a/src/deletion.cpp b/src/deletion.cpp new file mode 100644 index 0000000..eee808a --- /dev/null +++ b/src/deletion.cpp @@ -0,0 +1,267 @@ +#include "deletion.h" + +#include "file_util.h" +#include "library.h" +#include "library_index.h" +#include "media_server.h" +#include "offline.h" +#include "oshash.h" +#include "remote.h" +#include "settings.h" +#include "stash.h" +#include "stash_stream.h" +#include "strings.h" +#include "thumbnailer.h" +#include "video_player.h" + +#include +#include +#include +#include +#include + +namespace { + +// Runs `job` on a thread of its own; dropping the future doesn't wait for it. +template +auto detached(Job job) { + std::packaged_task task(std::move(job)); + auto result = task.get_future(); + std::thread(std::move(task)).detach(); + return result; +} + +// Why the playing file couldn't be deleted, as the delete dialog says it, +// and as the run log does. +std::string deleteError(DeleteStatus status, const std::string& error) { + const DeleteStrings& t = strings().deletion; + switch (status) { + case DeleteStatus::Changed: return t.changed; + case DeleteStatus::Gone: return t.gone; + case DeleteStatus::NotAFile: return t.notAFile; + case DeleteStatus::Denied: return t.denied; + case DeleteStatus::InUse: return t.inUse; + case DeleteStatus::Offline: return t.offline; + default: return error; + } +} +const char* deleteLogged(DeleteStatus status) { + static const char* const names[] = {"deleted", "changed", "gone", "not a file", "not allowed", + "in use", "server not answering", "failed"}; + return names[static_cast(status)]; +} + +} // namespace + +bool Deletion::request(const MenuCommand& c, const std::string& currentFile, + const std::string& streamOshash) { + // The dialog is open; the video pauses meanwhile, a slideshow stops. + if (c.path != currentFile) { // it changed meanwhile + menu_.cancelDelete(); + return false; + } + if (result_.valid()) return false; + info_ = {}; + info_.file = c.path; + info_.name = std::filesystem::path(c.path).filename().string(); + info_.photo = isPhotoFile(c.path); + expected_.clear(); + // A downloaded copy plays instead of its source (openVideo). + if (const Offline::Download* d = offline_.find(c.path); + d && d->state == Offline::State::Done && d->present && d->path == c.path) { + info_.source = d->source; + info_.copyRoot = d->root; + info_.size = d->size; + copy_ = d->id; + expected_ = d->oshash; + } + const std::string& source = info_.source; + target_ = source.empty() ? c.path + : isStashSource(source) ? stashSourceLocator(source) + : source; + const bool stream = isStashScene(target_); + if (stream && source.empty()) expected_ = streamOshash; + // A Stash scene's file, at the scene's location (a file here or its + // stream), never by oshash alone. + scene_ = 0; + sceneFiles_ = 0; + stashPath_.clear(); + oshash_.clear(); + throughStash_ = false; + if (const auto catalog = stash_ ? stash_->catalog() : nullptr; catalog && !target_.empty()) + if (const int i = stashSceneAt(*catalog, target_); i >= 0) { + const StashScene& s = catalog->scenes()[i]; + scene_ = s.id; + sceneFiles_ = s.oshashes.size(); + stashPath_ = stashFilePathAt(*catalog, target_); + if (isStashScene(target_) && source.empty()) info_.size = s.size; + } + resume_ = !info_.photo && !player_.playback().paused; + if (resume_) player_.command("set pause yes"); + lookup_ = detached([file = target_, stream, check = stream || !source.empty(), + expected = expected_, + ask = settings_.stash.writeBack && scene_ != 0 && + mediaServer(settings_.stash.kind).abilities().deleteFiles, + scene = scene_, stashPath = stashPath_, + url = settings_.stash.url, key = settings_.stash.apiKey, + unverified = settings_.stash.unverified()] { + Deletion::Look r; + if (file.empty()) + r.status = DeleteStatus::Gone; + else if (!stream) + r.status = stampOf(file, r.stamp); + if (r.status != DeleteStatus::Ok || (!ask && !check)) return r; + r.oshash = stream ? expected : fingerprintFile(file).oshash; + // A copy's source still the video downloaded; a stream the one + // opened (Stash's fresh query below matches it). + if (check && (r.oshash.empty() || r.oshash != expected)) r.status = DeleteStatus::Changed; + if (r.status != DeleteStatus::Ok || !ask || r.oshash.empty()) return r; + r.asked = true; + r.stash = lookUpStashFile(url, key, unverified, scene, r.oshash, stashPath); + return r; + }); + return true; +} + +void Deletion::cancel(const std::string& currentFile) { + lookup_ = {}; + if (resume_ && currentFile == info_.file) player_.command("set pause no"); + resume_ = false; +} + +void Deletion::confirm(const MenuCommand& c, const std::string& currentFile) { + // Only the file the dialog showed, as it showed it. + if (!info_.ready || c.path != info_.file || c.path != currentFile || + result_.valid()) + return; + resume_ = false; + const std::string target = target_; + // Stash deletes it only with Send to Stash on still; its stream + // only through Stash; a copy's source only if it is still the + // video downloaded. + const bool throughStash = throughStash_ && settings_.stash.writeBack; + if (c.value == 0 && (target.empty() || (isStashScene(target) && !throughStash) || + (!info_.source.empty() && !info_.sourceFound))) { + menu_.showDeleteError(deleteError(DeleteStatus::Denied, std::string())); + return; + } + // The player, the seek preview and a download from it let go of it. + const std::string from = isStashScene(target) ? stashSource(target) : target; + if (const Offline::Download* d = offline_.find(from); + d && d->source == from && d->state != Offline::State::Done) + offline_.cancel(d->id); + closeVideo(); + if (c.value > 0) { // only the downloaded copy + offline_.remove(copy_); + library_.forgetFile(c.path); + libraryIndex_.deleted(c.path); + std::printf("Delete: a downloaded copy: deleted\n"); + menu_.deleteEnded(std::string()); + return; + } + throughStash_ = throughStash; + result_ = std::async(std::launch::async, [target, stamp = stamp_, throughStash, + writeBack = settings_.stash.writeBack, + url = settings_.stash.url, + key = settings_.stash.apiKey, + unverified = settings_.stash.unverified(), + scene = scene_, + stashPath = stashPath_, + oshash = oshash_, + trash = info_.stashTrash] { + const bool here = !isStashScene(target); + DeleteOutcome r; + if (throughStash) + r = deleteThroughStash(url, key, unverified, writeBack, scene, oshash, stashPath, + here ? target : std::string(), stamp, trash); + else + r.status = removeFile(target, stamp, r.error); + if (r.status == DeleteStatus::Ok && here) + dropThumbnail(target, stamp.size, stamp.modified, stamp.nanos); + return r; + }); +} + +void Deletion::poll() { + // The delete dialog's file looked up; a deletion finished. + if (lookup_.valid() && + lookup_.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { + const Deletion::Look look = lookup_.get(); + DeleteInfo& info = info_; + const bool stream = isStashScene(target_); + DeleteStatus status = look.status; + if (status == DeleteStatus::Ok && !stream) { + stamp_ = look.stamp; + info.size = look.stamp.size; + } + oshash_ = look.oshash; + // Stash deletes it if a fresh query found the scene's one file with + // its path and oshash; its stream's file nobody else can. + throughStash_ = look.asked && look.stash.file != 0; + if (throughStash_) { + sceneFiles_ = look.stash.files.size(); + info.stash = DeleteInfo::Stash::Deletes; + info.otherFiles = static_cast(look.stash.files.size()) - 1; + info.stashTrash = !look.stash.trash.empty(); + } else if (stream) { + if (status == DeleteStatus::Ok) + status = !look.asked ? DeleteStatus::Denied + : !look.stash.answered ? DeleteStatus::Offline + : !look.stash.scene ? DeleteStatus::Gone + : DeleteStatus::Changed; + } else if (status == DeleteStatus::Ok && scene_ && + !(look.stash.answered && !look.stash.scene)) { + info.stash = look.stash.answered ? DeleteInfo::Stash::Unsure : DeleteInfo::Stash::Lists; + } + // A copy can go without its source. + info.sourceFound = !info.source.empty() && status == DeleteStatus::Ok; + info.sourceChanged = !info.source.empty() && status == DeleteStatus::Changed; + info.ready = status == DeleteStatus::Ok || !info.source.empty(); + if (info.ready) + menu_.askDelete(info); + else + menu_.showDeleteError(deleteError(status, std::string())); + } + if (result_.valid() && + result_.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { + const DeleteOutcome outcome = result_.get(); + const std::string& target = target_; + const bool stream = isStashScene(target); + std::printf("Delete: %s%s%s: %s%s%s\n", + stream ? "a scene's file in Stash" + : remote::isRemote(target) ? "a file on a server" + : "a file on this device", + info_.source.empty() ? "" : " and its downloaded copy", + throughStash_ ? " through Stash" : "", deleteLogged(outcome.status), + outcome.listed ? ", Stash still lists it" : "", + outcome.stashDeleted && outcome.status != DeleteStatus::Ok ? ", Stash deleted its file" + : ""); + if (outcome.status == DeleteStatus::Ok) { + if (!stream) { + library_.forgetFile(target); + libraryIndex_.deleted(target); + } + if (!info_.source.empty()) { + offline_.remove(copy_); + library_.forgetFile(info_.file); + libraryIndex_.deleted(info_.file); + } + forgetFolderListing(); + } + if (stash_ && scene_ && (outcome.status == DeleteStatus::Ok || outcome.stashDeleted)) { + if (sceneFiles_ == 1 && !stashPath_.empty()) stash_->hideScene(scene_); + if (throughStash_) stash_->syncNow(); + } + // Once Stash has deleted its file, never "Nothing was deleted". + menu_.deleteEnded(outcome.status == DeleteStatus::Ok ? std::string() + : outcome.stashDeleted ? std::string(strings().deletion.stashKeptHere) + : deleteError(outcome.status, outcome.error), + outcome.listed ? strings().deletion.stashLists : ""); + } +} + +void Deletion::dropDialog() { + lookup_ = {}; + resume_ = false; + menu_.cancelDelete(); +} diff --git a/src/deletion.h b/src/deletion.h new file mode 100644 index 0000000..a0aef4d --- /dev/null +++ b/src/deletion.h @@ -0,0 +1,84 @@ +#pragma once + +#include "file_ops.h" +#include "menu.h" +#include "stash_delete.h" + +#include +#include +#include +#include +#include + +class Library; +class LibraryIndex; +class Offline; +class Stash; +class VideoPlayer; +struct Settings; + +// Deleting the playing file (docs/alpha/delete-file.md): what the dialog +// shows, looked up in the background (a slow share must not freeze the +// headset), then the deletion, one at a time. +class Deletion { + public: + Deletion(Menu& menu, VideoPlayer& player, const Settings& settings, Library& library, + LibraryIndex& libraryIndex, Offline& offline, const std::unique_ptr& stash) + : menu_(menu), player_(player), settings_(settings), library_(library), + libraryIndex_(libraryIndex), offline_(offline), stash_(stash) {} + + // Closes the running video; set once, before the frames. + std::function closeVideo; + + // The menu's RequestDelete, CancelDelete and DeleteFile, for the file + // playing (`currentFile`). request() is true if the dialog's lookup started. + bool request(const MenuCommand& c, const std::string& currentFile, const std::string& streamOshash); + void cancel(const std::string& currentFile); + void confirm(const MenuCommand& c, const std::string& currentFile); + // Each frame: the lookup's and the deletion's results, once they are there. + void poll(); + // Playback moves on (another video, or none): a delete dialog still + // asking goes, with its lookup, so its confirm can't act on what came + // next. One confirmed (Deleting) stays. + void dropDialog(); + + private: + // The lookup's: the file's stamp (none for Stash's stream), and with + // Send to Stash on, its oshash and its scene's files as Stash has them. + struct Look { + DeleteStatus status = DeleteStatus::Ok; + FileStamp stamp; + std::string oshash; + bool asked = false; + StashFileLook stash; + }; + + Menu& menu_; + VideoPlayer& player_; + const Settings& settings_; + Library& library_; + LibraryIndex& libraryIndex_; + Offline& offline_; + const std::unique_ptr& stash_; + + DeleteInfo info_; + // What is deleted: the file playing, or a copy's source (with the + // copy), a scene's stream locator for one from Stash's; empty: a source + // on another Stash server. + std::string target_; + FileStamp stamp_; // the file's as the dialog shows it + int64_t scene_ = 0; // the Stash scene it is a file of; 0: none + size_t sceneFiles_ = 0; + std::string stashPath_; // Stash's path of it; empty: not known for sure + std::string oshash_; // the file's, as the lookup read it + // The oshash the file deleted must have: the download's for a copy's + // source, the one opened for a stream; empty: any (a file here). + std::string expected_; + bool throughStash_ = false; // Stash deletes it: Send to Stash on, its file found + std::future lookup_; // dropped without waiting + // From std::async: dropping it waits for the deletion, so it is only + // replaced once taken. + std::future result_; + bool resume_ = false; // the video played when the button was pressed + int64_t copy_ = 0; // the download whose copy plays +}; diff --git a/src/frame_scaler.cpp b/src/frame_scaler.cpp new file mode 100644 index 0000000..90a7d0c --- /dev/null +++ b/src/frame_scaler.cpp @@ -0,0 +1,56 @@ +#include "frame_scaler.h" + +extern "C" { +#include +#include +#include +} + +#include + +SwsContext* frameScaler(SwsContext* cached, const AVFrame* frame, int srcWidth, int width, + int height, int dstFormat, int flags) { + auto format = static_cast(frame->format); + bool fullRange = frame->color_range == AVCOL_RANGE_JPEG; + switch (format) { + case AV_PIX_FMT_YUVJ420P: format = AV_PIX_FMT_YUV420P; fullRange = true; break; + case AV_PIX_FMT_YUVJ422P: format = AV_PIX_FMT_YUV422P; fullRange = true; break; + case AV_PIX_FMT_YUVJ444P: format = AV_PIX_FMT_YUV444P; fullRange = true; break; + case AV_PIX_FMT_YUVJ440P: format = AV_PIX_FMT_YUV440P; fullRange = true; break; + case AV_PIX_FMT_YUVJ411P: format = AV_PIX_FMT_YUV411P; fullRange = true; break; + default: break; + } + SwsContext* sws = sws_getCachedContext(cached, srcWidth, frame->height, format, width, height, + static_cast(dstFormat), flags, nullptr, + nullptr, nullptr); + if (!sws) return nullptr; + const AVPixFmtDescriptor* desc = av_pix_fmt_desc_get(format); + if (desc && !(desc->flags & AV_PIX_FMT_FLAG_RGB)) { + int *inverse, *table, srcRange, dstRange, brightness, contrast, saturation; + if (sws_getColorspaceDetails(sws, &inverse, &srcRange, &table, &dstRange, &brightness, + &contrast, &saturation) >= 0) { + const int* coefficients = + sws_getCoefficients(frame->colorspace == AVCOL_SPC_BT709 ? SWS_CS_ITU709 : SWS_CS_DEFAULT); + sws_setColorspaceDetails(sws, coefficients, fullRange ? 1 : 0, table, dstRange, brightness, + contrast, saturation); + } + } + return sws; +} + +// swscale may write past the end of a row (it works in SIMD blocks), so it +// gets padded rows; the result is then copied into tightly packed pixels. +bool scaleInto(SwsContext* sws, const AVFrame* frame, int width, int height, + std::vector& pixels) { + const int stride = (width * 4 + 63) & ~63; + std::vector padded(static_cast(stride) * (height + 2) + 256); + uint8_t* planes[4] = {padded.data(), nullptr, nullptr, nullptr}; + int strides[4] = {stride, 0, 0, 0}; + if (sws_scale(sws, frame->data, frame->linesize, 0, frame->height, planes, strides) <= 0) + return false; + pixels.resize(static_cast(width) * height); + for (int y = 0; y < height; ++y) + std::memcpy(&pixels[static_cast(y) * width], padded.data() + static_cast(y) * stride, + static_cast(width) * 4); + return true; +} diff --git a/src/frame_scaler.h b/src/frame_scaler.h new file mode 100644 index 0000000..d70473b --- /dev/null +++ b/src/frame_scaler.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +struct SwsContext; +struct AVFrame; + +// A swscale context (`cached` reused when it fits, as sws_getCachedContext) +// converting the left `srcWidth` columns of a decoded frame to `width` × +// `height` pixels of `dstFormat`, with the frame's own range and matrix. +// FFmpeg's deprecated full-range formats (yuvj*, e.g. from JPEGs) are given +// as their plain formats with full range, which swscale otherwise warns +// about for every image. Null on failure. +SwsContext* frameScaler(SwsContext* cached, const AVFrame* frame, int srcWidth, int width, + int height, int dstFormat, int flags); + +// Scales a decoded frame with `sws` into tightly packed 32-bit pixels +// (width × height), safely: swscale may write past a row's end. +bool scaleInto(SwsContext* sws, const AVFrame* frame, int width, int height, + std::vector& pixels); diff --git a/src/funscript.cpp b/src/funscript.cpp index 8596d4a..05cb1e3 100644 --- a/src/funscript.cpp +++ b/src/funscript.cpp @@ -1,6 +1,7 @@ #include "funscript.h" #include "remote.h" +#include "server_json.h" #include "stash_stream.h" #include @@ -39,8 +40,7 @@ bool parseFunscript(const std::string& text, Funscript& script) { if (!j.is_object()) return false; const auto actions = j.find("actions"); if (actions == j.end() || !actions->is_array()) return false; - const auto flag = j.find("inverted"); - const bool inverted = flag != j.end() && flag->is_boolean() && flag->get(); + const bool inverted = server_json::flag(j, "inverted"); script.actions.reserve(actions->size()); for (const nlohmann::json& a : *actions) { if (!a.is_object()) continue; diff --git a/src/intiface.cpp b/src/intiface.cpp index 90d8ced..e31d8b7 100644 --- a/src/intiface.cpp +++ b/src/intiface.cpp @@ -1,6 +1,7 @@ #include "intiface.h" #include "platform.h" +#include "server_json.h" #include #include @@ -341,8 +342,7 @@ void Intiface::handle(const std::string& text) { } else if (type == "Error" && !errorShown_) { // The first of a connection's only: a device refusing commands says so each time. errorShown_ = true; - const auto why = body.find("ErrorMessage"); - const std::string reason = why != body.end() && why->is_string() ? why->get() : ""; + const std::string reason = server_json::text(body, "ErrorMessage"); std::fprintf(stderr, "Intiface: %.200s\n", reason.c_str()); } } diff --git a/src/library.cpp b/src/library.cpp index 0a39bcd..2eb1cda 100644 --- a/src/library.cpp +++ b/src/library.cpp @@ -5,6 +5,8 @@ #include "library_schema.h" // kLibrarySchema, made from library_schema.sql at build time #include "oshash.h" #include "app_dirs.h" +#include "server_json.h" +#include "sqlite_util.h" #include #include @@ -28,6 +30,8 @@ namespace fs = std::filesystem; using json = nlohmann::json; +using server_json::flag; +using server_json::number; namespace { @@ -158,19 +162,13 @@ std::string settingsJson(const VideoSettings& s) { return j.dump(); } -template -T field(const json& object, const char* key, T fallback) { - const auto it = object.find(key); - return it != object.end() && it->is_number() ? it->get() : fallback; -} - bool parseSettings(const std::string& text, VideoSettings& s) { const json j = json::parse(text, nullptr, false); if (j.is_discarded() || !j.is_object()) return false; s = VideoSettings{}; if (const auto format = j.find("format"); format != j.end() && format->is_object()) { - const int projection = field(*format, "projection", 0), stereo = field(*format, "stereo", 0), - packing = field(*format, "packing", 0); + const int projection = number(*format, "projection", 0), stereo = number(*format, "stereo", 0), + packing = number(*format, "packing", 0); if (projection >= 0 && projection < static_cast(Projection::kCount) && stereo >= 0 && stereo < static_cast(StereoLayout::kCount) && packing >= 0 && packing < static_cast(Packing::kCount)) { @@ -180,57 +178,52 @@ bool parseSettings(const std::string& text, VideoSettings& s) { s.format.packing = static_cast(packing); } } - s.brightness = field(j, "brightness", 0); - s.contrast = field(j, "contrast", 0); - s.saturation = field(j, "saturation", 0); - s.balance.warmth = std::clamp(field(j, "warmth", 0), -100, 100); - s.balance.tint = std::clamp(field(j, "tint", 0), -100, 100); - s.balance.exposure = std::clamp(field(j, "exposure", 0), -100, 100); - s.zoom = field(j, "zoom", 1.0f); - s.originForward = std::clamp(field(j, "origin_forward", 0.0f), -VideoSettings::kMaxOriginForward, + s.brightness = number(j, "brightness", 0); + s.contrast = number(j, "contrast", 0); + s.saturation = number(j, "saturation", 0); + s.balance.warmth = std::clamp(number(j, "warmth", 0), -100, 100); + s.balance.tint = std::clamp(number(j, "tint", 0), -100, 100); + s.balance.exposure = std::clamp(number(j, "exposure", 0), -100, 100); + s.zoom = number(j, "zoom", 1.0f); + s.originForward = std::clamp(number(j, "origin_forward", 0.0f), -VideoSettings::kMaxOriginForward, VideoSettings::kMaxOriginForward); if (const auto p = j.find("passthrough"); p != j.end() && p->is_boolean()) { s.passthrough = p->get(); s.passthroughChosen = true; // (older versions stored it only when on) } if (const auto g = j.find("green_check"); g != j.end() && g->is_object()) { - s.greenCheckVersion = field(*g, "version", 0); - const auto found = g->find("found"); - s.greenScreenFound = found != g->end() && found->is_boolean() && found->get(); + s.greenCheckVersion = number(*g, "version", 0); + s.greenScreenFound = flag(*g, "found"); } if (const auto fill = j.find("fill_check"); fill != j.end() && fill->is_object()) { - s.fillCheckVersion = field(*fill, "version", 0); - const auto found = fill->find("found"); - s.fillFound = found != fill->end() && found->is_boolean() && found->get() && - colourField(*fill, "colour", s.fillColour); + s.fillCheckVersion = number(*fill, "version", 0); + s.fillFound = flag(*fill, "found") && colourField(*fill, "colour", s.fillColour); } if (const auto mask = j.find("packed_mask"); mask != j.end() && mask->is_boolean()) s.packedMask = mask->get(); if (const auto layers = j.find("mask_layers"); layers != j.end() && layers->is_object()) { - s.maskLayersVersion = field(*layers, "version", 0); - const auto found = layers->find("found"); - s.maskLayersFound = found != layers->end() && found->is_boolean() && found->get(); + s.maskLayersVersion = number(*layers, "version", 0); + s.maskLayersFound = flag(*layers, "found"); } if (const auto hidden = j.find("second_layer_hidden"); hidden != j.end() && hidden->is_boolean()) s.secondLayerHidden = hidden->get(); - s.opacity = std::clamp(field(j, "opacity", 100), 0, 100); + s.opacity = std::clamp(number(j, "opacity", 100), 0, 100); if (const auto tv = j.find("tv_gamma"); tv != j.end() && tv->is_boolean()) s.legacyTvGamma = tv->get(); - s.volume = field(j, "volume", -1); + s.volume = number(j, "volume", -1); if (const auto key = j.find("green_screen"); key != j.end() && key->is_object()) { GreenScreen& g = s.greenScreen; - const auto on = key->find("on"); - g.on = on != key->end() && on->is_boolean() && on->get(); - const int source = field(*key, "background", 0); + g.on = flag(*key, "on"); + const int source = number(*key, "background", 0); if (source > 0 && source < static_cast(KeySource::kCount)) g.source = static_cast(source); if (g.source == KeySource::Picked && !colourField(*key, "picked", g.picked)) g.source = KeySource::Automatic; auto sliders = [](const json& object, KeySliders& k) { - k.strength = field(object, "strength", k.strength); - k.softness = field(object, "softness", k.softness); - k.spill = field(object, "spill", k.spill); - k.shrink = field(object, "shrink", k.shrink); + k.strength = number(object, "strength", k.strength); + k.softness = number(object, "softness", k.softness); + k.spill = number(object, "spill", k.spill); + k.shrink = number(object, "shrink", k.shrink); }; sliders(*key, g.green); if (const auto c = key->find("colour_key"); c != key->end() && c->is_object()) @@ -238,26 +231,26 @@ bool parseSettings(const std::string& text, VideoSettings& s) { } if (const auto focus = j.find("focus"); focus != j.end() && focus->is_object()) { FocusSettings f; - const int mode = field(*focus, "mode", static_cast(f.mode)); + const int mode = number(*focus, "mode", static_cast(f.mode)); if (mode >= 0 && mode < static_cast(FocusMode::kCount)) f.mode = static_cast(mode); - f.distanceCm = field(*focus, "distance_cm", f.distanceCm); - f.baselineMm = field(*focus, "baseline_mm", f.baselineMm); - f.minCm = field(*focus, "min_cm", f.minCm); - f.maxCm = field(*focus, "max_cm", f.maxCm); - f.speed = field(*focus, "speed", f.speed); - f.sensitivity = field(*focus, "sensitivity", f.sensitivity); - f.accuracy = field(*focus, "accuracy", f.accuracy); - f.pitchDeg = field(*focus, "pitch_deg", f.pitchDeg); - f.yawDeg = field(*focus, "yaw_deg", f.yawDeg); + f.distanceCm = number(*focus, "distance_cm", f.distanceCm); + f.baselineMm = number(*focus, "baseline_mm", f.baselineMm); + f.minCm = number(*focus, "min_cm", f.minCm); + f.maxCm = number(*focus, "max_cm", f.maxCm); + f.speed = number(*focus, "speed", f.speed); + f.sensitivity = number(*focus, "sensitivity", f.sensitivity); + f.accuracy = number(*focus, "accuracy", f.accuracy); + f.pitchDeg = number(*focus, "pitch_deg", f.pitchDeg); + f.yawDeg = number(*focus, "yaw_deg", f.yawDeg); // Through the videos.conf form, which keeps each value in its range. s.hasFocus = parseFocusToken(focusToken(f), s.focus); } if (const auto screen = j.find("screen"); screen != j.end() && screen->is_object()) { ScreenSize size; - size.distance = field(*screen, "distance_m", size.distance); - size.height = field(*screen, "height_m", size.height); - size.curve = field(*screen, "curve", size.curve); + size.distance = number(*screen, "distance_m", size.distance); + size.height = number(*screen, "height_m", size.height); + size.curve = number(*screen, "curve", size.curve); s.hasScreen = true; s.screen = size.clamped(); } @@ -266,10 +259,8 @@ bool parseSettings(const std::string& text, VideoSettings& s) { // Runs SQL without results; false (and logged) on an error. bool exec(sqlite3* db, const char* sql) { - char* error = nullptr; - if (sqlite3_exec(db, sql, nullptr, nullptr, &error) == SQLITE_OK) return true; - std::fprintf(stderr, "Library: %s\n", error ? error : sqlite3_errmsg(db)); - sqlite3_free(error); + if (sqlite::exec(db, sql)) return true; + std::fprintf(stderr, "Library: %s\n", sqlite3_errmsg(db)); return false; } diff --git a/src/library_index.cpp b/src/library_index.cpp index 76898f1..92dbb6f 100644 --- a/src/library_index.cpp +++ b/src/library_index.cpp @@ -3,6 +3,7 @@ #include "file_util.h" #include "app_dirs.h" #include "remote.h" +#include "sqlite_util.h" #include "stash_catalog.h" #include @@ -31,6 +32,9 @@ using File = LibraryIndex::File; namespace { +using sqlite::exec; +using sqlite::userVersion; + // The index is a disposable path cache, separate from playback history. constexpr int kVersion = 2; constexpr const char* kSchema = R"( @@ -71,10 +75,6 @@ std::string parentOf(const std::string& path) { return remote::isRemote(path) ? remote::parent(path) : fs::path(path).parent_path().string(); } -bool exec(sqlite3* db, const char* sql) { - return sqlite3_exec(db, sql, nullptr, nullptr, nullptr) == SQLITE_OK; -} - // Hidden folders are looked into, bins and lost+found aren't; hidden files // stay out, as the file browser leaves them out (macOS's ._ files and // .DS_Store with them). @@ -311,22 +311,13 @@ void LibraryIndex::Shared::load() { return exec(db, "PRAGMA locking_mode = EXCLUSIVE") && exec(db, "BEGIN EXCLUSIVE") && exec(db, "COMMIT"); }; - auto version = [&] { - sqlite3_stmt* st = nullptr; - int v = -1; - if (sqlite3_prepare_v2(db, "PRAGMA user_version", -1, &st, nullptr) == SQLITE_OK && - sqlite3_step(st) == SQLITE_ROW) - v = sqlite3_column_int(st, 0); - sqlite3_finalize(st); - return v; - }; if (!open()) { std::fprintf(stderr, "Library index: library_index.db not usable; kept in memory only\n"); sqlite3_close(db); db = nullptr; return; } - if (version() == 1) { + if (userVersion(db) == 1) { if (!exec(db, "BEGIN") || !exec(db, kUpgrade) || !exec(db, "PRAGMA user_version = 2") || !exec(db, "COMMIT")) { exec(db, "ROLLBACK"); @@ -336,7 +327,7 @@ void LibraryIndex::Shared::load() { return; } } - if (version() != kVersion) { + if (userVersion(db) != kVersion) { // Another layout, or not a database: made anew (it is only a cache). sqlite3_close(db); db = nullptr; diff --git a/src/main.cpp b/src/main.cpp index d148924..7022525 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,11 +2,11 @@ #include "app_dirs.h" #include "autofocus.h" #include "bluray.h" +#include "button_jobs.h" #include "direct_depth.h" #include "direct_video.h" #include "eye_resolution.h" #include "eye_targets.h" -#include "file_ops.h" #include "file_util.h" #include "first_run.h" #include "focus_marker.h" @@ -19,7 +19,6 @@ #include "hints.h" #include "video_check.h" #include "removable_drives.h" -#include "room_light.h" #include "gl_interop.h" #include "gl_util.h" #include "gpu_context.h" @@ -34,6 +33,7 @@ #include "notices.h" #include "offline.h" #include "options.h" +#include "passthrough.h" #include "performance_readout.h" #include "photo_preloader.h" #include "pixel_path.h" @@ -41,9 +41,11 @@ #include "presets.h" #include "refresh_rate.h" #include "decoder_holders.h" +#include "deletion.h" #include "diagnostics.h" #include "release_update.h" #include "run_log.h" +#include "running_video.h" #include "scene_renderer.h" #include "screen_control.h" #include "see_through.h" @@ -54,10 +56,10 @@ #include "setup_placement.h" #include "remote.h" #include "stash.h" -#include "stash_delete.h" #include "media_server.h" #include "stash_http.h" #include "stash_stream.h" +#include "stick_seek.h" #include "strings.h" #include "subtitle_overlay.h" #include "thumbnailer.h" @@ -92,7 +94,6 @@ #include #include #include -#include #include #include #include @@ -110,25 +111,8 @@ constexpr float kSurroundSubtitleDistance = 2.5f; constexpr float kSurroundSubtitleWidth = 2.0f; constexpr float kSurroundSubtitleDrop = 0.55f; constexpr float kTurnStep = kPi / 6; // 30 degrees per A or D press -// The buttons' Zoom in and out: a press steps the Zoom (180°/360°) setting -// as the menu's slider does; held past kZoomDelay, it goes on at kZoomRate -// until let go. -constexpr double kZoomDelay = 0.4; // seconds -constexpr double kZoomRate = 40; // percent a second // The viewpoint's and opacity's overlay stays this long after its gesture lets go. constexpr double kValueShown = 1.5; -// ... and the seek bar a held seek shows with the menu closed. -constexpr double kSeekBarLinger = 0.6; -// The stick's seeks stop this far before the end: a seek into it would end -// the video (and open the menu). -constexpr double kSeekEndMargin = 5.0; -// While a seek is held, the paused video shows the picture at the target at -// most this often, once the last one is shown and the target has moved on -// this far (each is a decoder restart on the Frame, about 250 ms). -constexpr double kHeldPictureEvery = 0.5; // seconds -constexpr double kHeldPictureMove = 1.0; // seconds of video -// Passthrough switched on by itself says so this long. -constexpr double kPassthroughNoticeShown = 5.0; // A microSD card or USB drive put in says so this long. constexpr double kDriveNoticeShown = 5.0; // Dragging the picture with the trigger: a smoothed copy of the hand's turn @@ -139,13 +123,6 @@ constexpr double kDragMaxStep = 0.1; // seconds struct App { VideoPlayer* player = nullptr; - std::string currentFile; - std::string streamOshash; // a Stash stream playing: its file's oshash as opened - ScreenPlacement screen; - VideoFormat format; - bool formatChosenByUser = false; // stops auto-detection from overriding the user - bool rememberFormat = false; // the user changed the format by key: store it - VideoSettings video; // what is remembered about the running video int slideshowSeconds = 0; // photos: show the next one after this long; 0 = off double nextSlideAt = 0; // glfwGetTime() when it does // Picking the background key's colour (MenuCommand::PickKeyColour): the @@ -156,13 +133,6 @@ struct App { float keyPickUv[2] = {}, keyPickPart[4] = {}; KeyPickNote keyPickNote = KeyPickNote::None; double recenterAt = 0; // glfwGetTime() of a recenter counting down; 0 = none - // Settings (VideoSettings::Part) of the running video changed in a run of - // small steps (a slider, a held stick, a drag), stored at glfwGetTime() - // saveAt; 0 = none waiting. - unsigned unsavedParts = 0; - double saveAt = 0; - bool screenChanged = false; // by key: keep the flat screen's new size - bool flipVideo = false; }; std::string utf8(unsigned int codepoint) { @@ -225,12 +195,6 @@ void printControls() { " Esc Esc quit (press twice)\n\n"); } -void printFormat(const VideoFormat& f, const char* reason) { - std::printf("Format (%s): %s, %s%s%s\n", reason, projectionName(f.projection), stereoName(f.stereo), - f.packing != Packing::Auto ? ", packing " : "", - f.packing != Packing::Auto ? packingName(f.packing) : ""); -} - // Text from the desktop clipboard, on one line. std::string clipboardText(GLFWwindow* window) { const char* clip = glfwGetClipboardString(window); @@ -245,6 +209,7 @@ std::string clipboardText(GLFWwindow* window) { // the running video change it at once. struct KeyboardInput { App& app; + RunningVideo& running; bool recenter = false; bool togglePassthrough = false; // T key; handled where the settings are bool toggleMenu = false; @@ -294,7 +259,7 @@ void KeyboardInput::onKey(GLFWwindow* window, int key, int action, int mods) { if (action != GLFW_PRESS) return; VideoPlayer& player = *app.player; - ScreenPlacement& screen = app.screen; + ScreenPlacement& screen = running.screen; switch (key) { case GLFW_KEY_ESCAPE: { // Quitting takes two presses, so a stray Esc doesn't end the video. @@ -313,34 +278,34 @@ void KeyboardInput::onKey(GLFWwindow* window, int key, int action, int mods) { case GLFW_KEY_DOWN: videoStep = -1; break; case GLFW_KEY_M: player.command("cycle mute"); break; case GLFW_KEY_P: - app.format.projection = nextProjection(app.format.projection); - app.rememberFormat = true; - printFormat(app.format, "manual"); + running.format.projection = nextProjection(running.format.projection); + running.rememberFormat = true; + printFormat(running.format, "manual"); break; case GLFW_KEY_L: - app.format.stereo = nextStereo(app.format.stereo); - app.rememberFormat = true; - printFormat(app.format, "manual"); + running.format.stereo = nextStereo(running.format.stereo); + running.rememberFormat = true; + printFormat(running.format, "manual"); break; case GLFW_KEY_C: screen.size.curve = screen.size.curve > 0 ? 0.0f : ScreenSize::kMaxCurve; - app.screenChanged = true; + running.screenChanged = true; break; case GLFW_KEY_T: togglePassthrough = true; break; case GLFW_KEY_R: recenter = true; break; case GLFW_KEY_F: - app.flipVideo = !app.flipVideo; - std::printf("Video flip: %s\n", app.flipVideo ? "on" : "off"); + running.flipVideo = !running.flipVideo; + std::printf("Video flip: %s\n", running.flipVideo ? "on" : "off"); break; case GLFW_KEY_W: case GLFW_KEY_S: screen.size.distance += key == GLFW_KEY_W ? -0.25f : 0.25f; - app.screenChanged = true; + running.screenChanged = true; break; case GLFW_KEY_Q: case GLFW_KEY_E: screen.size.height *= key == GLFW_KEY_Q ? 1 / 1.1f : 1.1f; - app.screenChanged = true; + running.screenChanged = true; break; default: break; } @@ -357,35 +322,6 @@ void KeyboardInput::onChar(unsigned int codepoint) { else if (codepoint == '-') app.player->command("add volume -5"); } -// Runs `job` on a thread of its own; dropping the future doesn't wait for it. -template -auto detached(Job job) { - std::packaged_task task(std::move(job)); - auto result = task.get_future(); - std::thread(std::move(task)).detach(); - return result; -} - -// Why the playing file couldn't be deleted, as the delete dialog says it, -// and as the run log does. -std::string deleteError(DeleteStatus status, const std::string& error) { - const DeleteStrings& t = strings().deletion; - switch (status) { - case DeleteStatus::Changed: return t.changed; - case DeleteStatus::Gone: return t.gone; - case DeleteStatus::NotAFile: return t.notAFile; - case DeleteStatus::Denied: return t.denied; - case DeleteStatus::InUse: return t.inUse; - case DeleteStatus::Offline: return t.offline; - default: return error; - } -} -const char* deleteLogged(DeleteStatus status) { - static const char* const names[] = {"deleted", "changed", "gone", "not a file", "not allowed", - "in use", "server not answering", "failed"}; - return names[static_cast(status)]; -} - // A link: a scene from Stash plays as its file does. bool isStream(const std::string& location) { return location.find("://") != std::string::npos && !remote::isRemote(location) && @@ -413,15 +349,15 @@ void catchQuitSignals() { // subtitle size, raise (percent of the picture) and distance apply. class SubtitlePlacement { public: - Mat4 update(const App& app, float frameAspect, Vec3 headPos, float headYaw, + Mat4 update(const RunningVideo& running, float frameAspect, Vec3 headPos, float headYaw, const Settings& settings) { - const ScreenPlacement& s = app.screen; + const ScreenPlacement& s = running.screen; const float scale = settings.subtitleSize / 100.0f; // 0 is where the user found them best: 30% of the picture lower than the // first placement (on the flat screen: below the picture). const float raise = (settings.subtitleRaise - 30) / 100.0f; - if (app.format.projection == Projection::Flat) { - const ScreenSurface screen(s, eyeDisplayAspect(app.format, frameAspect)); + if (running.format.projection == Projection::Flat) { + const ScreenSurface screen(s, eyeDisplayAspect(running.format, frameAspect)); const float screenH = screen.height(); const float w = screen.width() * 0.8f * scale, h = w / SubtitleOverlay::kAspect; const Vec3 local = {0.0f, -screenH / 2 + h / 2 + screenH * (0.04f + raise), @@ -766,48 +702,6 @@ int run(Options opts) { }; bool peeking = false; // Peek at the room is held: the room shows instead of the video double softwareSince = -1; // the video has played in software decoding since - // Passthrough switching itself on for videos made for it (see_through.h): - // once per video, when its size and settings are known. - // The green screen check, or the mask layer check for a video with a - // packed mask (video_check.h). - VideoCheck videoCheck; - bool passthroughSettled = false; - bool greenCheckAsked = false; // the green screen check was asked for, for this video - bool fillCheckPending = false; // ... and its fill check hasn't answered yet - double videoCheckAt = 0; // glfwGetTime() the check starts, a moment after the video opens - VideoCheck::Kind videoCheckKind = VideoCheck::Kind::GreenScreen; - std::set layersSeen; // videos whose mask's second layer MaskProbe found - const char* passthroughWhy = nullptr; // the notice's first line - double passthroughShownUntil = 0; - // The colour balance: the video's own (app.video.balance, saved with it), - // or while Match the room is on and the room is shown the room's, never - // saved: the room's light belongs to the room, not to a video. The switch - // stays as set for the run; with the room hidden (another video, passthrough - // off, Opacity at 100 %) the video's own is drawn, shown and edited until - // the room shows again. - RoomLight roomLight; - const bool roomReadable = kStandaloneHeadset && RoomLight::available(); - double roomFailedUntil = 0; // glfwGetTime() Match the room stops saying it failed - // Match the room, a switch: on, the room's reading (the run's first, or - // Read again's) times the strengths, from the video's own balance (grey - // cameras and a dark room leave the warmth and tint as they are). Moved by - // hand while on, the sliders stay as moved until the match is applied again - // (a strength, Read again). A reading is kept when it ends, but applied - // only if they were not moved by hand or reset after it was asked for. - ColourBalance roomBalance; - std::optional roomReading; // this run's latest - bool roomMatched = false; - // Hand moves while on, and Picture resets; their count when last asked. - unsigned balanceEdits = 0, roomAsked = 0; - // A new reading, unless one runs (which keeps the count it was asked with). - auto readRoom = [&] { - if (roomLight.start()) roomAsked = balanceEdits; - }; - auto applyRoomMatch = [&] { - if (roomMatched && roomReading) - roomBalance.match(roomReading->light, roomReading->colour, roomReading->white, - settings.matchColour / 100.0f, settings.matchBrightness / 100.0f); - }; // Frame rates and drops over the video: the setting's, or the command // line's for this run until the menu switches it. @@ -928,7 +822,8 @@ int run(Options opts) { App app; app.player = &player; - KeyboardInput keys{app}; + RunningVideo running{player, settings, library}; + KeyboardInput keys{app, running}; glfwSetWindowUserPointer(input, &keys); glfwSetKeyCallback(input, [](GLFWwindow* window, int key, int /*scancode*/, int action, int mods) { static_cast(glfwGetWindowUserPointer(window))->onKey(window, key, action, mods); @@ -938,38 +833,8 @@ int run(Options opts) { }); printControls(); - // Deleting the playing file (docs/alpha/delete-file.md): what the dialog - // shows, looked up in the background (a slow share must not freeze the - // headset), then the deletion, one at a time. - struct Deletion { - // The lookup's: the file's stamp (none for Stash's stream), and with - // Send to Stash on, its oshash and its scene's files as Stash has them. - struct Look { - DeleteStatus status = DeleteStatus::Ok; - FileStamp stamp; - std::string oshash; - bool asked = false; - StashFileLook stash; - }; - DeleteInfo info; - // What is deleted: the file playing, or a copy's source (with the - // copy), a scene's stream locator for one from Stash's; empty: a source - // on another Stash server. - std::string target; - FileStamp stamp; // the file's as the dialog shows it - int64_t scene = 0; // the Stash scene it is a file of; 0: none - size_t sceneFiles = 0; - std::string stashPath; // Stash's path of it; empty: not known for sure - std::string oshash; // the file's, as the lookup read it - // The oshash the file deleted must have: the download's for a copy's - // source, the one opened for a stream; empty: any (a file here). - std::string expected; - bool throughStash = false; // Stash deletes it: Send to Stash on, its file found - std::future lookup; // dropped without waiting - std::future result; - bool resume = false; // the video played when the button was pressed - int64_t copy = 0; // the download whose copy plays - } deletion; + Deletion deletion{menu, player, settings, library, libraryIndex, offline, stash}; + Passthrough passthrough{settings, library, xr, running.video, running.currentFile, running.format}; // Holding the grip on the menu moves it with the hand; the trigger off it // holds the flat screen (screenControl). struct MenuGrab { @@ -982,12 +847,6 @@ int run(Options opts) { // below, before the frames). GestureInput gestureInput; GestureInput::Host gestureHost; - // Scrub: where it takes the video, and the last picture shown on the way - // there (its target, when sent), as the stick's held seek. - struct Scrub { - bool on = false, sent = false; // ... a picture on the way - double from = 0, target = 0, picture = 0, pictureAt = 0; - } scrub; // Holding the trigger away from the menu turns the picture with the hand // (sideways, up/down and roll), for fine centring. struct TurnDrag { @@ -1039,45 +898,8 @@ int run(Options opts) { int knownWidth = 0, knownHeight = 0; TwoViews knownViews = TwoViews::No; bool formatDetected = false; // for this file: logged once, then as it changes - // The stick's seek (HeldSeek): from where, whether it paused the video, - // and whether the bar shows where it goes until the video is there. - HeldSeek heldSeek; - double heldSeekFrom = 0, heldSeekTarget = 0; - bool heldSeekPaused = false, heldSeekLanding = false; - bool heldSeekBar = false; // the strip placed for it, the menu closed - double heldSeekPicture = 0, heldSeekPictureAt = 0; // the last picture's target, when sent - double heldSeekBarUntil = 0; // ... shown after the stick let go - // Driven by a stick (not the arrow keys), it buzzes that hand: a tick each - // 10 s it goes, at most 8 a second, and a bump at the start or the end. - bool heldSeekStick = false, heldSeekAtLimit = false; - int heldSeekHand = 1; // the stick's - // The buttons' Subtitles and Opacity jobs: what they turn back on; the - // opacity, each video's last see-through value however it was set, for - // this run (by its library id, else where it is). - int64_t lastSubtitle = 0; - std::unordered_map lastSeeThrough; - std::string seeThroughFile; - int seeThroughSeen = 100; - auto seeThroughKey = [&] { - const VideoRecord r = library.record(app.currentFile); - return r.known() ? "#" + std::to_string(r.id) : app.currentFile; - }; - // Zoom in or out held: by which hand (-1 none), since when, and how far - // it has gone, on which file. It is stored once, when let go. - struct ZoomHold { - Job job = Job::None; - int hand = -1; - double start = 0, at = 0; - std::string file; - } zoomHold; - auto zoomBy = [&](double percent) { - app.video.zoom = std::clamp(app.video.zoom + static_cast(percent / 100), - VideoSettings::kMinZoomPercent / 100.0f, - VideoSettings::kMaxZoomPercent / 100.0f); - app.screen.zoom = app.video.zoom; - app.unsavedParts |= VideoSettings::kZoom; // stored with the rest if the video changes first - }; - double heldSeekTens = 0, heldSeekTickAt = 0; + StickSeek stickSeek{player, panel}; + ButtonJobs buttonJobs{player, running, settings, library}; HoldRepeat turnLeft(0.5, 0.35), turnRight(0.5, 0.35); // A and D // The controllers' buttons as jobs (controls.h), by each hand's type; the // bindings Your controllers and the hints show, made again when the @@ -1160,7 +982,7 @@ int run(Options opts) { auto startShuffle = [&] { shuffleSeed = (static_cast(seedSource()) << 32 | seedSource()) | 1; playStart = openedAs; - playStartFile = app.currentFile; + playStartFile = running.currentFile; }; // mpv starts a repeated video over by itself; it never reaches its end. auto applyAfterVideo = [&] { @@ -1183,92 +1005,12 @@ int run(Options opts) { resumeSaveAt = glfwGetTime() + 60; if (point == resumeSaved) return; resumeSaved = point; - library.setResume(app.currentFile, point); + library.setResume(running.currentFile, point); }; auto keepResume = [&] { saveResume(); videoOpened = false; }; - // Stores these parts (VideoSettings::Part) of the running video's - // settings: only what the user changed, so the rest of a record still - // being found stays as it is. - auto storeVideo = [&](unsigned parts) { library.setSettings(app.currentFile, app.video, parts); }; - // Keeps the volume for all videos, as mpv reports it: a second after it - // changes, so at most once a second while it keeps changing. Not before - // mpv has reported the one set at start, so its default can't overwrite it. - bool volumeApplied = false; - double volumeSaveAt = 0; - auto keepVolume = [&] { - volumeSaveAt = 0; - const int volume = static_cast(std::lround(player.playback().volume)); - if (!volumeApplied || volume == settings.volume) return; - settings.volume = volume; - saveSettings(settings); - }; - // Stores these parts soon, with whatever else changes meanwhile: at most - // twice a second while they keep changing. - auto storeVideoSoon = [&](unsigned parts) { - app.unsavedParts |= parts; - if (app.saveAt == 0) app.saveAt = glfwGetTime() + 0.5; - }; - // Stores what storeVideoSoon() still holds back. - auto saveUnsaved = [&] { - // A zoom being held: in whole percents, as when let go. - if (app.unsavedParts & VideoSettings::kZoom) { - app.video.zoom = std::round(app.video.zoom * 100) / 100; - app.screen.zoom = app.video.zoom; - } - // The screen's size is a setting for all videos (kScreen only marks it). - if (const unsigned parts = app.unsavedParts & ~VideoSettings::kScreen) storeVideo(parts); - if (app.unsavedParts & VideoSettings::kScreen) saveSettings(settings); // settings.screen - app.unsavedParts = 0; - app.saveAt = 0; - }; - // The flat screen's size was changed: for all videos. - auto keepScreenSize = [&] { - app.screen.size = app.screen.size.clamped(); - settings.screen = app.screen.size; - storeVideoSoon(VideoSettings::kScreen); - }; - // Passthrough switched on for a video made for it, saying so the first time ever. - auto passthroughByItself = [&](AutoPassthrough why) { - if (why == AutoPassthrough::None || app.video.passthrough) return; - app.video.passthrough = true; - if (why != AutoPassthrough::Mask && app.video.greenScreen.isDefault(app.video.colourKeyed())) - app.video.greenScreen.on = true; - const AutoPassthroughStrings& t = strings().autoPassthrough; - passthroughWhy = why == AutoPassthrough::Mask ? t.mask - : why == AutoPassthrough::Fill ? t.fill - : t.greenScreen; - if (!settings.passthroughNoticeSeen) { - passthroughShownUntil = glfwGetTime() + kPassthroughNoticeShown; - settings.passthroughNoticeSeen = true; - saveSettings(settings); - } - std::printf("Passthrough: on by itself (%s)\n", - why == AutoPassthrough::Mask ? "mask" - : why == AutoPassthrough::Fill ? "flat background" - : "green screen"); - }; // Puts the running video's remembered settings into effect. - auto applyVideoSettings = [&] { - if (app.video.hasFormat) { - app.format = app.video.format; - app.formatChosenByUser = true; - printFormat(app.format, "remembered"); - } - app.screen.zoom = app.video.zoom; - app.screen.size = settings.screen; - player.setPicture(app.video.brightness, app.video.contrast, app.video.saturation); - player.setTvGamma(settings.tvGamma); - }; - // Playback moves on (another video, or none): a delete dialog still - // asking goes, with its lookup, so its confirm can't act on what came - // next. One confirmed (Deleting) stays. - auto dropDeleteDialog = [&] { - deletion.lookup = {}; - deletion.resume = false; - menu.cancelDelete(); - }; // Opens a video with what is remembered about it. True if its format was // remembered. auto openVideo = [&](const std::string& requested) { @@ -1292,42 +1034,38 @@ int run(Options opts) { neighbor = {}; nextPhoto = {}; neighborStep = 0; - saveUnsaved(); + running.saveUnsaved(); keepResume(); - dropDeleteDialog(); - app.currentFile = path; - app.streamOshash = isStashScene(path) ? oshash : std::string(); + deletion.dropDialog(); + running.currentFile = path; + running.streamOshash = isStashScene(path) ? oshash : std::string(); scripts.open(isPhotoFile(path) ? std::string() : path); - app.formatChosenByUser = false; - app.format = guessVideoFormat(path, 0, 0); + running.formatChosenByUser = false; + running.format = guessVideoFormat(path, 0, 0); // Its settings from the library, else as kept before it (videos.conf), // which the library takes over. A file the library doesn't know yet may // be a moved one with settings of its own: they apply once it is found. - app.video = VideoSettings{}; + running.video = VideoSettings{}; openingRecord = library.record(path).id; if (!isPhotoFile(path)) library.open(path); awaitingRecord = library.available() && !library.known(path); - if (!library.settings(path, app.video)) { + if (!library.settings(path, running.video)) { VideoSettings legacy; if (memory.get(path, legacy)) { // Queue the fallback before user edits can create settings. A known // path must still resolve to the same identity before it can use it. library.carryOverSettings(path, legacy, awaitingRecord ? openingRecord : 0); - if (!openingRecord || !awaitingRecord) app.video = legacy; + if (!openingRecord || !awaitingRecord) running.video = legacy; } } awaitingResume = awaitingRecord && settings.resume && !isStream(path) && !isPhotoFile(path); resolvedResume = -1; - passthroughSettled = false; - greenCheckAsked = false; - fillCheckPending = false; - videoCheckAt = 0; - passthroughShownUntil = 0; + passthrough.videoChanged(isStream(path)); gestureInput.cancel(gestureHost); // a twist under way was the last video's gestureInput.hide(); controlInput.dropFileTaps(); // ... and a press waiting to skip or stop it opacityShownUntil = 0; - applyVideoSettings(); + running.applyVideoSettings(); knownWidth = knownHeight = 0; // re-detect the format once the size is known knownViews = TwoViews::No; formatDetected = false; @@ -1348,8 +1086,7 @@ int run(Options opts) { start = resumePoint(r.resumeSeconds, r.durationSeconds); } player.command("set pause no"); - heldSeek.cancel(); - heldSeekPaused = heldSeekLanding = heldSeekBar = false; + stickSeek.cancel(); player.load(path, std::max(0.0, start)); if (start > 0) std::printf("Resuming at %s\n", clockTime(start).c_str()); } @@ -1358,24 +1095,23 @@ int run(Options opts) { // pointed at then comes about 0.4 s sooner over a LAN. seekPreview.videoChanged(path, isStream(path) || isStashScene(path)); app.nextSlideAt = glfwGetTime() + app.slideshowSeconds; // each photo gets its full time - return app.video.hasFormat; + return running.video.hasFormat; }; // Closes the running video or photo and leaves the scene empty, keeping // where it was left as switching to another would. auto closeVideo = [&] { - if (app.currentFile.empty()) return; - dropDeleteDialog(); - saveUnsaved(); + if (running.currentFile.empty()) return; + deletion.dropDialog(); + running.saveUnsaved(); keepResume(); player.stop(); - heldSeek.cancel(); - heldSeekPaused = heldSeekLanding = heldSeekBar = false; + stickSeek.cancel(); seekPreview.close(); - app.currentFile.clear(); - app.streamOshash.clear(); + running.currentFile.clear(); + running.streamOshash.clear(); scripts.open({}); - app.video.passthrough = false; - app.video.opacity = 100; // the empty scene isn't blended; the video keeps its saved value + running.video.passthrough = false; + running.video.opacity = 100; // the empty scene isn't blended; the video keeps its saved value gestureInput.cancel(gestureHost); gestureInput.hide(); controlInput.dropFileTaps(); @@ -1386,20 +1122,13 @@ int run(Options opts) { awaitingRecord = false; awaitingResume = false; }; + deletion.closeVideo = closeVideo; // Stores the current format for this video (after the user chose it). auto rememberFormat = [&] { - app.formatChosenByUser = true; - app.video.hasFormat = true; - app.video.format = app.format; - storeVideo(VideoSettings::kFormat); - }; - // At once, also while a slider is held (mpv takes them asynchronously, - // direct frames recompute their colour matrix); stored soon, not per step. - auto applyPicture = [&](unsigned parts) { - if (parts != VideoSettings::kZoom) - player.setPicture(app.video.brightness, app.video.contrast, app.video.saturation); - app.screen.zoom = app.video.zoom; - storeVideoSoon(parts); + running.formatChosenByUser = true; + running.video.hasFormat = true; + running.video.format = running.format; + running.storeVideo(VideoSettings::kFormat); }; // A Stash scene given on the command line opens once Stash's catalog is there. std::string startScene = isStashScene(opts.file) ? opts.file : ""; @@ -1411,18 +1140,18 @@ int run(Options opts) { auto stepVideo = [&](int step, bool atEnd = false) { const bool replaced = endStep; // Previous or Next pressed while an end's step is under way endStep = false; - if (app.currentFile.empty()) return; - if (isStream(app.currentFile)) { + if (running.currentFile.empty()) return; + if (isStream(running.currentFile)) { say(strings().jobs.notForStreams); return; } - const bool shuffle = afterVideo() == AfterVideo::Shuffle && !isPhotoFile(app.currentFile); + const bool shuffle = afterVideo() == AfterVideo::Shuffle && !isPhotoFile(running.currentFile); // Opened from a list in the menu (Stash's scenes): through that list. std::string next; if (!menu.listNeighbor(openedAs, step, next, {shuffle ? shuffleSeed : 0, playStart})) { neighborStep = neighbor.valid() && !neighborWrap && !replaced ? neighborStep + step : step; neighborWrap = false; - neighbor = mediaNeighbor(app.currentFile, neighborStep, false, + neighbor = mediaNeighbor(running.currentFile, neighborStep, false, {shuffle ? shuffleSeed : 0, playStartFile}); endStep = atEnd; endStepRestarts = player.counts().restarts; @@ -1458,15 +1187,7 @@ int run(Options opts) { settings.performancePreset = presets.matching(settings); userPresetShown = presets.shownUserPreset(userPresets, settings, pickedUserPreset); }; - // Sharpen changed in a run of steps (its slider, a twist): matched and - // saved half a second after the first, at most twice a second. 0 = none. - double sharpenSaveAt = 0; - auto keepSharpen = [&] { - if (sharpenSaveAt == 0) return; - sharpenSaveAt = 0; - matchPreset(); - saveSettings(settings); - }; + running.matchPreset = matchPreset; auto applyPendingResolution = [&] { const int value = pendingResolution; pendingResolution = 0; @@ -1588,13 +1309,6 @@ int run(Options opts) { app.keyPickNote = KeyPickNote::None; }; - // The eye images are blended over the room (the headset's cameras, where - // the runtime blends): with passthrough on, or Opacity below 100, with or - // without passthrough (whose mask or key it doesn't bring). Match the room - // applies only then. - auto roomShown = [&] { - return xr.alphaBlendSupported() && (app.video.passthrough || app.video.opacity < 100); - }; // A PC whose runtime doesn't blend, with the setting on: passthrough draws // the room in key green, for a streamer that keys it out on the headset. auto roomKeyed = [&] { @@ -1632,82 +1346,60 @@ int run(Options opts) { case MenuCommand::PreviousVideo: stepVideo(-1); break; case MenuCommand::NextVideo: stepVideo(1); break; case MenuCommand::SetProjection: - app.format.projection = static_cast(static_cast(c.value)); + running.format.projection = static_cast(static_cast(c.value)); rememberFormat(); - printFormat(app.format, "manual"); + printFormat(running.format, "manual"); break; case MenuCommand::SetStereo: - app.format.stereo = static_cast(static_cast(c.value)); + running.format.stereo = static_cast(static_cast(c.value)); rememberFormat(); - printFormat(app.format, "manual"); + printFormat(running.format, "manual"); break; case MenuCommand::SetPacking: - app.format.packing = static_cast(static_cast(c.value)); + running.format.packing = static_cast(static_cast(c.value)); rememberFormat(); - printFormat(app.format, "manual"); + printFormat(running.format, "manual"); break; case MenuCommand::SetBrightness: - app.video.brightness = static_cast(c.value); - applyPicture(VideoSettings::kBrightness); + running.video.brightness = static_cast(c.value); + running.applyPicture(VideoSettings::kBrightness); break; case MenuCommand::SetContrast: - app.video.contrast = static_cast(c.value); - applyPicture(VideoSettings::kContrast); + running.video.contrast = static_cast(c.value); + running.applyPicture(VideoSettings::kContrast); break; case MenuCommand::SetSaturation: - app.video.saturation = static_cast(c.value); - applyPicture(VideoSettings::kSaturation); + running.video.saturation = static_cast(c.value); + running.applyPicture(VideoSettings::kSaturation); break; case MenuCommand::SetWarmth: // the colour balance: applied while drawing case MenuCommand::SetTint: - case MenuCommand::SetExposure: { - // The video's, saved, or while the room's is matched the room's, not. - const bool matching = roomMatched && roomShown(); - ColourBalance& balance = matching ? roomBalance : app.video.balance; - const int value = std::clamp(static_cast(c.value), -100, 100); - // Each its own part, as brightness etc.: an edit before the video's - // record is found leaves the other two as saved. - const bool warmth = c.type == MenuCommand::SetWarmth, tint = c.type == MenuCommand::SetTint; - (warmth ? balance.warmth : tint ? balance.tint : balance.exposure) = value; - if (matching) ++balanceEdits; - else - storeVideoSoon(warmth ? VideoSettings::kWarmth - : tint ? VideoSettings::kTint - : VideoSettings::kExposure); + case MenuCommand::SetExposure: + if (const unsigned part = passthrough.setBalance(c)) running.storeVideoSoon(part); break; - } case MenuCommand::ToggleMatchRoom: // off: the video's own balance again - if (!roomShown()) break; // the switch is disabled while the room is hidden - roomFailedUntil = 0; - roomMatched = !roomMatched; - if (roomMatched) { - roomBalance = app.video.balance; - roomAsked = balanceEdits; // a reading still under way is for this one - if (roomReading) applyRoomMatch(); - else readRoom(); - } + passthrough.toggle(); break; case MenuCommand::ReadRoomAgain: - roomFailedUntil = 0; - if (roomMatched && roomShown()) readRoom(); + passthrough.readAgain(); break; case MenuCommand::SetMatchColour: settings.matchColour = std::clamp(static_cast(c.value), 0, 100); saveSettings(settings); - applyRoomMatch(); + passthrough.applyRoomMatch(); break; case MenuCommand::SetMatchBrightness: settings.matchBrightness = std::clamp(static_cast(c.value), 0, 100); saveSettings(settings); - applyRoomMatch(); + passthrough.applyRoomMatch(); break; case MenuCommand::SetOpacity: // applied while drawing - app.video.opacity = static_cast(c.value); - storeVideoSoon(VideoSettings::kOpacity); + running.video.opacity = static_cast(c.value); + running.storeVideoSoon(VideoSettings::kOpacity); break; case MenuCommand::SetZoom: - app.video.zoom = static_cast(c.value / 100.0); - applyPicture(VideoSettings::kZoom); + running.video.zoom = static_cast(c.value / 100.0); + running.applyPicture(VideoSettings::kZoom); break; case MenuCommand::ToggleTvGamma: settings.tvGamma = !settings.tvGamma; @@ -1716,21 +1408,18 @@ int run(Options opts) { saveSettings(settings); break; case MenuCommand::ResetPicture: - app.video.brightness = app.video.contrast = app.video.saturation = 0; - app.video.balance = {}; - if (roomShown()) { // a hidden room keeps its switch for when it shows again - roomMatched = false; - ++balanceEdits; - } - app.video.zoom = 1.0f; - app.video.originForward = 0; - applyPicture(VideoSettings::kPicture | VideoSettings::kOrigin); + running.video.brightness = running.video.contrast = running.video.saturation = 0; + running.video.balance = {}; + passthrough.pictureReset(); + running.video.zoom = 1.0f; + running.video.originForward = 0; + running.applyPicture(VideoSettings::kPicture | VideoSettings::kOrigin); break; case MenuCommand::SetOriginForward: - app.video.originForward = std::clamp(static_cast(c.value / 100.0), + running.video.originForward = std::clamp(static_cast(c.value / 100.0), -VideoSettings::kMaxOriginForward, VideoSettings::kMaxOriginForward); - storeVideoSoon(VideoSettings::kOrigin); + running.storeVideoSoon(VideoSettings::kOrigin); break; case MenuCommand::Paste: menu.typeText(clipboardText(input)); break; case MenuCommand::SetSlideshow: @@ -1741,16 +1430,16 @@ int run(Options opts) { case MenuCommand::SetScreenDistance: case MenuCommand::SetScreenHeight: case MenuCommand::SetScreenCurve: { - ScreenSize& size = app.screen.size; + ScreenSize& size = running.screen.size; (c.type == MenuCommand::SetScreenDistance ? size.distance : c.type == MenuCommand::SetScreenHeight ? size.height : size.curve) = static_cast(c.value / 100); - keepScreenSize(); + running.keepScreenSize(); break; } case MenuCommand::ResetScreen: - app.screen.size = settings.screen = ScreenSize{}; - storeVideoSoon(VideoSettings::kScreen); + running.screen.size = settings.screen = ScreenSize{}; + running.storeVideoSoon(VideoSettings::kScreen); break; case MenuCommand::Recenter: // From the menu: two seconds to look where "front" should be. @@ -1759,12 +1448,12 @@ int run(Options opts) { case MenuCommand::ToggleAutoPassthrough: settings.autoPassthrough = !settings.autoPassthrough; saveSettings(settings); - passthroughSettled = false; // for the video playing too + passthrough.resettle(); // for the video playing too break; case MenuCommand::ToggleKeyGreen: settings.keyGreen = !settings.keyGreen; saveSettings(settings); - passthroughSettled = false; // Automatic passthrough, for the video playing + passthrough.resettle(); // Automatic passthrough, for the video playing break; case MenuCommand::ToggleVideoMipmaps: settings.videoMipmaps = !settings.videoMipmaps; @@ -1922,7 +1611,7 @@ int run(Options opts) { case MenuCommand::SetSharpen: settings.sharpen = std::clamp(static_cast(c.value), 0, 300); player.setSharpened(settings.sharpen > 0); - if (sharpenSaveAt == 0) sharpenSaveAt = glfwGetTime() + 0.5; + running.keepSharpenSoon(); break; case MenuCommand::ToggleToneLook: settings.toneLook = !settings.toneLook; @@ -2035,18 +1724,18 @@ int run(Options opts) { break; case MenuCommand::TogglePackedMask: { // Nothing is stored when the choice is what the name says. - const bool on = !packedMask(app.currentFile, app.video); - app.video.packedMask = on == hasPackedAlpha(app.currentFile) ? std::nullopt + const bool on = !packedMask(running.currentFile, running.video); + running.video.packedMask = on == hasPackedAlpha(running.currentFile) ? std::nullopt : std::optional(on); - storeVideo(VideoSettings::kPackedMask); + running.storeVideo(VideoSettings::kPackedMask); std::printf("Passthrough: mask in the video %s\n", on ? "on" : "off"); break; } case MenuCommand::ToggleSecondLayer: - app.video.secondLayerHidden = !app.video.secondLayerHidden; - storeVideo(VideoSettings::kSecondLayer); + running.video.secondLayerHidden = !running.video.secondLayerHidden; + running.storeVideo(VideoSettings::kSecondLayer); std::printf("Passthrough: the mask's second layer %s\n", - app.video.secondLayerHidden ? "hidden" : "shown"); + running.video.secondLayerHidden ? "hidden" : "shown"); break; case MenuCommand::ToggleGreenScreen: case MenuCommand::SetKeyStrength: @@ -2054,9 +1743,9 @@ int run(Options opts) { case MenuCommand::SetKeySpill: case MenuCommand::SetKeyShrink: case MenuCommand::SetKeyBackground: { - GreenScreen& key = app.video.greenScreen; + GreenScreen& key = running.video.greenScreen; const int value = static_cast(c.value); - KeySliders& sliders = app.video.keySliders(); + KeySliders& sliders = running.video.keySliders(); if (c.type == MenuCommand::ToggleGreenScreen) key.on = !key.on; else if (c.type == MenuCommand::SetKeyBackground) key.source = value == static_cast(KeySource::GreenScreen) ? KeySource::GreenScreen @@ -2065,15 +1754,15 @@ int run(Options opts) { else if (c.type == MenuCommand::SetKeySoftness) sliders.softness = value; else if (c.type == MenuCommand::SetKeyShrink) sliders.shrink = value; else sliders.spill = value; - storeVideoSoon(VideoSettings::kGreenScreen); + running.storeVideoSoon(VideoSettings::kGreenScreen); break; } case MenuCommand::PickKeyColour: // Where the key is used: passthrough on a surround video, without its own mask. - if (app.video.passthrough && app.video.greenScreen.on && !app.currentFile.empty() && - app.format.projection != Projection::Flat && - !(packedMask(app.currentFile, app.video) && maskFormat(app.format))) { - app.keyPickFor = app.currentFile; + if (running.video.passthrough && running.video.greenScreen.on && !running.currentFile.empty() && + running.format.projection != Projection::Flat && + !(packedMask(running.currentFile, running.video) && maskFormat(running.format))) { + app.keyPickFor = running.currentFile; app.keyPickNote = KeyPickNote::None; std::printf("Background key: pick a colour\n"); } @@ -2085,21 +1774,15 @@ int run(Options opts) { // What the group shows: the key's sliders only while the green // screen is on (passthrough on, not the video's own mask) and removes // something, Match the room's strengths only while it is on. - if (roomReadable && roomMatched && roomShown()) { - const Settings defaults; - settings.matchColour = defaults.matchColour; - settings.matchBrightness = defaults.matchBrightness; - saveSettings(settings); - applyRoomMatch(); - } + passthrough.resetMatch(); unsigned parts = VideoSettings::kOpacity; - const bool own = packedMask(app.currentFile, app.video) && maskFormat(app.format); - if (app.video.passthrough && app.video.greenScreen.on && !own && app.video.keyRemoves()) { - app.video.keySliders() = GreenScreen().sliders(app.video.colourKeyed()); + const bool own = packedMask(running.currentFile, running.video) && maskFormat(running.format); + if (running.video.passthrough && running.video.greenScreen.on && !own && running.video.keyRemoves()) { + running.video.keySliders() = GreenScreen().sliders(running.video.colourKeyed()); parts |= VideoSettings::kGreenScreen; } - app.video.opacity = 100; - storeVideoSoon(parts); + running.video.opacity = 100; + running.storeVideoSoon(parts); break; } case MenuCommand::SetSubtitleSize: @@ -2113,12 +1796,12 @@ int run(Options opts) { player.setSubtitleStyle(settings.subtitleSize / 100.0, settings.subtitleRaise); break; case MenuCommand::SetFocus: - if (applyFocusControl(static_cast(c.option), c.value, app.video.hasFocus, - app.video.focus, settings.focus, settings.focusPrefs)) { + if (applyFocusControl(static_cast(c.option), c.value, running.video.hasFocus, + running.video.focus, settings.focus, settings.focusPrefs)) { matchPreset(); // a user's preset keeps the focus defaults saveSettings(settings); } - storeVideo(VideoSettings::kFocus); + running.storeVideo(VideoSettings::kFocus); break; case MenuCommand::Quit: keys.quit = true; break; case MenuCommand::OpenFile: @@ -2155,133 +1838,11 @@ int run(Options opts) { : "set sid no"); break; case MenuCommand::LoadSubtitle: player.addSubtitle(c.path); break; - case MenuCommand::RequestDelete: { - // The dialog is open; the video pauses meanwhile, a slideshow stops. - if (c.path != app.currentFile) { // it changed meanwhile - menu.cancelDelete(); - break; - } - if (deletion.result.valid()) break; - deletion.info = {}; - deletion.info.file = c.path; - deletion.info.name = std::filesystem::path(c.path).filename().string(); - deletion.info.photo = isPhotoFile(c.path); - deletion.expected.clear(); - // A downloaded copy plays instead of its source (openVideo). - if (const Offline::Download* d = offline.find(c.path); - d && d->state == Offline::State::Done && d->present && d->path == c.path) { - deletion.info.source = d->source; - deletion.info.copyRoot = d->root; - deletion.info.size = d->size; - deletion.copy = d->id; - deletion.expected = d->oshash; - } - const std::string& source = deletion.info.source; - deletion.target = source.empty() ? c.path - : isStashSource(source) ? stashSourceLocator(source) - : source; - const bool stream = isStashScene(deletion.target); - if (stream && source.empty()) deletion.expected = app.streamOshash; - // A Stash scene's file, at the scene's location (a file here or its - // stream), never by oshash alone. - deletion.scene = 0; - deletion.sceneFiles = 0; - deletion.stashPath.clear(); - deletion.oshash.clear(); - deletion.throughStash = false; - if (const auto catalog = stash ? stash->catalog() : nullptr; catalog && !deletion.target.empty()) - if (const int i = stashSceneAt(*catalog, deletion.target); i >= 0) { - const StashScene& s = catalog->scenes()[i]; - deletion.scene = s.id; - deletion.sceneFiles = s.oshashes.size(); - deletion.stashPath = stashFilePathAt(*catalog, deletion.target); - if (isStashScene(deletion.target) && source.empty()) deletion.info.size = s.size; - } - deletion.resume = !deletion.info.photo && !player.playback().paused; - if (deletion.resume) player.command("set pause yes"); - app.slideshowSeconds = 0; - deletion.lookup = detached([file = deletion.target, stream, check = stream || !source.empty(), - expected = deletion.expected, - ask = settings.stash.writeBack && deletion.scene != 0 && - mediaServer(settings.stash.kind).abilities().deleteFiles, - scene = deletion.scene, stashPath = deletion.stashPath, - url = settings.stash.url, key = settings.stash.apiKey, - unverified = settings.stash.unverified()] { - Deletion::Look r; - if (file.empty()) - r.status = DeleteStatus::Gone; - else if (!stream) - r.status = stampOf(file, r.stamp); - if (r.status != DeleteStatus::Ok || (!ask && !check)) return r; - r.oshash = stream ? expected : fingerprintFile(file).oshash; - // A copy's source still the video downloaded; a stream the one - // opened (Stash's fresh query below matches it). - if (check && (r.oshash.empty() || r.oshash != expected)) r.status = DeleteStatus::Changed; - if (r.status != DeleteStatus::Ok || !ask || r.oshash.empty()) return r; - r.asked = true; - r.stash = lookUpStashFile(url, key, unverified, scene, r.oshash, stashPath); - return r; - }); - break; - } - case MenuCommand::CancelDelete: - deletion.lookup = {}; - if (deletion.resume && app.currentFile == deletion.info.file) player.command("set pause no"); - deletion.resume = false; - break; - case MenuCommand::DeleteFile: { - // Only the file the dialog showed, as it showed it. - if (!deletion.info.ready || c.path != deletion.info.file || c.path != app.currentFile || - deletion.result.valid()) - break; - deletion.resume = false; - const std::string target = deletion.target; - // Stash deletes it only with Send to Stash on still; its stream - // only through Stash; a copy's source only if it is still the - // video downloaded. - const bool throughStash = deletion.throughStash && settings.stash.writeBack; - if (c.value == 0 && (target.empty() || (isStashScene(target) && !throughStash) || - (!deletion.info.source.empty() && !deletion.info.sourceFound))) { - menu.showDeleteError(deleteError(DeleteStatus::Denied, std::string())); - break; - } - // The player, the seek preview and a download from it let go of it. - const std::string from = isStashScene(target) ? stashSource(target) : target; - if (const Offline::Download* d = offline.find(from); - d && d->source == from && d->state != Offline::State::Done) - offline.cancel(d->id); - closeVideo(); - if (c.value > 0) { // only the downloaded copy - offline.remove(deletion.copy); - library.forgetFile(c.path); - libraryIndex.deleted(c.path); - std::printf("Delete: a downloaded copy: deleted\n"); - menu.deleteEnded(std::string()); - break; - } - deletion.throughStash = throughStash; - deletion.result = std::async(std::launch::async, [target, stamp = deletion.stamp, throughStash, - writeBack = settings.stash.writeBack, - url = settings.stash.url, - key = settings.stash.apiKey, - unverified = settings.stash.unverified(), - scene = deletion.scene, - stashPath = deletion.stashPath, - oshash = deletion.oshash, - trash = deletion.info.stashTrash] { - const bool here = !isStashScene(target); - DeleteOutcome r; - if (throughStash) - r = deleteThroughStash(url, key, unverified, writeBack, scene, oshash, stashPath, - here ? target : std::string(), stamp, trash); - else - r.status = removeFile(target, stamp, r.error); - if (r.status == DeleteStatus::Ok && here) - dropThumbnail(target, stamp.size, stamp.modified, stamp.nanos); - return r; - }); + case MenuCommand::RequestDelete: + if (deletion.request(c, running.currentFile, running.streamOshash)) app.slideshowSeconds = 0; break; - } + case MenuCommand::CancelDelete: deletion.cancel(running.currentFile); break; + case MenuCommand::DeleteFile: deletion.confirm(c, running.currentFile); break; case MenuCommand::UseServer: // None (-1), or a kind's own setup in use and on: the one it // replaces is kept as it was left. @@ -2418,7 +1979,7 @@ int run(Options opts) { gestureHost.why = [&](GestureValue v) -> const char* { using V = GestureValue; const JobStrings& said = strings().jobs; - const bool open = !app.currentFile.empty(), photo = isPhotoFile(app.currentFile); + const bool open = !running.currentFile.empty(), photo = isPhotoFile(running.currentFile); switch (gestureValueInfo(v).where) { case GestureWhere::Anywhere: break; case GestureWhere::File: @@ -2430,11 +1991,11 @@ int run(Options opts) { break; case GestureWhere::Surround: if (!open) return said.nothingOpen; - if (app.format.projection == Projection::Flat) return said.notForFlat; + if (running.format.projection == Projection::Flat) return said.notForFlat; break; case GestureWhere::Flat: if (!open) return said.nothingOpen; - if (app.format.projection != Projection::Flat) return said.flatOnly; + if (running.format.projection != Projection::Flat) return said.flatOnly; break; } switch (v) { @@ -2445,28 +2006,28 @@ int run(Options opts) { case V::MatchBrightness: case V::MatchColour: // Where the menu shows them: Match the room on, the room shown. - if (!roomReadable) return said.notOnHeadset; - if (!roomShown()) return said.needsPassthrough; - if (!roomMatched) return strings().gestures.needsMatchRoom; + if (!passthrough.roomReadable) return said.notOnHeadset; + if (!passthrough.roomShown()) return said.needsPassthrough; + if (!passthrough.matched()) return strings().gestures.needsMatchRoom; break; case V::KeyStrength: case V::KeyEdges: case V::KeySpill: case V::KeyShrink: if (!xr.alphaBlendSupported() && !roomKeyed()) return said.noRoom; - if (!app.video.passthrough) return said.needsPassthrough; - if (packedMask(app.currentFile, app.video) && maskFormat(app.format)) return said.ownMask; - if (!app.video.greenScreen.on) return strings().gestures.needsRemoveBackground; + if (!running.video.passthrough) return said.needsPassthrough; + if (packedMask(running.currentFile, running.video) && maskFormat(running.format)) return said.ownMask; + if (!running.video.greenScreen.on) return strings().gestures.needsRemoveBackground; // As the menu hides their sliders: Automatic found nothing to remove. - if (!app.video.keyRemoves()) return strings().gestures.nothingRemoved; + if (!running.video.keyRemoves()) return strings().gestures.nothingRemoved; break; case V::Scrub: - if (player.loading() || player.playback().duration <= kSeekEndMargin || heldSeek.active()) return ""; + if (player.loading() || player.playback().duration <= kSeekEndMargin || stickSeek.active()) return ""; break; case V::Rating: - if (isStream(app.currentFile)) return said.notForStreams; + if (isStream(running.currentFile)) return said.notForStreams; if (!library.available()) return said.ratingsLocked; - if (!library.known(app.currentFile)) return ""; // its rating isn't read yet + if (!library.known(running.currentFile)) return ""; // its rating isn't read yet break; default: break; } @@ -2474,31 +2035,32 @@ int run(Options opts) { }; gestureHost.read = [&](GestureValue v) -> double { using V = GestureValue; - const ColourBalance& balance = roomMatched && roomShown() ? roomBalance : app.video.balance; - const KeySliders& key = app.video.keySliders(); + const ColourBalance& balance = + passthrough.balance(passthrough.matched() && passthrough.roomShown()); + const KeySliders& key = running.video.keySliders(); switch (v) { case V::Volume: return player.playback().volume; - case V::Opacity: return app.video.opacity; + case V::Opacity: return running.video.opacity; case V::MatchBrightness: return settings.matchBrightness; case V::MatchColour: return settings.matchColour; case V::KeyStrength: return key.strength; case V::KeyEdges: return key.softness; case V::KeySpill: return key.spill; case V::KeyShrink: return key.shrink; - case V::Brightness: return app.video.brightness; - case V::Contrast: return app.video.contrast; - case V::Saturation: return app.video.saturation; + case V::Brightness: return running.video.brightness; + case V::Contrast: return running.video.contrast; + case V::Saturation: return running.video.saturation; case V::Warmth: return balance.warmth; case V::Tint: return balance.tint; case V::Exposure: return balance.exposure; case V::Sharpen: return settings.sharpen; - case V::Zoom: return app.video.zoom * 100.0; - case V::Viewpoint: return app.video.originForward * 100.0; - case V::ScreenDistance: return app.screen.size.distance * 100.0; - case V::ScreenHeight: return app.screen.size.height * 100.0; - case V::ScreenCurve: return app.screen.size.curve * 100.0; - case V::Scrub: return scrub.on ? scrub.target : player.playback().position; - case V::Rating: return library.record(app.currentFile).rating * 2.0; + case V::Zoom: return running.video.zoom * 100.0; + case V::Viewpoint: return running.video.originForward * 100.0; + case V::ScreenDistance: return running.screen.size.distance * 100.0; + case V::ScreenHeight: return running.screen.size.height * 100.0; + case V::ScreenCurve: return running.screen.size.curve * 100.0; + case V::Scrub: return stickSeek.scrubValue(); + case V::Rating: return library.record(running.currentFile).rating * 2.0; case V::ScriptTiming: return settings.scripts.offsetMs; case V::SubtitleSize: return settings.subtitleSize; case V::SubtitleRaise: return settings.subtitleRaise; @@ -2509,11 +2071,11 @@ int run(Options opts) { }; gestureHost.write = [&](GestureValue v, double value) { if (v == GestureValue::Scrub) { - scrub.target = value; + stickSeek.scrubTo(value); } else if (v == GestureValue::Rating) { // As Rating up and down do, by half stars. - const int now = static_cast(std::lround(library.record(app.currentFile).rating * 2)); - menu.stepRating(app.currentFile, static_cast(std::lround(value)) - now); + const int now = static_cast(std::lround(library.record(running.currentFile).rating * 2)); + menu.stepRating(running.currentFile, static_cast(std::lround(value)) - now); } else { execute({gestureValueInfo(v).command, value}); } @@ -2525,21 +2087,16 @@ int run(Options opts) { }; gestureHost.began = [&](GestureValue v) { if (v != GestureValue::Scrub) return; - scrub.on = true; - scrub.sent = false; - scrub.from = scrub.target = scrub.picture = player.playback().position; - scrub.pictureAt = glfwGetTime(); + stickSeek.beginScrub(glfwGetTime()); awaitingResume = false; // a seek of the user's }; gestureHost.ended = [&](GestureValue v, bool released) { if (v != GestureValue::Scrub) return; - // Let go: exactly there; the video played on meanwhile. - if (released && (scrub.sent || std::abs(scrub.target - scrub.from) > 0.01)) - player.seekTo(scrub.target, true); - scrub.on = false; + stickSeek.endScrub(released); }; gestureHost.say = [&](const char* text) { say(text); }; gestureHost.buzz = [&](int hand, float amplitude, double seconds) { buzz(hand, amplitude, seconds); }; + stickSeek.buzz = [&](int hand, float amplitude, double seconds) { buzz(hand, amplitude, seconds); }; bool xrQuit = false; FrameTimer timer(opts.timing); @@ -2570,15 +2127,14 @@ int run(Options opts) { if (settings.scripts.enabled) { // Held too while the headset is taken off, though the video plays on. const PlaybackState& p = player.playback(); - scripts.sync(p.position, !app.currentFile.empty() && !p.paused && !p.endReached && + scripts.sync(p.position, !running.currentFile.empty() && !p.paused && !p.endReached && !player.seeking() && !player.loading() && !player.failed() && xr.userPresence() != 0); } if (kStandaloneHeadset && opts.hwdec == "v4l2m2m") { - if (!xr.isVisible() && heldSeek.active()) { - if (heldSeekPaused) player.command("set pause no"); - heldSeek.cancel(); - heldSeekPaused = heldSeekLanding = heldSeekBar = false; + if (!xr.isVisible() && stickSeek.active()) { + if (stickSeek.pausedVideo()) player.command("set pause no"); + stickSeek.cancel(); } player.setPresentationActive(xr.isVisible()); } @@ -2591,9 +2147,9 @@ int run(Options opts) { // A Stash scene's file on a server that doesn't play plays from Stash's // stream instead (once: the stream is no server's file), if that serves it. // Not one the decoder refused: the stream is the same video. - if (player.failed() && !player.decoderRefused() && remote::isRemote(app.currentFile) && stash && + if (player.failed() && !player.decoderRefused() && remote::isRemote(running.currentFile) && stash && stash->catalog()) - if (const int i = stash->catalog()->sceneByPath(app.currentFile); i >= 0) { + if (const int i = stash->catalog()->sceneByPath(running.currentFile); i >= 0) { const StashScene& scene = stash->catalog()->scenes()[i]; if (!scene.oshashes.empty() && scene.oshashes.front() == scene.oshash) { std::printf("Server failed: the scene plays from its media server's stream\n"); @@ -2607,10 +2163,10 @@ int run(Options opts) { const bool opened = player.takeOpened(); // Played after freeing the decoder: a later refusal (after a sleep) is asked about again. if (opened && player.loadCount() == decoderRescue.retry) decoderRescue.retry = 0; - if (opened && setupBanner && !isPhotoFile(app.currentFile)) hideSetupBanner(); - if (opened && !app.currentFile.empty() && !isStream(app.currentFile) && - !isPhotoFile(app.currentFile)) { - library.recordPlay(app.currentFile); + if (opened && setupBanner && !isPhotoFile(running.currentFile)) hideSetupBanner(); + if (opened && !running.currentFile.empty() && !isStream(running.currentFile) && + !isPhotoFile(running.currentFile)) { + library.recordPlay(running.currentFile); videoOpened = true; videoOpenedAt = glfwGetTime(); resumeSaveAt = glfwGetTime() + 60; @@ -2620,7 +2176,7 @@ int run(Options opts) { if (videoOpened && glfwGetTime() >= resumeSaveAt) saveResume(); if (videoOpened && !durationKept && player.playback().duration > 0) { durationKept = true; - library.setDuration(app.currentFile, player.playback().duration); + library.setDuration(running.currentFile, player.playback().duration); } if (keys.videoStep != 0) { @@ -2628,47 +2184,34 @@ int run(Options opts) { keys.videoStep = 0; } - if (app.saveAt > 0 && glfwGetTime() >= app.saveAt) { - // A zoom still held waits for its letting go. - const unsigned held = zoomHold.hand >= 0 ? app.unsavedParts & VideoSettings::kZoom : 0; - app.unsavedParts &= ~held; - saveUnsaved(); - app.unsavedParts |= held; - } - if (const int volume = static_cast(std::lround(player.playback().volume)); - !volumeApplied) - volumeApplied = volume == settings.volume; - else if (volume != settings.volume && volumeSaveAt == 0) - volumeSaveAt = glfwGetTime() + 1; - if (volumeSaveAt > 0 && glfwGetTime() >= volumeSaveAt) keepVolume(); - if (sharpenSaveAt > 0 && glfwGetTime() >= sharpenSaveAt) keepSharpen(); + running.saveDue(buttonJobs.zoomHeld()); // The library's background results; the playing file's record may be // among them. - if (library.poll() && awaitingRecord && library.known(app.currentFile)) { + if (library.poll() && awaitingRecord && library.known(running.currentFile)) { awaitingRecord = false; if (awaitingResume) { - const VideoRecord r = library.record(app.currentFile); + const VideoRecord r = library.record(running.currentFile); resolvedResume = resumePoint(r.resumeSeconds, r.durationSeconds); } VideoSettings kept; - bool hasSettings = library.settings(app.currentFile, kept); - if (!hasSettings && openingRecord == library.record(app.currentFile).id && - memory.get(app.currentFile, kept)) { - library.carryOverSettings(app.currentFile, kept); + bool hasSettings = library.settings(running.currentFile, kept); + if (!hasSettings && openingRecord == library.record(running.currentFile).id && + memory.get(running.currentFile, kept)) { + library.carryOverSettings(running.currentFile, kept); hasSettings = true; } // The save timer may still hold user edits when identity arrives. // Restore the other fields without replacing those pending changes. - if (hasSettings) kept.take(app.video, app.unsavedParts & ~VideoSettings::kScreen); - if (hasSettings && kept != app.video) { + if (hasSettings) kept.take(running.video, running.unsavedParts & ~VideoSettings::kScreen); + if (hasSettings && kept != running.video) { // Without a format of its own, the file's is detected again. - if (app.video.hasFormat && !kept.hasFormat) { - app.formatChosenByUser = false; + if (running.video.hasFormat && !kept.hasFormat) { + running.formatChosenByUser = false; knownWidth = -1; formatDetected = false; } - app.video = kept; - applyVideoSettings(); + running.video = kept; + running.applyVideoSettings(); } } // Identity can arrive before mpv opens, or shortly after playback starts. @@ -2689,9 +2232,9 @@ int run(Options opts) { } if (nextPhoto.valid() && nextPhoto.wait_for(std::chrono::seconds(0)) == std::future_status::ready) - photoPreloader.request(app.currentFile, nextPhoto.get()); + photoPreloader.request(running.currentFile, nextPhoto.get()); // Sought back from the end, or seeking since: it doesn't go on. - if (endStep && (!player.playback().endReached || heldSeek.active() || + if (endStep && (!player.playback().endReached || stickSeek.active() || player.counts().restarts != endStepRestarts)) { neighbor = {}; neighborStep = 0; @@ -2714,105 +2257,31 @@ int run(Options opts) { // mpv keeps a video that reached its end paused on its last frame. Play // the next video and Shuffle go on from there; with no next one, as for // Stop, the menu opens. - const bool atEnd = player.playback().endReached && !app.currentFile.empty() && - !isPhotoFile(app.currentFile); + const bool atEnd = player.playback().endReached && !running.currentFile.empty() && + !isPhotoFile(running.currentFile); if (atEnd != wasAtEnd) { const AfterVideo after = afterVideo(); if (atEnd && (after == AfterVideo::Next || after == AfterVideo::Shuffle) && - !isStream(app.currentFile)) + !isStream(running.currentFile)) stepVideo(1, true); else menuAtEnd = atEnd; } wasAtEnd = atEnd; // Slideshow: the next photo in the folder, after the last one the first. - if (app.slideshowSeconds > 0 && isPhotoFile(app.currentFile) && + if (app.slideshowSeconds > 0 && isPhotoFile(running.currentFile) && glfwGetTime() >= app.nextSlideAt && !neighbor.valid()) { neighborStep = 1; neighborWrap = true; - neighbor = mediaNeighbor(app.currentFile, 1, true); + neighbor = mediaNeighbor(running.currentFile, 1, true); } - // The delete dialog's file looked up; a deletion finished. - if (deletion.lookup.valid() && - deletion.lookup.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { - const Deletion::Look look = deletion.lookup.get(); - DeleteInfo& info = deletion.info; - const bool stream = isStashScene(deletion.target); - DeleteStatus status = look.status; - if (status == DeleteStatus::Ok && !stream) { - deletion.stamp = look.stamp; - info.size = look.stamp.size; - } - deletion.oshash = look.oshash; - // Stash deletes it if a fresh query found the scene's one file with - // its path and oshash; its stream's file nobody else can. - deletion.throughStash = look.asked && look.stash.file != 0; - if (deletion.throughStash) { - deletion.sceneFiles = look.stash.files.size(); - info.stash = DeleteInfo::Stash::Deletes; - info.otherFiles = static_cast(look.stash.files.size()) - 1; - info.stashTrash = !look.stash.trash.empty(); - } else if (stream) { - if (status == DeleteStatus::Ok) - status = !look.asked ? DeleteStatus::Denied - : !look.stash.answered ? DeleteStatus::Offline - : !look.stash.scene ? DeleteStatus::Gone - : DeleteStatus::Changed; - } else if (status == DeleteStatus::Ok && deletion.scene && - !(look.stash.answered && !look.stash.scene)) { - info.stash = look.stash.answered ? DeleteInfo::Stash::Unsure : DeleteInfo::Stash::Lists; - } - // A copy can go without its source. - info.sourceFound = !info.source.empty() && status == DeleteStatus::Ok; - info.sourceChanged = !info.source.empty() && status == DeleteStatus::Changed; - info.ready = status == DeleteStatus::Ok || !info.source.empty(); - if (info.ready) - menu.askDelete(info); - else - menu.showDeleteError(deleteError(status, std::string())); - } - if (deletion.result.valid() && - deletion.result.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { - const DeleteOutcome outcome = deletion.result.get(); - const std::string& target = deletion.target; - const bool stream = isStashScene(target); - std::printf("Delete: %s%s%s: %s%s%s\n", - stream ? "a scene's file in Stash" - : remote::isRemote(target) ? "a file on a server" - : "a file on this device", - deletion.info.source.empty() ? "" : " and its downloaded copy", - deletion.throughStash ? " through Stash" : "", deleteLogged(outcome.status), - outcome.listed ? ", Stash still lists it" : "", - outcome.stashDeleted && outcome.status != DeleteStatus::Ok ? ", Stash deleted its file" - : ""); - if (outcome.status == DeleteStatus::Ok) { - if (!stream) { - library.forgetFile(target); - libraryIndex.deleted(target); - } - if (!deletion.info.source.empty()) { - offline.remove(deletion.copy); - library.forgetFile(deletion.info.file); - libraryIndex.deleted(deletion.info.file); - } - forgetFolderListing(); - } - if (stash && deletion.scene && (outcome.status == DeleteStatus::Ok || outcome.stashDeleted)) { - if (deletion.sceneFiles == 1 && !deletion.stashPath.empty()) stash->hideScene(deletion.scene); - if (deletion.throughStash) stash->syncNow(); - } - // Once Stash has deleted its file, never "Nothing was deleted". - menu.deleteEnded(outcome.status == DeleteStatus::Ok ? std::string() - : outcome.stashDeleted ? std::string(strings().deletion.stashKeptHere) - : deleteError(outcome.status, outcome.error), - outcome.listed ? strings().deletion.stashLists : ""); - } + deletion.poll(); // Re-guess the format once the real frame size is known. - if (app.rememberFormat) { // changed by key + if (running.rememberFormat) { // changed by key rememberFormat(); - app.rememberFormat = false; + running.rememberFormat = false; } // And once mpv says how it decodes a 3D Blu-ray video's two views. Not // from the last file's while the next one opens. @@ -2822,12 +2291,12 @@ int run(Options opts) { knownWidth = player.width(); knownHeight = player.height(); knownViews = views; - if (!app.formatChosenByUser) { - const VideoFormat guess = guessVideoFormat(app.currentFile, knownWidth, knownHeight, views); - if (!formatDetected || guess.projection != app.format.projection || - guess.stereo != app.format.stereo || guess.packing != app.format.packing) + if (!running.formatChosenByUser) { + const VideoFormat guess = guessVideoFormat(running.currentFile, knownWidth, knownHeight, views); + if (!formatDetected || guess.projection != running.format.projection || + guess.stereo != running.format.stereo || guess.packing != running.format.packing) printFormat(guess, "detected"); - app.format = guess; + running.format = guess; formatDetected = true; } } @@ -2837,27 +2306,7 @@ int run(Options opts) { // the runtime must blend, or key green stand in for it. const bool passthroughAvailable = xr.alphaBlendSupported() || roomKeyed(); const bool autoPassthroughOn = settings.autoPassthrough && passthroughAvailable; - if (!passthroughSettled && knownWidth > 0 && !awaitingRecord && !app.currentFile.empty()) { - passthroughSettled = true; - const std::string& path = app.currentFile; - if (autoPassthroughOn && !isPhotoFile(path) && !isStream(path)) - passthroughByItself(autoPassthrough(path, app.format, app.video)); - // The fill check, for the key's Automatic, also where passthrough is on by hand. - const bool fillWanted = fillCheckWanted(path, app.format, app.video) && - (autoPassthroughOn || app.video.passthrough); - if (!greenCheckAsked && !isPhotoFile(path) && !isStream(path) && - ((autoPassthroughOn && greenCheckWanted(path, app.format, app.video)) || fillWanted)) { - greenCheckAsked = fillCheckPending = true; - videoCheckAt = glfwGetTime() + 2.0; - videoCheckKind = VideoCheck::Kind::GreenScreen; - } - // Whatever the setting: a mask's second layer shows whenever passthrough does. - if (!isPhotoFile(path) && !isStream(path) && layerCheckWanted(path, app.format, app.video)) { - videoCheckAt = glfwGetTime() + 2.0; - videoCheckKind = VideoCheck::Kind::MaskLayers; - fillCheckPending = false; // a green screen check under way is replaced - } - } + passthrough.settle(autoPassthroughOn, knownWidth > 0 && !awaitingRecord); if (RemovableDrives::Change change; drives.poll(change)) { menu.drivesChanged(change.removed); offline.drivesChanged(); @@ -2887,12 +2336,12 @@ int run(Options opts) { } } // Looks for new videos in the pinned folders wait while a video is open. - libraryIndex.setVideoOpen(!app.currentFile.empty() && !isPhotoFile(app.currentFile)); + libraryIndex.setVideoOpen(!running.currentFile.empty() && !isPhotoFile(running.currentFile)); // ... and so does looking for Stash's folders. - if (stash) stash->setVideoOpen(!app.currentFile.empty() && !isPhotoFile(app.currentFile)); + if (stash) stash->setVideoOpen(!running.currentFile.empty() && !isPhotoFile(running.currentFile)); // Downloads and new thumbnails wait while a video plays. const bool videoPlaying = - !app.currentFile.empty() && !isPhotoFile(app.currentFile) && !player.playback().paused; + !running.currentFile.empty() && !isPhotoFile(running.currentFile) && !player.playback().paused; offline.setPlaying(videoPlaying); thumbnailer.setPlaying(videoPlaying); std::vector downloaded; @@ -2901,49 +2350,19 @@ int run(Options opts) { offline.watchStash(stash && stash->catalog() && (stash->catalog()->stats().streamed > 0 || !offline.downServers().empty())); for (const Offline::Download& d : downloaded) library.addCopy(d.path, d.oshash, d.size, d.mtime); - if (videoCheckAt > 0 && glfwGetTime() >= videoCheckAt) { - videoCheckAt = 0; - videoCheck.start(app.currentFile, app.format, videoCheckKind); - } - if (VideoCheck::Result checked; videoCheck.result(checked)) { - // Kept for the video, even if another plays by now: it runs once. - VideoSettings result; - const bool current = checked.path == app.currentFile; - if (current && checked.kind == VideoCheck::Kind::GreenScreen) fillCheckPending = false; - if (!checked.answered) { - // None: it runs again next time. - } else if (checked.kind == VideoCheck::Kind::GreenScreen) { - result.greenCheckVersion = VideoCheck::kGreenVersion; - result.greenScreenFound = checked.found; - result.fillCheckVersion = VideoCheck::kFillVersion; - result.fillFound = checked.fillFound; - if (checked.fillFound) result.fillColour = checked.fillColour; - const unsigned parts = VideoSettings::kGreenCheck | VideoSettings::kFillCheck; - library.setSettings(checked.path, result, parts); - if (current) { - app.video.take(result, parts); - if (autoPassthroughOn) - passthroughByItself(autoPassthrough(checked.path, app.format, app.video)); - } - } else if (!layersSeen.count(checked.path)) { // else found while it played - result.maskLayersVersion = VideoCheck::kLayersVersion; - result.maskLayersFound = checked.found; - library.setSettings(checked.path, result, VideoSettings::kMaskLayers); - if (current) app.video.take(result, VideoSettings::kMaskLayers); - } - } + passthrough.poll(autoPassthroughOn); // 3D and surround video always get floating subtitles (mpv's would be cut // in half or end up behind you); for 2D video the setting decides. const bool floatingSubtitles = settings.floatingSubtitles || - app.format.stereo != StereoLayout::Mono || app.format.projection != Projection::Flat; + running.format.stereo != StereoLayout::Mono || running.format.projection != Projection::Flat; player.setSubtitlesInFrame(!floatingSubtitles); subtitles.setText(floatingSubtitles ? player.playback().subtitleText : ""); // Until the new file's first frame arrives, the texture still holds the old // video, which would show cut apart in the new format; show nothing instead. - bool photo = isPhotoFile(app.currentFile); - bool loading = !photo && player.loading() && !app.currentFile.empty(); + bool photo = isPhotoFile(running.currentFile); + bool loading = !photo && player.loading() && !running.currentFile.empty(); if (keys.togglePassthrough && !passthroughAvailable) { // The video keeps its choice for a runtime that shows the room. keys.togglePassthrough = false; @@ -2952,47 +2371,26 @@ int run(Options opts) { } if (keys.togglePassthrough) { keys.togglePassthrough = false; - app.video.passthrough = !app.video.passthrough; - app.video.passthroughChosen = true; // never switched by itself again - passthroughShownUntil = 0; - storeVideo(VideoSettings::kPassthrough); - std::printf("Passthrough: %s\n", app.video.passthrough ? "on" : "off"); - // On by hand after the video settled: the fill check its key's - // Automatic needs, if it wasn't asked for then. - const std::string& path = app.currentFile; - if (app.video.passthrough && passthroughSettled && !greenCheckAsked && !path.empty() && - !isPhotoFile(path) && !isStream(path) && fillCheckWanted(path, app.format, app.video)) { - greenCheckAsked = fillCheckPending = true; - videoCheckAt = glfwGetTime(); - videoCheckKind = VideoCheck::Kind::GreenScreen; - } + running.video.passthrough = !running.video.passthrough; + running.video.passthroughChosen = true; // never switched by itself again + running.storeVideo(VideoSettings::kPassthrough); + std::printf("Passthrough: %s\n", running.video.passthrough ? "on" : "off"); + passthrough.switchedByHand(); } // Passthrough, where the runtime blends (the Frame itself, or a PC whose // runtime shows the headset's camera): the eye images are blended over // the camera by their alpha. Where it doesn't there is none, unless a PC // is set to draw the room in key green. const bool canBlend = xr.alphaBlendSupported(); - const bool alphaPassthrough = app.video.passthrough && canBlend; - const bool keyPassthrough = app.video.passthrough && roomKeyed(); - const bool blended = roomShown(); + const bool alphaPassthrough = running.video.passthrough && canBlend; + const bool keyPassthrough = running.video.passthrough && roomKeyed(); + const bool blended = passthrough.roomShown(); // Peek at the room, held: the video at no opacity over the room, none of // its settings changed. const bool peek = peeking && canBlend; // The room's balance, while the switch is on and the room is shown. - const bool roomMatching = roomMatched && blended; - // A room reading that ended: kept for the run and matched while the - // switch is on (unless the sliders were moved or reset since it was asked - // for), or a moment saying it failed. The switch stays as it was set: - // with no earlier reading to use nothing is matched yet, and Read again - // tries once more. - if (std::optional reading; roomLight.take(reading)) { - if (reading) { - roomReading = reading; - if (roomAsked == balanceEdits) applyRoomMatch(); - } else { - roomFailedUntil = glfwGetTime() + 4; - } - } + const bool roomMatching = passthrough.matched() && blended; + passthrough.pollRoom(); // Saved on every change of folder, so even a killed player reopens there. if (!menu.directory().empty() && menu.directory() != settings.lastFolder) { settings.lastFolder = menu.directory(); @@ -3064,15 +2462,15 @@ int run(Options opts) { int photoWidth = 0, photoHeight = 0; bool stillLoading = false; auto choosePicture = [&] { - photo = isPhotoFile(app.currentFile); - loading = !photo && player.loading() && !app.currentFile.empty(); + photo = isPhotoFile(running.currentFile); + loading = !photo && player.loading() && !running.currentFile.empty(); videoImage = nullptr; videoTexture = 0; photoImage = nullptr; frameAspect = player.aspect(); photoWidth = photoHeight = 0; if (photo) { - photoImage = photoPreloader.image(app.currentFile, photoWidth, photoHeight); + photoImage = photoPreloader.image(running.currentFile, photoWidth, photoHeight); if (photoImage) { videoImage = &photoImage->texture(); videoTexture = photoImage->glTexture(); @@ -3080,17 +2478,17 @@ int run(Options opts) { if (!photoSized) { // the size is known now: guess the format photoSized = true; std::printf("Photo size: %dx%d\n", photoWidth, photoHeight); - if (!app.formatChosenByUser) { - app.format = guessVideoFormat(app.currentFile, photoWidth, photoHeight); - printFormat(app.format, "detected"); + if (!running.formatChosenByUser) { + running.format = guessVideoFormat(running.currentFile, photoWidth, photoHeight); + printFormat(running.format, "detected"); } } } - } else if (!loading && !app.currentFile.empty()) { + } else if (!loading && !running.currentFile.empty()) { videoImage = player.texture(); videoTexture = player.glTexture(); } - stillLoading = !app.currentFile.empty() && !videoImage && (photo || loading); + stillLoading = !running.currentFile.empty() && !videoImage && (photo || loading); }; choosePicture(); @@ -3121,16 +2519,16 @@ int run(Options opts) { } if ((initialRecenter || (keys.recenter && !menu.setupRunning())) && headValid) { if (keys.recenter) { - if (app.video.originForward != 0) + if (running.video.originForward != 0) viewpointShownUntil = now + kValueShown; // "Centered": it did go back - app.video.originForward = 0; + running.video.originForward = 0; // Also mark a provisional zero: a late identity restore must not // bring back a remembered origin after an explicit recenter. - storeVideoSoon(VideoSettings::kOrigin); + running.storeVideoSoon(VideoSettings::kOrigin); } - app.screen.anchorPosition = headPos; - app.screen.anchorRotation = frame; - app.screen.turn = 0.0f; + running.screen.anchorPosition = headPos; + running.screen.anchorRotation = frame; + running.screen.turn = 0.0f; turnDrag.tracking = false; // a drag goes on from here, without catching up first if (panel.open) panel.placeInFrontOf(headPos, menuAt); // the menu comes along keys.recenter = false; @@ -3288,11 +2686,7 @@ int run(Options opts) { } } keys.toggleMenu = false; - if (app.video.opacity < 100 && !app.currentFile.empty() && - (app.video.opacity != seeThroughSeen || app.currentFile != seeThroughFile)) - lastSeeThrough[seeThroughKey()] = app.video.opacity; - seeThroughFile = app.currentFile; - seeThroughSeen = app.video.opacity; + buttonJobs.keepSeeThrough(); // The buttons' other jobs, as the menu's or the strip's controls do // them. Menu and Recenter are above and below, Choose is the trigger's. // Not while setup's Your controllers shows what each does. @@ -3304,7 +2698,7 @@ int run(Options opts) { buzz(hand, 0.2f, 0.014); const JobInfo& info = jobInfo(job); const JobStrings& said = strings().jobs; - const bool open = !app.currentFile.empty(); + const bool open = !running.currentFile.empty(); if ((info.needs == JobNeeds::File || info.needs == JobNeeds::Video) && !open) { say(said.nothingOpen); continue; @@ -3313,50 +2707,29 @@ int run(Options opts) { say(said.notForPhotos); continue; } - MenuCommand c = info.command; - if (info.length != JobLength::None) - c.value *= info.length == JobLength::Skip ? settings.skipSeconds : settings.bigSkipSeconds; - const PlaybackState& p = player.playback(); + ButtonJobs::Context context; + context.now = now; + context.photo = photo; + context.slideshow = app.slideshowSeconds > 0; + context.passthroughAvailable = passthroughAvailable; + context.alphaBlend = xr.alphaBlendSupported(); + context.roomReadable = passthrough.roomReadable; + context.roomShown = passthrough.roomShown(); + context.roomMatched = passthrough.matched(); + context.afterVideo = afterVideo(); + JobAction action = buttonJobs.press(job, hand, context); + MenuCommand& c = action.command; + // These need the stick's seek or the menu: done here. switch (job) { - case Job::PlayPause: - // A photo's is the slideshow's: it stops one running. - if (photo) { - c = {}; - if (app.slideshowSeconds > 0) c = {MenuCommand::SetSlideshow, 0.0}; - else say(said.notForPhotos); - } - break; - case Job::PreviousChapter: - case Job::NextChapter: { - if (player.loading()) break; - if (p.chapters.empty()) { - say(said.noChapters); - break; - } - // Back: to the start of this chapter first, more than 5 s into it. - const bool into = job == Job::PreviousChapter && p.chapter >= 0 && - p.chapter < static_cast(p.chapters.size()) && - p.position - p.chapters[p.chapter].time > 5; - const int to = p.chapter + (job == Job::NextChapter ? 1 : into ? 0 : -1); - if (to >= 0 && to < static_cast(p.chapters.size())) - c = {MenuCommand::SeekTo, p.chapters[to].time}; - else - say(to < 0 ? said.firstChapter : said.lastChapter); - break; - } case Job::FrameBack: case Job::FrameForward: // Not while the stick seeks (its release may play on). - if (!heldSeek.holding() && !heldSeekLanding && player.frameStep(job == Job::FrameBack)) + if (!stickSeek.held() && player.frameStep(job == Job::FrameBack)) awaitingResume = false; // a seek of the user's break; - case Job::AfterVideo: - // As the strip's list, the next choice. - c = {MenuCommand::SetAfterVideo, static_cast((static_cast(afterVideo()) + 1) % 4)}; - break; case Job::RatingUp: case Job::RatingDown: - if (isStream(app.currentFile)) { + if (isStream(running.currentFile)) { say(said.notForStreams); break; } @@ -3364,8 +2737,8 @@ int run(Options opts) { say(said.ratingsLocked); break; } - menu.stepRating(app.currentFile, job == Job::RatingUp ? 1 : -1); - if (const float rating = library.record(app.currentFile).rating; rating > 0) { + menu.stepRating(running.currentFile, job == Job::RatingUp ? 1 : -1); + if (const float rating = library.record(running.currentFile).rating; rating > 0) { char stars[16]; std::snprintf(stars, sizeof(stars), "%g", rating); sayf(said.rating, stars); @@ -3382,10 +2755,10 @@ int run(Options opts) { say(said.notInSetup); break; } - if (!menu.canRequestDelete(app.currentFile)) { + if (!menu.canRequestDelete(running.currentFile)) { using D = MenuView::Deletable; const D d = menu.deletable(); - if (isStream(app.currentFile)) say(said.notForStreams); + if (isStream(running.currentFile)) say(said.notForStreams); else if (d == D::NeedsSendToStash) say(said.deleteNeedsStash); else if (d == D::StashDown) say(strings().deletion.tipStashDown); else if (d == D::No) say(said.serverKeeps); @@ -3399,184 +2772,17 @@ int run(Options opts) { if (!app.keyPickFor.empty()) endKeyPick(); c = menu.requestDelete(); break; - case Job::VolumeUp: - case Job::VolumeDown: { - // As + and - do, within the volume gesture's 0..100. - const long volume = std::lround(p.volume); - const long to = job == Job::VolumeUp ? std::max(volume, std::min(volume + 5, 100L)) - : std::max(volume - 5, 0L); - c = {MenuCommand::SetVolume, static_cast(to)}; - sayf(said.volume, static_cast(to)); - break; - } - case Job::NextAudioTrack: - case Job::Subtitles: { - if (player.loading()) break; // the last file's tracks until it opens - const char* type = job == Job::Subtitles ? "sub" : "audio"; - std::vector tracks; - int chosen = -1; - for (const Track& t : p.tracks) - if (t.type == type) { - if (t.selected) chosen = static_cast(tracks.size()); - tracks.push_back(&t); - } - const Strings& words = strings(); - if (job == Job::NextAudioTrack) { - if (tracks.size() > 1) { - const Track& next = *tracks[(chosen + 1) % tracks.size()]; - c = {MenuCommand::SelectAudio, static_cast(next.id)}; - sayf(said.audioTrack, trackName(next, words).c_str()); - } else { - say(said.noOtherAudio); - } - } else if (chosen >= 0) { - lastSubtitle = tracks[chosen]->id; - c = {MenuCommand::SelectSubtitle, 0}; - sayf(said.switched, words.subtitles, words.off); - } else if (!tracks.empty()) { - const Track* on = tracks[0]; - for (const Track* t : tracks) - if (t->id == lastSubtitle) on = t; - c = {MenuCommand::SelectSubtitle, static_cast(on->id)}; - sayf(said.switched, words.subtitles, trackName(*on, words).c_str()); - } else { - say(said.noSubtitles); - } - break; - } - case Job::Passthrough: - if (!passthroughAvailable) { - say(said.noRoom); - c = {}; - } - break; - case Job::PeekRoom: - if (!xr.alphaBlendSupported()) say(said.noRoom); - break; - case Job::SeeThrough: - // Solid, and back to the see-through it had. - if (!xr.alphaBlendSupported()) { - say(said.noRoom); - break; - } - if (app.video.opacity < 100) { - c = {MenuCommand::SetOpacity, 100.0}; - } else { - // (stored before the library knew it: by where it is) - auto last = lastSeeThrough.find(seeThroughKey()); - if (last == lastSeeThrough.end()) last = lastSeeThrough.find(app.currentFile); - c = {MenuCommand::SetOpacity, last != lastSeeThrough.end() ? last->second : 50.0}; - } - opacityShownUntil = now + kValueShown; - break; - case Job::MatchRoom: - // Where the menu shows its switch: where the room's light is read. - if (!roomReadable) { - say(said.notOnHeadset); - c = {}; - } else if (!roomShown()) { - say(said.needsPassthrough); - } - break; - case Job::ResetScreen: - // As Video settings' Screen group: a flat screen's only. - if (app.format.projection != Projection::Flat) { - say(said.flatOnly); - c = {}; - } - break; - case Job::RemoveBackground: - // Where its switch shows: passthrough on, without the video's own mask. - if (!passthroughAvailable) - say(said.noRoom); - else if (!app.video.passthrough) - say(said.needsPassthrough); - else if (packedMask(app.currentFile, app.video) && maskFormat(app.format)) - say(said.ownMask); - else - c = {MenuCommand::ToggleGreenScreen}; - break; - case Job::ZoomIn: - case Job::ZoomOut: - if (app.format.projection == Projection::Flat) { - say(said.notForFlat); - break; - } - zoomHold = {job, hand, now, now, app.currentFile}; - zoomBy(job == Job::ZoomIn ? VideoSettings::kZoomStepPercent : -VideoSettings::kZoomStepPercent); - gestureInput.show(GestureValue::Zoom, now); - break; - case Job::StereoFocus: - case Job::ShowFocusTarget: { - const bool stereo = job == Job::StereoFocus; - if (!stereo && !settings.focusPrefs.enabled) { // its switch is greyed out - say(said.needsFocus); - break; - } - c = {MenuCommand::SetFocus, - (stereo ? settings.focusPrefs.enabled : settings.focusPrefs.showTarget) ? 0.0 : 1.0}; - c.option = static_cast(stereo ? FocusControl::Enabled : FocusControl::ShowTarget); - break; - } default: break; } - // Mute and passthrough change later (mpv's, and where the settings - // are): as they will be. - const bool wasMuted = p.muted, hadPassthrough = app.video.passthrough; + if (!action.said.empty()) say(std::move(action.said)); + if (action.showOpacity) opacityShownUntil = now + kValueShown; + if (action.showRing != GestureValue::Count) gestureInput.show(action.showRing, now); if (c.type != MenuCommand::None) execute(c); // The switches whose change doesn't show by itself, as they are now. - { - const Strings& words = strings(); - const auto switched = [&](const char* name, bool on) { - sayf(said.switched, name, on ? words.on : words.off); - }; - switch (job) { - // Not where they said why they do nothing. - case Job::Mute: switched(words.jobs.sound, wasMuted); break; - case Job::Passthrough: - if (c.type != MenuCommand::None) switched(words.jobs.passthrough, !hadPassthrough); - break; - case Job::MatchRoom: - if (c.type != MenuCommand::None && roomShown()) switched(words.colourBalance.matchRoom, roomMatched); - break; - case Job::RemoveBackground: - if (c.type != MenuCommand::None) switched(words.greenScreenOn, app.video.greenScreen.on); - break; - case Job::ResetPicture: say(said.pictureReset); break; - case Job::AfterVideo: say(words.afterVideo.choices[static_cast(afterVideo())]); break; - case Job::Scripts: switched(words.scripts.group, settings.scripts.enabled); break; - case Job::Motion: switched(words.focus.motion, settings.motionEmulation); break; - case Job::ToneLook: switched(words.toneLook, settings.toneLook); break; - case Job::TvGamma: switched(words.tvGamma, settings.tvGamma); break; - case Job::StereoFocus: switched(words.focus.enabled, settings.focusPrefs.enabled); break; - default: break; - } - } + if (std::string text = buttonJobs.saidAfter(job, afterVideo()); !text.empty()) say(std::move(text)); } peeking = !practising && jobs.held[static_cast(Job::PeekRoom)] != 0; - if (zoomHold.hand >= 0) { - if (app.currentFile != zoomHold.file) { - zoomHold.hand = -1; // stored as the video changed - } else if (const int other = 1 - zoomHold.hand; - app.format.projection != Projection::Flat && !jobs.isHeld(zoomHold.job, zoomHold.hand) && - (jobs.isHeld(Job::ZoomIn, other) || jobs.isHeld(Job::ZoomOut, other))) { - // Let go while the other hand holds a zoom too: it goes on with that. - zoomHold.job = jobs.isHeld(Job::ZoomIn, other) ? Job::ZoomIn : Job::ZoomOut; - zoomHold.hand = other; - zoomHold.at = now; - } else if (app.format.projection == Projection::Flat || !jobs.isHeld(zoomHold.job, zoomHold.hand)) { - // In whole percents, as the slider sets it. - app.video.zoom = std::round(app.video.zoom * 100) / 100; - app.screen.zoom = app.video.zoom; - storeVideoSoon(VideoSettings::kZoom); - zoomHold.hand = -1; - } else if (now > zoomHold.start + kZoomDelay) { - const double from = std::max(zoomHold.at, zoomHold.start + kZoomDelay); - zoomBy((zoomHold.job == Job::ZoomIn ? kZoomRate : -kZoomRate) * (now - from)); - zoomHold.at = now; - gestureInput.show(GestureValue::Zoom, now); - } - } + if (buttonJobs.holdZoom(jobs, now)) gestureInput.show(GestureValue::Zoom, now); if (jobs.wasPressed(Job::Recenter) && !menu.setupRunning()) { keys.recenter = true; recentered = true; @@ -3627,21 +2833,14 @@ int run(Options opts) { gestureInput.update(input, settings.gestures, settings.controls, g, controlInput, gestureHost); if (gestureInput.changing() && gestureInput.gesture().value == GestureValue::Volume) volumeTwisted = true; - // Scrub: the picture follows as the stick's held seek's does. - if (scrub.on && !player.seeking() && now - scrub.pictureAt >= kHeldPictureEvery && - std::abs(scrub.target - scrub.picture) >= kHeldPictureMove) { - player.seekTo(scrub.target, false); - scrub.picture = scrub.target; - scrub.pictureAt = now; - scrub.sent = true; - } + stickSeek.followScrub(now); } // The trigger off the menu, a corner's handle and stick up/down: the flat screen. - if (app.format.projection == Projection::Flat && videoImage && headValid) { + if (running.format.projection == Projection::Flat && videoImage && headValid) { ScreenControl::Frame screenFrame; screenFrame.up = up; - screenFrame.aspect = eyeDisplayAspect(app.format, frameAspect); + screenFrame.aspect = eyeDisplayAspect(running.format, frameAspect); screenFrame.dt = dt; screenFrame.now = now; screenFrame.onMenu[0] = onMenu[0]; @@ -3650,14 +2849,14 @@ int run(Options opts) { screenFrame.sticksFree = !listMode; for (int h = 0; h < 2; ++h) screenFrame.triggerTaken[h] = gestureInput.claims(h, Control::Trigger); const bool wasHolding = screenControl.holding(); - if (screenControl.update(input, screenFrame, app.screen)) keepScreenSize(); + if (screenControl.update(input, screenFrame, running.screen)) running.keepScreenSize(); if (!wasHolding && screenControl.holding()) buzz(screenControl.hand(), 0.25f, 0.012); } else { screenControl.reset(); } - if (app.screenChanged) { - app.screenChanged = false; - keepScreenSize(); + if (running.screenChanged) { + running.screenChanged = false; + running.keepScreenSize(); } // Picking the key's colour: the trigger away from the menu reads it @@ -3666,9 +2865,9 @@ int run(Options opts) { // picture's axes, and onto its stereo correction's sphere, as // surround.frag). The dot is where the laser below draws it. if (!app.keyPickFor.empty() && - (app.keyPickFor != app.currentFile || !panel.open || !app.video.passthrough || - !app.video.greenScreen.on || app.format.projection == Projection::Flat || - (packedMask(app.currentFile, app.video) && maskFormat(app.format)))) + (app.keyPickFor != running.currentFile || !panel.open || !running.video.passthrough || + !running.video.greenScreen.on || running.format.projection == Projection::Flat || + (packedMask(running.currentFile, running.video) && maskFormat(running.format)))) endKeyPick(); const bool keyPicking = !app.keyPickFor.empty(); // Not while the room is peeked at: the video isn't seen. @@ -3681,9 +2880,9 @@ int run(Options opts) { const Mat4 view = rotation(eye.orientation); const Vec3 dotAt = t.aimPosition + aimDirection(t) * laserLength; Vec3 d = transformDir(transposedRotation(view), normalize(dotAt - eye.position)); - if (d.z < 0) d = normalize(Vec3{d.x / app.screen.zoom, d.y / app.screen.zoom, d.z}); + if (d.z < 0) d = normalize(Vec3{d.x / running.screen.zoom, d.y / running.screen.zoom, d.z}); Vec3 inPicture = - transformDir(transposedRotation(app.screen.rotation()), transformDir(view, d)); + transformDir(transposedRotation(running.screen.rotation()), transformDir(view, d)); if (shownCorrection.on && shownCorrection.distance > 0) { const Vec3 viewer = shownCorrection.viewer - shownCorrection.camera; const float along = dot(viewer, inPicture); @@ -3691,7 +2890,7 @@ int run(Options opts) { shownCorrection.distance * shownCorrection.distance; inPicture = normalize(viewer + inPicture * (std::sqrt(std::max(reach, 0.0f)) - along)); } - app.keyPickWanted = KeyPicker::pointOf(app.format, frameAspect, app.flipVideo, inPicture, + app.keyPickWanted = KeyPicker::pointOf(running.format, frameAspect, running.flipVideo, inPicture, app.keyPickUv, app.keyPickPart); break; } @@ -3699,7 +2898,7 @@ int run(Options opts) { // Trigger away from the menu: drag the 180°/360° picture around you (the // flat screen's is ScreenControl's). Releasing stops it where it is // shown; what the smoothing had not caught up is dropped. - const bool noDrag = screenControl.holding() || app.format.projection == Projection::Flat; + const bool noDrag = screenControl.holding() || running.format.projection == Projection::Flat; if (turnDrag.hand >= 0 && (!input.hands[turnDrag.hand].select || noDrag || menuGrab.hand == turnDrag.hand)) turnDrag.hand = -1; @@ -3726,9 +2925,9 @@ int run(Options opts) { const double step = std::clamp(time - turnDrag.lastTime, 0.0, kDragMaxStep); const float alpha = 1.0f - std::exp(-kDragResponse * static_cast(step)); const Quat next = slerpShortest(turnDrag.smoothHand, t.aimOrientation, alpha); - app.screen.anchorRotation = - rotation(next * conjugate(turnDrag.smoothHand)) * app.screen.rotation(); - app.screen.turn = 0.0f; + running.screen.anchorRotation = + rotation(next * conjugate(turnDrag.smoothHand)) * running.screen.rotation(); + running.screen.turn = 0.0f; turnDrag.smoothHand = next; } turnDrag.lastTime = time; @@ -3756,7 +2955,7 @@ int run(Options opts) { std::abs(h.stickY) < adjust::kStickRelease; } if (!panel.open || typing || centred) valueStick = false; - if (!valueStick && panel.open && !typing && !heldSeek.active() && + if (!valueStick && panel.open && !typing && !stickSeek.active() && std::abs(x) >= adjust::kStickPress && menu.pointedValue()) valueStick = true; if (valueLess.update(valueStick && x <= -adjust::kStickPress, now)) execute(menu.stepValue(-1)); @@ -3764,99 +2963,20 @@ int run(Options opts) { } { - const bool seekable = !app.currentFile.empty() && !photo; - const PlaybackState& p = player.playback(); - // A stick counts sideways once it is mostly sideways; then all of its - // sideways push, so a thumb drifting up or down keeps the hold. Of - // the two, the one pushed further sideways seeks, until it lets go. - if (!heldSeek.active()) { - float most = 0.0f; - for (int h = 0; h < 2; ++h) { - const HandState& g = input.hands[h]; - if (std::abs(g.stickX) > std::abs(g.stickY) && std::abs(g.stickX) > most) { - most = std::abs(g.stickX); - heldSeekHand = h; - } - } - } - const HandState& seekStick = input.hands[heldSeekHand]; - const float x = typing || valueStick ? 0.0f : seekStick.stickX; - const float sideways = - heldSeek.active() || std::abs(x) > std::abs(seekStick.stickY) ? x : 0.0f; - const float back = seekable ? std::max(keys.seekBackKey ? 1.0f : 0.0f, -sideways) : 0.0f; - const float forward = seekable ? std::max(keys.seekForwardKey ? 1.0f : 0.0f, sideways) : 0.0f; - // Its limits from where it started: the video plays on until a hold. - const double from = heldSeek.active() ? heldSeekFrom : p.position; - // A tap goes Skip's length by the stick, the keyboard's arrows 10 s: - // by the input that starts it. - if (!heldSeek.active()) - heldSeek.setTap(std::abs(sideways) >= HeldSeek::kPress ? settings.skipSeconds : 10); - const HeldSeek::Step step = - heldSeek.update(back, forward, now, -from, - p.duration > 0 ? p.duration - kSeekEndMargin - from : 1e9, p.duration); - if (step.pressed) { - awaitingResume = false; - heldSeekFrom = p.position; - heldSeekBar = false; // a tap shows none - heldSeekStick = std::abs(sideways) >= HeldSeek::kPress; - heldSeekAtLimit = false; - if (heldSeekStick) buzz(heldSeekHand, 0.15f, 0.010); - } - if (step.holdStarted) { - // The picture waits, and is silent, until the stick lets go; with - // the menu closed, the strip alone shows where it goes meanwhile. - heldSeekPaused = !p.paused; - if (heldSeekPaused) player.command("set pause yes"); - heldSeekBar = !panel.open && headValid; - if (heldSeekBar) panel.placeInFrontOf(headPos, menuAt); - heldSeekPicture = heldSeekFrom; - heldSeekPictureAt = now; - heldSeekTens = std::floor(std::abs(heldSeek.distance()) / 10); - } - if (heldSeek.holding()) { - heldSeekTarget = heldSeekFrom + heldSeek.distance(); - if (!player.seeking() && now - heldSeekPictureAt >= kHeldPictureEvery && - std::abs(heldSeekTarget - heldSeekPicture) >= kHeldPictureMove) { - player.seekTo(heldSeekTarget, false); - heldSeekPicture = heldSeekTarget; - heldSeekPictureAt = now; - } - if (heldSeekStick) { - const double end = p.duration > 0 ? p.duration - kSeekEndMargin : 1e9; - const bool atLimit = heldSeekTarget <= 0.01 || heldSeekTarget >= end - 0.01; - const double tens = std::floor(std::abs(heldSeek.distance()) / 10); - if (atLimit && !heldSeekAtLimit) { - buzz(heldSeekHand, 0.3f, 0.020); - } else if (tens != heldSeekTens && now - heldSeekTickAt >= 0.125) { - buzz(heldSeekHand, 0.1f, 0.006); - heldSeekTickAt = now; - } - heldSeekAtLimit = atLimit; - heldSeekTens = tens; - } - } - if (step.released) { - // A tap jumps on from where the video is now; a hold lands on the - // keyframe before its target, never past it into the end, unless - // its last picture is already there. - if (step.held && heldSeekStick) buzz(heldSeekHand, 0.2f, 0.014); - bool sent = step.distance != 0; - if (step.held) { - const double target = heldSeekFrom + step.distance; - sent = std::abs(target - heldSeekPicture) > 0.01; - if (sent) player.seekTo(target, false); - } else if (sent) { - player.seekBy(step.distance); - } - if (heldSeekPaused) player.command("set pause no"); - heldSeekPaused = false; - heldSeekLanding = step.held && (sent || player.seeking()); - heldSeekBarUntil = now + kSeekBarLinger; - } - if (heldSeekLanding && !player.seeking()) heldSeekLanding = false; - } - if (turnLeft.update(keys.turnLeftKey, now)) app.screen.turn = wrapAngle(app.screen.turn - kTurnStep); - if (turnRight.update(keys.turnRightKey, now)) app.screen.turn = wrapAngle(app.screen.turn + kTurnStep); + StickSeek::Frame seekFrame; + seekFrame.now = now; + seekFrame.seekable = !running.currentFile.empty() && !photo; + seekFrame.sticksTaken = typing || valueStick; + seekFrame.backKey = keys.seekBackKey; + seekFrame.forwardKey = keys.seekForwardKey; + seekFrame.skipSeconds = settings.skipSeconds; + seekFrame.headValid = headValid; + seekFrame.headPos = headPos; + seekFrame.menuAt = menuAt; + if (stickSeek.update(input, seekFrame)) awaitingResume = false; + } + if (turnLeft.update(keys.turnLeftKey, now)) running.screen.turn = wrapAngle(running.screen.turn - kTurnStep); + if (turnRight.update(keys.turnRightKey, now)) running.screen.turn = wrapAngle(running.screen.turn + kTurnStep); if (listMode) { // Lists glide: the further the stick is tilted, the faster (up to // ~14 rows a second), with a small dead zone around the middle. @@ -3889,7 +3009,7 @@ int run(Options opts) { } else { listPushSeconds = 0; listPushSign = 0; - if (app.format.projection != Projection::Flat && videoImage && + if (running.format.projection != Projection::Flat && videoImage && !input.hands[0].grip && !input.hands[1].grip) { int direction = 0; for (int i = 0; i < 2; ++i) @@ -3897,9 +3017,9 @@ int run(Options opts) { direction += input.hands[i].stickY > 0 ? 1 : -1; if (direction) { constexpr float kMax = VideoSettings::kMaxOriginForward; - app.video.originForward = - std::clamp(app.video.originForward + direction * 0.05f * dt, -kMax, kMax); - storeVideoSoon(VideoSettings::kOrigin); + running.video.originForward = + std::clamp(running.video.originForward + direction * 0.05f * dt, -kMax, kMax); + running.storeVideoSoon(VideoSettings::kOrigin); viewpointShownUntil = now + kValueShown; } } @@ -3925,11 +3045,11 @@ int run(Options opts) { // Stereo focus: the video's own settings, else the defaults; none while // it is off for all videos. - const FocusSettings& focusSettings = app.video.hasFocus ? app.video.focus : settings.focus; + const FocusSettings& focusSettings = running.video.hasFocus ? running.video.focus : settings.focus; FocusInput focusIn; focusIn.settings = focusSettings; - focusIn.format = app.format; - focusIn.video = app.currentFile; + focusIn.format = running.format; + focusIn.video = running.currentFile; focusIn.shown = videoImage != nullptr; focusIn.texture = videoTexture; if (photoImage) @@ -3937,7 +3057,7 @@ int run(Options opts) { else if (!photo) focusIn.prepareRead = [&player] { return player.prepareRead(); }; if (!photo && !videoTexture) focusIn.drawer = directDepth.source(player.directCurrent()); - focusIn.flip = app.flipVideo; + focusIn.flip = running.flipVideo; focusIn.position = photo ? 0.0 : player.playback().position; focusIn.paused = photo || player.playback().paused; focusIn.headValid = headValid && xr.eyeCount() == 2; @@ -3949,35 +3069,35 @@ int run(Options opts) { if (!settings.focusPrefs.autoIpd) focusIn.viewerIpd = settings.focusPrefs.ipdTenthMm / 1e4f; if (headValid) focusIn.motion = emulatedMotion(settings.motionEmulation, settings.motionDistance, headPos, - app.screen.anchorPosition); + running.screen.anchorPosition); focusIn.head = headRot; - focusIn.picture = app.screen.rotation(); + focusIn.picture = running.screen.rotation(); // Static placement and head motion share the correction's sphere limit. - if (app.format.projection != Projection::Flat && app.video.originForward != 0) + if (running.format.projection != Projection::Flat && running.video.originForward != 0) focusIn.motion = focusIn.motion + - transformDir(focusIn.picture, {0, 0, -app.video.originForward}); - focusIn.zoom = app.screen.zoom; + transformDir(focusIn.picture, {0, 0, -running.video.originForward}); + focusIn.zoom = running.screen.zoom; // Only passthrough the eye images show: without alpha blending or // key green the video is drawn whole. focusIn.seeThrough = seeThrough(alphaPassthrough || keyPassthrough, - packedMask(app.currentFile, app.video), app.format, - app.video, !photo && player.tvGammaImage(), keyPicking); + packedMask(running.currentFile, running.video), running.format, + running.video, !photo && player.tvGammaImage(), keyPicking); // A second layer not found yet (by the keyframe check, which may not // have run or answered): looked for while the video plays. const bool probeWanted = maskProbeReady && !photo && focusIn.seeThrough.packedAlpha && - !app.video.maskLayersFound && !player.playback().paused && !player.seeking() && + !running.video.maskLayersFound && !player.playback().paused && !player.seeking() && !player.loading(); DepthPatchDrawer* probeDrawer = !photo && !videoTexture && maskProbeDirectReady && !keyPicker.busy() ? maskProbeDirect.source(player.directCurrent()) : nullptr; - if (maskProbe.update(now, app.currentFile, probeWanted, videoTexture, + if (maskProbe.update(now, running.currentFile, probeWanted, videoTexture, [&player] { return player.prepareFullSizeRead(); }, probeDrawer)) { - app.video.maskLayersVersion = VideoCheck::kLayersVersion; - app.video.maskLayersFound = true; - layersSeen.insert(app.currentFile); - storeVideo(VideoSettings::kMaskLayers); + running.video.maskLayersVersion = VideoCheck::kLayersVersion; + running.video.maskLayersFound = true; + passthrough.layersFound(); + running.storeVideo(VideoSettings::kMaskLayers); } // The key's colour where it was pointed at: read once, then taken as // the video's background, and the menu comes back. A frame that stays @@ -4003,9 +3123,9 @@ int run(Options opts) { KeyColour picked; switch (keyPicker.result(picked)) { case KeyPicker::Result::Picked: - app.video.greenScreen.source = KeySource::Picked; - app.video.greenScreen.picked = picked; - storeVideoSoon(VideoSettings::kGreenScreen); + running.video.greenScreen.source = KeySource::Picked; + running.video.greenScreen.picked = picked; + running.storeVideoSoon(VideoSettings::kGreenScreen); endKeyPick(); std::printf("Background key: picked %d, %d, %d\n", picked.r, picked.g, picked.b); break; @@ -4033,11 +3153,11 @@ int run(Options opts) { auto ready = [](const auto& f) { return f.valid() && f.wait_for(std::chrono::seconds(0)) == std::future_status::ready; }; - const bool refused = player.decoderRefused() && !app.currentFile.empty(); + const bool refused = player.decoderRefused() && !running.currentFile.empty(); const uint64_t opening = player.loadCount(); if (refused && r.handled != opening && !r.holders.valid() && !r.freed.valid()) { r.handled = opening; - r.path = app.currentFile; + r.path = running.currentFile; r.at = player.refusedAt(); r.ask = false; // Refused again once freed: not Steam's doing, or not only. @@ -4078,7 +3198,7 @@ int run(Options opts) { if (ready(r.freed)) { r.freed.get(); r.busy = Busy::No; - if (current && app.currentFile == r.path) { + if (current && running.currentFile == r.path) { r.retry = opening + 1; // load() counts one more player.load(r.path, r.at); } @@ -4139,10 +3259,7 @@ int run(Options opts) { previousRunCrashed() && diagnostics.state() != DiagnosticsExport::State::Saved; view.playback = player.playback(); view.hardwareAv1 = player.hardwareAv1(); - if (heldSeek.holding() || heldSeekLanding) { - view.playback.position = heldSeekTarget; - if (heldSeekPaused) view.playback.paused = false; // only waiting for the stick - } + stickSeek.fill(view.playback); // Software decoding the strip warns of, once it has lasted a second // (not a decoder restarting after a seek). if (photo || loading || !videoImage || player.counts().decoder != "no") @@ -4152,48 +3269,47 @@ int run(Options opts) { view.softwareDecoding = softwareSince >= 0 && now - softwareSince >= 1.0; view.scripts = settings.scripts; view.scriptStatus = scripts.status(); - view.format = app.format; - view.halfPacked = isHalfPacked(app.format); - view.screen = ScreenView::of(app.screen.size); - view.currentFile = app.currentFile; + view.format = running.format; + view.halfPacked = isHalfPacked(running.format); + view.screen = ScreenView::of(running.screen.size); + view.currentFile = running.currentFile; view.playbackFailed = player.failed(); - view.discEncrypted = player.failed() && bdmv::isEncrypted(app.currentFile); - view.decoderBusy = player.decoderRefused() && decoderRescue.path == app.currentFile && + view.discEncrypted = player.failed() && bdmv::isEncrypted(running.currentFile); + view.decoderBusy = player.decoderRefused() && decoderRescue.path == running.currentFile && (decoderRescue.busy == decoder_holders::Busy::Steam || decoderRescue.busy == decoder_holders::Busy::StillBusy); view.accent = settings.accent; view.floatingSubtitles = settings.floatingSubtitles; - view.streaming = isStream(app.currentFile); + view.streaming = isStream(running.currentFile); view.videoWidth = photo ? photoWidth : player.width(); view.videoHeight = photo ? photoHeight : player.height(); - if (photo) view.playback.title = std::filesystem::path(app.currentFile).filename().string(); + if (photo) view.playback.title = std::filesystem::path(running.currentFile).filename().string(); view.background = settings.background; view.autoPassthrough = settings.autoPassthrough; view.keyGreen = settings.keyGreen; view.passthroughAvailable = passthroughAvailable; view.passthrough = alphaPassthrough || keyPassthrough; - view.greenScreen = app.video.greenScreen; - view.colourKey = app.video.colourKeyed(); - view.keyColour = app.video.keyColour(); + view.greenScreen = running.video.greenScreen; + view.colourKey = running.video.colourKeyed(); + view.keyColour = running.video.keyColour(); view.keyPicking = !app.keyPickFor.empty(); view.keyPickNote = app.keyPickNote; - view.fillChecked = app.video.fillCheckVersion > 0; - view.fillChecking = fillCheckPending; - view.greenScreenFound = app.video.greenCheckVersion > 0 && app.video.greenScreenFound; - view.packedAlpha = packedMask(app.currentFile, app.video); - view.maskFormat = maskFormat(app.format); - view.maskLayers = app.video.maskLayersFound; - view.secondLayerHidden = app.video.secondLayerHidden; - view.opacity = app.video.opacity; + view.fillChecked = running.video.fillCheckVersion > 0; + view.greenScreenFound = running.video.greenCheckVersion > 0 && running.video.greenScreenFound; + view.packedAlpha = packedMask(running.currentFile, running.video); + view.maskFormat = maskFormat(running.format); + view.maskLayers = running.video.maskLayersFound; + view.secondLayerHidden = running.video.secondLayerHidden; + view.opacity = running.video.opacity; view.opacityApplies = canBlend; view.subtitleSize = settings.subtitleSize; view.subtitleRaise = settings.subtitleRaise; view.subtitleDistance = settings.subtitleDistance; - view.photo = !app.currentFile.empty() && isPhotoFile(app.currentFile); + view.photo = !running.currentFile.empty() && isPhotoFile(running.currentFile); // A scene from Stash's stream only through Stash (docs/alpha/delete-file.md). // A scene played from its server: only through a server that deletes. - view.deletable = app.currentFile.empty() || view.streaming ? MenuView::Deletable::No - : !isStashScene(app.currentFile) ? MenuView::Deletable::Yes + view.deletable = running.currentFile.empty() || view.streaming ? MenuView::Deletable::No + : !isStashScene(running.currentFile) ? MenuView::Deletable::Yes : !mediaServer(settings.stash.kind).abilities().deleteFiles ? MenuView::Deletable::No : !settings.stash.writeBack ? MenuView::Deletable::NeedsSendToStash @@ -4201,21 +3317,15 @@ int run(Options opts) { : MenuView::Deletable::Yes; view.slideshowSeconds = app.slideshowSeconds; view.afterVideo = afterVideo(); - view.brightness = app.video.brightness; - view.contrast = app.video.contrast; - view.saturation = app.video.saturation; - view.balance = roomMatching ? roomBalance : app.video.balance; - view.roomMatch = !roomReadable ? RoomMatch::Hidden - : !blended ? RoomMatch::Off - : roomLight.reading() ? RoomMatch::Reading - : now < roomFailedUntil ? RoomMatch::Failed - : RoomMatch::Ready; - view.roomMatched = roomMatched; + view.brightness = running.video.brightness; + view.contrast = running.video.contrast; + view.saturation = running.video.saturation; + passthrough.fill(view, blended, roomMatching, now); view.matchColour = settings.matchColour; view.matchBrightness = settings.matchBrightness; view.tvGamma = settings.tvGamma; - view.zoom = app.video.zoom; - view.originForward = static_cast(std::lround(app.video.originForward * 100)); + view.zoom = running.video.zoom; + view.originForward = static_cast(std::lround(running.video.originForward * 100)); view.videoMipmaps = settings.videoMipmaps; view.antiShimmer = antiShimmer; view.sharpen = settings.sharpen; @@ -4257,8 +3367,8 @@ int run(Options opts) { view.resolutionNotice = settings.resolutionNotice; view.focus.settings = focusSettings; view.focus.preferences = settings.focusPrefs; - view.focus.own = app.video.hasFocus; - view.focus.supported = stereoCorrectionSupported(app.format) && xr.eyeCount() == 2; + view.focus.own = running.video.hasFocus; + view.focus.supported = stereoCorrectionSupported(running.format) && xr.eyeCount() == 2; view.focus.unavailable = !autofocus.available(); view.focus.targetNotice = targetNotice(focusTargets.status()); view.motionEmulation = settings.motionEmulation; @@ -4377,7 +3487,7 @@ int run(Options opts) { menu.pointingAtVolume(); if (videoImage && !photo && !player.playback().paused && !panel.open && headValid) { const Vec3 ahead = transformDir(rotation(headRot), {0.0f, 0.0f, -1.0f}); - const Vec3 centre = transformDir(app.screen.rotation(), {0.0f, 0.0f, -1.0f}); + const Vec3 centre = transformDir(running.screen.rotation(), {0.0f, 0.0f, -1.0f}); // Only where something recenters (a hint names it). const int recenter = static_cast(ControlAction::Recenter); f.videoAway = dot(ahead, centre) < std::cos(70.0f * kPi / 180) && @@ -4403,7 +3513,7 @@ int run(Options opts) { // menu closed, in place of the menu's (which goes at once). const bool panelOn[2] = {panel.open && menu.panelShown(Menu::kMain), panel.open && menu.panelShown(Menu::kBrowser)}; - const bool heldStrip = !panel.open && heldSeekBar && (heldSeek.holding() || now < heldSeekBarUntil); + const bool heldStrip = !panel.open && stickSeek.stripShown(now); if (heldStrip) { menuFade.hide(); for (PanelFade& f : panelFades) { @@ -4413,13 +3523,13 @@ int run(Options opts) { } // The seek bar preview: a frame of the video where the pointer is. double hoverFraction = 0; - if (panel.open && !loading && !app.currentFile.empty() && menu.seekHover(hoverFraction)) { + if (panel.open && !loading && !running.currentFile.empty() && menu.seekHover(hoverFraction)) { SeekPreview::Playing playing; - playing.location = app.currentFile; + playing.location = running.currentFile; playing.duration = player.playback().duration; - playing.format = app.format; + playing.format = running.format; playing.views = player.playback().views; - playing.flip = app.flipVideo; + playing.flip = running.flipVideo; seekPreview.show(hoverFraction, playing, panel.panel(menu, Menu::kMain)); } else if (panelOn[Menu::kMain] || !panelFades[Menu::kMain].fade.drawn()) { // it fades with the strip seekPreview.hide(); @@ -4428,41 +3538,41 @@ int run(Options opts) { : keyPassthrough ? ClearMode::KeyGreen : ClearMode::Dark; // The night sky around the flat screen (with passthrough: the room). - scene.sky = app.format.projection == Projection::Flat && settings.background && + scene.sky = running.format.projection == Projection::Flat && settings.background && scene.clear == ClearMode::Dark; VideoDraw& video = scene.video.emplace(); video.texture = videoImage; - video.format = app.format; + video.format = running.format; video.frameAspect = frameAspect; - video.flip = app.flipVideo; - video.screen = app.screen; + video.flip = running.flipVideo; + video.screen = running.screen; video.photo = photo; video.seeThrough = focusIn.seeThrough; - video.opacity = peek ? 0 : app.video.opacity; - const std::array gains = (roomMatching ? roomBalance : app.video.balance).gains(); + video.opacity = peek ? 0 : running.video.opacity; + const std::array gains = passthrough.balance(roomMatching).gains(); for (int i = 0; i < 3; ++i) video.balance[i] = gains[i] - 1.0f; // Brightness etc. are applied while drawing to photos, and to videos // while a mask or key reads the frame; else mpv (or YuvColor) does it. const bool readsFrame = video.readsFrame(scene.clear); player.setPlainPicture(readsFrame); if (photo || readsFrame) { - video.adjust[0] = app.video.brightness / 100.0f; - video.adjust[1] = app.video.contrast / 100.0f; - video.adjust[2] = app.video.saturation / 100.0f; + video.adjust[0] = running.video.brightness / 100.0f; + video.adjust[1] = running.video.contrast / 100.0f; + video.adjust[2] = running.video.saturation / 100.0f; } video.tvGamma = !photo && player.tvGammaImage(); video.mipmaps = photo || settings.videoMipmaps; // photos always have theirs video.antiShimmer = antiShimmer; video.look = settings.toneLook; video.sharpen = settings.sharpen / 100.0f; - video.key = app.video.keySliders(); + video.key = running.video.keySliders(); video.correction = focusOut.correction; shownCorrection = focusOut.correction.eyes[0]; if (videoImage && xr.eyeCount() > 0) { - const ScreenSurface screen(app.screen, eyeDisplayAspect(app.format, frameAspect)); - samplingLog.update(describeEyeSampling(app.format, photo ? photoWidth : player.width(), + const ScreenSurface screen(running.screen, eyeDisplayAspect(running.format, frameAspect)); + samplingLog.update(describeEyeSampling(running.format, photo ? photoWidth : player.width(), photo ? photoHeight : player.height(), - app.screen.zoom, + running.screen.zoom, screen.width() / screen.distance(), xr.eyePixelsPerDegree(0, false), photo || settings.videoMipmaps), @@ -4484,12 +3594,12 @@ int run(Options opts) { overlays.push_back(item); }; if (!subtitles.empty() && headValid && !loading) - addText(subtitles, subtitlePlacement.update(app, player.aspect(), headPos, - yawFromQuat(headRot), settings)); + addText(subtitles, subtitlePlacement.update(running, player.aspect(), headPos, + yawFromQuat(headRot), settings)); if ((stillLoading || (!photo && player.failed())) && headValid) { // Where the picture will be, the size of the messages in front of the eyes. using decoder_holders::Busy; - const Busy busy = player.decoderRefused() && decoderRescue.path == app.currentFile + const Busy busy = player.decoderRefused() && decoderRescue.path == running.currentFile ? decoderRescue.busy : Busy::No; // While the decoder's holders are found or freed, it isn't a failure yet. @@ -4497,7 +3607,7 @@ int run(Options opts) { loadingText.set(menu, failed ? NoticeIcon::Warning : NoticeIcon::None, busy == Busy::Freeing ? strings().decoderBusy.freeing : !failed ? strings().loading - : bdmv::isEncrypted(app.currentFile) ? strings().discEncrypted + : bdmv::isEncrypted(running.currentFile) ? strings().discEncrypted : busy != Busy::No ? strings().decoderBusy.busy : strings().playbackFailed); constexpr float kAt = 2.0f, kScale = kAt / notice_place::kNear * notice_place::kScale; @@ -4509,7 +3619,7 @@ int run(Options opts) { PerformanceReadout::State state; const double period = xr.displayPeriod(); state.displayRate = period > 0 ? 1.0 / period : 0; - state.video = !photo && !app.currentFile.empty(); + state.video = !photo && !running.currentFile.empty(); state.paused = player.playback().paused; state.waiting = loading || player.seeking(); state.sourceFps = player.playback().fps; @@ -4640,7 +3750,7 @@ int run(Options opts) { // One at a time, the newest: a gesture's value shows on the flat // screen too, as does the screen's distance or height the stick sets. // The flat screen has no viewpoint, but See-through's opacity. - const bool flat = app.format.projection == Projection::Flat; + const bool flat = running.format.projection == Projection::Flat; const double valueUntil = flat ? opacityShownUntil : std::max(viewpointShownUntil, opacityShownUntil); const bool screenNewer = screenControl.shown() != GestureValue::Count && @@ -4688,17 +3798,17 @@ int run(Options opts) { char text[160]; const bool opacity = flat || opacityShownUntil > viewpointShownUntil; if (opacity) { - std::snprintf(text, sizeof(text), strings().opacityOverlay, app.video.opacity); + std::snprintf(text, sizeof(text), strings().opacityOverlay, running.video.opacity); } else { - const int percent = static_cast(std::lround(app.video.originForward * 100)); + const int percent = static_cast(std::lround(running.video.originForward * 100)); std::snprintf(text, sizeof(text), strings().viewpoint.overlay, viewpointText(percent).c_str()); } notices.show(menu, Notices::Value, opacity ? NoticeIcon::None : NoticeIcon::Viewpoint, text); } - if (now < passthroughShownUntil && passthroughWhy && app.video.passthrough && headValid) + if (const char* why = passthrough.notice(now); why && headValid) notices.show(menu, Notices::Passthrough, NoticeIcon::Passthrough, - std::string(passthroughWhy) + "\n" + strings().autoPassthrough.undo); + std::string(why) + "\n" + strings().autoPassthrough.undo); if (now < driveShownUntil && headValid) notices.show(menu, Notices::Drive, driveIcon, driveText); if (headValid) { @@ -4711,7 +3821,7 @@ int run(Options opts) { } // Match the room reads the view: nothing drawn meanwhile, so it shows the // room alone. - const bool roomBlank = roomLight.blank(); + const bool roomBlank = passthrough.roomBlank(); if (roomBlank) { scene.video.reset(); scene.overlays.clear(); @@ -4812,7 +3922,7 @@ int run(Options opts) { } } gpu.collect(); - if (drawn && roomBlank) roomLight.blankSubmitted(); + if (drawn && roomBlank) passthrough.blankSubmitted(); xr.setAlphaBlend(blended || peek || roomBlank); xr.releaseEyes(); if (shownAgain) xr.endFrameShownAgain(); @@ -4838,9 +3948,9 @@ int run(Options opts) { } if (quitSignal) std::printf("Quitting (signal %d)\n", static_cast(quitSignal)); if (opts.timing) std::printf("Frame reuse: frames %s\n", reuseReport(nullptr).c_str()); - saveUnsaved(); - keepVolume(); - keepSharpen(); + running.saveUnsaved(); + running.keepVolume(); + running.keepSharpen(); keepResume(); gazeCorrection.endSitting(); if (gazeCorrection.takeChanged()) { diff --git a/src/media_client.cpp b/src/media_client.cpp index 195a6ea..1ce5a55 100644 --- a/src/media_client.cpp +++ b/src/media_client.cpp @@ -39,11 +39,6 @@ bool mentions(const std::string& body, const char* word) { return lower.find(word) != std::string::npos; } -size_t appendToString(char* data, size_t size, size_t count, void* target) { - static_cast(target)->append(data, size * count); - return size * count; -} - // One request's progress: what it adds to the client's bytes received, and // whether the client was cancelled. struct Transfer { @@ -91,7 +86,7 @@ bool MediaClient::send(const Call& call, long& status, std::string& body, std::s curl_easy_setopt(curl, CURLOPT_POSTFIELDS, call.body.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, static_cast(call.body.size())); } - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, appendToString); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, stashAppend<>); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body); curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""); // compressed if the server can curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, quick_ ? kQuickConnectSeconds : kConnectSeconds); diff --git a/src/menu.cpp b/src/menu.cpp index b0b2145..48e9750 100644 --- a/src/menu.cpp +++ b/src/menu.cpp @@ -277,48 +277,7 @@ void Menu::update(const MenuView& view) { sliderChanged(MenuCommand::SetScriptRangeLow); sliderChanged(MenuCommand::SetScriptRangeHigh); } - // The eye size can change while playing (a later Auto resolution, or - // --resolution-cycle, or the Resolution slider, which redraws nothing - // itself): only the video settings page shows it. - if (page_ == Page::VideoSettings && videoSection_ == VideoSection::Display) { - const ResolutionStatus status = resolutionStatus(view); - const ResolutionStatus was = resolutionStatus(view_); - if (status != was || view.videoResolution != view_.videoResolution || - view.videoResolutionEffective != view_.videoResolutionEffective || - view.resolutionOverride != view_.resolutionOverride || - view.resolutionNotice != view_.resolutionNotice) { - // Its note coming or going, or taking a line more or less, moves the - // rows under it, so all of the page is drawn again; a new text in it - // only its own rows. - const int lines = resolutionNoteLines(view); - if (lines != resolutionNoteLines(view_)) - browserChanged(); - else - sliderChanged(MenuCommand::SetVideoResolution, kit::kRowStep + lines * kit::kNoteLine); - } - } - // The presets: only Video settings' Display shows them. Which one is - // lit changes only their group (unless the list is open); a new listing - // also the list, or the name being typed's check. - if (page_ == Page::VideoSettings) { - const bool lit = view.performancePreset != view_.performancePreset || - view.userPresetShown != view_.userPresetShown; - if (view.userPresetsListed != view_.userPresetsListed || - (lit && dropdown_ == Dropdown::Presets)) - browserChanged(); - else if (lit && presetBox_[2] > 0) - browserChanged(presetBox_[1] - 4, presetBox_[1] + presetBox_[3] + 4, presetBox_[0] - 4, - presetBox_[0] + presetBox_[2] + 4); - } - // ... and the Library's banner names it. - if (page_ == Page::Library && view.setupBanner && - view.performancePreset != view_.performancePreset) - dirty_ = true; - if (page_ == Page::Focus) { - if (!(view.focus == view_.focus)) focusChanged(view.focus); - if (view.motionEmulation != view_.motionEmulation) browserChanged(); - if (view.motionDistance != view_.motionDistance) sliderChanged(MenuCommand::SetMotionDistance); - } + if (const auto pageUpdate = pageKind().update) pageUpdate(*this, view); updateControls(view); if (library_ && (changed || library_->generation() != currentGeneration_)) { const VideoRecord current = library_->record(view.currentFile); @@ -350,9 +309,7 @@ void Menu::update(const MenuView& view) { // New thumbnails only matter while the file browser shows them. They are // drawn in batches: each redraw of the browser costs a little. const bool newThumbnails = thumbnailer_ && thumbnailer_->update(); - if (newThumbnails && - (page_ == Page::Files || page_ == Page::Library || page_ == Page::Offline || stashPage())) - thumbnailsPending_ = true; + if (newThumbnails && pageIs(PageKind::kThumbnails)) thumbnailsPending_ = true; if (setup_) SetupPages::update(*this); if (stashCovers_) updateStash(); if (thumbnailsPending_ && browserRow_ < 0) { @@ -434,6 +391,40 @@ void Menu::update(const MenuView& view) { } } +void Menu::updateVideoSettings(const MenuView& view) { + // The eye size can change while playing (a later Auto resolution, or + // --resolution-cycle, or the Resolution slider, which redraws nothing + // itself): only the video settings page shows it. + if (videoSection_ == VideoSection::Display) { + const ResolutionStatus status = resolutionStatus(view); + const ResolutionStatus was = resolutionStatus(view_); + if (status != was || view.videoResolution != view_.videoResolution || + view.videoResolutionEffective != view_.videoResolutionEffective || + view.resolutionOverride != view_.resolutionOverride || + view.resolutionNotice != view_.resolutionNotice) { + // Its note coming or going, or taking a line more or less, moves the + // rows under it, so all of the page is drawn again; a new text in it + // only its own rows. + const int lines = resolutionNoteLines(view); + if (lines != resolutionNoteLines(view_)) + browserChanged(); + else + sliderChanged(MenuCommand::SetVideoResolution, kit::kRowStep + lines * kit::kNoteLine); + } + } + // The presets: only Video settings' Display shows them. Which one is + // lit changes only their group (unless the list is open); a new listing + // also the list, or the name being typed's check. + const bool lit = view.performancePreset != view_.performancePreset || + view.userPresetShown != view_.userPresetShown; + if (view.userPresetsListed != view_.userPresetsListed || + (lit && dropdown_ == Dropdown::Presets)) + browserChanged(); + else if (lit && presetBox_[2] > 0) + browserChanged(presetBox_[1] - 4, presetBox_[1] + presetBox_[3] + 4, presetBox_[0] - 4, + presetBox_[0] + presetBox_[2] + 4); +} + bool Menu::panelShown(PanelId panel) const { if (setup_) return panel == kSetup; switch (panel) { @@ -1003,13 +994,90 @@ void Menu::glideList() { if (!listOpen() || atEnd || std::abs(d.velocity) < kGlideStop) d.gliding = false; } +// By Page, in its order: flags, layout, drawHeading, leave, update. +const Menu::PageKind Menu::kPages[] = { + {0, nullptr, nullptr, nullptr, nullptr}, // Main: no page in the browser + {PageKind::kGrouped | PageKind::kKept, // Settings + [](Menu& m) { + const size_t first = m.buttons_.size(); + m.layoutSettings(); + m.scrollGroups(first); + }, + nullptr, StashPages::leaveSettings, nullptr}, + {PageKind::kAlone | PageKind::kGrouped, // VideoSettings + [](Menu& m) { m.layoutVideoSettings(); }, nullptr, nullptr, + [](Menu& m, const MenuView& view) { m.updateVideoSettings(view); }}, + {PageKind::kList | PageKind::kPictures | PageKind::kThumbnails | PageKind::kKept, // Files + [](Menu& m) { m.layoutFilesPage(); }, + [](Menu& m, cairo_t* cr) { + m.drawFilesHeading(cr); + m.drawGroups(cr); // the SMB form's + }, + [](Menu& m) { m.saveBrowsing(); }, nullptr}, + {PageKind::kList | PageKind::kPictures | PageKind::kThumbnails | PageKind::kKept, // Library + [](Menu& m) { m.layoutLibraryPage(); }, + [](Menu& m, cairo_t* cr) { m.drawLibraryHeading(cr); }, + [](Menu& m) { m.libraryPlace_ = m.listPlace(m.libraryPaths(), m.gallery_ ? kGalleryColumns : 1); }, + [](Menu& m, const MenuView& view) { + // Its banner names the performance preset. + if (view.setupBanner && view.performancePreset != m.view_.performancePreset) m.dirty_ = true; + }}, + {PageKind::kAlone | PageKind::kGrouped, // Focus + [](Menu& m) { m.layoutFocus(); }, nullptr, nullptr, + [](Menu& m, const MenuView& view) { + if (!(view.focus == m.view_.focus)) m.focusChanged(view.focus); + if (view.motionEmulation != m.view_.motionEmulation) m.browserChanged(); + if (view.motionDistance != m.view_.motionDistance) m.sliderChanged(MenuCommand::SetMotionDistance); + }}, + {PageKind::kStash | PageKind::kList | PageKind::kPictures | PageKind::kThumbnails | + PageKind::kKept, // StashScenes + StashPages::layoutScenes, + [](Menu& m, cairo_t* cr) { StashPages::drawScenesHeading(m, cr); }, StashPages::leaveScenes, + nullptr}, + {PageKind::kStash | PageKind::kList | PageKind::kThumbnails | PageKind::kKept, // StashHome + StashPages::layoutHome, [](Menu& m, cairo_t* cr) { StashPages::drawHomeHeading(m, cr); }, + StashPages::leaveHome, nullptr}, + {PageKind::kStash | PageKind::kList | PageKind::kThumbnails | PageKind::kKept, // StashPerformers + StashPages::layoutPerformers, + [](Menu& m, cairo_t* cr) { StashPages::drawPerformersHeading(m, cr); }, + StashPages::leavePerformers, nullptr}, + {PageKind::kStash | PageKind::kList | PageKind::kThumbnails | PageKind::kKept, // StashPerformer + StashPages::layoutPerformer, + [](Menu& m, cairo_t* cr) { StashPages::drawPerformerHeading(m, cr); }, + StashPages::leavePerformer, nullptr}, + {PageKind::kStash | PageKind::kList | PageKind::kThumbnails | PageKind::kKept, // StashStudios + StashPages::layoutStudios, [](Menu& m, cairo_t* cr) { StashPages::drawStudiosHeading(m, cr); }, + StashPages::leaveStudios, nullptr}, + {PageKind::kStash | PageKind::kList | PageKind::kThumbnails | PageKind::kKept, // StashStudio + StashPages::layoutStudio, [](Menu& m, cairo_t* cr) { StashPages::drawStudioHeading(m, cr); }, + StashPages::leaveStudio, nullptr}, + {PageKind::kList | PageKind::kKept, // Network + [](Menu& m) { m.layoutNetworkPage(); }, nullptr, nullptr, nullptr}, + {PageKind::kList | PageKind::kPictures | PageKind::kThumbnails | PageKind::kKept, // Offline + [](Menu& m) { m.layoutOfflinePage(); }, + [](Menu& m, cairo_t* cr) { m.drawOfflineHeading(cr); }, + [](Menu& m) { m.offlineScroll_ = m.scrollOffset_ + m.scrollFraction_; }, nullptr}, + {PageKind::kGrouped, // Places + [](Menu& m) { + const size_t first = m.buttons_.size(); + m.layoutPlacesPage(); + if (m.placeRename_.path.empty()) + m.scrollGroups(first); + else + m.pageScrollMax_ = 0; // over the keyboard, it fits + }, + nullptr, nullptr, nullptr}, + {PageKind::kStash | PageKind::kThumbnails, // StashSceneDetails + StashPages::layoutSceneDetails, + [](Menu& m, cairo_t* cr) { StashPages::drawSceneDetailsHeading(m, cr); }, + StashPages::leaveSceneDetails, nullptr}, +}; + void Menu::showPage(Page page) { + static_assert(std::size(kPages) == static_cast(Page::StashSceneDetails) + 1); stopPreview(); - if (page_ == Page::Files) saveBrowsing(); - if (page_ == Page::Library) - libraryPlace_ = listPlace(libraryPaths(), gallery_ ? kGalleryColumns : 1); - if (page_ == Page::Offline) offlineScroll_ = scrollOffset_ + scrollFraction_; - if (stashMenu_) StashPages::leavePage(*this); + // Stash's pages are left only while its menu is there. + if (const auto leave = pageKind().leave; leave && (stashMenu_ || !stashPage())) leave(*this); // The folder's list keeps its place (openDirectory() restores it); the // other list pages restore theirs once shown (showListPage()). if (page != Page::Files) { @@ -1027,9 +1095,7 @@ void Menu::showPage(Page page) { // A change's notice on the Controls page is for the visit it was made in. if (controls_) controls_->noticeShown = false; page_ = page; - if (page == Page::Files || page == Page::Library || page == Page::Network || - page == Page::Settings || page == Page::Offline || stashListPage()) - lastBrowserPage_ = page; + if (pageIs(PageKind::kKept)) lastBrowserPage_ = page; editing_ = false; smbForm_ = {}; placeRename_ = {}; @@ -1271,12 +1337,7 @@ void Menu::layoutBrowser() { const bool naming = page_ == Page::VideoSettings && presetName_.open; pageTop_ = naming ? 0 : pageAloneTop(); const size_t first = buttons_.size(); - auto layoutAlone = [&] { - if (page_ == Page::VideoSettings) - layoutVideoSettings(); - else - layoutFocus(); - }; + auto layoutAlone = [&] { pageKind().layout(*this); }; layoutAlone(); // A row the every-row measure missed: the kept top rises by what is // missing, once, and the page is laid out again from there. @@ -1299,38 +1360,7 @@ void Menu::layoutBrowser() { return; } layoutNavigation(); - if (page_ == Page::Settings) { - const size_t first = buttons_.size(); - layoutSettings(); - scrollGroups(first); - return; - } - if (page_ == Page::Files) { - layoutFilesPage(); - return; - } - if (page_ == Page::Library) { - layoutLibraryPage(); - return; - } - if (page_ == Page::Network) { - layoutNetworkPage(); - return; - } - if (page_ == Page::Offline) { - layoutOfflinePage(); - return; - } - if (page_ == Page::Places) { - const size_t first = buttons_.size(); - layoutPlacesPage(); - if (placeRename_.path.empty()) - scrollGroups(first); - else - pageScrollMax_ = 0; // over the keyboard, it fits - return; - } - if (stashPage()) StashPages::layoutPage(*this); + pageKind().layout(*this); } // The navigation column (the kit's): File explorer with the places under it @@ -1891,15 +1921,8 @@ void Menu::drawBrowser(cairo_t* cr) { } drawKeyboard(cr); // Headings and labels. - if (page_ == Page::Files) { - drawFilesHeading(cr); - drawGroups(cr); // the SMB form's - } else if (page_ == Page::Library) { - drawLibraryHeading(cr); - } else if (page_ == Page::Offline) { - drawOfflineHeading(cr); - } else if (stashPage()) { - StashPages::drawHeading(*this, cr); + if (const auto heading = pageKind().drawHeading) { + heading(*this, cr); } else { drawGroups(cr); if (controlsShown()) drawControls(cr); diff --git a/src/menu.h b/src/menu.h index 0105418..ae23e42 100644 --- a/src/menu.h +++ b/src/menu.h @@ -366,8 +366,7 @@ class Menu { bool listOpen() const { if (view_.keyPicking) return false; // the page is hidden if (dialog_ == Dialog::WhatsNew) return whatsNew_.max > 0; // its notes, over the page - return page_ == Page::Files || page_ == Page::Library || page_ == Page::Network || - page_ == Page::Offline || stashListPage() || (groupedPage() && pageScrollMax_ > 0) || + return pageIs(PageKind::kList) || (groupedPage() && pageScrollMax_ > 0) || (page_ == Page::StashSceneDetails && side_.w > 0 && side_.max > 0); } @@ -446,6 +445,28 @@ class Menu { enum class Page { Main, Settings, VideoSettings, Files, Library, Focus, StashScenes, StashHome, StashPerformers, StashPerformer, StashStudios, StashStudio, Network, Offline, Places, StashSceneDetails }; // the strip's Scene tab (menu_stash_scene.cpp) + // What each page is and does, by Page (kPages, menu.cpp). + struct PageKind { + enum : unsigned { + kAlone = 1, // pageAlone() + kGrouped = 2, // groupedPage() + kList = 4, // a scrolling list or grid (listOpen()) + kStash = 8, // stashPage() + kPictures = 16, // picturesAlone() + kThumbnails = 32, // shows the thumbnailer's pictures (update()) + kKept = 64, // the browser where it was last (lastBrowserPage_) + }; + unsigned is; + void (*layout)(Menu&); // layoutBrowser(): the page under the navigation column, or alone + // drawBrowser(): its headings and labels under its buttons; none: its groups. + void (*drawHeading)(Menu&, cairo_t*); + void (*leave)(Menu&); // showPage(): before another page shows + // update(): the new view, before it is kept (view_ is the last). + void (*update)(Menu&, const MenuView&); + }; + static const PageKind kPages[]; + const PageKind& pageKind() const { return kPages[static_cast(page_)]; } + bool pageIs(unsigned flags) const { return (pageKind().is & flags) == flags; } enum class FileKind { Video, Subtitle }; enum class Icon { None, Play, Pause, Stop, Previous, Next, Back10, Forward10, VolumeUp, Mute, Folder, FolderUp, Settings, Recenter, Trash, Power, @@ -641,6 +662,7 @@ class Menu { // The settings pages (menu_settings.cpp, menu_video_settings.cpp, menu_focus.cpp). void layoutSettings(); void layoutVideoSettings(); + void updateVideoSettings(const MenuView& view); // its eye size and presets changed (update()) // The menu's parts (menu_parts.h): a page alone, its groups, their rows. class Row; class GroupLayout; @@ -763,7 +785,7 @@ class Menu { void drawBrowser(cairo_t* cr); // Video settings and stereo focus show on the page alone, without the // sources column. - bool pageAlone() const { return page_ == Page::VideoSettings || page_ == Page::Focus; } + bool pageAlone() const { return pageIs(PageKind::kAlone); } // ... and only as tall as their content needs: the panel's bottom where // it always is, its top lower. The page is laid out from pageTop_ down // (0 on the other pages); the panel starts at panelTop_, higher than that @@ -790,9 +812,7 @@ class Menu { // doesn't fit (the debug fit check). double videoSettingsBottom(bool advanced, bool check); double focusBottom(bool advanced, bool check); - bool groupedPage() const { - return page_ == Page::Settings || page_ == Page::Places || pageAlone(); - } + bool groupedPage() const { return pageIs(PageKind::kGrouped); } void layoutNavigation(); Places places_; LibraryIndex* index_ = nullptr; @@ -1197,10 +1217,7 @@ class Menu { Painted paintedPart(cairo_t* cr, double x, double y, double w, double h) const; mutable std::unordered_set logosComing_; // tiles drawn before their studio's logo // Pages whose only pictures are those of pictureOf(). - bool picturesAlone() const { - return page_ == Page::Files || page_ == Page::Library || page_ == Page::StashScenes || - page_ == Page::Offline; - } + bool picturesAlone() const { return pageIs(PageKind::kPictures); } // New thumbnails or covers: redraws only the rows and cards on screen whose // picture changed. False on pages that also show pictures of other kinds. bool picturesChanged(); @@ -2007,12 +2024,8 @@ class Menu { return stashMenu_ && (stashPage() || page_ == Page::Settings); } // Stash's pages with a scrolling list or grid (and a side column). - bool stashListPage() const { - return page_ == Page::StashScenes || page_ == Page::StashPerformers || - page_ == Page::StashPerformer || page_ == Page::StashStudios || - page_ == Page::StashStudio || page_ == Page::StashHome; - } - bool stashPage() const { return stashListPage() || page_ == Page::StashSceneDetails; } + bool stashListPage() const { return pageIs(PageKind::kStash | PageKind::kList); } + bool stashPage() const { return pageIs(PageKind::kStash); } const std::string& stashText() const; // First-run setup's pages, laid out and drawn by SetupPages (menu_setup.h) diff --git a/src/menu_stash.cpp b/src/menu_stash.cpp index e4f8b91..c1125ab 100644 --- a/src/menu_stash.cpp +++ b/src/menu_stash.cpp @@ -52,25 +52,6 @@ void StashPages::attach(Menu& m) { } } -void StashPages::leavePage(Menu& m) { - if (m.page_ == Menu::Page::StashScenes) - leaveScenes(m); - else if (m.page_ == Menu::Page::StashPerformers) - leavePerformers(m); - else if (m.page_ == Menu::Page::StashPerformer) - leavePerformer(m); - else if (m.page_ == Menu::Page::StashStudios) - leaveStudios(m); - else if (m.page_ == Menu::Page::StashStudio) - leaveStudio(m); - else if (m.page_ == Menu::Page::StashSceneDetails) - leaveSceneDetails(m); - else if (m.page_ == Menu::Page::StashHome) - leaveHome(m); - else if (m.page_ == Menu::Page::Settings) - leaveSettings(m); -} - void StashPages::leaveSettings(Menu& m) { if (!m.stashMenu_) return; StashMenu& st = state(m); @@ -90,32 +71,6 @@ bool StashPages::showAgain(Menu& m, Menu::Page page) { } } -void StashPages::layoutPage(Menu& m) { - switch (m.page_) { - case Menu::Page::StashHome: layoutHome(m); break; - case Menu::Page::StashScenes: layoutScenes(m); break; - case Menu::Page::StashPerformers: layoutPerformers(m); break; - case Menu::Page::StashPerformer: layoutPerformer(m); break; - case Menu::Page::StashStudios: layoutStudios(m); break; - case Menu::Page::StashStudio: layoutStudio(m); break; - case Menu::Page::StashSceneDetails: layoutSceneDetails(m); break; - default: break; - } -} - -void StashPages::drawHeading(const Menu& m, cairo_t* cr) { - switch (m.page_) { - case Menu::Page::StashHome: drawHomeHeading(m, cr); break; - case Menu::Page::StashScenes: drawScenesHeading(m, cr); break; - case Menu::Page::StashPerformers: drawPerformersHeading(m, cr); break; - case Menu::Page::StashPerformer: drawPerformerHeading(m, cr); break; - case Menu::Page::StashStudios: drawStudiosHeading(m, cr); break; - case Menu::Page::StashStudio: drawStudioHeading(m, cr); break; - case Menu::Page::StashSceneDetails: drawSceneDetailsHeading(m, cr); break; - default: break; - } -} - // Each frame: redraws for a new catalog, a sync's state, changed settings // or the library's changed ratings and plays, where they show. void StashPages::update(Menu& m) { diff --git a/src/menu_stash.h b/src/menu_stash.h index ac5706a..b326d2e 100644 --- a/src/menu_stash.h +++ b/src/menu_stash.h @@ -444,15 +444,12 @@ struct StashPages { // false if neither is open. static bool layoutSettingsPanel(Menu& m); static void layoutSendPanel(Menu& m); - static void leavePage(Menu& m); // showPage(): before another page shows // Settings' section left, or another server chosen in it: a Save under // way saves nothing, and what the last one found is no longer said. static void leaveSettings(Menu& m); // Menu::showListPage(): a Stash list page shown again as it was left; // false for none of Stash's. static bool showAgain(Menu& m, Menu::Page page); - static void layoutPage(Menu& m); // layoutBrowser(): the Stash page shown - static void drawHeading(const Menu& m, cairo_t* cr); // drawBrowser(): ... under its buttons static void drawButton(const Menu& m, cairo_t* cr, const Button& b, const double ink[4]); static void setText(Menu& m, const std::string& text); static MenuCommand submitText(Menu& m); diff --git a/src/passthrough.cpp b/src/passthrough.cpp new file mode 100644 index 0000000..0a91a90 --- /dev/null +++ b/src/passthrough.cpp @@ -0,0 +1,221 @@ +#include "passthrough.h" + +#include "file_util.h" +#include "library.h" +#include "menu_command.h" +#include "menu_view.h" +#include "see_through.h" +#include "settings.h" +#include "strings.h" +#include "xr_context.h" + +#include + +#include +#include + +namespace { + +// Passthrough switched on by itself says so this long. +constexpr double kPassthroughNoticeShown = 5.0; + +} // namespace + +bool Passthrough::roomShown() const { + return xr.alphaBlendSupported() && (video.passthrough || video.opacity < 100); +} + +void Passthrough::videoChanged(bool stream) { + this->stream = stream; + passthroughSettled = false; + greenCheckAsked = false; + fillCheckPending = false; + videoCheckAt = 0; + passthroughShownUntil = 0; +} + +// Passthrough switched on for a video made for it, saying so the first time ever. +void Passthrough::passthroughByItself(AutoPassthrough why) { + if (why == AutoPassthrough::None || video.passthrough) return; + video.passthrough = true; + if (why != AutoPassthrough::Mask && video.greenScreen.isDefault(video.colourKeyed())) + video.greenScreen.on = true; + const AutoPassthroughStrings& t = strings().autoPassthrough; + passthroughWhy = why == AutoPassthrough::Mask ? t.mask + : why == AutoPassthrough::Fill ? t.fill + : t.greenScreen; + if (!settings.passthroughNoticeSeen) { + passthroughShownUntil = glfwGetTime() + kPassthroughNoticeShown; + settings.passthroughNoticeSeen = true; + saveSettings(settings); + } + std::printf("Passthrough: on by itself (%s)\n", + why == AutoPassthrough::Mask ? "mask" + : why == AutoPassthrough::Fill ? "flat background" + : "green screen"); +} + +void Passthrough::settle(bool autoPassthroughOn, bool ready) { + if (passthroughSettled || !ready || currentFile.empty()) return; + passthroughSettled = true; + const std::string& path = currentFile; + if (autoPassthroughOn && !isPhotoFile(path) && !stream) + passthroughByItself(autoPassthrough(path, format, video)); + // The fill check, for the key's Automatic, also where passthrough is on by hand. + const bool fillWanted = fillCheckWanted(path, format, video) && + (autoPassthroughOn || video.passthrough); + if (!greenCheckAsked && !isPhotoFile(path) && !stream && + ((autoPassthroughOn && greenCheckWanted(path, format, video)) || fillWanted)) { + greenCheckAsked = fillCheckPending = true; + videoCheckAt = glfwGetTime() + 2.0; + videoCheckKind = VideoCheck::Kind::GreenScreen; + } + // Whatever the setting: a mask's second layer shows whenever passthrough does. + if (!isPhotoFile(path) && !stream && layerCheckWanted(path, format, video)) { + videoCheckAt = glfwGetTime() + 2.0; + videoCheckKind = VideoCheck::Kind::MaskLayers; + fillCheckPending = false; // a green screen check under way is replaced + } +} + +void Passthrough::poll(bool autoPassthroughOn) { + if (videoCheckAt > 0 && glfwGetTime() >= videoCheckAt) { + videoCheckAt = 0; + videoCheck.start(currentFile, format, videoCheckKind); + } + if (VideoCheck::Result checked; videoCheck.result(checked)) { + // Kept for the video, even if another plays by now: it runs once. + VideoSettings result; + const bool current = checked.path == currentFile; + if (current && checked.kind == VideoCheck::Kind::GreenScreen) fillCheckPending = false; + if (!checked.answered) { + // None: it runs again next time. + } else if (checked.kind == VideoCheck::Kind::GreenScreen) { + result.greenCheckVersion = VideoCheck::kGreenVersion; + result.greenScreenFound = checked.found; + result.fillCheckVersion = VideoCheck::kFillVersion; + result.fillFound = checked.fillFound; + if (checked.fillFound) result.fillColour = checked.fillColour; + const unsigned parts = VideoSettings::kGreenCheck | VideoSettings::kFillCheck; + library.setSettings(checked.path, result, parts); + if (current) { + video.take(result, parts); + if (autoPassthroughOn) + passthroughByItself(autoPassthrough(checked.path, format, video)); + } + } else if (!layersSeen.count(checked.path)) { // else found while it played + result.maskLayersVersion = VideoCheck::kLayersVersion; + result.maskLayersFound = checked.found; + library.setSettings(checked.path, result, VideoSettings::kMaskLayers); + if (current) video.take(result, VideoSettings::kMaskLayers); + } + } +} + +void Passthrough::switchedByHand() { + passthroughShownUntil = 0; + // On by hand after the video settled: the fill check its key's + // Automatic needs, if it wasn't asked for then. + const std::string& path = currentFile; + if (video.passthrough && passthroughSettled && !greenCheckAsked && !path.empty() && + !isPhotoFile(path) && !stream && fillCheckWanted(path, format, video)) { + greenCheckAsked = fillCheckPending = true; + videoCheckAt = glfwGetTime(); + videoCheckKind = VideoCheck::Kind::GreenScreen; + } +} + +const char* Passthrough::notice(double now) const { + return now < passthroughShownUntil && passthroughWhy && video.passthrough ? passthroughWhy + : nullptr; +} + +// A new reading, unless one runs (which keeps the count it was asked with). +void Passthrough::readRoom() { + if (roomLight.start()) roomAsked = balanceEdits; +} + +void Passthrough::applyRoomMatch() { + if (roomMatched && roomReading) + roomBalance.match(roomReading->light, roomReading->colour, roomReading->white, + settings.matchColour / 100.0f, settings.matchBrightness / 100.0f); +} + +void Passthrough::toggle() { + if (!roomShown()) return; // the switch is disabled while the room is hidden + roomFailedUntil = 0; + roomMatched = !roomMatched; + if (roomMatched) { + roomBalance = video.balance; + roomAsked = balanceEdits; // a reading still under way is for this one + if (roomReading) applyRoomMatch(); + else readRoom(); + } +} + +void Passthrough::readAgain() { + roomFailedUntil = 0; + if (roomMatched && roomShown()) readRoom(); +} + +unsigned Passthrough::setBalance(const MenuCommand& c) { + // The video's, saved, or while the room's is matched the room's, not. + const bool matching = roomMatched && roomShown(); + ColourBalance& balance = matching ? roomBalance : video.balance; + const int value = std::clamp(static_cast(c.value), -100, 100); + // Each its own part, as brightness etc.: an edit before the video's + // record is found leaves the other two as saved. + const bool warmth = c.type == MenuCommand::SetWarmth, tint = c.type == MenuCommand::SetTint; + (warmth ? balance.warmth : tint ? balance.tint : balance.exposure) = value; + if (matching) { + ++balanceEdits; + return 0; + } + return warmth ? VideoSettings::kWarmth + : tint ? VideoSettings::kTint + : VideoSettings::kExposure; +} + +void Passthrough::pictureReset() { + if (roomShown()) { // a hidden room keeps its switch for when it shows again + roomMatched = false; + ++balanceEdits; + } +} + +void Passthrough::resetMatch() { + if (roomReadable && roomMatched && roomShown()) { + const Settings defaults; + settings.matchColour = defaults.matchColour; + settings.matchBrightness = defaults.matchBrightness; + saveSettings(settings); + applyRoomMatch(); + } +} + +// A room reading that ended: kept for the run and matched while the +// switch is on (unless the sliders were moved or reset since it was asked +// for), or a moment saying it failed. The switch stays as it was set: +// with no earlier reading to use nothing is matched yet, and Read again +// tries once more. +void Passthrough::pollRoom() { + if (std::optional reading; roomLight.take(reading)) { + if (reading) { + roomReading = reading; + if (roomAsked == balanceEdits) applyRoomMatch(); + } else { + roomFailedUntil = glfwGetTime() + 4; + } + } +} + +void Passthrough::fill(MenuView& view, bool blended, bool roomMatching, double now) const { + view.fillChecking = fillCheckPending; + view.balance = roomMatching ? roomBalance : video.balance; + view.roomMatch = !roomReadable ? RoomMatch::Hidden + : !blended ? RoomMatch::Off + : roomLight.reading() ? RoomMatch::Reading + : now < roomFailedUntil ? RoomMatch::Failed + : RoomMatch::Ready; + view.roomMatched = roomMatched; +} diff --git a/src/passthrough.h b/src/passthrough.h new file mode 100644 index 0000000..d856785 --- /dev/null +++ b/src/passthrough.h @@ -0,0 +1,125 @@ +#pragma once + +#include "colour_balance.h" +#include "platform.h" +#include "room_light.h" +#include "video_check.h" + +#include +#include +#include + +class Library; +class XrContext; +enum class AutoPassthrough; +struct MenuCommand; +struct MenuView; +struct Settings; + +// The room behind the video: passthrough switching itself on for videos +// made for it, the checks that tell, and Match the room. `video`, +// `currentFile` and `format` are the playing video's, kept by the app. +// Main thread only. +class Passthrough { + public: + Passthrough(Settings& settings, Library& library, const XrContext& xr, VideoSettings& video, + const std::string& currentFile, const VideoFormat& format) + : settings(settings), library(library), xr(xr), video(video), currentFile(currentFile), + format(format) {} + + // The eye images are blended over the room (the headset's cameras, where + // the runtime blends): with passthrough on, or Opacity below 100, with or + // without passthrough (whose mask or key it doesn't bring). Match the room + // applies only then. + bool roomShown() const; + + // A video opens (`stream`: a link): it settles again, without the last + // one's checks and notice. + void videoChanged(bool stream); + // Automatic passthrough or Key green switched: for the video playing too. + void resettle() { passthroughSettled = false; } + // Each frame. Once the video's size (so its format) and its settings are + // known (`ready`): passthrough for a video made for it, and the checks it + // needs. `autoPassthroughOn`: the setting, where the room can show. + void settle(bool autoPassthroughOn, bool ready); + // Each frame: a check that is due starts, and one that finished is kept. + void poll(bool autoPassthroughOn); + // Passthrough switched by hand (it is already switched). + void switchedByHand(); + // MaskProbe found the playing video's second layer. + void layersFound() { layersSeen.insert(currentFile); } + // The notice's first line while passthrough switched on by itself says + // so; else null. + const char* notice(double now) const; + + const bool roomReadable = kStandaloneHeadset && RoomLight::available(); + bool matched() const { return roomMatched; } + // The menu's ToggleMatchRoom and ReadRoomAgain. + void toggle(); + void readAgain(); + // The menu's SetWarmth, SetTint or SetExposure: the video's part to save, + // or 0 if the room's balance took it. + unsigned setBalance(const MenuCommand& c); + // Picture reset the video's balance. + void pictureReset(); + // The passthrough group's reset: Match the room's strengths, where shown. + void resetMatch(); + // The strengths changed. + void applyRoomMatch(); + // The balance drawn: the room's while `matching` (on, the room shown), + // else the video's own. + const ColourBalance& balance(bool matching) const { + return matching ? roomBalance : video.balance; + } + // Each frame: a room reading that ended. + void pollRoom(); + bool roomBlank() const { return roomLight.blank(); } + void blankSubmitted() { roomLight.blankSubmitted(); } + // `blended` and `roomMatching` as the frame found them. + void fill(MenuView& view, bool blended, bool roomMatching, double now) const; + + private: + void passthroughByItself(AutoPassthrough why); + void readRoom(); + + Settings& settings; + Library& library; + const XrContext& xr; + VideoSettings& video; + const std::string& currentFile; + const VideoFormat& format; + + // Passthrough switching itself on for videos made for it (see_through.h): + // once per video, when its size and settings are known. + // The green screen check, or the mask layer check for a video with a + // packed mask (video_check.h). + VideoCheck videoCheck; + bool passthroughSettled = false; + bool stream = false; // the video is a link + bool greenCheckAsked = false; // the green screen check was asked for, for this video + bool fillCheckPending = false; // ... and its fill check hasn't answered yet + double videoCheckAt = 0; // glfwGetTime() the check starts, a moment after the video opens + VideoCheck::Kind videoCheckKind = VideoCheck::Kind::GreenScreen; + std::set layersSeen; // videos whose mask's second layer MaskProbe found + const char* passthroughWhy = nullptr; // the notice's first line + double passthroughShownUntil = 0; + // The colour balance: the video's own (RunningVideo::video.balance, saved with it), + // or while Match the room is on and the room is shown the room's, never + // saved: the room's light belongs to the room, not to a video. The switch + // stays as set for the run; with the room hidden (another video, passthrough + // off, Opacity at 100 %) the video's own is drawn, shown and edited until + // the room shows again. + RoomLight roomLight; + double roomFailedUntil = 0; // glfwGetTime() Match the room stops saying it failed + // Match the room, a switch: on, the room's reading (the run's first, or + // Read again's) times the strengths, from the video's own balance (grey + // cameras and a dark room leave the warmth and tint as they are). Moved by + // hand while on, the sliders stay as moved until the match is applied again + // (a strength, Read again). A reading is kept when it ends, but applied + // only if they were not moved by hand or reset after it was asked for. + ColourBalance roomBalance; + std::optional roomReading; // this run's latest + bool roomMatched = false; + // Hand moves while on, and Picture resets; their count when last asked. + unsigned balanceEdits = 0, roomAsked = 0; +}; diff --git a/src/photo_preloader.cpp b/src/photo_preloader.cpp index 4dadddf..0535411 100644 --- a/src/photo_preloader.cpp +++ b/src/photo_preloader.cpp @@ -1,6 +1,6 @@ #include "photo_preloader.h" -#include "thumbnailer.h" // frameScaler, scaleInto +#include "frame_scaler.h" #include "remote_avio.h" extern "C" { diff --git a/src/running_video.cpp b/src/running_video.cpp new file mode 100644 index 0000000..306a75e --- /dev/null +++ b/src/running_video.cpp @@ -0,0 +1,107 @@ +#include "running_video.h" + +#include "library.h" +#include "playback_state.h" +#include "settings.h" +#include "video_player.h" + +#include + +#include +#include +#include + +void printFormat(const VideoFormat& f, const char* reason) { + std::printf("Format (%s): %s, %s%s%s\n", reason, projectionName(f.projection), stereoName(f.stereo), + f.packing != Packing::Auto ? ", packing " : "", + f.packing != Packing::Auto ? packingName(f.packing) : ""); +} + +void RunningVideo::zoomBy(double percent) { + video.zoom = std::clamp(video.zoom + static_cast(percent / 100), + VideoSettings::kMinZoomPercent / 100.0f, + VideoSettings::kMaxZoomPercent / 100.0f); + screen.zoom = video.zoom; + unsavedParts |= VideoSettings::kZoom; // stored with the rest if the video changes first +} + +void RunningVideo::storeVideo(unsigned parts) { library.setSettings(currentFile, video, parts); } + +void RunningVideo::keepVolume() { + volumeSaveAt = 0; + const int volume = static_cast(std::lround(player.playback().volume)); + if (!volumeApplied || volume == settings.volume) return; + settings.volume = volume; + saveSettings(settings); +} + +void RunningVideo::storeVideoSoon(unsigned parts) { + unsavedParts |= parts; + if (saveAt == 0) saveAt = glfwGetTime() + 0.5; +} + +void RunningVideo::saveUnsaved() { + // A zoom being held: in whole percents, as when let go. + if (unsavedParts & VideoSettings::kZoom) { + video.zoom = std::round(video.zoom * 100) / 100; + screen.zoom = video.zoom; + } + // The screen's size is a setting for all videos (kScreen only marks it). + if (const unsigned parts = unsavedParts & ~VideoSettings::kScreen) storeVideo(parts); + if (unsavedParts & VideoSettings::kScreen) saveSettings(settings); // settings.screen + unsavedParts = 0; + saveAt = 0; +} + +void RunningVideo::keepScreenSize() { + screen.size = screen.size.clamped(); + settings.screen = screen.size; + storeVideoSoon(VideoSettings::kScreen); +} + +void RunningVideo::applyVideoSettings() { + if (video.hasFormat) { + format = video.format; + formatChosenByUser = true; + printFormat(format, "remembered"); + } + screen.zoom = video.zoom; + screen.size = settings.screen; + player.setPicture(video.brightness, video.contrast, video.saturation); + player.setTvGamma(settings.tvGamma); +} + +void RunningVideo::applyPicture(unsigned parts) { + if (parts != VideoSettings::kZoom) + player.setPicture(video.brightness, video.contrast, video.saturation); + screen.zoom = video.zoom; + storeVideoSoon(parts); +} + +void RunningVideo::keepSharpenSoon() { + if (sharpenSaveAt == 0) sharpenSaveAt = glfwGetTime() + 0.5; +} + +void RunningVideo::keepSharpen() { + if (sharpenSaveAt == 0) return; + sharpenSaveAt = 0; + matchPreset(); + saveSettings(settings); +} + +void RunningVideo::saveDue(bool zoomHeld) { + if (saveAt > 0 && glfwGetTime() >= saveAt) { + // A zoom still held waits for its letting go. + const unsigned held = zoomHeld ? unsavedParts & VideoSettings::kZoom : 0; + unsavedParts &= ~held; + saveUnsaved(); + unsavedParts |= held; + } + if (const int volume = static_cast(std::lround(player.playback().volume)); + !volumeApplied) + volumeApplied = volume == settings.volume; + else if (volume != settings.volume && volumeSaveAt == 0) + volumeSaveAt = glfwGetTime() + 1; + if (volumeSaveAt > 0 && glfwGetTime() >= volumeSaveAt) keepVolume(); + if (sharpenSaveAt > 0 && glfwGetTime() >= sharpenSaveAt) keepSharpen(); +} diff --git a/src/running_video.h b/src/running_video.h new file mode 100644 index 0000000..ffc366a --- /dev/null +++ b/src/running_video.h @@ -0,0 +1,79 @@ +#pragma once + +#include "flat_screen.h" +#include "video_format.h" +#include "video_memory.h" + +#include +#include + +class Library; +class VideoPlayer; +struct Settings; + +void printFormat(const VideoFormat& f, const char* reason); + +// The running video: its file, format, screen and what is remembered about +// it, and the changes to it and to the volume and Sharpen that are stored a +// moment later rather than at every step. Main thread only. +class RunningVideo { + public: + RunningVideo(VideoPlayer& player, Settings& settings, Library& library) + : player(player), settings(settings), library(library) {} + + std::string currentFile; + std::string streamOshash; // a Stash stream playing: its file's oshash as opened + ScreenPlacement screen; + VideoFormat format; + bool formatChosenByUser = false; // stops auto-detection from overriding the user + bool rememberFormat = false; // the user changed the format by key: store it + VideoSettings video; // what is remembered about the running video + // Settings (VideoSettings::Part) of the running video changed in a run of + // small steps (a slider, a held stick, a drag), stored at glfwGetTime() + // saveAt; 0 = none waiting. + unsigned unsavedParts = 0; + double saveAt = 0; + bool screenChanged = false; // by key: keep the flat screen's new size + bool flipVideo = false; + + // After a covered setting changes: the preset they now match, else + // Custom; set once, before the frames. + std::function matchPreset; + + void zoomBy(double percent); + // Stores these parts (VideoSettings::Part) of the running video's + // settings: only what the user changed, so the rest of a record still + // being found stays as it is. + void storeVideo(unsigned parts); + // Keeps the volume for all videos, as mpv reports it: a second after it + // changes, so at most once a second while it keeps changing. Not before + // mpv has reported the one set at start, so its default can't overwrite it. + void keepVolume(); + // Stores these parts soon, with whatever else changes meanwhile: at most + // twice a second while they keep changing. + void storeVideoSoon(unsigned parts); + // Stores what storeVideoSoon() still holds back. + void saveUnsaved(); + // The flat screen's size was changed: for all videos. + void keepScreenSize(); + // Puts the running video's remembered settings into effect. + void applyVideoSettings(); + // At once, also while a slider is held (mpv takes them asynchronously, + // direct frames recompute their colour matrix); stored soon, not per step. + void applyPicture(unsigned parts); + // Sharpen changed in a run of steps (its slider, a twist): matched and + // saved half a second after the first, at most twice a second. + void keepSharpenSoon(); + void keepSharpen(); + // Each frame: what is due to be stored. `zoomHeld`: a zoom is still held. + void saveDue(bool zoomHeld); + + private: + VideoPlayer& player; + Settings& settings; + Library& library; + + bool volumeApplied = false; + double volumeSaveAt = 0; + double sharpenSaveAt = 0; // 0 = none +}; diff --git a/src/server_json.h b/src/server_json.h index e0ab16a..7c4054e 100644 --- a/src/server_json.h +++ b/src/server_json.h @@ -6,9 +6,8 @@ #include #include -// Reading a media server's JSON answers without trusting their shape, for -// the kinds' clients: a member that is missing or of another type reads as -// empty. +// Reading JSON without trusting its shape, a media server's answers or a +// file's: a member that is missing or of another type reads as empty. namespace server_json { using json = nlohmann::json; diff --git a/src/sqlite_util.cpp b/src/sqlite_util.cpp new file mode 100644 index 0000000..c0c7632 --- /dev/null +++ b/src/sqlite_util.cpp @@ -0,0 +1,14 @@ +#include "sqlite_util.h" + +namespace sqlite { + +bool exec(sqlite3* db, const char* sql) { + return sqlite3_exec(db, sql, nullptr, nullptr, nullptr) == SQLITE_OK; +} + +int userVersion(sqlite3* db) { + Statement st(db, "PRAGMA user_version"); + return st.ok() && st.next() ? static_cast(st.integer(0)) : -1; +} + +} // namespace sqlite diff --git a/src/sqlite_util.h b/src/sqlite_util.h new file mode 100644 index 0000000..463d2b1 --- /dev/null +++ b/src/sqlite_util.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#include + +#include + +namespace sqlite { + +// One prepared statement, bound and read by column number. +class Statement { + public: + Statement(sqlite3* db, const char* sql) { + if (sqlite3_prepare_v2(db, sql, -1, &st_, nullptr) != SQLITE_OK) st_ = nullptr; + } + ~Statement() { sqlite3_finalize(st_); } + Statement(const Statement&) = delete; + Statement& operator=(const Statement&) = delete; + bool ok() const { return st_ != nullptr; } + + Statement& bind(int i, const std::string& s) { + if (s.empty()) sqlite3_bind_null(st_, i); + else sqlite3_bind_text(st_, i, s.data(), static_cast(s.size()), SQLITE_TRANSIENT); + return *this; + } + Statement& bind(int i, int64_t v) { + sqlite3_bind_int64(st_, i, v); + return *this; + } + Statement& bind(int i, double v) { + sqlite3_bind_double(st_, i, v); + return *this; + } + // Runs a bound INSERT; false on an error. + bool run() { + const bool done = sqlite3_step(st_) == SQLITE_DONE; + sqlite3_reset(st_); + sqlite3_clear_bindings(st_); + return done; + } + + bool next() { return sqlite3_step(st_) == SQLITE_ROW; } + std::string text(int i) const { + const unsigned char* t = sqlite3_column_text(st_, i); + return t ? std::string(reinterpret_cast(t), sqlite3_column_bytes(st_, i)) + : std::string(); + } + int64_t integer(int i) const { return sqlite3_column_int64(st_, i); } + double real(int i) const { return sqlite3_column_double(st_, i); } + + private: + sqlite3_stmt* st_ = nullptr; +}; + +// Runs SQL without results; false on an error (sqlite3_errmsg says which). +bool exec(sqlite3* db, const char* sql); + +// PRAGMA user_version; -1 if it can't be read. +int userVersion(sqlite3* db); + +} // namespace sqlite diff --git a/src/stash.cpp b/src/stash.cpp index 4e01352..23dad51 100644 --- a/src/stash.cpp +++ b/src/stash.cpp @@ -4,22 +4,15 @@ #include "offline.h" #include "run_log.h" #include "app_dirs.h" -#include "stash_store.h" #include "stash_stream.h" -#include "strings.h" #include -#include #include #include -#include -#include #include #include #include -namespace fs = std::filesystem; - namespace { // Stashes destroyed whose workers are still stopping. @@ -49,6 +42,8 @@ bool samePlace(const StashFolderFinder::Mapping& a, const StashFolderFinder::Map return true; } +} // namespace + std::vector historyOf(const StashCatalog& catalog, const Library& library) { std::vector history(catalog.scenes().size()); for (size_t i = 0; i < history.size(); ++i) { @@ -72,8 +67,6 @@ std::vector historyOf(const StashCatalog& catalog, const Library& return history; } -} // namespace - Stash::Stash(const StashSettings& settings, Library& library) : settings_(settings), library_(library), @@ -443,190 +436,3 @@ std::vector Stash::history() const { const auto& catalog = sync_->catalog(); return catalog ? historyOf(*catalog, library_) : std::vector(); } - -namespace { - -double msSince(std::chrono::steady_clock::time_point start) { - return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); -} - -uintmax_t folderSize(const fs::path& dir) { - std::error_code ec; - uintmax_t total = 0; - for (fs::recursive_directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec)) - if (it->is_regular_file(ec)) total += it->file_size(ec); - return total; -} - -// The time one query takes, in microseconds: the median of many. -double timeQuery(const StashCatalog& catalog, const StashFilter& filter, const StashOrder& order, - const std::vector& history, size_t& matches) { - std::vector times; - for (int i = 0; i < 101; ++i) { - const auto start = std::chrono::steady_clock::now(); - const StashResult result = catalog.query(filter, order, &history); - times.push_back(msSince(start) * 1000); - matches = result.scenes.size(); - } - std::nth_element(times.begin(), times.begin() + 50, times.end()); - return times[50]; -} - -} // namespace - -int runStashSyncDiagnostic(const StashSettings& settings) { - const char* name = mediaServer(settings.kind).name(); - if (settings.url.empty()) { - std::printf("%s: %s\n", name, strings().stash.setupHint); - return 0; - } - hideInRunLog(urlHost(settings.url), kHiddenServer); - std::printf("%s: syncing from %s\n", name, settings.url.c_str()); - // The library's formats and history, if it is free (not open in a - // running VideoFrameVR). - Library library; - library.load(); - const StashLibraryFormats formats = library.formatsByHash(); - - StashStatus status; - const auto start = std::chrono::steady_clock::now(); - const auto catalog = stashSyncOnce(settings, formats, status); - const double totalMs = msSince(start); - if (!catalog) { - std::printf("%s: sync failed: %s\n", name, status.error.c_str()); - return 1; - } - if (!status.error.empty()) std::printf("%s: %s\n", name, status.error.c_str()); - const StashCatalogStats& stats = catalog->stats(); - - std::printf("Server: %s %s\n", name, catalog->version().c_str()); - std::printf("Scenes: %d on the server, %d with a file here, %d from its stream, %d not listed\n", - stats.stashScenes, stats.listed, stats.streamed, - stats.stashScenes - stats.listed - stats.streamed); - for (const StashCatalogFolder& f : catalog->folders()) { - const std::string here = f.folder.empty() ? "" : settings.localPath(f.folder); - std::printf(" %s: %d scenes, %d here, %d from its stream%s%s\n", - f.folder.empty() ? "in none of the server's folders" : f.folder.c_str(), f.scenes, - f.listed, f.streamed, here.empty() ? "" : ", at ", here.c_str()); - } - std::printf(" VR %d (own format %d, frame %d, name %d, the server's tag %d), 2D %d\n", stats.vr, - stats.vrBy[1], stats.vrBy[2], stats.vrBy[3], stats.vrBy[4], stats.listed + stats.streamed - stats.vr); - int covers = 0; - for (const StashScene& s : catalog->scenes()) covers += !s.cover.empty(); - std::printf(" with a cover %d\n", covers); - int shown = 0, images = 0; - for (const StashPerformer& p : catalog->performers()) { - shown += stashShown(p.gender, false); - images += !p.image.empty(); - } - std::printf("Performers: %zu (%d shown without the male performers setting, %d with an image)\n", - catalog->performers().size(), shown, images); - int logos = 0, withScenes = 0; - for (const StashStudio& s : catalog->studios()) { - logos += !s.image.empty(); - withScenes += s.scenes > 0; - } - std::printf("Studios: %zu (%d with scenes here, %d with a logo)\n", catalog->studios().size(), - withScenes, logos); - int mergedGroups = 0; - for (const StashTag& t : catalog->tags()) mergedGroups += t.ids.size() > 1; - std::printf("Tags: %d on the server, %zu after merging duplicates (%d merged from 2 or more)\n", - stats.stashTags, catalog->tags().size(), mergedGroups); - std::printf("Groups: %zu\n", catalog->groups().size()); - if (library.available()) - std::printf("Library: %d fingerprinted videos, %d of them on the server\n", stats.libraryVideos, - stats.libraryMatched); - else - std::printf("Library: not available (in use?): no own formats, no history\n"); - - std::printf("Timings: fetch %.0f ms (%.1f MB), parse %.0f ms, store %.0f ms, files %.0f ms, " - "catalog %.0f ms; %.0f ms in all\n", - status.fetchMs, status.bytes / 1e6, status.parseMs, status.storeMs, stats.checkMs, - stats.buildMs, totalMs); - { - const auto loadStart = std::chrono::steady_clock::now(); - StashStore store(mediaServer(settings.kind)); - StashData data; - if (store.load(data)) { - const double loadMs = msSince(loadStart); - const StashCatalogStats copy = StashCatalog::build(data, settings, formats)->stats(); - std::printf(" from the local copy (at start): load %.0f ms, files %.0f ms, catalog %.0f ms\n", - loadMs, copy.checkMs, copy.buildMs); - } - } - - // Queries over every scene, with the facets. - const std::vector history = historyOf(*catalog, library); - int topTag = -1, topPerformer = -1, topHair = -1; - { - StashFilter vr; - vr.format = StashFormat::VR; - const StashResult r = catalog->query(vr, {}, &history); - if (!r.tags.empty()) topTag = r.tags.front().index; - if (!r.performers.empty()) topPerformer = r.performers.front().index; - const auto& hair = r.looks[static_cast(StashLookKind::Hair)]; - if (!hair.empty()) topHair = hair.front().index; - } - struct Case { - const char* name; - StashFilter filter; - StashOrder order; - }; - std::vector cases; - cases.push_back({"all scenes, by release date", {}, {}}); - { - Case c{"VR, by title", {}, {StashSort::Title, false, 0}}; - c.filter.format = StashFormat::VR; - cases.push_back(c); - } - { - Case c{"VR, top performer and tag, by rating", {}, {StashSort::Rating, true, 0}}; - c.filter.format = StashFormat::VR; - if (topPerformer >= 0) c.filter.performers.include = {topPerformer}; - if (topTag >= 0) c.filter.tags.include = {topTag}; - cases.push_back(c); - } - { - Case c{"looks, cast, resolution, history, random", {}, {StashSort::Random, true, 42}}; - if (topHair >= 0) c.filter.looks[static_cast(StashLookKind::Hair)].include = {topHair}; - c.filter.looks[static_cast(StashLookKind::Cup)].include = { - static_cast(StashCup::C), static_cast(StashCup::D)}; - c.filter.women = stashBit(StashWomen::One); - c.filter.men = stashBit(StashMen::None) | stashBit(StashMen::One); - c.filter.resolutions = stashBit(StashResolution::VR8K) | stashBit(StashResolution::VR7K) | - stashBit(StashResolution::VR6K) | stashBit(StashResolution::VR5K); - c.filter.history = stashBit(StashHistoryOption::Unplayed); - c.filter.addedSince = {static_cast(std::time(nullptr)) - 30 * 86400}; - cases.push_back(c); - } - { - Case c{"text search \"an\", tags any of, by plays", {}, {StashSort::Plays, true, 0}}; - c.filter.text = "an"; - c.filter.tags.all = false; - for (int i = 0; i < 3 && i < static_cast(catalog->tags().size()); ++i) - c.filter.tags.include.push_back(i); - cases.push_back(c); - } - std::printf("Queries over %zu scenes (filter, facets and order; median of 101):\n", - catalog->scenes().size()); - for (const Case& c : cases) { - size_t matches = 0; - const double us = timeQuery(*catalog, c.filter, c.order, history, matches); - std::printf(" %-44s %5zu scenes %6.0f us\n", c.name, matches, us); - } - { - const auto historyStart = std::chrono::steady_clock::now(); - historyOf(*catalog, library); - std::printf(" the library's history of every scene: %.2f ms\n", msSince(historyStart)); - } - - std::error_code ec; - const fs::path copy = StashStore::path(mediaServer(settings.kind)); - std::printf("Files: %s %.1f MB", copy.filename().c_str(), fs::file_size(copy, ec) / 1e6); - const fs::path imageCache = cacheDir() / mediaServer(settings.kind).id(); - if (fs::is_directory(imageCache, ec)) - std::printf(", image cache %.0f MB\n", folderSize(imageCache) / 1e6); - else - std::printf(", no image cache\n"); - return 0; -} diff --git a/src/stash.h b/src/stash.h index b1915fb..eb2fd9f 100644 --- a/src/stash.h +++ b/src/stash.h @@ -191,6 +191,9 @@ int stashSceneAt(const StashCatalog& catalog, const std::string& location); // stashStreamOf() requires); empty if not known for sure. std::string stashFilePathAt(const StashCatalog& catalog, const std::string& location); +// The library's history of each of the catalog's scenes, in its order. +std::vector historyOf(const StashCatalog& catalog, const Library& library); + // --stash-sync: one sync without the headset, with the settings (Stash on // for this run whatever they say), printing what it found and how long each // step and a few queries took. The exit code. diff --git a/src/stash_client.cpp b/src/stash_client.cpp index cd5c325..8fa713a 100644 --- a/src/stash_client.cpp +++ b/src/stash_client.cpp @@ -18,6 +18,7 @@ using json = nlohmann::json; using server_json::array; +using server_json::flag; using server_json::member; using server_json::number; using server_json::text; @@ -141,11 +142,6 @@ bool publicRefusal(long status, const std::string& body) { // Signing in: connecting may take this long. constexpr long kConnectSeconds = 10; -size_t appendToString(char* data, size_t size, size_t count, void* target) { - static_cast(target)->append(data, size * count); - return size * count; -} - // An id, which GraphQL sends as a string; 0 if there is none. int64_t id(const json& object) { const auto it = object.find("id"); @@ -214,8 +210,7 @@ void readRest(const json& d, StashData& data) { if (const auto ui = c->find("ui"); ui != c->end() && ui->is_object()) if (const std::string tag = text(*ui, "vrTag"); !tag.empty()) data.vrTag = tag; for (const json& f : array(member(member(d, "configuration"), "general"), "stashes")) { - const auto exclude = f.find("excludeVideo"); - const bool videos = exclude == f.end() || !exclude->is_boolean() || !exclude->get(); + const bool videos = !flag(f, "excludeVideo"); if (const std::string path = text(f, "path"); videos && !path.empty()) data.libraryFolders.push_back(path); } @@ -241,8 +236,7 @@ void readRest(const json& d, StashData& data) { p.careerStart = text(j, "career_start"); p.careerEnd = text(j, "career_end"); p.image = image(j, "image_path"); - const auto favorite = j.find("favorite"); - p.favorite = favorite != j.end() && favorite->is_boolean() && favorite->get(); + p.favorite = flag(j, "favorite"); data.performers.push_back(std::move(p)); } for (const json& j : array(member(d, "findStudios"), "studios")) @@ -532,7 +526,7 @@ bool StashClient::signIn(const std::string& user, const std::string& password, s std::string body; char message[CURL_ERROR_SIZE] = ""; curl_easy_setopt(curl, CURLOPT_COOKIEFILE, ""); // the session cookie, for the requests after - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, appendToString); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, stashAppend<>); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body); curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, kConnectSeconds); diff --git a/src/stash_diagnostic.cpp b/src/stash_diagnostic.cpp new file mode 100644 index 0000000..c07ae32 --- /dev/null +++ b/src/stash_diagnostic.cpp @@ -0,0 +1,204 @@ +#include "stash.h" + +#include "app_dirs.h" +#include "library.h" +#include "run_log.h" +#include "stash_store.h" +#include "strings.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace { + +double msSince(std::chrono::steady_clock::time_point start) { + return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); +} + +uintmax_t folderSize(const fs::path& dir) { + std::error_code ec; + uintmax_t total = 0; + for (fs::recursive_directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec)) + if (it->is_regular_file(ec)) total += it->file_size(ec); + return total; +} + +// The time one query takes, in microseconds: the median of many. +double timeQuery(const StashCatalog& catalog, const StashFilter& filter, const StashOrder& order, + const std::vector& history, size_t& matches) { + std::vector times; + for (int i = 0; i < 101; ++i) { + const auto start = std::chrono::steady_clock::now(); + const StashResult result = catalog.query(filter, order, &history); + times.push_back(msSince(start) * 1000); + matches = result.scenes.size(); + } + std::nth_element(times.begin(), times.begin() + 50, times.end()); + return times[50]; +} + +} // namespace + +int runStashSyncDiagnostic(const StashSettings& settings) { + const char* name = mediaServer(settings.kind).name(); + if (settings.url.empty()) { + std::printf("%s: %s\n", name, strings().stash.setupHint); + return 0; + } + hideInRunLog(urlHost(settings.url), kHiddenServer); + std::printf("%s: syncing from %s\n", name, settings.url.c_str()); + // The library's formats and history, if it is free (not open in a + // running VideoFrameVR). + Library library; + library.load(); + const StashLibraryFormats formats = library.formatsByHash(); + + StashStatus status; + const auto start = std::chrono::steady_clock::now(); + const auto catalog = stashSyncOnce(settings, formats, status); + const double totalMs = msSince(start); + if (!catalog) { + std::printf("%s: sync failed: %s\n", name, status.error.c_str()); + return 1; + } + if (!status.error.empty()) std::printf("%s: %s\n", name, status.error.c_str()); + const StashCatalogStats& stats = catalog->stats(); + + std::printf("Server: %s %s\n", name, catalog->version().c_str()); + std::printf("Scenes: %d on the server, %d with a file here, %d from its stream, %d not listed\n", + stats.stashScenes, stats.listed, stats.streamed, + stats.stashScenes - stats.listed - stats.streamed); + for (const StashCatalogFolder& f : catalog->folders()) { + const std::string here = f.folder.empty() ? "" : settings.localPath(f.folder); + std::printf(" %s: %d scenes, %d here, %d from its stream%s%s\n", + f.folder.empty() ? "in none of the server's folders" : f.folder.c_str(), f.scenes, + f.listed, f.streamed, here.empty() ? "" : ", at ", here.c_str()); + } + std::printf(" VR %d (own format %d, frame %d, name %d, the server's tag %d), 2D %d\n", stats.vr, + stats.vrBy[1], stats.vrBy[2], stats.vrBy[3], stats.vrBy[4], stats.listed + stats.streamed - stats.vr); + int covers = 0; + for (const StashScene& s : catalog->scenes()) covers += !s.cover.empty(); + std::printf(" with a cover %d\n", covers); + int shown = 0, images = 0; + for (const StashPerformer& p : catalog->performers()) { + shown += stashShown(p.gender, false); + images += !p.image.empty(); + } + std::printf("Performers: %zu (%d shown without the male performers setting, %d with an image)\n", + catalog->performers().size(), shown, images); + int logos = 0, withScenes = 0; + for (const StashStudio& s : catalog->studios()) { + logos += !s.image.empty(); + withScenes += s.scenes > 0; + } + std::printf("Studios: %zu (%d with scenes here, %d with a logo)\n", catalog->studios().size(), + withScenes, logos); + int mergedGroups = 0; + for (const StashTag& t : catalog->tags()) mergedGroups += t.ids.size() > 1; + std::printf("Tags: %d on the server, %zu after merging duplicates (%d merged from 2 or more)\n", + stats.stashTags, catalog->tags().size(), mergedGroups); + std::printf("Groups: %zu\n", catalog->groups().size()); + if (library.available()) + std::printf("Library: %d fingerprinted videos, %d of them on the server\n", stats.libraryVideos, + stats.libraryMatched); + else + std::printf("Library: not available (in use?): no own formats, no history\n"); + + std::printf("Timings: fetch %.0f ms (%.1f MB), parse %.0f ms, store %.0f ms, files %.0f ms, " + "catalog %.0f ms; %.0f ms in all\n", + status.fetchMs, status.bytes / 1e6, status.parseMs, status.storeMs, stats.checkMs, + stats.buildMs, totalMs); + { + const auto loadStart = std::chrono::steady_clock::now(); + StashStore store(mediaServer(settings.kind)); + StashData data; + if (store.load(data)) { + const double loadMs = msSince(loadStart); + const StashCatalogStats copy = StashCatalog::build(data, settings, formats)->stats(); + std::printf(" from the local copy (at start): load %.0f ms, files %.0f ms, catalog %.0f ms\n", + loadMs, copy.checkMs, copy.buildMs); + } + } + + // Queries over every scene, with the facets. + const std::vector history = historyOf(*catalog, library); + int topTag = -1, topPerformer = -1, topHair = -1; + { + StashFilter vr; + vr.format = StashFormat::VR; + const StashResult r = catalog->query(vr, {}, &history); + if (!r.tags.empty()) topTag = r.tags.front().index; + if (!r.performers.empty()) topPerformer = r.performers.front().index; + const auto& hair = r.looks[static_cast(StashLookKind::Hair)]; + if (!hair.empty()) topHair = hair.front().index; + } + struct Case { + const char* name; + StashFilter filter; + StashOrder order; + }; + std::vector cases; + cases.push_back({"all scenes, by release date", {}, {}}); + { + Case c{"VR, by title", {}, {StashSort::Title, false, 0}}; + c.filter.format = StashFormat::VR; + cases.push_back(c); + } + { + Case c{"VR, top performer and tag, by rating", {}, {StashSort::Rating, true, 0}}; + c.filter.format = StashFormat::VR; + if (topPerformer >= 0) c.filter.performers.include = {topPerformer}; + if (topTag >= 0) c.filter.tags.include = {topTag}; + cases.push_back(c); + } + { + Case c{"looks, cast, resolution, history, random", {}, {StashSort::Random, true, 42}}; + if (topHair >= 0) c.filter.looks[static_cast(StashLookKind::Hair)].include = {topHair}; + c.filter.looks[static_cast(StashLookKind::Cup)].include = { + static_cast(StashCup::C), static_cast(StashCup::D)}; + c.filter.women = stashBit(StashWomen::One); + c.filter.men = stashBit(StashMen::None) | stashBit(StashMen::One); + c.filter.resolutions = stashBit(StashResolution::VR8K) | stashBit(StashResolution::VR7K) | + stashBit(StashResolution::VR6K) | stashBit(StashResolution::VR5K); + c.filter.history = stashBit(StashHistoryOption::Unplayed); + c.filter.addedSince = {static_cast(std::time(nullptr)) - 30 * 86400}; + cases.push_back(c); + } + { + Case c{"text search \"an\", tags any of, by plays", {}, {StashSort::Plays, true, 0}}; + c.filter.text = "an"; + c.filter.tags.all = false; + for (int i = 0; i < 3 && i < static_cast(catalog->tags().size()); ++i) + c.filter.tags.include.push_back(i); + cases.push_back(c); + } + std::printf("Queries over %zu scenes (filter, facets and order; median of 101):\n", + catalog->scenes().size()); + for (const Case& c : cases) { + size_t matches = 0; + const double us = timeQuery(*catalog, c.filter, c.order, history, matches); + std::printf(" %-44s %5zu scenes %6.0f us\n", c.name, matches, us); + } + { + const auto historyStart = std::chrono::steady_clock::now(); + historyOf(*catalog, library); + std::printf(" the library's history of every scene: %.2f ms\n", msSince(historyStart)); + } + + std::error_code ec; + const fs::path copy = StashStore::path(mediaServer(settings.kind)); + std::printf("Files: %s %.1f MB", copy.filename().c_str(), fs::file_size(copy, ec) / 1e6); + const fs::path imageCache = cacheDir() / mediaServer(settings.kind).id(); + if (fs::is_directory(imageCache, ec)) + std::printf(", image cache %.0f MB\n", folderSize(imageCache) / 1e6); + else + std::printf(", no image cache\n"); + return 0; +} diff --git a/src/stash_http.h b/src/stash_http.h index f261484..a2a34c6 100644 --- a/src/stash_http.h +++ b/src/stash_http.h @@ -2,6 +2,8 @@ #include +#include +#include #include #include #include @@ -76,6 +78,17 @@ std::string stashUnreachable(CURLcode code, const StashSetupStrings& text); // Whether a transfer failed on the server's certificate alone (self-signed, // another issuer, expired, another name), which the user may accept. bool stashUntrusted(CURLcode code); +// A curl write callback: appends to the std::string in CURLOPT_WRITEDATA, +// and aborts the transfer if that would make it longer than kMax bytes. +template +size_t stashAppend(char* data, size_t size, size_t count, void* to) { + auto& bytes = *static_cast(to); + const size_t n = size * count; + if (bytes.size() + n > kMax) return 0; + bytes.append(data, n); + return n; +} + // The host a typed address names, in lower case: what a certificate // accepted unverified is kept for (StashSettings::unverifiedHost). std::string stashHost(const std::string& typed); diff --git a/src/stash_images.cpp b/src/stash_images.cpp index 636fa38..1a26e13 100644 --- a/src/stash_images.cpp +++ b/src/stash_images.cpp @@ -1,7 +1,7 @@ #include "stash_images.h" #include "media_server.h" -#include "thumbnailer.h" // scaleInto +#include "frame_scaler.h" #include #include @@ -528,13 +528,6 @@ bool encodePng(const Picture& p, std::string& out) { return ok; } -size_t appendDownload(char* data, size_t size, size_t count, void* target) { - auto* body = static_cast(target); - if (body->size() + size * count > kMaxDownload) return 0; // too big: aborts - body->append(data, size * count); - return size * count; -} - int stopWhenQuitting(void* quit, curl_off_t, curl_off_t, curl_off_t, curl_off_t) { return static_cast*>(quit)->load() ? 1 : 0; } @@ -1233,7 +1226,7 @@ void StashImages::State::downloadLoop() { CURLcode code = CURLE_FAILED_INIT; if (curl) { curl_easy_reset(curl); // keeps the connection - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, appendDownload); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, stashAppend); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L); diff --git a/src/stash_outbox.cpp b/src/stash_outbox.cpp new file mode 100644 index 0000000..3d53317 --- /dev/null +++ b/src/stash_outbox.cpp @@ -0,0 +1,213 @@ +#include "stash_outbox.h" + +#include "app_dirs.h" +#include "sqlite_util.h" + +#include +#include +#include +#include +#include + +#include + +namespace fs = std::filesystem; + +namespace { + +using sqlite::Statement; +using sqlite::exec; +using sqlite::userVersion; + +constexpr int kOutboxVersion = 1; + +constexpr const char* kOutboxSchema = R"( +CREATE TABLE ratings (oshash TEXT PRIMARY KEY, stars REAL NOT NULL, queued_at INTEGER NOT NULL) + WITHOUT ROWID; +CREATE TABLE plays ( + id INTEGER PRIMARY KEY, oshash TEXT NOT NULL, played_at INTEGER NOT NULL, + queued_at INTEGER NOT NULL); +CREATE TABLE sent_plays ( + oshash TEXT NOT NULL, scene_id INTEGER NOT NULL, played_at INTEGER NOT NULL, + sent_at INTEGER NOT NULL, found INTEGER NOT NULL); +CREATE INDEX sent_plays_oshash ON sent_plays (oshash); +PRAGMA user_version = 1; +)"; + +int64_t unixNow() { return static_cast(std::time(nullptr)); } + +} // namespace + +StashOutbox::StashOutbox(const std::string& server, bool original) : original_(original) { + uint64_t hash = 14695981039346656037ull; // FNV-1a + for (const unsigned char c : server) hash = (hash ^ c) * 1099511628211ull; + char name[48]; + std::snprintf(name, sizeof(name), "stash_outbox-%016llx.db", static_cast(hash)); + path_ = (dataDir() / name).string(); +} + +StashOutbox::~StashOutbox() { sqlite3_close(db_); } + +bool StashOutbox::adopt() { + std::error_code ec; + const std::string single = (dataDir() / "stash_outbox.db").string(); + if (!original_ || fs::exists(path_, ec) || !fs::exists(single, ec)) return true; + // Its write-ahead log folded in first, so it moves as one file; not while + // another connection has it open (a stopping write-back's). + sqlite3* db = nullptr; + bool ok = sqlite3_open_v2(single.c_str(), &db, SQLITE_OPEN_READWRITE, nullptr) == SQLITE_OK; + if (ok) { + Statement mode(db, "PRAGMA journal_mode = DELETE"); + ok = mode.ok() && mode.next() && mode.text(0) == "delete"; + } + sqlite3_close(db); + if (ok) fs::rename(single, path_, ec); + if (!ok || ec) { + error_ = "stash_outbox.db could not be taken over yet; nothing is sent"; + return false; + } + return true; +} + +bool StashOutbox::fail(const char* what) { + error_ = std::string(what) + (db_ ? std::string(" (") + sqlite3_errmsg(db_) + ")" : std::string()); + if (db_ && !sqlite3_get_autocommit(db_)) exec(db_, "ROLLBACK"); + return false; +} + +bool StashOutbox::open() { + if (db_) return true; + error_.clear(); + if (!adopt()) return false; + std::error_code ec; + fs::create_directories(dataDir(), ec); + if (sqlite3_open_v2(path_.c_str(), &db_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nullptr) != + SQLITE_OK) { + fail("stash_outbox.db could not be opened"); + sqlite3_close(db_); + db_ = nullptr; + return false; + } + sqlite3_busy_timeout(db_, 1000); + int version = userVersion(db_); + if (version == 0) { + bool empty = false; + { + Statement count(db_, "SELECT count(*) FROM sqlite_master"); + empty = count.ok() && count.next() && count.integer(0) == 0; + } + if (empty) { + if (!exec(db_, "PRAGMA journal_mode = WAL") || !exec(db_, "BEGIN") || + !exec(db_, kOutboxSchema) || !exec(db_, "COMMIT")) { + fail("stash_outbox.db could not be made"); + sqlite3_close(db_); + db_ = nullptr; + return false; + } + version = kOutboxVersion; + } + } + if (version != kOutboxVersion) { + // Not ours to throw away: what waits in it can't be fetched again. + error_ = "stash_outbox.db is from another version of VideoFrameVR; nothing is sent"; + sqlite3_close(db_); + db_ = nullptr; + return false; + } + exec(db_, "PRAGMA journal_mode = WAL"); // also for a file taken over + exec(db_, "PRAGMA synchronous = NORMAL"); + return true; +} + +bool StashOutbox::addRating(const std::string& oshash, float stars, bool replace) { + if (!open()) return false; + Statement st(db_, replace ? "INSERT OR REPLACE INTO ratings VALUES (?1, ?2, ?3)" + : "INSERT OR IGNORE INTO ratings VALUES (?1, ?2, ?3)"); + if (!st.ok() || !st.bind(1, oshash).bind(2, static_cast(stars)).bind(3, unixNow()).run()) + return fail("stash_outbox.db could not be written"); + return true; +} + +bool StashOutbox::addPlays(const std::string& oshash, int64_t at, int count) { + if (!open()) return false; + bool ok = exec(db_, "BEGIN IMMEDIATE"); + { + Statement st(db_, "INSERT INTO plays (oshash, played_at, queued_at) VALUES (?1, ?2, ?3)"); + ok = ok && st.ok(); + for (int i = 0; ok && i < count; ++i) ok = st.bind(1, oshash).bind(2, at).bind(3, unixNow()).run(); + } + if (!(ok && exec(db_, "COMMIT"))) return fail("stash_outbox.db could not be written"); + return true; +} + +bool StashOutbox::waiting(std::vector& ratings, std::vector& plays) { + ratings.clear(); + plays.clear(); + std::error_code ec; + if (!db_ && !adopt()) return false; + if (!db_ && !fs::exists(path_, ec)) return true; // nothing kept yet + if (!open()) return false; + bool ok = exec(db_, "BEGIN"); + { + Statement r(db_, "SELECT oshash, stars FROM ratings ORDER BY queued_at"); + ok = ok && r.ok(); + while (ok && r.next()) ratings.push_back({r.text(0), static_cast(r.real(1))}); + Statement p(db_, "SELECT id, oshash, played_at FROM plays ORDER BY id"); + ok = ok && p.ok(); + while (ok && p.next()) plays.push_back({p.integer(0), p.text(1), p.integer(2)}); + } + if (!(ok && exec(db_, "COMMIT"))) return fail("stash_outbox.db could not be read"); + return true; +} + +bool StashOutbox::ratingDone(const Rating& rating) { + if (!open()) return false; + Statement st(db_, "DELETE FROM ratings WHERE oshash = ?1 AND stars = ?2"); + if (!st.ok() || !st.bind(1, rating.oshash).bind(2, static_cast(rating.stars)).run()) + return fail("stash_outbox.db could not be written"); + return true; +} + +bool StashOutbox::playsDone(const std::vector& plays, int64_t scene, + const std::vector& found) { + if (!open()) return false; + bool ok = exec(db_, "BEGIN IMMEDIATE"); + { + Statement remove(db_, "DELETE FROM plays WHERE id = ?1"); + Statement keep(db_, "INSERT INTO sent_plays VALUES (?1, ?2, ?3, ?4, ?5)"); + ok = ok && remove.ok() && keep.ok(); + for (size_t i = 0; ok && i < plays.size(); ++i) + ok = remove.bind(1, plays[i].row).run() && + keep.bind(1, plays[i].oshash).bind(2, scene).bind(3, plays[i].at).bind(4, unixNow()) + .bind(5, static_cast(i < found.size() && found[i])).run(); + } + if (!(ok && exec(db_, "COMMIT"))) return fail("stash_outbox.db could not be written"); + return true; +} + +bool StashOutbox::drop(const std::vector& ratings, const std::vector& plays) { + if (!open()) return false; + bool ok = exec(db_, "BEGIN IMMEDIATE"); + { + Statement r(db_, "DELETE FROM ratings WHERE oshash = ?1 AND stars = ?2"); + Statement p(db_, "DELETE FROM plays WHERE id = ?1"); + ok = ok && r.ok() && p.ok(); + for (const Rating& x : ratings) + ok = ok && r.bind(1, x.oshash).bind(2, static_cast(x.stars)).run(); + for (const Play& x : plays) ok = ok && p.bind(1, x.row).run(); + } + if (!(ok && exec(db_, "COMMIT"))) return fail("stash_outbox.db could not be written"); + return true; +} + +bool StashOutbox::sent(std::unordered_map>& times) { + times.clear(); + std::error_code ec; + if (!db_ && !adopt()) return false; + if (!db_ && !fs::exists(path_, ec)) return true; + if (!open()) return false; + Statement st(db_, "SELECT oshash, played_at FROM sent_plays"); + if (!st.ok()) return fail("stash_outbox.db could not be read"); + while (st.next()) times[st.text(0)].push_back(st.integer(1)); + return true; +} diff --git a/src/stash_outbox.h b/src/stash_outbox.h new file mode 100644 index 0000000..9e02215 --- /dev/null +++ b/src/stash_outbox.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include +#include + +struct sqlite3; + +// Write-back's own file (docs/stash.md, "Write-back safety"): the app's +// ratings and plays waiting to be sent to Stash, and the plays sent (or +// found there already), so none is sent twice. Kept apart from stash.db, +// which is only a copy of Stash's data and is made anew whenever its layout +// changes: this file's contents can't be fetched again, so it is never +// deleted or made anew here (a file of another version is left alone and +// write-back waits). One per server, so another server never gets one's +// changes or takes its sent plays for its own. Made only once write-back +// has something to keep. Blocks on the file: one worker thread. +class StashOutbox { + public: + // `server` as StashClient::server() has it. + // `server`: what its file is named by (serverIdentity()). `original`: + // the one outbox from before there was one per server may be taken over + // (the first kind's only: it was that kind's). + StashOutbox(const std::string& server, bool original); + ~StashOutbox(); + StashOutbox(const StashOutbox&) = delete; + StashOutbox& operator=(const StashOutbox&) = delete; + + // Opens (or makes) the file; false (and error()) if it can't be used. + bool open(); + + struct Rating { + std::string oshash; + float stars = 0; // 0: cleared in the app, sent as null + }; + struct Play { + int64_t row = 0; + std::string oshash; + int64_t at = 0; // Unix seconds + }; + // A rating to send; `replace`: over one still waiting (else only if none waits). + bool addRating(const std::string& oshash, float stars, bool replace); + // `count` plays at `at`. + bool addPlays(const std::string& oshash, int64_t at, int count); + bool waiting(std::vector& ratings, std::vector& plays); + // Sent: leaves the outbox, unless it was replaced meanwhile. + bool ratingDone(const Rating& rating); + // Delivered to `scene`, each sent or (found) already in Stash's history: + // they leave the outbox and are kept as sent, in one transaction. + bool playsDone(const std::vector& plays, int64_t scene, const std::vector& found); + // Not Stash's (no scene has the oshash): they leave the outbox unsent. + bool drop(const std::vector& ratings, const std::vector& plays); + // The times of the plays sent or found, by oshash. + bool sent(std::unordered_map>& times); + const std::string& error() const { return error_; } + + // dataDir()/stash_outbox-.db. The single file kept + // before there was one per server, dataDir()/stash_outbox.db, was the one + // server's: it becomes the file of the server in the settings when write- + // back next looks for it. + const std::string& path() const { return path_; } + + private: + bool fail(const char* what); + // Takes the single file over if it is there; false if it can't be yet. + bool adopt(); + std::string path_; + bool original_ = false; + sqlite3* db_ = nullptr; + std::string error_; +}; diff --git a/src/stash_preview.cpp b/src/stash_preview.cpp index 8cdde1e..e2c4dfa 100644 --- a/src/stash_preview.cpp +++ b/src/stash_preview.cpp @@ -1,7 +1,7 @@ #include "stash_preview.h" #include "media_server.h" -#include "thumbnailer.h" // frameScaler +#include "frame_scaler.h" #include #include diff --git a/src/stash_store.cpp b/src/stash_store.cpp index fbaa389..4083ffe 100644 --- a/src/stash_store.cpp +++ b/src/stash_store.cpp @@ -1,10 +1,9 @@ #include "stash_store.h" #include "app_dirs.h" +#include "sqlite_util.h" #include -#include -#include #include #include #include @@ -17,6 +16,10 @@ namespace fs = std::filesystem; namespace { +using sqlite::Statement; +using sqlite::exec; +using sqlite::userVersion; + // The layout this build writes (PRAGMA user_version). A file with another // is made anew at the next sync, and meanwhile counts as no copy; but for // kVersionBefore's, which is read as it is: the same without files.id and @@ -77,60 +80,6 @@ std::vector splitLines(const std::string& text) { return list; } -// One prepared statement, bound and read by column number. -class Statement { - public: - Statement(sqlite3* db, const char* sql) { - if (sqlite3_prepare_v2(db, sql, -1, &st_, nullptr) != SQLITE_OK) st_ = nullptr; - } - ~Statement() { sqlite3_finalize(st_); } - Statement(const Statement&) = delete; - Statement& operator=(const Statement&) = delete; - bool ok() const { return st_ != nullptr; } - - Statement& bind(int i, const std::string& s) { - if (s.empty()) sqlite3_bind_null(st_, i); - else sqlite3_bind_text(st_, i, s.data(), static_cast(s.size()), SQLITE_TRANSIENT); - return *this; - } - Statement& bind(int i, int64_t v) { - sqlite3_bind_int64(st_, i, v); - return *this; - } - Statement& bind(int i, double v) { - sqlite3_bind_double(st_, i, v); - return *this; - } - // Runs a bound INSERT; false on an error. - bool run() { - const bool done = sqlite3_step(st_) == SQLITE_DONE; - sqlite3_reset(st_); - sqlite3_clear_bindings(st_); - return done; - } - - bool next() { return sqlite3_step(st_) == SQLITE_ROW; } - std::string text(int i) const { - const unsigned char* t = sqlite3_column_text(st_, i); - return t ? std::string(reinterpret_cast(t), sqlite3_column_bytes(st_, i)) - : std::string(); - } - int64_t integer(int i) const { return sqlite3_column_int64(st_, i); } - double real(int i) const { return sqlite3_column_double(st_, i); } - - private: - sqlite3_stmt* st_ = nullptr; -}; - -bool exec(sqlite3* db, const char* sql) { - return sqlite3_exec(db, sql, nullptr, nullptr, nullptr) == SQLITE_OK; -} - -int userVersion(sqlite3* db) { - Statement st(db, "PRAGMA user_version"); - return st.ok() && st.next() ? static_cast(st.integer(0)) : -1; -} - } // namespace std::string StashStore::path(const MediaServer& kind) { @@ -464,198 +413,3 @@ bool StashStore::scenes(const std::string& server, const std::string& kind, sqlite3_close(db); return ok; } - -namespace { - -constexpr int kOutboxVersion = 1; - -constexpr const char* kOutboxSchema = R"( -CREATE TABLE ratings (oshash TEXT PRIMARY KEY, stars REAL NOT NULL, queued_at INTEGER NOT NULL) - WITHOUT ROWID; -CREATE TABLE plays ( - id INTEGER PRIMARY KEY, oshash TEXT NOT NULL, played_at INTEGER NOT NULL, - queued_at INTEGER NOT NULL); -CREATE TABLE sent_plays ( - oshash TEXT NOT NULL, scene_id INTEGER NOT NULL, played_at INTEGER NOT NULL, - sent_at INTEGER NOT NULL, found INTEGER NOT NULL); -CREATE INDEX sent_plays_oshash ON sent_plays (oshash); -PRAGMA user_version = 1; -)"; - -int64_t unixNow() { return static_cast(std::time(nullptr)); } - -} // namespace - -StashOutbox::StashOutbox(const std::string& server, bool original) : original_(original) { - uint64_t hash = 14695981039346656037ull; // FNV-1a - for (const unsigned char c : server) hash = (hash ^ c) * 1099511628211ull; - char name[48]; - std::snprintf(name, sizeof(name), "stash_outbox-%016llx.db", static_cast(hash)); - path_ = (dataDir() / name).string(); -} - -StashOutbox::~StashOutbox() { sqlite3_close(db_); } - -bool StashOutbox::adopt() { - std::error_code ec; - const std::string single = (dataDir() / "stash_outbox.db").string(); - if (!original_ || fs::exists(path_, ec) || !fs::exists(single, ec)) return true; - // Its write-ahead log folded in first, so it moves as one file; not while - // another connection has it open (a stopping write-back's). - sqlite3* db = nullptr; - bool ok = sqlite3_open_v2(single.c_str(), &db, SQLITE_OPEN_READWRITE, nullptr) == SQLITE_OK; - if (ok) { - Statement mode(db, "PRAGMA journal_mode = DELETE"); - ok = mode.ok() && mode.next() && mode.text(0) == "delete"; - } - sqlite3_close(db); - if (ok) fs::rename(single, path_, ec); - if (!ok || ec) { - error_ = "stash_outbox.db could not be taken over yet; nothing is sent"; - return false; - } - return true; -} - -bool StashOutbox::fail(const char* what) { - error_ = std::string(what) + (db_ ? std::string(" (") + sqlite3_errmsg(db_) + ")" : std::string()); - if (db_ && !sqlite3_get_autocommit(db_)) exec(db_, "ROLLBACK"); - return false; -} - -bool StashOutbox::open() { - if (db_) return true; - error_.clear(); - if (!adopt()) return false; - std::error_code ec; - fs::create_directories(dataDir(), ec); - if (sqlite3_open_v2(path_.c_str(), &db_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nullptr) != - SQLITE_OK) { - fail("stash_outbox.db could not be opened"); - sqlite3_close(db_); - db_ = nullptr; - return false; - } - sqlite3_busy_timeout(db_, 1000); - int version = userVersion(db_); - if (version == 0) { - bool empty = false; - { - Statement count(db_, "SELECT count(*) FROM sqlite_master"); - empty = count.ok() && count.next() && count.integer(0) == 0; - } - if (empty) { - if (!exec(db_, "PRAGMA journal_mode = WAL") || !exec(db_, "BEGIN") || - !exec(db_, kOutboxSchema) || !exec(db_, "COMMIT")) { - fail("stash_outbox.db could not be made"); - sqlite3_close(db_); - db_ = nullptr; - return false; - } - version = kOutboxVersion; - } - } - if (version != kOutboxVersion) { - // Not ours to throw away: what waits in it can't be fetched again. - error_ = "stash_outbox.db is from another version of VideoFrameVR; nothing is sent"; - sqlite3_close(db_); - db_ = nullptr; - return false; - } - exec(db_, "PRAGMA journal_mode = WAL"); // also for a file taken over - exec(db_, "PRAGMA synchronous = NORMAL"); - return true; -} - -bool StashOutbox::addRating(const std::string& oshash, float stars, bool replace) { - if (!open()) return false; - Statement st(db_, replace ? "INSERT OR REPLACE INTO ratings VALUES (?1, ?2, ?3)" - : "INSERT OR IGNORE INTO ratings VALUES (?1, ?2, ?3)"); - if (!st.ok() || !st.bind(1, oshash).bind(2, static_cast(stars)).bind(3, unixNow()).run()) - return fail("stash_outbox.db could not be written"); - return true; -} - -bool StashOutbox::addPlays(const std::string& oshash, int64_t at, int count) { - if (!open()) return false; - bool ok = exec(db_, "BEGIN IMMEDIATE"); - { - Statement st(db_, "INSERT INTO plays (oshash, played_at, queued_at) VALUES (?1, ?2, ?3)"); - ok = ok && st.ok(); - for (int i = 0; ok && i < count; ++i) ok = st.bind(1, oshash).bind(2, at).bind(3, unixNow()).run(); - } - if (!(ok && exec(db_, "COMMIT"))) return fail("stash_outbox.db could not be written"); - return true; -} - -bool StashOutbox::waiting(std::vector& ratings, std::vector& plays) { - ratings.clear(); - plays.clear(); - std::error_code ec; - if (!db_ && !adopt()) return false; - if (!db_ && !fs::exists(path_, ec)) return true; // nothing kept yet - if (!open()) return false; - bool ok = exec(db_, "BEGIN"); - { - Statement r(db_, "SELECT oshash, stars FROM ratings ORDER BY queued_at"); - ok = ok && r.ok(); - while (ok && r.next()) ratings.push_back({r.text(0), static_cast(r.real(1))}); - Statement p(db_, "SELECT id, oshash, played_at FROM plays ORDER BY id"); - ok = ok && p.ok(); - while (ok && p.next()) plays.push_back({p.integer(0), p.text(1), p.integer(2)}); - } - if (!(ok && exec(db_, "COMMIT"))) return fail("stash_outbox.db could not be read"); - return true; -} - -bool StashOutbox::ratingDone(const Rating& rating) { - if (!open()) return false; - Statement st(db_, "DELETE FROM ratings WHERE oshash = ?1 AND stars = ?2"); - if (!st.ok() || !st.bind(1, rating.oshash).bind(2, static_cast(rating.stars)).run()) - return fail("stash_outbox.db could not be written"); - return true; -} - -bool StashOutbox::playsDone(const std::vector& plays, int64_t scene, - const std::vector& found) { - if (!open()) return false; - bool ok = exec(db_, "BEGIN IMMEDIATE"); - { - Statement remove(db_, "DELETE FROM plays WHERE id = ?1"); - Statement keep(db_, "INSERT INTO sent_plays VALUES (?1, ?2, ?3, ?4, ?5)"); - ok = ok && remove.ok() && keep.ok(); - for (size_t i = 0; ok && i < plays.size(); ++i) - ok = remove.bind(1, plays[i].row).run() && - keep.bind(1, plays[i].oshash).bind(2, scene).bind(3, plays[i].at).bind(4, unixNow()) - .bind(5, static_cast(i < found.size() && found[i])).run(); - } - if (!(ok && exec(db_, "COMMIT"))) return fail("stash_outbox.db could not be written"); - return true; -} - -bool StashOutbox::drop(const std::vector& ratings, const std::vector& plays) { - if (!open()) return false; - bool ok = exec(db_, "BEGIN IMMEDIATE"); - { - Statement r(db_, "DELETE FROM ratings WHERE oshash = ?1 AND stars = ?2"); - Statement p(db_, "DELETE FROM plays WHERE id = ?1"); - ok = ok && r.ok() && p.ok(); - for (const Rating& x : ratings) - ok = ok && r.bind(1, x.oshash).bind(2, static_cast(x.stars)).run(); - for (const Play& x : plays) ok = ok && p.bind(1, x.row).run(); - } - if (!(ok && exec(db_, "COMMIT"))) return fail("stash_outbox.db could not be written"); - return true; -} - -bool StashOutbox::sent(std::unordered_map>& times) { - times.clear(); - std::error_code ec; - if (!db_ && !adopt()) return false; - if (!db_ && !fs::exists(path_, ec)) return true; - if (!open()) return false; - Statement st(db_, "SELECT oshash, played_at FROM sent_plays"); - if (!st.ok()) return fail("stash_outbox.db could not be read"); - while (st.next()) times[st.text(0)].push_back(st.integer(1)); - return true; -} diff --git a/src/stash_store.h b/src/stash_store.h index 784ed8b..6f7584f 100644 --- a/src/stash_store.h +++ b/src/stash_store.h @@ -8,8 +8,6 @@ #include #include -struct sqlite3; - // The local copy of a media server's data: a file per kind in dataDir() // (stash.db, xbvr.db), SQLite, so that going to another kind and back // finds the copy as it was. Everything in it can be fetched again, so it is @@ -41,67 +39,3 @@ class StashStore { std::string path_; std::string error_; }; - -// Write-back's own file (docs/stash.md, "Write-back safety"): the app's -// ratings and plays waiting to be sent to Stash, and the plays sent (or -// found there already), so none is sent twice. Kept apart from stash.db, -// which is only a copy of Stash's data and is made anew whenever its layout -// changes: this file's contents can't be fetched again, so it is never -// deleted or made anew here (a file of another version is left alone and -// write-back waits). One per server, so another server never gets one's -// changes or takes its sent plays for its own. Made only once write-back -// has something to keep. Blocks on the file: one worker thread. -class StashOutbox { - public: - // `server` as StashClient::server() has it. - // `server`: what its file is named by (serverIdentity()). `original`: - // the one outbox from before there was one per server may be taken over - // (the first kind's only: it was that kind's). - StashOutbox(const std::string& server, bool original); - ~StashOutbox(); - StashOutbox(const StashOutbox&) = delete; - StashOutbox& operator=(const StashOutbox&) = delete; - - // Opens (or makes) the file; false (and error()) if it can't be used. - bool open(); - - struct Rating { - std::string oshash; - float stars = 0; // 0: cleared in the app, sent as null - }; - struct Play { - int64_t row = 0; - std::string oshash; - int64_t at = 0; // Unix seconds - }; - // A rating to send; `replace`: over one still waiting (else only if none waits). - bool addRating(const std::string& oshash, float stars, bool replace); - // `count` plays at `at`. - bool addPlays(const std::string& oshash, int64_t at, int count); - bool waiting(std::vector& ratings, std::vector& plays); - // Sent: leaves the outbox, unless it was replaced meanwhile. - bool ratingDone(const Rating& rating); - // Delivered to `scene`, each sent or (found) already in Stash's history: - // they leave the outbox and are kept as sent, in one transaction. - bool playsDone(const std::vector& plays, int64_t scene, const std::vector& found); - // Not Stash's (no scene has the oshash): they leave the outbox unsent. - bool drop(const std::vector& ratings, const std::vector& plays); - // The times of the plays sent or found, by oshash. - bool sent(std::unordered_map>& times); - const std::string& error() const { return error_; } - - // dataDir()/stash_outbox-.db. The single file kept - // before there was one per server, dataDir()/stash_outbox.db, was the one - // server's: it becomes the file of the server in the settings when write- - // back next looks for it. - const std::string& path() const { return path_; } - - private: - bool fail(const char* what); - // Takes the single file over if it is there; false if it can't be yet. - bool adopt(); - std::string path_; - bool original_ = false; - sqlite3* db_ = nullptr; - std::string error_; -}; diff --git a/src/stash_stream.cpp b/src/stash_stream.cpp index dbad4b6..3147eac 100644 --- a/src/stash_stream.cpp +++ b/src/stash_stream.cpp @@ -440,13 +440,6 @@ std::string httpDate(int64_t seconds) { return text; } -size_t keep(char* data, size_t size, size_t count, void* to) { - auto& bytes = *static_cast(to); - const size_t n = size * count; - if (bytes.size() + n > 64 * 1024) return 0; // a range was asked for - bytes.append(data, n); - return n; -} } // namespace std::string stashSource(std::string_view locator) { @@ -485,7 +478,8 @@ FileFingerprint stashFingerprint(const std::string& source, bool& gone) { uint64_t length = 0; curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, contentRange); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &length); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, keep); + // A range was asked for. + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, stashAppend<64 * 1024>); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bytes); curl_easy_setopt(curl, CURLOPT_FILETIME, 1L); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); diff --git a/src/stash_write_back.cpp b/src/stash_write_back.cpp index 7308c7b..fcd2b27 100644 --- a/src/stash_write_back.cpp +++ b/src/stash_write_back.cpp @@ -1,6 +1,7 @@ #include "stash_write_back.h" #include "media_client.h" +#include "stash_outbox.h" #include "stash_store.h" #include diff --git a/src/stick_seek.cpp b/src/stick_seek.cpp new file mode 100644 index 0000000..194e16d --- /dev/null +++ b/src/stick_seek.cpp @@ -0,0 +1,153 @@ +#include "stick_seek.h" + +#include "playback_state.h" +#include "video_player.h" +#include "vr_space.h" + +#include +#include + +namespace { + +// The seek bar a held seek shows with the menu closed stays this long after +// the stick lets go. +constexpr double kSeekBarLinger = 0.6; +// While a seek is held, the paused video shows the picture at the target at +// most this often, once the last one is shown and the target has moved on +// this far (each is a decoder restart on the Frame, about 250 ms). +constexpr double kHeldPictureEvery = 0.5; // seconds +constexpr double kHeldPictureMove = 1.0; // seconds of video + +} // namespace + +bool StickSeek::update(const ControllerState& input, const Frame& frame) { + const double now = frame.now; + const PlaybackState& p = player.playback(); + // A stick counts sideways once it is mostly sideways; then all of its + // sideways push, so a thumb drifting up or down keeps the hold. Of + // the two, the one pushed further sideways seeks, until it lets go. + if (!heldSeek.active()) { + float most = 0.0f; + for (int h = 0; h < 2; ++h) { + const HandState& g = input.hands[h]; + if (std::abs(g.stickX) > std::abs(g.stickY) && std::abs(g.stickX) > most) { + most = std::abs(g.stickX); + heldSeekHand = h; + } + } + } + const HandState& seekStick = input.hands[heldSeekHand]; + const float x = frame.sticksTaken ? 0.0f : seekStick.stickX; + const float sideways = + heldSeek.active() || std::abs(x) > std::abs(seekStick.stickY) ? x : 0.0f; + const float back = frame.seekable ? std::max(frame.backKey ? 1.0f : 0.0f, -sideways) : 0.0f; + const float forward = frame.seekable ? std::max(frame.forwardKey ? 1.0f : 0.0f, sideways) : 0.0f; + // Its limits from where it started: the video plays on until a hold. + const double from = heldSeek.active() ? heldSeekFrom : p.position; + // A tap goes Skip's length by the stick, the keyboard's arrows 10 s: + // by the input that starts it. + if (!heldSeek.active()) + heldSeek.setTap(std::abs(sideways) >= HeldSeek::kPress ? frame.skipSeconds : 10); + const HeldSeek::Step step = + heldSeek.update(back, forward, now, -from, + p.duration > 0 ? p.duration - kSeekEndMargin - from : 1e9, p.duration); + if (step.pressed) { + heldSeekFrom = p.position; + heldSeekBar = false; // a tap shows none + heldSeekStick = std::abs(sideways) >= HeldSeek::kPress; + heldSeekAtLimit = false; + if (heldSeekStick) buzz(heldSeekHand, 0.15f, 0.010); + } + if (step.holdStarted) { + // The picture waits, and is silent, until the stick lets go; with + // the menu closed, the strip alone shows where it goes meanwhile. + heldSeekPaused = !p.paused; + if (heldSeekPaused) player.command("set pause yes"); + heldSeekBar = !panel.open && frame.headValid; + if (heldSeekBar) panel.placeInFrontOf(frame.headPos, frame.menuAt); + heldSeekPicture = heldSeekFrom; + heldSeekPictureAt = now; + heldSeekTens = std::floor(std::abs(heldSeek.distance()) / 10); + } + if (heldSeek.holding()) { + heldSeekTarget = heldSeekFrom + heldSeek.distance(); + if (!player.seeking() && now - heldSeekPictureAt >= kHeldPictureEvery && + std::abs(heldSeekTarget - heldSeekPicture) >= kHeldPictureMove) { + player.seekTo(heldSeekTarget, false); + heldSeekPicture = heldSeekTarget; + heldSeekPictureAt = now; + } + if (heldSeekStick) { + const double end = p.duration > 0 ? p.duration - kSeekEndMargin : 1e9; + const bool atLimit = heldSeekTarget <= 0.01 || heldSeekTarget >= end - 0.01; + const double tens = std::floor(std::abs(heldSeek.distance()) / 10); + if (atLimit && !heldSeekAtLimit) { + buzz(heldSeekHand, 0.3f, 0.020); + } else if (tens != heldSeekTens && now - heldSeekTickAt >= 0.125) { + buzz(heldSeekHand, 0.1f, 0.006); + heldSeekTickAt = now; + } + heldSeekAtLimit = atLimit; + heldSeekTens = tens; + } + } + if (step.released) { + // A tap jumps on from where the video is now; a hold lands on the + // keyframe before its target, never past it into the end, unless + // its last picture is already there. + if (step.held && heldSeekStick) buzz(heldSeekHand, 0.2f, 0.014); + bool sent = step.distance != 0; + if (step.held) { + const double target = heldSeekFrom + step.distance; + sent = std::abs(target - heldSeekPicture) > 0.01; + if (sent) player.seekTo(target, false); + } else if (sent) { + player.seekBy(step.distance); + } + if (heldSeekPaused) player.command("set pause no"); + heldSeekPaused = false; + heldSeekLanding = step.held && (sent || player.seeking()); + heldSeekBarUntil = now + kSeekBarLinger; + } + if (heldSeekLanding && !player.seeking()) heldSeekLanding = false; + return step.pressed; +} + +void StickSeek::cancel() { + heldSeek.cancel(); + heldSeekPaused = heldSeekLanding = heldSeekBar = false; +} + +void StickSeek::fill(PlaybackState& shown) const { + if (heldSeek.holding() || heldSeekLanding) { + shown.position = heldSeekTarget; + if (heldSeekPaused) shown.paused = false; // only waiting for the stick + } +} + +void StickSeek::beginScrub(double now) { + scrub.on = true; + scrub.sent = false; + scrub.from = scrub.target = scrub.picture = player.playback().position; + scrub.pictureAt = now; +} + +void StickSeek::endScrub(bool released) { + // Let go: exactly there; the video played on meanwhile. + if (released && (scrub.sent || std::abs(scrub.target - scrub.from) > 0.01)) + player.seekTo(scrub.target, true); + scrub.on = false; +} + +double StickSeek::scrubValue() const { return scrub.on ? scrub.target : player.playback().position; } + +void StickSeek::followScrub(double now) { + // Scrub: the picture follows as the stick's held seek's does. + if (scrub.on && !player.seeking() && now - scrub.pictureAt >= kHeldPictureEvery && + std::abs(scrub.target - scrub.picture) >= kHeldPictureMove) { + player.seekTo(scrub.target, false); + scrub.picture = scrub.target; + scrub.pictureAt = now; + scrub.sent = true; + } +} diff --git a/src/stick_seek.h b/src/stick_seek.h new file mode 100644 index 0000000..0ed4b05 --- /dev/null +++ b/src/stick_seek.h @@ -0,0 +1,85 @@ +#pragma once + +#include "vr_input.h" + +#include + +struct MenuPanels; +struct PlaybackState; +class VideoPlayer; + +// The stick's seeks stop this far before the end: a seek into it would end +// the video (and open the menu). +constexpr double kSeekEndMargin = 5.0; + +// Either stick sideways, or the arrow keys, seek (HeldSeek): a tap jumps, a +// hold pauses the video and shows the strip while its target moves on, and +// the video goes there when it lets go. Also the Scrub gesture's picture, +// which follows its target as a hold's does. +class StickSeek { + public: + // What else is going on this frame. + struct Frame { + double now = 0; + bool seekable = false; // a video is open, not a photo + bool sticksTaken = false; // typing, or a stick steps a value: no stick seeks + bool backKey = false, forwardKey = false; // the arrow keys held down + int skipSeconds = 10; // Skip's length, a stick's tap + bool headValid = false; + Vec3 headPos; + Mat4 menuAt; // where the menu opens (menuFrame): a hold's strip goes there + }; + + StickSeek(VideoPlayer& player, MenuPanels& panel) : player(player), panel(panel) {} + + // A pulse on a controller; set once, before the frames. + std::function buzz; + + // Each frame. True if a seek of the user's started. + bool update(const ControllerState& input, const Frame& frame); + // Ends a seek at once, sending nothing (another video, or none). + void cancel(); + + // The input is down. + bool active() const { return heldSeek.active(); } + // A hold goes on, or the video isn't yet where it let go. + bool held() const { return heldSeek.holding() || heldSeekLanding; } + // The hold paused the video. + bool pausedVideo() const { return heldSeekPaused; } + // The playback the strip shows: while held(), where it goes. + void fill(PlaybackState& shown) const; + // The strip placed for a hold, the menu closed, still shown. + bool stripShown(double now) const { return heldSeekBar && (heldSeek.holding() || now < heldSeekBarUntil); } + + // The Scrub gesture (GestureInput::Host): where it takes the video. + void beginScrub(double now); + void endScrub(bool released); + void scrubTo(double target) { scrub.target = target; } + double scrubValue() const; + // Each frame, after the gestures: the picture follows a scrub. + void followScrub(double now); + + private: + VideoPlayer& player; + MenuPanels& panel; + + // Scrub: where it takes the video, and the last picture shown on the way + // there (its target, when sent), as the stick's held seek. + struct Scrub { + bool on = false, sent = false; // ... a picture on the way + double from = 0, target = 0, picture = 0, pictureAt = 0; + } scrub; + // The stick's seek (HeldSeek): from where, whether it paused the video, + // and whether the bar shows where it goes until the video is there. + HeldSeek heldSeek; + double heldSeekFrom = 0, heldSeekTarget = 0; + bool heldSeekPaused = false, heldSeekLanding = false; + bool heldSeekBar = false; // the strip placed for it, the menu closed + double heldSeekPicture = 0, heldSeekPictureAt = 0; // the last picture's target, when sent + double heldSeekBarUntil = 0; // ... shown after the stick let go + // Driven by a stick (not the arrow keys), it buzzes that hand: a tick each + // 10 s it goes, at most 8 a second, and a bump at the start or the end. + bool heldSeekStick = false, heldSeekAtLimit = false; + int heldSeekHand = 1; // the stick's + double heldSeekTens = 0, heldSeekTickAt = 0; +}; diff --git a/src/thumbnailer.cpp b/src/thumbnailer.cpp index 742a301..fe7ffd7 100644 --- a/src/thumbnailer.cpp +++ b/src/thumbnailer.cpp @@ -1,6 +1,7 @@ #include "thumbnailer.h" #include "file_util.h" +#include "frame_scaler.h" #include "platform.h" #include "app_dirs.h" #include "remote_avio.h" @@ -15,7 +16,6 @@ extern "C" { #include #include #include -#include #include } @@ -23,7 +23,6 @@ extern "C" { #include #include #include -#include #include #include #include @@ -58,57 +57,6 @@ struct Interrupt { } }; -} // namespace - -SwsContext* frameScaler(SwsContext* cached, const AVFrame* frame, int srcWidth, int width, - int height, int dstFormat, int flags) { - auto format = static_cast(frame->format); - bool fullRange = frame->color_range == AVCOL_RANGE_JPEG; - switch (format) { - case AV_PIX_FMT_YUVJ420P: format = AV_PIX_FMT_YUV420P; fullRange = true; break; - case AV_PIX_FMT_YUVJ422P: format = AV_PIX_FMT_YUV422P; fullRange = true; break; - case AV_PIX_FMT_YUVJ444P: format = AV_PIX_FMT_YUV444P; fullRange = true; break; - case AV_PIX_FMT_YUVJ440P: format = AV_PIX_FMT_YUV440P; fullRange = true; break; - case AV_PIX_FMT_YUVJ411P: format = AV_PIX_FMT_YUV411P; fullRange = true; break; - default: break; - } - SwsContext* sws = sws_getCachedContext(cached, srcWidth, frame->height, format, width, height, - static_cast(dstFormat), flags, nullptr, - nullptr, nullptr); - if (!sws) return nullptr; - const AVPixFmtDescriptor* desc = av_pix_fmt_desc_get(format); - if (desc && !(desc->flags & AV_PIX_FMT_FLAG_RGB)) { - int *inverse, *table, srcRange, dstRange, brightness, contrast, saturation; - if (sws_getColorspaceDetails(sws, &inverse, &srcRange, &table, &dstRange, &brightness, - &contrast, &saturation) >= 0) { - const int* coefficients = - sws_getCoefficients(frame->colorspace == AVCOL_SPC_BT709 ? SWS_CS_ITU709 : SWS_CS_DEFAULT); - sws_setColorspaceDetails(sws, coefficients, fullRange ? 1 : 0, table, dstRange, brightness, - contrast, saturation); - } - } - return sws; -} - -// swscale may write past the end of a row (it works in SIMD blocks), so it -// gets padded rows; the result is then copied into tightly packed pixels. -bool scaleInto(SwsContext* sws, const AVFrame* frame, int width, int height, - std::vector& pixels) { - const int stride = (width * 4 + 63) & ~63; - std::vector padded(static_cast(stride) * (height + 2) + 256); - uint8_t* planes[4] = {padded.data(), nullptr, nullptr, nullptr}; - int strides[4] = {stride, 0, 0, 0}; - if (sws_scale(sws, frame->data, frame->linesize, 0, frame->height, planes, strides) <= 0) - return false; - pixels.resize(static_cast(width) * height); - for (int y = 0; y < height; ++y) - std::memcpy(&pixels[static_cast(y) * width], padded.data() + static_cast(y) * stride, - static_cast(width) * 4); - return true; -} - -namespace { - // Picks the GPU (CUDA) output format when the decoder offers it. AVPixelFormat pickCuda(AVCodecContext*, const AVPixelFormat* formats) { for (const AVPixelFormat* f = formats; *f != AV_PIX_FMT_NONE; ++f) diff --git a/src/thumbnailer.h b/src/thumbnailer.h index 6ac18ee..9cc9d3b 100644 --- a/src/thumbnailer.h +++ b/src/thumbnailer.h @@ -12,24 +12,6 @@ #include typedef struct _cairo_surface cairo_surface_t; -struct SwsContext; -struct AVFrame; - -// A swscale context (`cached` reused when it fits, as sws_getCachedContext) -// converting the left `srcWidth` columns of a decoded frame to `width` × -// `height` pixels of `dstFormat`, with the frame's own range and matrix. -// FFmpeg's deprecated full-range formats (yuvj*, e.g. from JPEGs) are given -// as their plain formats with full range, which swscale otherwise warns -// about for every image. Null on failure. Also used by PhotoPreloader and -// Stash's images and previews. -SwsContext* frameScaler(SwsContext* cached, const AVFrame* frame, int srcWidth, int width, - int height, int dstFormat, int flags); - -// Scales a decoded frame with `sws` into tightly packed 32-bit pixels -// (width × height), safely: swscale may write past a row's end. Also used -// by PhotoPreloader. -bool scaleInto(SwsContext* sws, const AVFrame* frame, int width, int height, - std::vector& pixels); // A file the app deleted (with the size and date it had): its picture in // the disk cache goes too. Workers only. diff --git a/src/video_check.cpp b/src/video_check.cpp index 0a7b113..1388eab 100644 --- a/src/video_check.cpp +++ b/src/video_check.cpp @@ -2,7 +2,7 @@ #include "platform.h" #include "remote_avio.h" -#include "thumbnailer.h" // frameScaler +#include "frame_scaler.h" extern "C" { #include