Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C
27.1 KB
Raw Blame
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 RafaelNGP
#include "xcloud/gssv.h"

#include "auth/msa.h"
#include "net/http.h"
#include "util/json.h"
#include "platform/platform.h"
#include "util/log.h"
#include "xcloud/catalog.h"

#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <map>

namespace xc::xcloud {

namespace {
constexpr const char* kClientHeader = "XboxComBrowser";
constexpr int kLoginTries = 6;  // xCloud login: tries on a 5xx / no answer

// Sent like the Windows Xbox app does: "Windows" plus a 1080p display is what
// gets a 1080p stream; an Android device with a 720p display gets 720p.
const std::string& deviceInfo(Resolution res, bool preview = true) {
    auto build = [](bool hd, bool prev, int w = 1920, int h = 1080) {
        json::Value env = json::Value::object();
        env.set("clientAppId", prev ? "play.xbox.com" : "Microsoft.GamingApp");
        env.set("clientAppType", prev ? "browser" : "native");
        env.set("clientAppVersion", prev ? "26.1.97" : "2203.1001.4.0");
        env.set("clientSdkVersion", prev ? "10.3.7" : "8.5.2");
        env.set("httpEnvironment", "prod");
        env.set("sdkInstallId", "");
        json::Value app = json::Value::object();
        app.set("env", env);
        json::Value hw = json::Value::object();
        hw.set("make", hd ? "Microsoft" : "Google");
        hw.set("model", hd ? "Surface Pro" : "Pixel");
        hw.set("sdktype", prev ? "web" : "native");
        json::Value os = json::Value::object();
        os.set("name", hd ? "Windows 11" : "Android");
        os.set("ver", hd ? "22631.2715" : "14");
        os.set("platform", hd ? "desktop" : "phone");
        json::Value dims = json::Value::object();
        dims.set("widthInPixels", hd ? w : 1280);
        dims.set("heightInPixels", hd ? h : 720);
        json::Value dpi = json::Value::object();
        dpi.set("dpiX", 1);
        dpi.set("dpiY", 1);
        json::Value display = json::Value::object();
        display.set("dimensions", dims);
        display.set("pixelDensity", dpi);
        json::Value dev = json::Value::object();
        dev.set("hw", hw);
        dev.set("os", os);
        dev.set("displayInfo", display);
        json::Value v = json::Value::object();
        v.set("appInfo", app);
        v.set("dev", dev);
        return v.dump();
    };
    // 1440p: the xbox.com web client (SDK 10.6.62) in Edge on a 1440p display,
    // field for field as its X-MS-Device-Info interceptor builds it.
    auto makeQhd = [](bool prev) {
        json::Value env = json::Value::object();
        env.set("clientAppId", prev ? "play.xbox.com" : "www.xbox.com");
        env.set("clientAppType", "browser");
        env.set("clientAppVersion", "1.0.2610.0201");
        env.set("clientSdkVersion", "10.6.65");
        env.set("httpEnvironment", "prod");
        env.set("sdkInstallId", [] {  // filled in by the web client; random, per run (nothing of the console)
            uint8_t b[16];
            platform::randomBytes(b, sizeof b);
            b[6] = static_cast<uint8_t>((b[6] & 0x0f) | 0x40);
            b[8] = static_cast<uint8_t>((b[8] & 0x3f) | 0x80);
            char id[37];
            std::snprintf(id, sizeof id, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", b[0], b[1],
                          b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]);
            return std::string(id);
        }());
        json::Value app = json::Value::object();
        app.set("env", env);
        json::Value dims = json::Value::object();
        dims.set("heightInPixels", 1440);
        dims.set("widthInPixels", 2560);
        json::Value dpi = json::Value::object();
        dpi.set("dpiX", 1);
        dpi.set("dpiY", 1);
        json::Value display = json::Value::object();
        display.set("dimensions", dims);
        display.set("pixelDensity", dpi);
        json::Value browser = json::Value::object();
        browser.set("browserName", "edge");
        browser.set("browserVersion", "141.0.0.0");
        json::Value hw = json::Value::object();
        hw.set("make", "Microsoft");
        hw.set("model", "Windows");
        hw.set("platformType", "desktop");
        hw.set("sdkType", "web");
        json::Value os = json::Value::object();
        os.set("name", "windows");
        os.set("ver", "10.0");
        os.set("platform", "desktop");
        json::Value dev = json::Value::object();
        dev.set("displayInfo", display);
        dev.set("browser", browser);
        dev.set("hw", hw);
        dev.set("os", os);
        json::Value v = json::Value::object();
        v.set("appInfo", app);
        v.set("dev", dev);
        return v.dump();
    };
    // 1080p HQ: the web client on a Tizen TV with a 4K panel, as Better
    // xCloud sends it.
    auto makeTv = [](bool prev) {
        json::Value env = json::Value::object();
        env.set("clientAppId", prev ? "play.xbox.com" : "www.xbox.com");
        env.set("clientAppType", "browser");
        env.set("clientAppVersion", "26.1.97");
        env.set("clientSdkVersion", "10.3.7");
        env.set("httpEnvironment", "prod");
        env.set("sdkInstallId", "");
        json::Value app = json::Value::object();
        app.set("env", env);
        json::Value os = json::Value::object();
        os.set("name", "tizen");
        os.set("ver", "22631.2715");
        os.set("platform", "desktop");
        json::Value hw = json::Value::object();
        hw.set("make", "Microsoft");
        hw.set("model", "unknown");
        hw.set("sdktype", "web");
        json::Value browser = json::Value::object();
        browser.set("browserName", "chrome");
        browser.set("browserVersion", "140.0.3485.54");
        json::Value dims = json::Value::object();
        dims.set("widthInPixels", 4096);
        dims.set("heightInPixels", 2160);
        json::Value dpi = json::Value::object();
        dpi.set("dpiX", 1);
        dpi.set("dpiY", 1);
        json::Value display = json::Value::object();
        display.set("dimensions", dims);
        display.set("pixelDensity", dpi);
        json::Value dev = json::Value::object();
        dev.set("os", os);
        dev.set("hw", hw);
        dev.set("browser", browser);
        dev.set("displayInfo", display);
        json::Value v = json::Value::object();
        v.set("appInfo", app);
        v.set("dev", dev);
        return v.dump();
    };
    static const std::string qhd_p = makeQhd(true), qhd_np = makeQhd(false);
    static const std::string tv_p = makeTv(true), tv_np = makeTv(false);
    static const std::string hd_p = build(true, true), hd_np = build(true, false);
    static const std::string sd_p = build(false, true), sd_np = build(false, false);
    switch (res) {
    case Resolution::P720: return preview ? sd_p : sd_np;
    case Resolution::P1440: return preview ? qhd_p : qhd_np;
    case Resolution::P1080HQ: return preview ? tv_p : tv_np;
    default: return preview ? hd_p : hd_np;
    }
}

std::string describe(const net::Response& r) {
    if (r.status == 0) return r.error;
    std::string s = "HTTP " + std::to_string(r.status);
    std::string fields = errorFields(r.body);
    if (!fields.empty()) s += ": " + fields;
    return s;
}

SessionState parseState(const std::string& s) {
    if (s == "Provisioning") return SessionState::Provisioning;
    if (s == "WaitingForResources") return SessionState::WaitingForResources;
    if (s == "ReadyToConnect") return SessionState::ReadyToConnect;
    if (s == "Provisioned") return SessionState::Provisioned;
    if (s == "Failed") return SessionState::Failed;
    return SessionState::Unknown;
}

// The SDP/ICE endpoints wrap their payload as a JSON *string* inside
// "exchangeResponse"; unwrap it.
std::optional<json::Value> exchangePayload(const json::Value& v) {
    const auto& ex = v["exchangeResponse"];
    if (ex.isString()) return json::parse(ex.asString());
    if (ex.isObject() || ex.isArray()) return ex;
    return std::nullopt;
}
}  // namespace

