From 012ec60a57b66c5ac6766efebbb0cc2268bd53a9 Mon Sep 17 00:00:00 2001 From: seaweeduk <2912658+seaweeduk@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:50:52 +0000 Subject: [PATCH] Play funscripts on a stroker through Intiface --- CMakeLists.txt | 4 + src/diagnostics.cpp | 2 +- src/funscript.cpp | 103 +++++++++++ src/funscript.h | 35 ++++ src/intiface.cpp | 419 ++++++++++++++++++++++++++++++++++++++++++ src/intiface.h | 89 +++++++++ src/main.cpp | 44 +++++ src/menu.cpp | 9 + src/menu.h | 31 +++- src/menu_player.cpp | 17 ++ src/menu_scripts.cpp | 139 ++++++++++++++ src/menu_search.cpp | 8 +- src/menu_settings.cpp | 30 ++- src/offline.cpp | 9 + src/offline.h | 6 +- src/script_player.cpp | 412 +++++++++++++++++++++++++++++++++++++++++ src/script_player.h | 101 ++++++++++ src/settings.cpp | 13 ++ src/settings.h | 2 + src/stash_stream.cpp | 52 +++++- src/stash_stream.h | 4 + src/strings.cpp | 28 +++ src/strings.h | 33 ++++ src/strings_de.cpp | 24 +++ src/strings_es.cpp | 24 +++ src/strings_fr.cpp | 24 +++ src/strings_ja.cpp | 24 +++ src/strings_pt_br.cpp | 24 +++ src/strings_zh_cn.cpp | 24 +++ 29 files changed, 1710 insertions(+), 24 deletions(-) create mode 100644 src/funscript.cpp create mode 100644 src/funscript.h create mode 100644 src/intiface.cpp create mode 100644 src/intiface.h create mode 100644 src/menu_scripts.cpp create mode 100644 src/script_player.cpp create mode 100644 src/script_player.h diff --git a/CMakeLists.txt b/CMakeLists.txt index c2c6258..352fc6c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,9 +57,11 @@ add_executable(videoframevr src/foveation.cpp src/frame_reuse.cpp src/frame_grabber.cpp + src/funscript.cpp src/gl_interop.cpp src/gpu_context.cpp src/hints.cpp + src/intiface.cpp src/key_mask.cpp src/key_picker.cpp src/key_share.cpp @@ -87,6 +89,7 @@ add_executable(videoframevr src/menu_player.cpp src/menu_presets.cpp src/menu_rating.cpp + src/menu_scripts.cpp src/menu_search.cpp src/menu_settings.cpp src/menu_setup.cpp @@ -132,6 +135,7 @@ add_executable(videoframevr src/run_log.cpp src/scene_renderer.cpp src/screen_control.cpp + src/script_player.cpp src/see_through.cpp src/seek_preview.cpp src/settings.cpp diff --git a/src/diagnostics.cpp b/src/diagnostics.cpp index 0e3d1ba..ca4666d 100644 --- a/src/diagnostics.cpp +++ b/src/diagnostics.cpp @@ -51,7 +51,7 @@ std::string anonymisedSettings(const std::string& text) { if (eq != std::string::npos && eq + 1 < line.size()) { const std::string key = line.substr(0, eq), value = line.substr(eq + 1); bool secret = value.find('/') != std::string::npos; - for (const char* word : {"key", "url", "path", "folder", "password", "user", "host", "share"}) + for (const char* word : {"key", "url", "path", "folder", "password", "user", "host", "share", "address"}) secret = secret || key.find(word) != std::string::npos; if (secret) line = key + "="; } diff --git a/src/funscript.cpp b/src/funscript.cpp new file mode 100644 index 0000000..8596d4a --- /dev/null +++ b/src/funscript.cpp @@ -0,0 +1,103 @@ +#include "funscript.h" + +#include "remote.h" +#include "stash_stream.h" + +#include + +#include +#include +#include +#include + +namespace { + +// Scripts are a few hundred kilobytes at most; anything larger isn't one. +constexpr uint64_t kMaxBytes = 16 * 1024 * 1024; + +} // namespace + +int Funscript::actionAt(double ms) const { + const auto next = std::upper_bound(actions.begin(), actions.end(), ms, + [](double t, const Action& a) { return t < a.at; }); + return static_cast(next - actions.begin()) - 1; +} + +double Funscript::positionAt(double ms) const { + if (actions.empty()) return 0; + const int i = actionAt(ms); + if (i < 0) return actions.front().pos; + if (i + 1 >= static_cast(actions.size())) return actions.back().pos; + const Action& a = actions[i]; + const Action& b = actions[i + 1]; + return a.pos + (b.pos - a.pos) * (ms - a.at) / (b.at - a.at); +} + +bool parseFunscript(const std::string& text, Funscript& script) { + script.actions.clear(); + const nlohmann::json j = nlohmann::json::parse(text, nullptr, false); + 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(); + script.actions.reserve(actions->size()); + for (const nlohmann::json& a : *actions) { + if (!a.is_object()) continue; + const auto at = a.find("at"), pos = a.find("pos"); + if (at == a.end() || pos == a.end() || !at->is_number() || !pos->is_number()) continue; + const double ms = at->get(), place = pos->get(); + // A day is longer than any video; the limit keeps the times in an int. + if (!std::isfinite(ms) || !std::isfinite(place) || ms < 0 || ms > 86400000.0) continue; + const int p = static_cast(std::lround(std::clamp(place, 0.0, 100.0))); + script.actions.push_back({static_cast(std::lround(ms)), inverted ? 100 - p : p}); + } + // In time order, the last of those written for one time. + std::stable_sort(script.actions.begin(), script.actions.end(), + [](const Funscript::Action& a, const Funscript::Action& b) { return a.at < b.at; }); + std::vector unique; + unique.reserve(script.actions.size()); + for (const Funscript::Action& a : script.actions) { + if (!unique.empty() && unique.back().at == a.at) unique.back() = a; + else unique.push_back(a); + } + script.actions = std::move(unique); + if (script.actions.size() < 2) script.actions.clear(); + return !script.actions.empty(); +} + +std::string funscriptBeside(const std::string& location) { + if (location.empty() || isStashScene(location)) return {}; + // Links (http and the like) have no file beside them. + if (location.find("://") != std::string::npos && !remote::isRemote(location)) return {}; + const size_t slash = location.find_last_of('/'); + const size_t dot = location.find_last_of('.'); + const size_t name = slash == std::string::npos ? 0 : slash + 1; + const bool extension = dot != std::string::npos && dot > name; + return (extension ? location.substr(0, dot) : location) + ".funscript"; +} + +std::string readFunscript(const std::string& location) { + if (isStashScene(location)) return stashFunscript(location); + const std::string file = funscriptBeside(location); + if (file.empty()) return {}; + std::string bytes; + if (!remote::isRemote(file)) { + std::ifstream in(file, std::ios::binary | std::ios::ate); + if (!in || in.tellg() <= 0 || static_cast(in.tellg()) > kMaxBytes) return {}; + bytes.resize(static_cast(in.tellg())); + in.seekg(0); + if (!in.read(bytes.data(), static_cast(bytes.size()))) return {}; + return bytes; + } + remote::Status status; + const auto remoteFile = remote::File::open(file, status); + if (!remoteFile || remoteFile->size() == 0 || remoteFile->size() > kMaxBytes) return {}; + bytes.resize(remoteFile->size()); + for (uint64_t at = 0; at < bytes.size();) { + const int64_t n = remoteFile->read(at, bytes.data() + at, bytes.size() - at); + if (n <= 0) return {}; + at += static_cast(n); + } + return bytes; +} diff --git a/src/funscript.h b/src/funscript.h new file mode 100644 index 0000000..f0e7023 --- /dev/null +++ b/src/funscript.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +// A funscript: a device's stroke position over a video's time, as the +// .funscript file beside the video has it (JSON: "actions" of {"at": +// milliseconds, "pos": 0..100}). Only the stroke's script is read, not those +// of other axes (video.roll.funscript and the like). +struct Funscript { + struct Action { + int at = 0; // milliseconds from the video's start + int pos = 0; // 0 (the stroke's bottom) .. 100 (its top) + }; + std::vector actions; // in time order, one per time, at least two + + // The action playing at `ms`: the last one at or before it; -1 before the first. + int actionAt(double ms) const; + // Where the stroke is at `ms`, 0..100: on the line between its actions, + // at the first one's place before it and the last one's after it. + double positionAt(double ms) const; +}; + +// A script's text as a Funscript, "inverted" applied. Its "range" is left +// out: the range set in Settings limits the stroke instead. False if the +// text isn't a script with at least two actions. +bool parseFunscript(const std::string& text, Funscript& script); + +// The text of the script of the video at `location`: the file beside a local +// or remote (remote.h) video with its name and .funscript, or what Stash +// serves for a scene played from its stream. Empty if there is none. Blocks: +// worker threads only. +std::string readFunscript(const std::string& location); +// Where that file is, for a local or remote video; empty for anything else. +std::string funscriptBeside(const std::string& location); diff --git a/src/intiface.cpp b/src/intiface.cpp new file mode 100644 index 0000000..90d8ced --- /dev/null +++ b/src/intiface.cpp @@ -0,0 +1,419 @@ +#include "intiface.h" + +#include "platform.h" + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace { + +constexpr const char kDefaultPort[] = "12345"; +// A device list is a few kilobytes; a server that sends more isn't Intiface. +constexpr size_t kMaxMessage = 4 * 1024 * 1024; +// RFC 6455: what a server appends to the key before hashing it. +constexpr const char kAcceptGuid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + +int64_t nowMs() { + return std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count(); +} + +std::string lower(std::string s) { + for (char& c : s) + if (c >= 'A' && c <= 'Z') c = static_cast(c - 'A' + 'a'); + return s; +} + +// "host", "host:port", "[v6]:port", with or without ws:// before and a path +// after. False for an address that names no host, or an encrypted one. +bool parseAddress(std::string address, std::string& host, std::string& port) { + const auto blank = [](char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; }; + while (!address.empty() && blank(address.back())) address.pop_back(); + while (!address.empty() && blank(address.front())) address.erase(0, 1); + if (const size_t scheme = address.find("://"); scheme != std::string::npos) { + if (lower(address.substr(0, scheme)) != "ws") return false; + address.erase(0, scheme + 3); + } + address = address.substr(0, address.find('/')); + port = kDefaultPort; + if (!address.empty() && address[0] == '[') { + const size_t end = address.find(']'); + if (end == std::string::npos) return false; + host = address.substr(1, end - 1); + if (end + 1 < address.size() && address[end + 1] == ':') port = address.substr(end + 2); + } else if (const size_t colon = address.find(':'); + colon != std::string::npos && address.find(':', colon + 1) == std::string::npos) { + host = address.substr(0, colon); + port = address.substr(colon + 1); + } else { + host = address; // a name, an IPv4 address, or a bare IPv6 one + } + return !host.empty() && !port.empty() && + std::all_of(port.begin(), port.end(), [](char c) { return c >= '0' && c <= '9'; }); +} + +std::string base64(const unsigned char* bytes, size_t count) { + gchar* text = g_base64_encode(bytes, count); + std::string out = text; + g_free(text); + return out; +} + +// What a server answers a key with (Sec-WebSocket-Accept). +std::string acceptFor(const std::string& key) { + GChecksum* sum = g_checksum_new(G_CHECKSUM_SHA1); + const std::string text = key + kAcceptGuid; + g_checksum_update(sum, reinterpret_cast(text.data()), static_cast(text.size())); + guint8 digest[20]; + gsize length = sizeof(digest); + g_checksum_get_digest(sum, digest, &length); + g_checksum_free(sum); + return base64(digest, length); +} + +// A header's value in a response's head, names compared without regard to case. +std::string headerValue(const std::string& head, const std::string& name) { + const std::string wanted = lower(name) + ":"; + for (size_t line = head.find("\r\n"); line != std::string::npos;) { + const size_t start = line + 2, end = head.find("\r\n", start); + const std::string text = head.substr(start, end == std::string::npos ? end : end - start); + if (lower(text.substr(0, wanted.size())) == wanted) { + size_t value = wanted.size(); + while (value < text.size() && text[value] == ' ') ++value; + return text.substr(value); + } + line = end; + } + return {}; +} + +// A device of a DeviceList or DeviceAdded, if it moves along a stroke. +bool stroker(const json& d, Intiface::Device& device) { + if (!d.is_object()) return false; + const auto index = d.find("DeviceIndex"), messages = d.find("DeviceMessages"); + if (index == d.end() || !index->is_number_unsigned() || messages == d.end() || !messages->is_object()) + return false; + const auto linear = messages->find("LinearCmd"); + if (linear == messages->end() || !linear->is_array() || linear->empty()) return false; + device.index = index->get(); + device.strokes = static_cast(std::min(linear->size(), 16)); + device.name.clear(); + for (const char* key : {"DeviceDisplayName", "DeviceName"}) + if (const auto name = d.find(key); + device.name.empty() && name != d.end() && name->is_string()) + device.name = name->get(); + return true; +} + +} // namespace + +Intiface::~Intiface() { close(); } + +void Intiface::close() { + if (fd_ >= 0) ::close(fd_); + fd_ = -1; + gotServerInfo_ = listed_ = scanning_ = fragmentText_ = false; + maxPingMs_ = 0; + in_.clear(); + message_.clear(); + devices_.clear(); +} + +bool Intiface::connect(const std::string& address, int timeoutMs) { + close(); + std::string host, port; + if (!parseAddress(address, host, port)) return false; + const int64_t until = nowMs() + timeoutMs; + addrinfo hints{}, *found = nullptr; + hints.ai_socktype = SOCK_STREAM; + if (getaddrinfo(host.c_str(), port.c_str(), &hints, &found) != 0) return false; + for (const addrinfo* a = found; a && fd_ < 0; a = a->ai_next) { + const int fd = socket(a->ai_family, a->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, a->ai_protocol); + if (fd < 0) continue; + bool ok = ::connect(fd, a->ai_addr, a->ai_addrlen) == 0; + if (!ok && errno == EINPROGRESS) { + pollfd p{fd, POLLOUT, 0}; + int error = 0; + socklen_t length = sizeof(error); + const int wait = static_cast(std::max(0, until - nowMs())); + ok = poll(&p, 1, wait) == 1 && getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &length) == 0 && + error == 0; + } + if (ok) fd_ = fd; + else ::close(fd); + } + freeaddrinfo(found); + if (fd_ < 0) return false; + // Each command is one small packet that must leave at once. + const int on = 1; + setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)); + + // The WebSocket's opening: an HTTP request the server answers 101 to. + unsigned char random[16]; + std::random_device source; + for (unsigned char& byte : random) byte = static_cast(source()); + const std::string key = base64(random, sizeof(random)); + const std::string hostHeader = + (host.find(':') != std::string::npos ? "[" + host + "]" : host) + ":" + port; + const std::string request = "GET / HTTP/1.1\r\nHost: " + hostHeader + + "\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " + + key + "\r\nSec-WebSocket-Version: 13\r\n\r\n"; + size_t headEnd = std::string::npos; + bool ok = send(fd_, request.data(), request.size(), MSG_NOSIGNAL) == + static_cast(request.size()); + while (ok && (headEnd = in_.find("\r\n\r\n")) == std::string::npos) + ok = in_.size() < 16384 && waitReadable(until) && readSome(); + if (ok) { + const std::string head = in_.substr(0, headEnd + 2); + ok = head.compare(0, 12, "HTTP/1.1 101") == 0 && + headerValue(head, "Sec-WebSocket-Accept") == acceptFor(key); + in_.erase(0, headEnd + 4); + } + + // Buttplug's: who this is and which version it speaks, answered with ServerInfo. + ok = ok && sendMessage("RequestServerInfo", {{"ClientName", kAppTitle}, {"MessageVersion", 3}}); + while (ok && !gotServerInfo_) { + std::string text; + while (nextMessage(text)) handle(text); + if (fd_ < 0) ok = false; + else if (!gotServerInfo_) ok = waitReadable(until) && readSome(); + } + ok = ok && sendMessage("RequestDeviceList"); + if (!ok) close(); + return ok; +} + +bool Intiface::waitReadable(int64_t untilMs) { + if (fd_ < 0) return false; + const int64_t wait = untilMs - nowMs(); + pollfd p{fd_, POLLIN, 0}; + return wait > 0 && poll(&p, 1, static_cast(wait)) == 1; +} + +// What has arrived, without waiting; false at the connection's end. +bool Intiface::readSome() { + char buffer[16384]; + for (;;) { + const ssize_t n = recv(fd_, buffer, sizeof(buffer), 0); + if (n > 0) { + in_.append(buffer, static_cast(n)); + if (in_.size() > 2 * kMaxMessage) return false; + if (static_cast(n) < sizeof(buffer)) return true; + } else if (n == 0) { + return false; + } else if (errno == EAGAIN || errno == EWOULDBLOCK) { + return true; + } else if (errno != EINTR) { + return false; + } + } +} + +bool Intiface::receive() { + if (fd_ < 0) return false; + bool open = readSome(); + std::string text; + while (fd_ >= 0 && nextMessage(text)) handle(text); + if (fd_ < 0) return false; + if (!open) close(); + return open; +} + +bool Intiface::nextMessage(std::string& text) { + while (fd_ >= 0 && in_.size() >= 2) { + const auto byte = [&](size_t i) { return static_cast(in_[i]); }; + const bool fin = byte(0) & 0x80, masked = byte(1) & 0x80; + const int opcode = byte(0) & 0x0f; + uint64_t length = byte(1) & 0x7f; + size_t header = 2; + if (length == 126) { + if (in_.size() < 4) return false; + length = static_cast(byte(2)) << 8 | byte(3); + header = 4; + } else if (length == 127) { + if (in_.size() < 10) return false; + length = 0; + for (int i = 0; i < 8; ++i) length = length << 8 | byte(2 + i); + header = 10; + } + if (length > kMaxMessage) { + close(); + return false; + } + const size_t mask = header; + if (masked) header += 4; + if (in_.size() < header + length) return false; + std::string payload = in_.substr(header, static_cast(length)); + if (masked) + for (size_t i = 0; i < payload.size(); ++i) payload[i] ^= in_[mask + i % 4]; + in_.erase(0, header + static_cast(length)); + switch (opcode) { + case 0x8: // the server closes + close(); + return false; + case 0x9: // ping: answered with what it carried + if (!sendFrame(0xA, payload)) return false; + break; + case 0x1: // text + case 0x2: // binary: none is expected; skipped + message_ = std::move(payload); + fragmentText_ = opcode == 0x1; + break; + case 0x0: // more of a message sent in parts + if (message_.size() + payload.size() > kMaxMessage) { + close(); + return false; + } + message_ += payload; + break; + default: + continue; + } + if ((opcode == 0x0 || opcode == 0x1 || opcode == 0x2) && fin) { + const bool isText = fragmentText_; + text = std::move(message_); + message_.clear(); + if (isText) return true; + } + } + return false; +} + +// One or more messages, each an object under its type's name. +void Intiface::handle(const std::string& text) { + const json messages = json::parse(text, nullptr, false); + if (!messages.is_array()) return; + for (const json& message : messages) { + if (!message.is_object() || message.empty()) continue; + const std::string type = message.begin().key(); + const json& body = message.begin().value(); + if (!body.is_object()) continue; + if (type == "ServerInfo") { + gotServerInfo_ = true; + const auto ping = body.find("MaxPingTime"); + maxPingMs_ = ping != body.end() && ping->is_number_unsigned() + ? static_cast(std::min(ping->get(), 3600000)) + : 0; + } else if (type == "DeviceList") { + devices_.clear(); + listed_ = true; + const auto list = body.find("Devices"); + if (list == body.end() || !list->is_array()) continue; + for (const json& d : *list) + if (Device device; stroker(d, device)) { + devices_.push_back(std::move(device)); + ++added_; + } + } else if (type == "DeviceAdded") { + Device device; + if (!stroker(body, device)) continue; + devices_.erase(std::remove_if(devices_.begin(), devices_.end(), + [&](const Device& d) { return d.index == device.index; }), + devices_.end()); + devices_.push_back(std::move(device)); + ++added_; + } else if (type == "DeviceRemoved") { + const auto index = body.find("DeviceIndex"); + if (index == body.end() || !index->is_number_unsigned()) continue; + const int gone = index->get(); + devices_.erase(std::remove_if(devices_.begin(), devices_.end(), + [&](const Device& d) { return d.index == gone; }), + devices_.end()); + } else if (type == "ScanningFinished") { + scanning_ = false; + } 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() : ""; + std::fprintf(stderr, "Intiface: %.200s\n", reason.c_str()); + } + } +} + +void Intiface::move(double position, int ms) { + position = std::clamp(position, 0.0, 1.0); + ms = std::max(ms, 1); + // A copy: a send that fails closes the connection, and the list with it. + const std::vector devices = devices_; + for (const Device& d : devices) { + json vectors = json::array(); + for (int i = 0; i < d.strokes; ++i) + vectors.push_back({{"Index", i}, {"Duration", ms}, {"Position", position}}); + if (!sendMessage("LinearCmd", {{"DeviceIndex", d.index}, {"Vectors", std::move(vectors)}})) return; + } +} + +void Intiface::scan(bool on) { + if (sendMessage(on ? "StartScanning" : "StopScanning")) scanning_ = on; +} + +void Intiface::ping() { sendMessage("Ping"); } + +bool Intiface::sendMessage(const char* type) { return sendMessage(type, json::object()); } + +bool Intiface::sendMessage(const char* type, json fields) { + fields["Id"] = nextId_; + nextId_ = nextId_ == 0xFFFFFFFFu ? 1 : nextId_ + 1; // 0 is the server's own + return sendFrame(0x1, json::array({json{{type, std::move(fields)}}}).dump()); +} + +// One whole frame, masked as a client's must be. A send the socket can't +// take within two seconds ends the connection. +bool Intiface::sendFrame(int opcode, std::string_view payload) { + if (fd_ < 0) return false; + std::string frame; + frame.reserve(payload.size() + 14); + frame += static_cast(0x80 | opcode); + if (payload.size() < 126) { + frame += static_cast(0x80 | payload.size()); + } else if (payload.size() < 65536) { + frame += static_cast(0x80 | 126); + frame += static_cast(payload.size() >> 8); + frame += static_cast(payload.size() & 0xff); + } else { + frame += static_cast(0x80 | 127); + for (int shift = 56; shift >= 0; shift -= 8) + frame += static_cast(static_cast(payload.size()) >> shift & 0xff); + } + static thread_local std::minstd_rand random{std::random_device{}()}; + char mask[4]; + for (char& m : mask) m = static_cast(random()); + frame.append(mask, 4); + for (size_t i = 0; i < payload.size(); ++i) frame += static_cast(payload[i] ^ mask[i % 4]); + + const int64_t until = nowMs() + 2000; + for (size_t sent = 0; sent < frame.size();) { + const ssize_t n = send(fd_, frame.data() + sent, frame.size() - sent, MSG_NOSIGNAL); + if (n > 0) { + sent += static_cast(n); + continue; + } + const bool full = n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK); + pollfd p{fd_, POLLOUT, 0}; + const int64_t wait = until - nowMs(); + if (n < 0 && errno == EINTR) continue; + if (!full || wait <= 0 || poll(&p, 1, static_cast(wait)) != 1) { + close(); + return false; + } + } + return true; +} diff --git a/src/intiface.h b/src/intiface.h new file mode 100644 index 0000000..44ae322 --- /dev/null +++ b/src/intiface.h @@ -0,0 +1,89 @@ +#pragma once + +#include + +#include +#include +#include +#include + +// A connection to Intiface (Intiface Central or Intiface Engine, +// intiface.com): the app that drives the devices themselves, over Bluetooth, +// USB or serial, on this computer or another one on the network. It listens +// on a WebSocket (not an encrypted one: it offers none) and speaks the +// Buttplug protocol (buttplug.io), JSON messages. This client speaks version +// 3 of it, which Intiface Central 2 and later all take, and only what playing +// a script needs: the devices that move along a stroke (LinearCmd) are +// listed and moved, the others left alone. +// +// Not threaded: ScriptPlayer's worker owns it and makes every call. Only +// connect() waits, for at most its timeout; the rest returns at once. +class Intiface { + public: + // A device that moves along a stroke. + struct Device { + int index = 0; // the server's number for it + std::string name; // the user's name for it in Intiface, else its model + int strokes = 1; // how many of its parts move so: all of them get each move + }; + + Intiface() = default; + ~Intiface(); + Intiface(const Intiface&) = delete; + Intiface& operator=(const Intiface&) = delete; + + // Connects to "host", "host:port" or "ws://host:port" (port 12345, + // Intiface's own, when none is given) and asks for its devices. False if + // nothing there answers as Intiface within `timeoutMs`. + bool connect(const std::string& address, int timeoutMs); + void close(); + bool connected() const { return fd_ >= 0; } + // The socket, to wait on for what the server sends (-1: not connected). + int fd() const { return fd_; } + // Takes in what the server has sent. False once the connection is lost + // (it is closed then). + bool receive(); + + const std::vector& devices() const { return devices_; } + // Whether the server has said which devices it has: until then the list is empty. + bool listed() const { return listed_; } + // Counts the devices that have appeared, over all connections. + int added() const { return added_; } + // Moves every device to `position` (0 the stroke's bottom .. 1 its top) + // over `ms` milliseconds. + void move(double position, int ms); + + // Whether the server looks for devices (Bluetooth ones are only found + // while it does). It may stop by itself. + bool scanning() const { return scanning_; } + void scan(bool on); + + // The server closes a connection it hears no Ping on for this long, + // milliseconds; 0: it asks for none. + int maxPingMs() const { return maxPingMs_; } + void ping(); + + private: + bool sendFrame(int opcode, std::string_view payload); + // One Buttplug message of `type` with these fields and the next Id. + bool sendMessage(const char* type); + bool sendMessage(const char* type, nlohmann::json fields); + bool waitReadable(int64_t untilMs); + bool readSome(); + // The next whole message of those read; false if none is complete. + bool nextMessage(std::string& text); + void handle(const std::string& text); + + int fd_ = -1; + bool gotServerInfo_ = false; + bool listed_ = false; + int added_ = 0; + bool scanning_ = false; + bool errorShown_ = false; + int maxPingMs_ = 0; + uint32_t nextId_ = 1; + std::string in_; // bytes read, not yet a whole frame + std::string message_; // the frames of a message still arriving + bool fragmentText_ = false; + std::vector devices_; +}; diff --git a/src/main.cpp b/src/main.cpp index 463d2d8..df54eb8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -908,6 +908,10 @@ int run(Options opts) { menu.setOffline(&offline); // Stash (optional, docs/stash.md): none while it is off or not set up. std::unique_ptr stash; + // Funscripts on a device (script_player.h): nothing of it runs while off. + ScriptPlayer scripts; + scripts.configure(settings.scripts); + offline.setScripts(settings.scripts.enabled); if (settings.stash.enabled && !settings.stash.url.empty() && !setupForced) stash = std::make_unique(settings.stash, library); menu.setStash(stash.get()); @@ -1261,6 +1265,7 @@ int run(Options opts) { dropDeleteDialog(); app.currentFile = path; app.streamOshash = isStashScene(path) ? oshash : std::string(); + scripts.open(isPhotoFile(path) ? std::string() : path); app.formatChosenByUser = false; app.format = guessVideoFormat(path, 0, 0); // Its settings from the library, else as kept before it (videos.conf), @@ -1334,6 +1339,7 @@ int run(Options opts) { seekPreview.close(); app.currentFile.clear(); app.streamOshash.clear(); + scripts.open({}); app.video.passthrough = false; app.video.opacity = 100; // the empty scene isn't blended; the video keeps its saved value opacityTwist.cancel(); @@ -1942,6 +1948,35 @@ int run(Options opts) { settings.vibration = !settings.vibration; saveSettings(settings); break; + case MenuCommand::ToggleScripts: + case MenuCommand::SetScriptAddress: + case MenuCommand::SetScriptOffset: + case MenuCommand::SetScriptRangeLow: + case MenuCommand::SetScriptRangeHigh: { + ScriptSettings& s = settings.scripts; + const int value = static_cast(std::lround(c.value)); + if (c.type == MenuCommand::ToggleScripts) { + s.enabled = !s.enabled; + } else if (c.type == MenuCommand::SetScriptAddress) { + const size_t first = c.path.find_first_not_of(" \t"); + s.address = first == std::string::npos + ? std::string() + : c.path.substr(first, c.path.find_last_not_of(" \t") - first + 1); + } else if (c.type == MenuCommand::SetScriptOffset) { + s.offsetMs = std::clamp(value, -kScriptOffsetLimit, kScriptOffsetLimit); + } else if (c.type == MenuCommand::SetScriptRangeLow) { + // The other end keeps its distance. + s.rangeLow = std::clamp(value, 0, 100 - kScriptRangeGap); + s.rangeHigh = std::max(s.rangeHigh, s.rangeLow + kScriptRangeGap); + } else { + s.rangeHigh = std::clamp(value, kScriptRangeGap, 100); + s.rangeLow = std::min(s.rangeLow, s.rangeHigh - kScriptRangeGap); + } + saveSettings(settings); + scripts.configure(s); + offline.setScripts(s.enabled); + break; + } case MenuCommand::ToggleShowWhatsNew: settings.showWhatsNew = !settings.showWhatsNew; saveSettings(settings); @@ -2315,6 +2350,13 @@ int run(Options opts) { glfwPollEvents(); xr.pollEvents(xrQuit); player.pollEvents(); + 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 && + !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"); @@ -3489,6 +3531,8 @@ int run(Options opts) { else if (softwareSince < 0) softwareSince = now; 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); diff --git a/src/menu.cpp b/src/menu.cpp index 4fb03dc..ef51362 100644 --- a/src/menu.cpp +++ b/src/menu.cpp @@ -213,6 +213,8 @@ void Menu::update(const MenuView& view) { view.diagnostics != view_.diagnostics || view.diagnosticsFile != view_.diagnosticsFile || view.crashedLastRun != view_.crashedLastRun || view.downloadsTo != view_.downloadsTo || view.softwareDecoding != view_.softwareDecoding || view.stash.card != view_.stash.card || + view.scripts.enabled != view_.scripts.enabled || view.scripts.address != view_.scripts.address || + view.scriptStatus != view_.scriptStatus || view.deletable != view_.deletable || view.setupBanner != view_.setupBanner || view.showWhatsNew != view_.showWhatsNew || a.chapters.size() != b.chapters.size() || a.chapter != b.chapter; @@ -241,6 +243,12 @@ void Menu::update(const MenuView& view) { if (view.subtitleSize != view_.subtitleSize) sliderChanged(MenuCommand::SetSubtitleSize); if (view.subtitleRaise != view_.subtitleRaise) sliderChanged(MenuCommand::SetSubtitleRaise); if (view.subtitleDistance != view_.subtitleDistance) sliderChanged(MenuCommand::SetSubtitleDistance); + if (view.scripts.offsetMs != view_.scripts.offsetMs) sliderChanged(MenuCommand::SetScriptOffset); + // One pushes the other along to keep their gap. + if (view.scripts.rangeLow != view_.scripts.rangeLow || view.scripts.rangeHigh != view_.scripts.rangeHigh) { + 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. @@ -996,6 +1004,7 @@ void Menu::showPage(Page page) { smbForm_ = {}; placeRename_ = {}; presetName_ = {}; + scriptAddress_ = {}; presetDeleting_.clear(); // The user's presets as they are now (a file may have been copied in). if (page == Page::VideoSettings) command_.type = MenuCommand::ListUserPresets; diff --git a/src/menu.h b/src/menu.h index c0ef03f..d9b4d0f 100644 --- a/src/menu.h +++ b/src/menu.h @@ -123,7 +123,11 @@ struct MenuCommand { // option 1: its certificate accepted unverified StashCard, // the menu's "Use Stash?" card: value 1 used, 0 dismissed DismissSetupBanner, // the Library's "You're all set" after setup - ToggleShowWhatsNew }; // What's new opens by itself after updates + ToggleShowWhatsNew, // What's new opens by itself after updates + // Funscripts (script_player.h): on or off, Intiface's address + // (path), and the timing offset and stroke range (value). + ToggleScripts, SetScriptAddress, SetScriptOffset, SetScriptRangeLow, + SetScriptRangeHigh }; Type type = None; // seconds (Seek, SeekTo), enum index, track id (0 = off), volume 0..100, // 1 = only the downloaded copy (DeleteFile), picture value @@ -273,6 +277,8 @@ struct MenuView { std::string diagnosticsFile; // Saved: the zip's name bool crashedLastRun = false; // until its diagnostics are saved bool softwareDecoding = false; // the video plays without hardware decoding + ScriptSettings scripts; // funscripts on a device (script_player.h) + ScriptStatus scriptStatus; // ... how far the way to one has got, and whether the video has a script std::string downloadsTo; // Settings::downloadsTo // The strip's delete button (docs/alpha/delete-file.md): not shown // (nothing open, a link), shown, or shown disabled for a scene played @@ -799,13 +805,28 @@ class Menu { struct Tile; struct Action; struct Field; - // Settings' sections: General, and Stash (menu_stash_settings.cpp). - enum class SettingsSection { General, Stash }; + // Settings' sections: General, Stash (menu_stash_settings.cpp) and + // Funscripts (menu_scripts.cpp). + enum class SettingsSection { General, Stash, Scripts }; SettingsSection settingsSection_ = SettingsSection::General; // `stash`: what the Stash section shows, if not what it shows now (the fit check). void layoutSettingsSection(SettingsSection section, const StashSettingsShown* stash = nullptr); void layoutHelpGroup(PageLayout& page, int column); // What's new, Save diagnostics void showStashSettings(); // Settings, opened on its Stash section + // Funscripts played on a device (menu_scripts.cpp): Settings' Funscripts + // section, and Intiface's address being typed, alone on the page over the + // keyboard. + void layoutScriptSettings(PageLayout& page); + void layoutScriptAddress(); + void openScriptAddress(); + MenuCommand submitScriptAddress(); + void showScriptSettings(); // Settings, opened on its Funscripts section + std::string scriptStatusText() const; // how far the way to a device has got; empty while off + struct ScriptAddress { + bool open = false; + std::string text; // typed + }; + ScriptAddress scriptAddress_; // A page's header as laid out: its title and what it is about (drawn by // drawGroups()); no title: none. struct PageHead { @@ -1135,7 +1156,8 @@ class Menu { if (setup_) return (smbForm_.kind != SmbForm::Kind::None || setupText()) && editing_; return (page_ == Page::Files || page_ == Page::Library || page_ == Page::Network || page_ == Page::Places || stashTextPage() || - (page_ == Page::VideoSettings && presetName_.open)) && + (page_ == Page::VideoSettings && presetName_.open) || + (page_ == Page::Settings && scriptAddress_.open)) && editing_; } bool editing_ = false; @@ -1145,6 +1167,7 @@ class Menu { if (smbForm_.kind != SmbForm::Kind::None) return smbForm_.text[smbForm_.field]; if (page_ == Page::Places) return placeRename_.text; if (page_ == Page::VideoSettings && presetName_.open) return presetName_.text; + if (page_ == Page::Settings && scriptAddress_.open) return scriptAddress_.text; return stashTextPage() ? stashText() : page_ == Page::Library ? libraryFilter_ : fileFilter_; } // The text cursor in the field typed into: a byte of filterText(), kept diff --git a/src/menu_player.cpp b/src/menu_player.cpp index d702284..f79dde0 100644 --- a/src/menu_player.cpp +++ b/src/menu_player.cpp @@ -106,6 +106,23 @@ void Menu::layoutMain() { } } } + // The video's funscript: red while no device plays it, and the way to + // its settings. + if (view_.scriptStatus.script) { + const bool ready = view_.scriptStatus.link == ScriptLink::Ready; + if (Button* b = chip(t.scripts.label, !ready, [this] { + showScriptSettings(); + return MenuCommand{}; + })) { + if (ready) { + char playing[512]; + std::snprintf(playing, sizeof(playing), t.scripts.tipPlaying, view_.scriptStatus.device.c_str()); + b->tooltip = playing; + } else { + b->tooltip = std::string(t.scripts.tipNoDevice) + "\n" + scriptStatusText(); + } + } + } const bool update = view_.releaseUpdate == ReleaseUpdate::State::Available || view_.releaseUpdate == ReleaseUpdate::State::DownloadFailed; const bool notice = (update || view_.crashedLastRun) && diff --git a/src/menu_scripts.cpp b/src/menu_scripts.cpp new file mode 100644 index 0000000..6030048 --- /dev/null +++ b/src/menu_scripts.cpp @@ -0,0 +1,139 @@ +#include "menu_parts.h" + +#include "platform.h" + +#include +#include + +// Funscripts played on a device through Intiface (script_player.h): their +// section in Settings, Intiface's address being typed, and the strip's label +// (layoutMain() in menu_player.cpp draws it). + +std::string Menu::scriptStatusText() const { + const ScriptStrings& t = text().scripts; + const ScriptStatus& s = view_.scriptStatus; + char line[512]; + switch (s.link) { + case ScriptLink::Off: return {}; + case ScriptLink::NoAddress: return t.noAddress; + case ScriptLink::Connecting: return t.connecting; + case ScriptLink::NoServer: return t.noServer; + case ScriptLink::NoDevice: return t.noDevice; + case ScriptLink::Ready: + if (s.devices > 1) std::snprintf(line, sizeof(line), t.readyMore, s.device.c_str(), s.devices - 1); + else std::snprintf(line, sizeof(line), t.ready, s.device.c_str()); + return line; + } + return {}; +} + +void Menu::showScriptSettings() { + showPage(Page::Settings); + settingsSection_ = SettingsSection::Scripts; +} + +// Settings' Funscripts section: the switch; while on, where Intiface is and +// how far the way to a device has got, and beside it the timing and the part +// of the stroke used. +void Menu::layoutScriptSettings(PageLayout& page) { + const ScriptStrings& t = text().scripts; + const ScriptSettings& s = view_.scripts; + GroupLayout scripts = page.group(0, t.group); + scripts.toggle(t.use, s.enabled, command(MenuCommand::ToggleScripts)).tip(t.offHint); + if (!s.enabled) { + scripts.note(t.offHint); + return; + } + scripts.labelsFor({t.address}); + const bool empty = s.address.empty(); + scripts + .field(t.address, !empty ? s.address : kStandaloneHeadset ? t.notSet : t.thisComputer, + [this] { + openScriptAddress(); + return MenuCommand{}; + }, + empty) + .tip(t.addressHint); + Lamp lamp = Lamp::None; + switch (view_.scriptStatus.link) { + case ScriptLink::Ready: lamp = Lamp::Ok; break; + case ScriptLink::Connecting: lamp = Lamp::Busy; break; + case ScriptLink::NoServer: + case ScriptLink::NoDevice: lamp = Lamp::Failed; break; + case ScriptLink::Off: + case ScriptLink::NoAddress: break; + } + scripts.status(lamp, scriptStatusText()); + + // The device's motion: earlier or later than the script, and the part of + // its stroke used. Each end pushes the other along to keep their gap + // (main.cpp). + GroupLayout motion = page.group(1, t.motion); + motion.labelsFor({t.offset, t.rangeLow, t.rangeHigh}); + const auto ms = [](int v, bool tick) { + char text[32]; + std::snprintf(text, sizeof(text), v ? "%+d%s" : "%d%s", v, tick ? "" : " ms"); + return std::string(text); + }; + motion.value(t.offset, MenuCommand::SetScriptOffset, s.offsetMs, -kScriptOffsetLimit, + kScriptOffsetLimit, ms(s.offsetMs, false), 10) + .format(ms) + .mark(0) + .tip(t.offsetHint); + motion.note(t.offsetHint); + motion.value(t.rangeLow, MenuCommand::SetScriptRangeLow, s.rangeLow, 0, 100 - kScriptRangeGap, + std::to_string(s.rangeLow) + " %") + .format(withUnit(" %")) + .tip(t.rangeHint); + motion.value(t.rangeHigh, MenuCommand::SetScriptRangeHigh, s.rangeHigh, kScriptRangeGap, 100, + std::to_string(s.rangeHigh) + " %") + .format(withUnit(" %")) + .tip(t.rangeHint); + motion.note(t.rangeHint); +} + +void Menu::openScriptAddress() { + scriptAddress_ = {true, view_.scripts.address}; + dropdown_ = Dropdown::None; + editing_ = true; + dirty_ = true; +} + +MenuCommand Menu::submitScriptAddress() { + MenuCommand c; + c.type = MenuCommand::SetScriptAddress; + c.path = scriptAddress_.text; + scriptAddress_ = {}; + editing_ = false; + dirty_ = true; + return c; +} + +// The address field in a group alone on the page, the keyboard under it: +// what to type and what Intiface needs set for it, and Save. +void Menu::layoutScriptAddress() { + const ScriptStrings& t = text().scripts; + PageLayout page(*this, text().settings); + GroupLayout group = page.group(0, t.group); + group.labelsFor({t.address}); + Field field; + field.text = scriptAddress_.text; + if (!kStandaloneHeadset) field.example = t.thisComputer; + field.typing = editing_; + field.action = [this] { + editing_ = true; + return MenuCommand{}; + }; + group.field(t.address, field); + group.note(kStandaloneHeadset ? std::string(t.addressHint) + : std::string(t.addressHint) + " " + t.addressLocal, + false, 6); + group.buttons({{t.save, "", [this] { return submitScriptAddress(); }, false, true}, + {text().cancel, "", [this] { + scriptAddress_ = {}; + editing_ = false; + dirty_ = true; + return MenuCommand{}; + }}}); + if (editing_) layoutKeyboard(); +} diff --git a/src/menu_search.cpp b/src/menu_search.cpp index 1c0968b..920dec1 100644 --- a/src/menu_search.cpp +++ b/src/menu_search.cpp @@ -173,6 +173,11 @@ void Menu::setFilter(const std::string& text) { typedChanged(); return; } + if (page_ == Page::Settings && scriptAddress_.open) { + scriptAddress_.text = text.substr(0, 200); + typedChanged(); + return; + } if (page_ == Page::VideoSettings && presetName_.open) { // Whether Save turns into Replace, or is refused, shows with each key. // At most 40 characters. @@ -207,13 +212,14 @@ MenuCommand Menu::submitText() { return {}; } if (page_ == Page::VideoSettings && presetName_.open) return submitPresetName(); + if (page_ == Page::Settings && scriptAddress_.open) return submitScriptAddress(); if (editingFilter() && stashTextPage()) return StashPages::submitText(*this); if (editingFilter()) stopEditing(); return {}; } void Menu::stopEditing() { - if (editingFilter() && stashTextPage()) { + if (editingFilter() && stashTextPage() && !scriptAddress_.open) { StashPages::stopEditing(*this); } else if (editingFilter()) { // The keyboard goes; the words and what they found stay. diff --git a/src/menu_settings.cpp b/src/menu_settings.cpp index 6d3b0e6..1b470a4 100644 --- a/src/menu_settings.cpp +++ b/src/menu_settings.cpp @@ -4,10 +4,11 @@ #include -// Settings: a page in two sections, built from the menu's parts. +// Settings: a page in three sections, built from the menu's parts. // General: the menu and its colour, the view, playback, subtitles, Help. // Stash: its server and folders, how it syncs, and sending to it // (menu_stash_settings.cpp). +// Funscripts: played on a device through Intiface (menu_scripts.cpp). // Video settings (menu_video_settings.cpp) and stereo focus (menu_focus.cpp) // are tabs of the playback strip and show without the sources column. The // page never scrolls (the debug fit check says where it would). @@ -24,6 +25,12 @@ std::string metres(int cm, bool unit = true) { } // namespace void Menu::layoutSettings() { + // Intiface's address being typed in: alone, over the keyboard. Before + // Stash's panel, which takes any typing here for its own. + if (scriptAddress_.open) { + layoutScriptAddress(); + return; + } // Stash's server being typed in (its fields over the keyboard), or its // ratings and plays being sent: alone. if (stashMenu_ && StashPages::layoutSettingsPanel(*this)) return; @@ -41,17 +48,22 @@ void Menu::showStashSettings() { void Menu::layoutSettingsSection(SettingsSection section, const StashSettingsShown* stash) { const Strings& t = text(); PageLayout page(*this, t.settings); - page.sections({t.general, t.stash.group}, static_cast(section), [this](int i) { - settingsSection_ = static_cast(i); - dropdown_ = Dropdown::None; - dirty_ = true; - }); + page.sections({t.general, t.stash.group, t.scripts.group}, static_cast(section), + [this](int i) { + settingsSection_ = static_cast(i); + dropdown_ = Dropdown::None; + dirty_ = true; + }); page.pageSwitch(t.advancedSettings, view_.advancedSettings, command(MenuCommand::ToggleAdvancedSettings), t.tipAdvanced); if (section == SettingsSection::Stash) { StashPages::layoutSettings(*this, page, stash ? *stash : StashPages::settingsShown(*this)); return; } + if (section == SettingsSection::Scripts) { + layoutScriptSettings(page); + return; + } #ifndef NDEBUG const bool checking = fitCase_ != nullptr; #else @@ -253,6 +265,12 @@ void Menu::checkSettingsFit() { const StashSettingsShown fullest = StashPages::fullestSettings(); fitCase_ = " (Stash, every row)"; layoutSettingsSection(SettingsSection::Stash, &fullest); + // Funscripts: on, an address, the longest state. + v.scripts.enabled = true; + v.scripts.address = "192.168.100.200:12345"; + v.scriptStatus.link = ScriptLink::NoDevice; + fitCase_ = " (Funscripts, every row)"; + layoutSettingsSection(SettingsSection::Scripts); fitCase_ = nullptr; buttons_.erase(buttons_.begin() + static_cast(buttons), buttons_.end()); diff --git a/src/offline.cpp b/src/offline.cpp index 50a1934..521fec6 100644 --- a/src/offline.cpp +++ b/src/offline.cpp @@ -1,6 +1,7 @@ #include "offline.h" #include "file_util.h" +#include "funscript.h" #include "oshash.h" #include "removable_drives.h" #include "settings.h" @@ -131,6 +132,7 @@ struct Offline::Shared { std::condition_variable wake, watchWake; bool quit = false, playing = false, pausedAll = false, rescan = false; bool watchStash = false, stashDown = false; + std::atomic scripts{false}; // funscripts are copied with their videos std::vector items; int64_t nextId = 1; std::vector drives; @@ -601,6 +603,11 @@ void Offline::Shared::copy(Download& d) { if (stash) for (const StashCaption& c : stashCaptions(d.source)) keep(copyStem + (c.language.empty() ? "" : "." + c.language) + ".vtt", c.text); + // Its funscript, kept (and removed) as a subtitle is. + if (scripts && validUtf8(copyStem)) + if (const std::string script = stash ? stashFunscript(d.source) : readFunscript(d.source); + !script.empty()) + keep(copyStem + ".funscript", script); struct stat st {}; ::stat(d.path.c_str(), &st); std::lock_guard lock(mutex); @@ -880,6 +887,8 @@ void Offline::pauseAll(bool paused) { sh.wake.notify_all(); } +void Offline::setScripts(bool on) { shared_->scripts = on; } + void Offline::setPlaying(bool playing) { if (playing == playing_) return; playing_ = playing; diff --git a/src/offline.h b/src/offline.h index 2d4fc9c..38dd9b8 100644 --- a/src/offline.h +++ b/src/offline.h @@ -19,7 +19,7 @@ // connection or a card taken out: from its .part file's length less the // last 8 MiB, or from the start if the source changed. A copy is checked by // its size and oshash before it is renamed into place; its subtitles come -// with it. Downloads pause while a video plays. A second thread asks the +// with it, and its funscript while those are played. Downloads pause while a video plays. A second thread asks the // servers signed in to whether they answer (away from home they don't), and // Stash while a scene may play or download from its stream. // Main thread only; nothing here waits for a file or the network. @@ -46,7 +46,7 @@ class Offline { uint64_t size = 0, copied = 0; int64_t mtime = 0; // the source's, when copying started int64_t doneAt = 0; // Unix seconds - std::vector subtitles; // copied beside it + std::vector subtitles; // copied beside it (its funscript too) State state = State::Queued; Why why = Why::None; bool present = false; // done, and the copy is there now @@ -92,6 +92,8 @@ class Offline { bool pausedAll() const { return pausedAll_; } // While a video plays, nothing is copied. void setPlaying(bool playing); + // Whether a video's funscript (funscript.h) is copied with it. + void setScripts(bool on); // Drives came or went: looked at again now. void drivesChanged(); diff --git a/src/script_player.cpp b/src/script_player.cpp new file mode 100644 index 0000000..a5617d1 --- /dev/null +++ b/src/script_player.cpp @@ -0,0 +1,412 @@ +#include "script_player.h" + +#include "funscript.h" +#include "intiface.h" +#include "platform.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +// A position that hasn't changed for this long is a video standing still. +// mpv reports one per video frame, so this is three frames of a 10 fps video. +constexpr double kStallSeconds = 0.3; +// The video's clock is where the last position says, adjusted a little by +// each new one; one further off than this is a seek. +constexpr double kSeekSeconds = 0.1; +constexpr int kConnectMs = 3000; // a try to reach Intiface gives up after this +constexpr int kRetryMs = 5000; // ... and the next one starts this much later +constexpr int kScanAgainMs = 15000; // a scan the server ended is asked for again after this +// Commands are sent at least this far apart: no device takes them faster, +// and a Bluetooth one's queue would fall behind the video. Of actions closer +// together than this, the ones in between are left out. (The gap Intiface +// reports for a device isn't used: to this version of the protocol it says +// 100 ms for all of them.) +constexpr int kMinGapMs = 20; +// The first move after the video starts, resumes or jumps brings the device +// from wherever it is to the script: over at least this long for a whole +// stroke, less in proportion. +constexpr int kCatchUpMs = 200; +constexpr int kHoldMs = 100; // the move that stops the device where the video stopped + +double steadySeconds() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +} // namespace + +std::string scriptAddress(const ScriptSettings& settings) { + if (!settings.address.empty()) return settings.address; + return kStandaloneHeadset ? "" : "localhost"; +} + +struct ScriptPlayer::Shared { + std::mutex mutex; + int wake = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); // written to wake the worker + bool quit = false; + ScriptSettings settings; + std::shared_ptr script; // the playing video's; null: none (or not read yet) + uint64_t load = 0; // counts open(): a script read for an earlier one is dropped + // The video's clock: while `playing`, it is at steadySeconds() + base. + // `jump` counts every break in it (stops, starts and seeks), after which + // the device is sent afresh. + bool playing = false; + double base = 0; + uint64_t jump = 0; + ScriptStatus status; + std::promise done; // the worker has stopped the device and gone + + ~Shared() { + if (wake >= 0) close(wake); + } + void wakeWorker() { + const uint64_t one = 1; + if (wake >= 0 && write(wake, &one, sizeof(one)) < 0) { + // Full: it is waking already. + } + } +}; + +namespace { + +void run(std::shared_ptr shared) { + ScriptPlayer::Shared& s = *shared; + Intiface link; + std::string connectedTo; + bool tried = false; // the first try's outcome is known + int64_t retryAt = 0, scanAt = 0, pingAt = 0; + int devicesSeen = 0; // Intiface::added() as of the last move + // What the device was last sent: which break in the clock, script and + // settings it was for, the action it is on its way from, and where to. + uint64_t sentJump = 0; + const Funscript* sentScript = nullptr; + ScriptSettings sentSettings; + int sentAction = -2; + bool sent = false; // any of the script since the video last started moving + // The last move sent, which says where the device is: from and to where + // along the stroke, when, and how long it takes. + struct Move { + double from = 0, to = 0, ms = 1; + int64_t at = 0; + bool known = false; // anything was sent since the device appeared + bool under = false; // it may still be on its way + bool guessed = false; // it set off from an unknown place: only where it ends is known + } move; + + const auto nowMs = [] { return static_cast(steadySeconds() * 1000); }; + const auto where = [&] { + return move.from + (move.to - move.from) * std::clamp((nowMs() - move.at) / move.ms, 0.0, 1.0); + }; + // Whether where() is where the device is. + const auto placed = [&] { return move.known && (!move.guessed || nowMs() - move.at >= move.ms); }; + for (;;) { + ScriptSettings settings; + std::shared_ptr script; + bool quit, playing; + double base; + uint64_t jump; + { + std::lock_guard lock(s.mutex); + quit = s.quit; + settings = s.settings; + script = s.script; + playing = s.playing; + base = s.base; + jump = s.jump; + } + const auto place = [&](double pos) { + return (settings.rangeLow + pos / 100.0 * (settings.rangeHigh - settings.rangeLow)) / 100.0; + }; + // Stops the device: a short move to where its last one has taken it. + // Whatever stopped the video (or the script, the connection's address, + // the app), the device doesn't finish a stroke the video didn't. Except + // one from an unknown place: sent where it is guessed to be, it would + // hurry there. (Intiface's StopDeviceCmd doesn't stop a stroke.) + const auto hold = [&] { + if (move.under && !move.guessed && link.connected() && !link.devices().empty() && + nowMs() - move.at < move.ms) { + const double here = where(); + link.move(here, kHoldMs); + move = {here, here, kHoldMs, nowMs(), true, false, false}; + } + move.under = false; + }; + if (quit) { + hold(); + break; + } + + // The connection: another address closes it, and none is tried again + // every few seconds. + const std::string address = scriptAddress(settings); + ScriptStatus status; + if (link.connected() && address != connectedTo) { + hold(); + link.close(); + retryAt = 0; + tried = false; + } + if (address != connectedTo && !link.connected()) { + tried = false; + retryAt = 0; + } + if (!link.connected() && !address.empty() && nowMs() >= retryAt) { + if (!tried) { + std::lock_guard lock(s.mutex); + s.status.link = ScriptLink::Connecting; + s.status.device.clear(); + s.status.devices = 0; + } + connectedTo = address; + if (link.connect(address, kConnectMs)) { + std::printf("Intiface: connected\n"); + pingAt = scanAt = 0; + sent = false; + } else { + retryAt = nowMs() + kRetryMs; + } + tried = true; + continue; // the settings may have changed meanwhile + } + int64_t wakeAt = INT64_MAX; + const int64_t now = nowMs(); + const bool wasConnected = link.connected(); + if (!link.connected()) { + status.link = address.empty() ? ScriptLink::NoAddress + : tried ? ScriptLink::NoServer + : ScriptLink::Connecting; + if (!address.empty()) wakeAt = retryAt; + move = {}; + sent = false; + } else { + // Bluetooth devices are only found while the server scans: it does + // until one is there. Not before it has said which it has already. + if (link.devices().empty()) { + if (link.listed() && !link.scanning() && now >= scanAt) { + link.scan(true); + scanAt = now + kScanAgainMs; + } + if (link.listed() && !link.scanning()) wakeAt = std::min(wakeAt, scanAt); + } else if (link.scanning()) { + link.scan(false); + } + if (link.maxPingMs() > 0) { + if (now >= pingAt) { + link.ping(); + pingAt = now + std::max(1, link.maxPingMs() / 2); + } + wakeAt = std::min(wakeAt, pingAt); + } + status.link = !link.listed() ? ScriptLink::Connecting + : link.devices().empty() ? ScriptLink::NoDevice + : ScriptLink::Ready; + status.devices = static_cast(link.devices().size()); + if (!link.devices().empty()) status.device = link.devices().front().name; + // A device that has just appeared may be anywhere, and is sent to the + // script at once, with the others. + if (link.devices().empty() || link.added() != devicesSeen) { + devicesSeen = link.added(); + move = {}; + sent = false; + } + } + + // The script: at each action, the move to the next one. + if (link.connected() && !link.devices().empty() && script && playing) { + const double t = (steadySeconds() + base) * 1000 + settings.offsetMs; + const std::vector& actions = script->actions; + const int count = static_cast(actions.size()); + const int at = script->actionAt(t); + const bool fresh = !sent || jump != sentJump || script.get() != sentScript || + settings != sentSettings; + const bool due = fresh || at > sentAction; + const int64_t soonest = move.known ? move.at + kMinGapMs : 0; + if (due && nowMs() < soonest) { + wakeAt = std::min(wakeAt, soonest); + } else { + if (due) { + // After the last action, its place: where the script ends, also + // when the actions before it came too close together to send. + const Funscript::Action& next = actions[std::min(at + 1, count - 1)]; + const double target = place(next.pos); + const bool known = placed(); + const double from = known ? where() : target; + // A device not where the script has it takes its time to get there. + const double catchUp = !fresh ? 0 : (known ? std::abs(target - from) : 1.0) * kCatchUpMs; + // While the script rests it is already there, not on its way until the rest ends. + const bool resting = fresh && (at < 0 || actions[at].pos == next.pos); + const double ms = std::max({resting ? 0.0 : next.at - t, catchUp, 1.0}); + // One already there (the script rests) isn't sent again. + if (fresh || target != move.to) { + link.move(target, static_cast(std::lround(ms))); + move = {from, target, ms, nowMs(), true, true, !known}; + } + sentAction = at; + sentJump = jump; + sentScript = script.get(); + sentSettings = settings; + sent = true; + } + if (sentAction + 1 < count) + wakeAt = std::min(wakeAt, nowMs() + static_cast(std::ceil(std::max( + 0.0, actions[sentAction + 1].at - t)))); + } + } else if (link.connected()) { + hold(); + sent = false; + } + // A command that couldn't be sent closed the connection. + if (wasConnected && !link.connected()) { + std::printf("Intiface: connection lost\n"); + retryAt = nowMs() + 1000; + continue; + } + + { + std::lock_guard lock(s.mutex); + if (s.quit) continue; + status.script = s.script != nullptr; + s.status = status; + } + pollfd waits[2] = {{s.wake, POLLIN, 0}, {link.fd(), POLLIN, 0}}; + const int64_t wait = wakeAt == INT64_MAX ? -1 : std::max(0, wakeAt - nowMs()); + poll(waits, link.connected() ? 2 : 1, static_cast(std::min(wait, 60000))); + if (waits[0].revents) { + uint64_t count; + while (read(s.wake, &count, sizeof(count)) > 0) { + } + } + if (link.connected() && waits[1].revents && !link.receive()) { + std::printf("Intiface: connection lost\n"); + retryAt = nowMs() + 1000; + } + } + link.close(); + s.done.set_value(); +} + +} // namespace + +ScriptPlayer::~ScriptPlayer() { stop(true); } + +void ScriptPlayer::configure(const ScriptSettings& settings) { + const bool was = settings_.enabled; + settings_ = settings; + if (was && !settings.enabled) stop(false); + if (!settings.enabled) return; + if (!was) { + start(); + return; + } + std::lock_guard lock(shared_->mutex); + if (shared_->settings == settings) return; + shared_->settings = settings; + shared_->wakeWorker(); +} + +void ScriptPlayer::start() { + shared_ = std::make_shared(); + shared_->settings = settings_; + shared_->status.link = ScriptLink::Connecting; + playing_ = false; + lastSeconds_ = -1; + std::thread(run, shared_).detach(); + load(); +} + +// The worker is told to go and left to: it may be waiting on a connection +// for seconds. `wait`: but for the moment it takes to stop the device. +void ScriptPlayer::stop(bool wait) { + if (!shared_) return; + std::future done = shared_->done.get_future(); + { + std::lock_guard lock(shared_->mutex); + shared_->quit = true; + shared_->wakeWorker(); + } + if (wait) done.wait_for(std::chrono::milliseconds(250)); + shared_.reset(); +} + +void ScriptPlayer::open(const std::string& location) { + location_ = location; + if (shared_) load(); +} + +// Reads the playing video's script on a thread of its own: its server may +// take seconds to answer, and the worker keeps time meanwhile. +void ScriptPlayer::load() { + uint64_t mine; + // The last video's clock isn't this one's: it starts when this one moves. + playing_ = false; + { + std::lock_guard lock(shared_->mutex); + mine = ++shared_->load; + shared_->script.reset(); + shared_->status.script = false; + shared_->playing = false; + shared_->wakeWorker(); + } + if (location_.empty()) return; + std::thread([shared = shared_, location = location_, mine] { + auto script = std::make_shared(); + if (!parseFunscript(readFunscript(location), *script)) return; + std::lock_guard lock(shared->mutex); + if (shared->quit || shared->load != mine) return; + std::printf("Script: %zu actions\n", script->actions.size()); + shared->script = std::move(script); + shared->status.script = true; + shared->wakeWorker(); + }).detach(); +} + +void ScriptPlayer::sync(double seconds, bool playing) { + if (!shared_) return; + const double now = steadySeconds(); + if (seconds != lastSeconds_) { + lastSeconds_ = seconds; + lastChange_ = now; + } else if (!playing_ && !playing) { + return; + } + const bool moving = playing && now - lastChange_ < kStallSeconds; + const double base = seconds - now; + if (moving == playing_) { + if (!moving || lastChange_ != now) return; + // Each new position corrects the clock a little: readily forward (a + // late one only looks behind), slowly back. + const double off = base - base_; + const bool seek = std::abs(off) > kSeekSeconds; + base_ = seek ? base : base_ + off * (off > 0 ? 0.5 : 0.02); + std::lock_guard lock(shared_->mutex); + shared_->base = base_; + if (seek) { + ++shared_->jump; + shared_->wakeWorker(); + } + return; + } + playing_ = moving; + base_ = base; + std::lock_guard lock(shared_->mutex); + shared_->playing = moving; + shared_->base = base; + ++shared_->jump; + shared_->wakeWorker(); +} + +ScriptStatus ScriptPlayer::status() const { + if (!shared_) return {}; + std::lock_guard lock(shared_->mutex); + return shared_->status; +} diff --git a/src/script_player.h b/src/script_player.h new file mode 100644 index 0000000..a432072 --- /dev/null +++ b/src/script_player.h @@ -0,0 +1,101 @@ +#pragma once + +#include +#include + +// Plays a video's funscript (funscript.h) on a device through Intiface +// (intiface.h): the device strokes in time with the video. Off by default; +// while off none of this runs: no thread, no connection, and no script is +// looked for. +// +// The app tells it which video plays and, every frame, where that video is. +// A worker thread does the rest: it keeps the connection to Intiface (trying +// again every few seconds while nothing answers), and at each of the +// script's actions sends the move to the next one, to arrive when the video +// reaches it. The device is held where it is as soon as the video stops +// moving, for whatever reason: paused, seeking, buffering, at its end, the +// headset taken off. + +// Kept in settings.conf as script_* keys. +struct ScriptSettings { + bool enabled = false; + // Where Intiface listens: "host" or "host:port" (port 12345 when none is + // given). Empty: this computer on a PC; not set up on a headset, where + // Intiface runs on another device. + std::string address; + // The device is sent each move this much earlier, milliseconds (later if + // negative): what it and its connection take to react. + int offsetMs = 0; + // The part of the device's stroke the script's 0..100 is played on, percent. + int rangeLow = 0, rangeHigh = 100; + + bool operator==(const ScriptSettings& o) const { + return enabled == o.enabled && address == o.address && offsetMs == o.offsetMs && + rangeLow == o.rangeLow && rangeHigh == o.rangeHigh; + } + bool operator!=(const ScriptSettings& o) const { return !(*this == o); } +}; +constexpr int kScriptOffsetLimit = 1000; // offsetMs is within this of 0 +constexpr int kScriptRangeGap = 10; // rangeHigh is at least this above rangeLow + +// The address Intiface is looked for at: the one set, else this computer's +// on a PC; empty if there is none to try. +std::string scriptAddress(const ScriptSettings& settings); + +// How far the way to a device has got. +enum class ScriptLink { + Off, // the setting is off + NoAddress, // no address to look for Intiface at + Connecting, // the first try is under way + NoServer, // nothing answers as Intiface there (tried again every few seconds) + NoDevice, // Intiface answers, but has no device that strokes + Ready, // a device is there +}; + +struct ScriptStatus { + ScriptLink link = ScriptLink::Off; + std::string device; // Ready: its name + int devices = 0; // ... and how many there are (all of them move) + bool script = false; // the video playing has a script + bool operator==(const ScriptStatus& o) const { + return link == o.link && device == o.device && devices == o.devices && script == o.script; + } + bool operator!=(const ScriptStatus& o) const { return !(*this == o); } +}; + +// All calls from one thread (the render loop's); none waits on the network +// or a disk. +class ScriptPlayer { + public: + ScriptPlayer() = default; + ~ScriptPlayer(); + ScriptPlayer(const ScriptPlayer&) = delete; + ScriptPlayer& operator=(const ScriptPlayer&) = delete; + + // The settings as they are now: starts or stops the worker with `enabled`. + void configure(const ScriptSettings& settings); + // The video playing is now the one at `location` (a path, a remote + // locator or a Stash scene's; empty: none): its script is looked for. + void open(const std::string& location); + // Every frame: where the video is, seconds, and whether it is meant to be + // moving (not paused, seeking or loading). One that says so but whose + // position stands still counts as stopped. + void sync(double seconds, bool playing); + ScriptStatus status() const; + + struct Shared; + + private: + void start(); + void stop(bool wait); + void load(); + + std::shared_ptr shared_; // while enabled + ScriptSettings settings_; + std::string location_; + // sync()'s own: the position last seen and when it changed, and what the + // worker was last told. + double lastSeconds_ = -1, lastChange_ = 0; + bool playing_ = false; + double base_ = 0; +}; diff --git a/src/settings.cpp b/src/settings.cpp index f57694e..20610fa 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -119,6 +119,11 @@ std::string allLines(const Settings& s) { out << "screen_height_cm=" << s.screen.height * 100 << "\n"; out << "screen_curve=" << s.screen.curve << "\n"; out << stashSettingLines(s.stash); + out << "script_enabled=" << (s.scripts.enabled ? 1 : 0) << "\n"; + out << "script_address=" << s.scripts.address << "\n"; + out << "script_offset_ms=" << s.scripts.offsetMs << "\n"; + out << "script_range_low=" << s.scripts.rangeLow << "\n"; + out << "script_range_high=" << s.scripts.rangeHigh << "\n"; return out.str(); } @@ -292,6 +297,12 @@ static Settings readEntries(Settings s, const Entries& file, bool oldFoveation) else if (key == "screen_distance_cm") s.screen.distance = std::atof(value.c_str()) / 100; else if (key == "screen_height_cm") s.screen.height = std::atof(value.c_str()) / 100; else if (key == "screen_curve") s.screen.curve = static_cast(std::atof(value.c_str())); + else if (key == "script_enabled") s.scripts.enabled = value == "1"; + else if (key == "script_address") s.scripts.address = value; + else if (key == "script_offset_ms") + s.scripts.offsetMs = std::clamp(std::atoi(value.c_str()), -kScriptOffsetLimit, kScriptOffsetLimit); + else if (key == "script_range_low") s.scripts.rangeLow = std::atoi(value.c_str()); + else if (key == "script_range_high") s.scripts.rangeHigh = std::atoi(value.c_str()); else if (!readStashSetting(key, value, s.stash)) focusRead |= focus.read(key, value); } // stash_path_from left empty: none (the same paths on both). @@ -305,6 +316,8 @@ static Settings readEntries(Settings s, const Entries& file, bool oldFoveation) s.foveationRing, s.foveationOutside); if (focusRead) focus.finish(s.focus, s.focusPrefs); s.screen = s.screen.clamped(); + s.scripts.rangeLow = std::clamp(s.scripts.rangeLow, 0, 100 - kScriptRangeGap); + s.scripts.rangeHigh = std::clamp(s.scripts.rangeHigh, s.scripts.rangeLow + kScriptRangeGap, 100); return s; } diff --git a/src/settings.h b/src/settings.h index 40b48a5..e3bcb59 100644 --- a/src/settings.h +++ b/src/settings.h @@ -5,6 +5,7 @@ #include "flat_screen.h" #include "focus_settings.h" #include "foveation.h" +#include "script_player.h" #include "stash_settings.h" #include @@ -109,6 +110,7 @@ struct Settings { // The flat screen of videos without their own size: the last one set. ScreenSize screen; StashSettings stash; // the optional Stash integration (stash_settings.h) + ScriptSettings scripts; // funscripts played on a device through Intiface (script_player.h) }; // The defaults; on the Frame (platform.h) what suits its hardware. diff --git a/src/stash_stream.cpp b/src/stash_stream.cpp index a8efde2..508b470 100644 --- a/src/stash_stream.cpp +++ b/src/stash_stream.cpp @@ -528,20 +528,25 @@ bool stashAnswers() { return r.code == CURLE_OK && r.status == 200; } +namespace { +// The server served now and the scene a locator or a source names on it; +// false if it is another server's. +bool sceneAt(std::string_view location, Server& server, long long& id) { + if (isStashSource(location)) return servedFor(location, server, id); + int number = 0; + if (std::sscanf(std::string(location).c_str(), "stashscene://%d/%lld", &number, &id) != 2) + return false; + std::lock_guard lock(servedMutex); + server = served; + return server.number && server.number == number; +} +} // namespace + std::vector stashCaptions(std::string_view location) { std::vector captions; Server server; long long id = 0; - if (isStashSource(location)) { - if (!servedFor(location, server, id)) return captions; - } else { - int number = 0; - if (std::sscanf(std::string(location).c_str(), "stashscene://%d/%lld", &number, &id) != 2) - return captions; - std::lock_guard lock(servedMutex); - server = served; - if (!server.number || server.number != number) return captions; - } + if (!sceneAt(location, server, id)) return captions; CURL* curl = curl_easy_init(); if (!curl) return captions; curl_slist* headers = curl_slist_append(keyHeader(server), "Content-Type: application/json"); @@ -589,6 +594,33 @@ std::vector stashCaptions(std::string_view location) { return captions; } +std::string stashFunscript(std::string_view location) { + Server server; + long long id = 0; + if (!sceneAt(location, server, id)) return {}; + CURL* curl = curl_easy_init(); + if (!curl) return {}; + curl_slist* headers = keyHeader(server); + std::string bytes; + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, +[](char* data, size_t size, size_t count, void* to) { + auto& bytes = *static_cast(to); + if (bytes.size() > 16 * 1024 * 1024) return size_t(0); + bytes.append(data, size * count); + return size * count; + }); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bytes); + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, 3000L); + curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 10000L); + const StashReply r = + stashPerform(curl, server.address, server.address.pathOn("/scene/" + std::to_string(id) + "/funscript"), + [&] { bytes.clear(); }, false); + curl_easy_cleanup(curl); + curl_slist_free_all(headers); + return r.code == CURLE_OK && r.status == 200 ? bytes : std::string(); +} + struct StashReader::Impl { std::shared_ptr stream; }; diff --git a/src/stash_stream.h b/src/stash_stream.h index e8f9d2f..c59b717 100644 --- a/src/stash_stream.h +++ b/src/stash_stream.h @@ -76,6 +76,10 @@ struct StashCaption { std::string text; }; std::vector stashCaptions(std::string_view location); +// A scene's funscript (funscript.h), the file Stash found beside its first +// file, for a locator or a source; empty if it has none. Blocks: worker +// threads only. +std::string stashFunscript(std::string_view location); // A source's file read in order from `offset`, by playback's reader (two // blocks ahead, again from where it stopped after a dropped connection). diff --git a/src/strings.cpp b/src/strings.cpp index 233bbef..0ffe23d 100644 --- a/src/strings.cpp +++ b/src/strings.cpp @@ -1126,6 +1126,34 @@ const Strings kEnglish = { "Updated from %s to %s", }, "Move the sharp area using the correction learned from menu clicks. Off uses the runtime's gaze. Independent of stereo focus.", + { + "Funscripts", + "Play funscripts on a device", + "Moves a stroker in time with videos that have a funscript beside them or in Stash. Needs " + "Intiface Central.", + "Intiface address", + "This computer", + "Not set", + "The name or IP address of the computer or phone running Intiface Central, with its port if " + "it isn't 12345. There, switch on \"Listen on all network interfaces\" and start the server.", + "Leave it empty if Intiface Central runs on this computer.", + "Save", + "Connecting to Intiface …", + "Enter the address of the device running Intiface Central.", + "Intiface isn't answering. Check that its server is started.", + "Intiface has no stroker connected. Switch yours on.", + "Connected: %s", + "Connected: %s and %d more", + "Timing", + "Above 0 the device moves earlier, below 0 later.", + "Stroke from", + "Stroke to", + "The part of the device's stroke that is used.", + "Motion", + "Funscript", + "Playing this video's funscript on %s.", + "This video has a funscript, but no device is connected.", + }, }; const Strings kGerman = germanStrings(kEnglish); diff --git a/src/strings.h b/src/strings.h index 54ef613..f3e22c6 100644 --- a/src/strings.h +++ b/src/strings.h @@ -937,6 +937,38 @@ struct WhatsNewStrings { const char* updatedFrom; // printf: the version before, this one }; +// Funscripts played on a device through Intiface (script_player.h): the +// Settings group, the address being typed, and the strip's label. "Intiface" +// and "funscript" are names, and the quoted Intiface setting is English there. +struct ScriptStrings { + const char* group; + const char* use; + const char* offHint; + const char* address; + const char* thisComputer; // the address field while empty on a PC + const char* notSet; // ... and on a headset + const char* addressHint; // under the field being typed into + const char* addressLocal; // ... on a PC, after it + const char* save; + // How far the way to a device has got (ScriptLink). + const char* connecting; + const char* noAddress; + const char* noServer; + const char* noDevice; + const char* ready; // printf: the device's name + const char* readyMore; // printf: a device's name, how many others + const char* offset; + const char* offsetHint; + const char* rangeLow; + const char* rangeHigh; + const char* rangeHint; + const char* motion; // the group of the timing and the stroke + // The strip's label while the video has a script, and its tooltips. + const char* label; + const char* tipPlaying; // printf: the device's name + const char* tipNoDevice; +}; + // All text shown in VR. struct Strings { const char* noVideo; @@ -1229,6 +1261,7 @@ struct Strings { ColourBalanceStrings colourBalance; WhatsNewStrings whatsNew; const char* foveationLearnedHint; + ScriptStrings scripts; }; const Strings& strings(); diff --git a/src/strings_de.cpp b/src/strings_de.cpp index 52c35bb..e13ad67 100644 --- a/src/strings_de.cpp +++ b/src/strings_de.cpp @@ -1236,5 +1236,29 @@ Strings germanStrings(const Strings& english) { s.whatsNew.showAfterUpdates = "Nach Updates anzeigen"; s.whatsNew.updatedFrom = "Aktualisiert von %s auf %s"; s.foveationLearnedHint = "Den scharfen Bereich mit der aus Menüklicks erlernten Korrektur bewegen. Aus nutzt den Blick der Laufzeit. Unabhängig vom Stereofokus."; + s.scripts.group = "Funscripts"; + s.scripts.use = "Funscripts auf einem Gerät abspielen"; + s.scripts.offHint = "Bewegt ein Gerät im Takt von Videos, neben denen oder zu denen in Stash ein Funscript liegt. Benötigt Intiface Central."; + s.scripts.address = "Intiface-Adresse"; + s.scripts.thisComputer = "Dieser Computer"; + s.scripts.notSet = "Nicht festgelegt"; + s.scripts.addressHint = "Name oder IP-Adresse des Computers oder Telefons, auf dem Intiface Central läuft, mit Port, falls er nicht 12345 ist. Dort „Listen on all network interfaces“ einschalten und den Server starten."; + s.scripts.addressLocal = "Leer lassen, wenn Intiface Central auf diesem Computer läuft."; + s.scripts.save = "Speichern"; + s.scripts.connecting = "Verbinde mit Intiface …"; + s.scripts.noAddress = "Adresse des Geräts eingeben, auf dem Intiface Central läuft."; + s.scripts.noServer = "Intiface antwortet nicht. Prüfen, ob sein Server gestartet ist."; + s.scripts.noDevice = "In Intiface ist kein passendes Gerät verbunden. Gerät einschalten."; + s.scripts.ready = "Verbunden: %s"; + s.scripts.readyMore = "Verbunden: %s und %d weitere"; + s.scripts.offset = "Timing"; + s.scripts.offsetHint = "Über 0 bewegt sich das Gerät früher, unter 0 später."; + s.scripts.rangeLow = "Hub von"; + s.scripts.rangeHigh = "Hub bis"; + s.scripts.rangeHint = "Der genutzte Teil des Hubs."; + s.scripts.motion = "Bewegung"; + s.scripts.label = "Funscript"; + s.scripts.tipPlaying = "Das Funscript dieses Videos läuft auf %s."; + s.scripts.tipNoDevice = "Dieses Video hat ein Funscript, aber kein Gerät ist verbunden."; return s; } diff --git a/src/strings_es.cpp b/src/strings_es.cpp index 0737a63..740efab 100644 --- a/src/strings_es.cpp +++ b/src/strings_es.cpp @@ -1236,5 +1236,29 @@ Strings spanishStrings(const Strings& english) { s.whatsNew.showAfterUpdates = "Mostrar tras actualizar"; s.whatsNew.updatedFrom = "Actualizado de %s a %s"; s.foveationLearnedHint = "Mover la zona nítida con la corrección aprendida de los clics en menús. Desactivado usa la mirada del sistema. Independiente del enfoque estéreo."; + s.scripts.group = "Funscripts"; + s.scripts.use = "Reproducir funscripts en un dispositivo"; + s.scripts.offHint = "Mueve un dispositivo al ritmo de los vídeos que tienen un funscript junto a ellos o en Stash. Requiere Intiface Central."; + s.scripts.address = "Dirección de Intiface"; + s.scripts.thisComputer = "Este ordenador"; + s.scripts.notSet = "Sin definir"; + s.scripts.addressHint = "Nombre o dirección IP del ordenador o teléfono con Intiface Central, con su puerto si no es 12345. Allí, activa «Listen on all network interfaces» e inicia el servidor."; + s.scripts.addressLocal = "Déjala vacía si Intiface Central está en este ordenador."; + s.scripts.save = "Guardar"; + s.scripts.connecting = "Conectando con Intiface …"; + s.scripts.noAddress = "Introduce la dirección del dispositivo con Intiface Central."; + s.scripts.noServer = "Intiface no responde. Comprueba que su servidor esté iniciado."; + s.scripts.noDevice = "Intiface no tiene ningún dispositivo compatible conectado. Enciende el tuyo."; + s.scripts.ready = "Conectado: %s"; + s.scripts.readyMore = "Conectado: %s y %d más"; + s.scripts.offset = "Sincronización"; + s.scripts.offsetHint = "Por encima de 0 el dispositivo se mueve antes; por debajo, después."; + s.scripts.rangeLow = "Recorrido desde"; + s.scripts.rangeHigh = "Recorrido hasta"; + s.scripts.rangeHint = "La parte del recorrido del dispositivo que se usa."; + s.scripts.motion = "Movimiento"; + s.scripts.label = "Funscript"; + s.scripts.tipPlaying = "Reproduciendo el funscript de este vídeo en %s."; + s.scripts.tipNoDevice = "Este vídeo tiene un funscript, pero no hay ningún dispositivo conectado."; return s; } diff --git a/src/strings_fr.cpp b/src/strings_fr.cpp index ead7187..2083c2e 100644 --- a/src/strings_fr.cpp +++ b/src/strings_fr.cpp @@ -1236,5 +1236,29 @@ Strings frenchStrings(const Strings& english) { s.whatsNew.showAfterUpdates = "Afficher après les mises à jour"; s.whatsNew.updatedFrom = "Mis à jour de %s vers %s"; s.foveationLearnedHint = "Déplacer la zone nette avec la correction apprise des clics dans les menus. Désactivé, utilise le regard du système. Indépendant de la mise au point stéréo."; + s.scripts.group = "Funscripts"; + s.scripts.use = "Lire les funscripts sur un appareil"; + s.scripts.offHint = "Fait bouger un appareil au rythme des vidéos accompagnées d’un funscript, à côté d’elles ou dans Stash. Nécessite Intiface Central."; + s.scripts.address = "Adresse d’Intiface"; + s.scripts.thisComputer = "Cet ordinateur"; + s.scripts.notSet = "Non définie"; + s.scripts.addressHint = "Nom ou adresse IP de l’ordinateur ou du téléphone où tourne Intiface Central, avec son port s’il n’est pas 12345. Là, activez « Listen on all network interfaces » et démarrez le serveur."; + s.scripts.addressLocal = "Laissez vide si Intiface Central tourne sur cet ordinateur."; + s.scripts.save = "Enregistrer"; + s.scripts.connecting = "Connexion à Intiface …"; + s.scripts.noAddress = "Saisissez l’adresse de l’appareil où tourne Intiface Central."; + s.scripts.noServer = "Intiface ne répond pas. Vérifiez que son serveur est démarré."; + s.scripts.noDevice = "Aucun appareil compatible n’est connecté à Intiface. Allumez le vôtre."; + s.scripts.ready = "Connecté : %s"; + s.scripts.readyMore = "Connecté : %s et %d autres"; + s.scripts.offset = "Synchronisation"; + s.scripts.offsetHint = "Au-dessus de 0, l’appareil bouge plus tôt ; en dessous, plus tard."; + s.scripts.rangeLow = "Course de"; + s.scripts.rangeHigh = "Course à"; + s.scripts.rangeHint = "La partie de la course de l’appareil qui est utilisée."; + s.scripts.motion = "Mouvement"; + s.scripts.label = "Funscript"; + s.scripts.tipPlaying = "Le funscript de cette vidéo est lu sur %s."; + s.scripts.tipNoDevice = "Cette vidéo a un funscript, mais aucun appareil n’est connecté."; return s; } diff --git a/src/strings_ja.cpp b/src/strings_ja.cpp index a06403a..522038f 100644 --- a/src/strings_ja.cpp +++ b/src/strings_ja.cpp @@ -1236,5 +1236,29 @@ Strings japaneseStrings(const Strings& english) { s.whatsNew.showAfterUpdates = "アップデート後に表示"; s.whatsNew.updatedFrom = "%s から %s にアップデートしました"; s.foveationLearnedHint = "メニューのクリックから学習した補正で高精細領域を移動。オフではランタイムの視線を使用します。ステレオフォーカスとは独立した設定です。"; + s.scripts.group = "Funscript"; + s.scripts.use = "Funscriptをデバイスで再生"; + s.scripts.offHint = "動画と同じ場所またはStashにFunscriptがあると、動画に合わせてデバイスを動かします。Intiface Centralが必要です。"; + s.scripts.address = "Intifaceのアドレス"; + s.scripts.thisComputer = "このコンピューター"; + s.scripts.notSet = "未設定"; + s.scripts.addressHint = "Intiface Centralを実行しているコンピューターまたはスマートフォンの名前かIPアドレス。ポートが12345以外の場合は付けてください。そちらで「Listen on all network interfaces」をオンにしてサーバーを開始します。"; + s.scripts.addressLocal = "Intiface Centralがこのコンピューターで動いている場合は空のままにします。"; + s.scripts.save = "保存"; + s.scripts.connecting = "Intifaceに接続中…"; + s.scripts.noAddress = "Intiface Centralを実行しているデバイスのアドレスを入力してください。"; + s.scripts.noServer = "Intifaceが応答しません。サーバーが開始されているか確認してください。"; + s.scripts.noDevice = "Intifaceに対応デバイスが接続されていません。デバイスの電源を入れてください。"; + s.scripts.ready = "接続済み: %s"; + s.scripts.readyMore = "接続済み: %s ほか%d台"; + s.scripts.offset = "タイミング"; + s.scripts.offsetHint = "0より大きいとデバイスが早く、小さいと遅く動きます。"; + s.scripts.rangeLow = "ストローク下限"; + s.scripts.rangeHigh = "ストローク上限"; + s.scripts.rangeHint = "デバイスのストロークのうち使用する範囲。"; + s.scripts.motion = "動き"; + s.scripts.label = "Funscript"; + s.scripts.tipPlaying = "この動画のFunscriptを%sで再生中。"; + s.scripts.tipNoDevice = "この動画にはFunscriptがありますが、デバイスが接続されていません。"; return s; } diff --git a/src/strings_pt_br.cpp b/src/strings_pt_br.cpp index 5996b5d..bdb0276 100644 --- a/src/strings_pt_br.cpp +++ b/src/strings_pt_br.cpp @@ -1236,5 +1236,29 @@ Strings brazilianPortugueseStrings(const Strings& english) { s.whatsNew.showAfterUpdates = "Mostrar após atualizações"; s.whatsNew.updatedFrom = "Atualizado de %s para %s"; s.foveationLearnedHint = "Mover a área nítida com a correção aprendida com cliques nos menus. Desativado usa o olhar do sistema. Independente do foco estéreo."; + s.scripts.group = "Funscripts"; + s.scripts.use = "Reproduzir funscripts em um dispositivo"; + s.scripts.offHint = "Move um dispositivo no ritmo dos vídeos que têm um funscript ao lado deles ou no Stash. Requer o Intiface Central."; + s.scripts.address = "Endereço do Intiface"; + s.scripts.thisComputer = "Este computador"; + s.scripts.notSet = "Não definido"; + s.scripts.addressHint = "Nome ou endereço IP do computador ou celular com o Intiface Central, com a porta se não for 12345. Lá, ative “Listen on all network interfaces” e inicie o servidor."; + s.scripts.addressLocal = "Deixe vazio se o Intiface Central estiver neste computador."; + s.scripts.save = "Salvar"; + s.scripts.connecting = "Conectando ao Intiface …"; + s.scripts.noAddress = "Digite o endereço do dispositivo com o Intiface Central."; + s.scripts.noServer = "O Intiface não responde. Verifique se o servidor foi iniciado."; + s.scripts.noDevice = "O Intiface não tem nenhum dispositivo compatível conectado. Ligue o seu."; + s.scripts.ready = "Conectado: %s"; + s.scripts.readyMore = "Conectado: %s e mais %d"; + s.scripts.offset = "Sincronia"; + s.scripts.offsetHint = "Acima de 0 o dispositivo se move antes; abaixo, depois."; + s.scripts.rangeLow = "Curso de"; + s.scripts.rangeHigh = "Curso até"; + s.scripts.rangeHint = "A parte do curso do dispositivo que é usada."; + s.scripts.motion = "Movimento"; + s.scripts.label = "Funscript"; + s.scripts.tipPlaying = "Reproduzindo o funscript deste vídeo em %s."; + s.scripts.tipNoDevice = "Este vídeo tem um funscript, mas nenhum dispositivo está conectado."; return s; } diff --git a/src/strings_zh_cn.cpp b/src/strings_zh_cn.cpp index 7929e70..5039002 100644 --- a/src/strings_zh_cn.cpp +++ b/src/strings_zh_cn.cpp @@ -1236,5 +1236,29 @@ Strings simplifiedChineseStrings(const Strings& english) { s.whatsNew.showAfterUpdates = "更新后显示"; s.whatsNew.updatedFrom = "已从 %s 更新到 %s"; s.foveationLearnedHint = "使用从菜单点击中学到的校正移动清晰区域。关闭时使用运行时的视线数据。此设置独立于立体对焦。"; + s.scripts.group = "Funscript"; + s.scripts.use = "在设备上播放 Funscript"; + s.scripts.offHint = "视频旁或 Stash 中有 Funscript 时,让设备随视频同步运动。需要 Intiface Central。"; + s.scripts.address = "Intiface 地址"; + s.scripts.thisComputer = "本机"; + s.scripts.notSet = "未设置"; + s.scripts.addressHint = "运行 Intiface Central 的电脑或手机的名称或 IP 地址;端口不是 12345 时请一并填写。在那里开启“Listen on all network interfaces”并启动服务器。"; + s.scripts.addressLocal = "如果 Intiface Central 在本机运行,请留空。"; + s.scripts.save = "保存"; + s.scripts.connecting = "正在连接 Intiface…"; + s.scripts.noAddress = "请输入运行 Intiface Central 的设备的地址。"; + s.scripts.noServer = "Intiface 没有响应。请确认其服务器已启动。"; + s.scripts.noDevice = "Intiface 未连接兼容设备。请打开你的设备。"; + s.scripts.ready = "已连接:%s"; + s.scripts.readyMore = "已连接:%s 及另外 %d 台"; + s.scripts.offset = "时间偏移"; + s.scripts.offsetHint = "大于 0 时设备提前运动,小于 0 时延后。"; + s.scripts.rangeLow = "行程下限"; + s.scripts.rangeHigh = "行程上限"; + s.scripts.rangeHint = "使用设备行程中的这一段。"; + s.scripts.motion = "动作"; + s.scripts.label = "Funscript"; + s.scripts.tipPlaying = "正在 %s 上播放此视频的 Funscript。"; + s.scripts.tipNoDevice = "此视频有 Funscript,但未连接设备。"; return s; }