const char* toString(SessionState s) {
    switch (s) {
        case SessionState::Provisioning: return "Provisioning";
        case SessionState::WaitingForResources: return "WaitingForResources";
        case SessionState::ReadyToConnect: return "ReadyToConnect";
        case SessionState::Provisioned: return "Provisioned";
        case SessionState::Failed: return "Failed";
        default: return "Unknown";
    }
}

const Region* GssvLogin::defaultRegion() const {
    for (const auto& r : regions)
        if (r.isDefault) return &r;
    return regions.empty() ? nullptr : &regions.front();
}

std::string GssvClient::url(const std::string& path) const { return region_.baseUri + path; }

std::string GssvClient::sessionUrl(const std::string& suffix) const {
    std::string p = sessionPath_;
    if (!p.empty() && p.front() != '/') p.insert(p.begin(), '/');
    return region_.baseUri + p + suffix;
}

static net::Request authed(Resolution res, bool preview, const GssvLogin& l, std::string method, std::string url,
                           std::string body = {}) {
    net::Request req;
    req.method = std::move(method);
    req.url = std::move(url);
    req.body = std::move(body);
    req.headers = {{"Authorization", "Bearer " + l.gsToken},
                   {"x-gssv-client", kClientHeader},
                   {"X-MS-Device-Info", deviceInfo(res, preview)}};
    if (!req.body.empty() || req.method == "POST") req.headers.emplace_back("Content-Type", "application/json");
    return req;
}

std::string errorFields(const std::string& body) {
    auto j = json::parse(body);
    if (!j || !j->isObject()) return {};
    std::string out;
    auto add = [&](const json::Value& v) {
        for (const char* key : {"status", "code", "errorCode", "message", "errorMessage", "reason"}) {
            const auto& f = v[key];
            std::string text = f.isString() ? f.str() : f.isNumber() ? std::to_string(f.asInt()) : std::string();
            if (!text.empty()) out += (out.empty() ? "" : ", ") + std::string(key) + "=" + text.substr(0, 200);
        }
    };
    add(*j);
    add((*j)["errorDetails"]);
    return out;
}

const char* loginCountryAddress(const std::string& country) {
    static const struct {
        const char* country;
        const char* address;
    } kAddresses[] = {{"br", "169.150.198.66"},
                      {"jp", "138.199.21.239"},
                      {"kr", "121.125.60.151"},
                      {"pl", "45.134.212.66"},
                      {"us", "143.244.47.65"}};
    for (const auto& a : kAddresses)
        if (country == a.country) return a.address;
    return nullptr;
}

bool GssvClient::login(const auth::XblToken& gssvXsts, std::string& err) {
    json::Value body = json::Value::object();
    body.set("token", gssvXsts.token);
    body.set("offeringId", offering_);

    net::Request req;
    req.method = "POST";
    req.url = "https://" + offering_ + ".gssv-play-prod.xboxlive.com/v2/login/user";
    req.headers = {{"Content-Type", "application/json"}, {"x-gssv-client", kClientHeader}};
    req.body = body.dump();
    if (const char* address = loginCountryAddress(loginCountry_)) {
        req.headers.emplace_back("X-Forwarded-For", address);
        XC_LOGI("xCloud login as country %s", loginCountry_.c_str());  // not the address
    }
    // The service fails now and then with a 5xx (or is slow to answer) and
    // works a little later: up to six tries, 1, 2, 4, 8 and 8 s apart. A refusal
    // (4xx) is an answer, not tried again.
    net::Response r;
    std::optional<json::Value> j;
    for (int attempt = 1;; ++attempt) {
        r = net::perform(req);
        j = json::parse(r.body);
        if (r.ok() && j && (*j)["gsToken"].isString()) break;
        bool transient = r.status == 0 || r.status == 408 || r.status == 429 || r.status >= 500;
        if (!transient || attempt == kLoginTries) break;
        XC_LOGW("xCloud login: %s, trying again (%d/%d)", describe(r).c_str(), attempt + 1, kLoginTries);
        platform::sleepMs(1000u << std::min(attempt - 1, 3));
    }
    loginStatus_ = r.status;
    if (!r.ok() || !j || !(*j)["gsToken"].isString()) {
        err = "xCloud login failed: " + describe(r);
        if (r.status == 403) err += " (no Game Pass plan with cloud gaming, or xCloud is not available in this region)";
        return false;
    }
    if (std::getenv("XC_DUMP_LOGIN")) {
        // Diagnostics: everything except the token itself.
        json::Value copy = *j;
        copy.set("gsToken", "<redacted>");
        XC_LOGI("login response: %s", copy.dump().substr(0, 6000).c_str());
    }
    login_ = {};
    login_.gsToken = (*j)["gsToken"].str();
    login_.market = (*j)["market"].str();
    login_.expiresAt = auth::unixNow() + (*j)["durationInSeconds"].asInt(3600);
    for (const auto& r : (*j)["offeringSettings"]["regions"].items()) {
        Region reg;
        reg.name = r["name"].str();
        reg.baseUri = r["baseUri"].str();
        reg.isDefault = r["isDefault"].asBool();
        if (!reg.baseUri.empty()) login_.regions.push_back(std::move(reg));
    }
    if (const Region* def = login_.defaultRegion()) {
        region_ = *def;
    } else {
        err = "xCloud login returned no regions";
        return false;
    }
    XC_LOGI("xCloud login ok: market=%s region=%s (%zu regions)", login_.market.c_str(), region_.name.c_str(),
            login_.regions.size());
    return true;
}

bool GssvClient::listTitles(std::vector<Title>& out, std::string& err, bool recentOnly) {
    out.clear();
    uint64_t started = platform::nowMs();
    std::string continuation;
    int pages = 0;
    std::map<std::string, int> inputTypes;  // for the log: how many titles take each
    do {
        std::string path = recentOnly ? "/v2/titles/mru?mr=25" : "/v2/titles?mr=200";
        if (!continuation.empty()) path += "&ct=" + net::urlEncode(continuation);
        auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", url(path)));
        auto j = json::parse(r.body);
        if (!r.ok() || !j) {
            err = "title list failed: " + describe(r);
            return false;
        }
        // Debugging: XC_DUMP_TITLES="ID1,ID2" prints those entries as sent.
        static const char* dump = std::getenv("XC_DUMP_TITLES");
        for (const auto& t : (*j)["results"].items()) {
            if (dump && ("," + std::string(dump) + ",").find("," + t["titleId"].str() + ",") != std::string::npos)
                std::printf("%s\n", t.dump().c_str());
            Title title;
            title.titleId = t["titleId"].str();
            title.productId = t["details"]["productId"].str();
            title.hasEntitlement = t["details"]["hasEntitlement"].asBool();
            title.xboxTitleId = t["details"]["xboxTitleId"].str();
            title.isFreeInStore = t["details"]["isFreeInStore"].asBool();
            for (const auto& alt : t["details"]["alternateProductIds"].items()) {
                if (alt.isString() && !alt.str().empty()) title.alternateProductIds.push_back(alt.str());
            }
            if (title.productId.empty() && !title.alternateProductIds.empty()) {
                title.productId = title.alternateProductIds[0];
            }
            for (const auto& input : t["details"]["supportedInputTypes"].items()) {
                ++inputTypes[input.str()];
                if (input.str() == "MKB") title.mouseKeyboard = true;
            }
            // What lets this account play it: a subscription's program
            // (CALLISTO for Game Pass in the cloud) or F2P; none when bought.
            for (const auto& program : t["details"]["userPrograms"].items())
                if (program.str() != "F2P") title.viaSubscription = true;
            if (!title.titleId.empty() && !isNonGameAddon(title.titleId)) out.push_back(std::move(title));
        }
        // The next page; a token that repeats, an empty page or too many
        // pages end the list (a server that always says "more" can't loop).
        std::string next = recentOnly ? std::string() : (*j)["continuationToken"].str();
        ++pages;
        if (!next.empty() && (next == continuation || (*j)["results"].items().empty() || pages >= 50)) {
            XC_LOGW("title list: stopped paging after %d page(s), %zu titles", pages, out.size());
            next.clear();
        }
        continuation = next;
    } while (!continuation.empty() && out.size() < 10000);
    XC_LOGI("title list%s: %zu titles in %llu ms", recentOnly ? " (recent)" : "", out.size(),
            static_cast<unsigned long long>(platform::nowMs() - started));
    if (!inputTypes.empty()) {
        std::string types;
        for (const auto& [name, n] : inputTypes) types += (types.empty() ? "" : ", ") + name + " " + std::to_string(n);
        XC_LOGI("title list: input types: %s", types.c_str());
    }
    return true;
}

bool GssvClient::hydrateTitles(std::vector<Title>& titles, const std::string& market, const std::string& lang,
                               std::string& err) {
    std::map<std::string, std::vector<Title*>> byProduct;
    for (auto& t : titles)
        if (!t.productId.empty()) byProduct[t.productId].push_back(&t);

    std::vector<std::string> ids;
    for (const auto& [id, _] : byProduct) ids.push_back(id);

    constexpr size_t kBatch = 20;
    for (size_t i = 0; i < ids.size(); i += kBatch) {
        std::string list;
        for (size_t k = i; k < ids.size() && k < i + kBatch; ++k) {
            if (!list.empty()) list += ',';
            list += ids[k];
        }
        net::Request req;
        req.url = "https://displaycatalog.mp.microsoft.com/v7.0/products?bigIds=" + list +
                  "&market=" + market + "&languages=" + lang;
        auto r = net::perform(req);
        auto j = json::parse(r.body);
        if (!r.ok() || !j) {
            err = "catalog lookup failed: " + describe(r);
            return false;
        }
        for (const auto& p : (*j)["Products"].items()) {
            auto it = byProduct.find(p["ProductId"].str());
            if (it == byProduct.end()) continue;
            const auto& loc = p["LocalizedProperties"][0];
            std::string name = loc["ProductTitle"].str();
            std::string image;
            for (const char* purpose : {"Poster", "BoxArt", "Tile"}) {
                for (const auto& img : loc["Images"].items()) {
                    if (img["ImagePurpose"].str() == purpose) {
                        image = img["Uri"].str();
                        break;
                    }
                }
                if (!image.empty()) break;
            }
            if (image.rfind("//", 0) == 0) image = "https:" + image;
            for (Title* t : it->second) {
                t->name = name;
                t->imageUrl = image;
            }
        }
    }
    return true;
}

bool GssvClient::listConsoles(std::vector<Console>& out, std::string& err) {
    out.clear();
    auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", url("/v6/servers/home")));
    auto j = json::parse(r.body);
    if (!r.ok() || !j) {
        err = "console list failed: " + describe(r);
        return false;
    }
    for (const auto& c : (*j)["results"].items()) {
        static bool keysLogged = false;  // which fields the service sends (names only)
        if (!keysLogged) {
            keysLogged = true;
            std::string keys;
            for (const auto& [k, v] : c.members()) keys += k + (v.isString() ? "" : "*") + " ";
            XC_LOGI("console fields: %s", keys.c_str());
        }
        Console con;
        con.serverId = c["serverId"].str();
        con.deviceName = c["deviceName"].str();
        con.consoleType = c["consoleType"].str();
        con.powerState = c["powerState"].str();
        con.playPath = c["playPath"].str();
        con.outOfHomeWarning = c["outOfHomeWarning"].asBool();
        con.wirelessWarning = c["wirelessWarning"].asBool();
        if (!con.serverId.empty()) out.push_back(std::move(con));
    }
    return true;
}

bool GssvClient::startSession(const std::string& titleId, const std::string& locale, std::string& err, int* status) {
    json::Value settings = json::Value::object();
    settings.set("nanoVersion", "V3;WebrtcTransport.dll");
    settings.set("enableTextToSpeech", false);
    settings.set("magnifier", false);
    settings.set("highContrast", 0);
    settings.set("locale", locale);
    settings.set("useIceConnection", false);
    settings.set("timezoneOffsetMinutes", 0);
    settings.set("sdkType", "web");
    settings.set("osName", resolution_ == Resolution::P720       ? "android"
                           : resolution_ == Resolution::P1080HQ ? "tizen"
                                                                : "windows");
    settings.set("enableOptionalDataCollection", false);

    json::Value body = json::Value::object();
    bool home = offering_ == "xhome";
    body.set("clientSessionId", [] {  // a new id per session, as the web client sends
        uint8_t b[16];
        platform::randomBytes(b, sizeof b);
        b[6] = static_cast<uint8_t>((b[6] & 0x0f) | 0x40);
        b[8] = static_cast<uint8_t>((b[8] & 0x3f) | 0x80);
        char id[37];
        std::snprintf(id, sizeof id, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", b[0], b[1], b[2],
                      b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]);
        return std::string(id);
    }());
    body.set("titleId", home ? "" : titleId);
    body.set("systemUpdateGroup", "");
    body.set("settings", settings);
    body.set("serverId", home ? titleId : "");
    body.set("fallbackRegionNames", json::Value::array());

    std::string kind = offering_ == "xhome" ? "home" : "cloud";
    auto r = net::perform(authed(resolution_, previewFeatures_, login_, "POST", url("/v5/sessions/" + kind + "/play"), body.dump()));
    if (status) *status = r.status;
    auto j = json::parse(r.body);
    if (!r.ok() || !j || !(*j)["sessionPath"].isString()) {
        err = "session start failed: " + describe(r);
        return false;
    }
    sessionPath_ = (*j)["sessionPath"].str();
    XC_LOGI("session created");  // not its id
    return true;
}

bool GssvClient::sessionState(SessionStatus& out, std::string& err) {
    auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", sessionUrl("/state")));
    auto j = json::parse(r.body);
    if (!r.ok() || !j) {
        err = "session state failed: " + describe(r);
        return false;
    }
    out.raw = (*j)["state"].str();
    out.state = parseState(out.raw);
    out.errorCode = (*j)["errorDetails"]["code"].str();
    out.errorMessage = (*j)["errorDetails"]["message"].str();
    return true;
}

int GssvClient::titleWaitSeconds(const std::string& titleId) {
    if (titleId.empty() || login_.gsToken.empty()) return -1;
    auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", url("/v1/waittime/" + titleId)));
    auto j = json::parse(r.body);
    if (!r.ok() || !j) return -1;
    return static_cast<int>((*j)["estimatedTotalWaitTimeInSeconds"].asInt(-1));
}

bool GssvClient::connect(const std::string& msaTransferToken, std::string& err) {
    json::Value body = json::Value::object();
    body.set("userToken", msaTransferToken);
    auto r = net::perform(authed(resolution_, previewFeatures_, login_, "POST", sessionUrl("/connect"), body.dump()));
    if (!r.ok()) {
        err = "session connect failed: " + describe(r);
        return false;
    }
    return true;
}

bool GssvClient::sendSdpOffer(const std::string& sdp, std::string& err) {
    auto ver = [](int lo, int hi) {
        json::Value v = json::Value::object();
        v.set("minVersion", lo);
        v.set("maxVersion", hi);
        return v;
    };
    json::Value chatCfg = json::Value::object();
    chatCfg.set("bytesPerSample", 2);
    chatCfg.set("expectedClipDurationMs", 20);
    json::Value fmt = json::Value::object();
    fmt.set("codec", "opus");
    fmt.set("container", "webm");
    chatCfg.set("format", fmt);
    chatCfg.set("numChannels", 1);
    chatCfg.set("sampleFrequencyHz", 24000);

    json::Value cfg = json::Value::object();
    cfg.set("chatConfiguration", chatCfg);
    cfg.set("chat", ver(1, 1));
    cfg.set("control", ver(1, 3));
    cfg.set("input", ver(1, 9));
    cfg.set("message", ver(1, 1));

    json::Value body = json::Value::object();
    body.set("messageType", "offer");
    body.set("sdp", sdp);
    body.set("requestId", "1");
    body.set("configuration", cfg);
    auto r = net::perform(authed(resolution_, previewFeatures_, login_, "POST", sessionUrl("/sdp"), body.dump()));
    if (!r.ok()) {
        err = "SDP offer failed: " + describe(r);
        return false;
    }
    return true;
}

bool GssvClient::pollSdpAnswer(std::string& answer, std::string& err) {
    answer.clear();
    auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", sessionUrl("/sdp")));
    if (r.status == 204) return true;  // not ready yet
    auto j = json::parse(r.body);
    if (!r.ok() || !j) {
        err = "SDP answer failed: " + describe(r);
        return false;
    }
    auto payload = exchangePayload(*j);
    if (!payload) return true;
    if ((*payload)["status"].str("success") != "success") {
        err = "SDP negotiation rejected: " + errorFields(payload->dump());
        return false;
    }
    answer = (*payload)["sdp"].str();
    return true;
}

bool GssvClient::sendIceCandidates(const std::vector<IceCandidate>& candidates, std::string& err) {
    json::Value list = json::Value::array();
    for (const auto& c : candidates) {
        json::Value v = json::Value::object();
        v.set("candidate", c.candidate);
        v.set("sdpMid", c.sdpMid);
        v.set("sdpMLineIndex", c.sdpMLineIndex);
        list.push(v);
    }
    json::Value body = json::Value::object();
    body.set("messageType", "iceCandidate");
    body.set("candidate", list);
    auto r = net::perform(authed(resolution_, previewFeatures_, login_, "POST", sessionUrl("/ice"), body.dump()));
    if (!r.ok()) {
        err = "ICE upload failed: " + describe(r);
        return false;
    }
    return true;
}

bool GssvClient::pollIceCandidates(std::vector<IceCandidate>& out, std::string& err) {
    out.clear();
    auto r = net::perform(authed(resolution_, previewFeatures_, login_, "GET", sessionUrl("/ice")));
    if (r.status == 204) return true;
    auto j = json::parse(r.body);
    if (!r.ok() || !j) {
        err = "ICE poll failed: " + describe(r);
        return false;
    }
    auto payload = exchangePayload(*j);
    if (!payload) return true;
    for (const auto& c : payload->items()) {
        IceCandidate ic;
        ic.candidate = c["candidate"].str();
        ic.sdpMid = c["sdpMid"].str();
        ic.sdpMLineIndex = static_cast<int>(c["sdpMLineIndex"].asInt());
        if (!ic.candidate.empty()) out.push_back(std::move(ic));
    }
    return true;
}

bool GssvClient::keepalive(std::string& err) {
    auto req = authed(resolution_, previewFeatures_, login_, "POST", sessionUrl("/keepalive"));
    req.timeoutMs = 5000;
    auto r = net::perform(req);
    if (!r.ok()) {
        err = "keepalive failed: " + describe(r);
        return false;
    }
    return true;
}

void GssvClient::stopSession() {
    if (sessionPath_.empty()) return;
    auto req = authed(resolution_, previewFeatures_, login_, "DELETE", sessionUrl(""));
    req.timeoutMs = 3000;
    auto r = net::perform(req);
    XC_LOGI("session stopped (%s)", r.ok() ? "ok" : describe(r).c_str());
    sessionPath_.clear();
}

}  // namespace xc::xcloud