Skip to content

armgit / WacOS

Public Imported from GitHub
0

A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.

Rust
22.9 KB
Raw Blame
// letra.cpp: a letra da música na Ilha Dinâmica e na barra de menus (issue #342).
// O Windows (SMTC) manda o título e o artista, mas quase nenhum app manda a letra —
// e o KuGou Music nem manda o tempo da música (TimelineProperties vem todo zerado).
// Então aqui: 1) procura um .lrc nosso (pasta de letras ou ao lado do arquivo);
//             2) senão busca na API pública do NetEase Cloud Music, a mesma que
//                vários players abertos usam para achar a letra de quem toca;
//             3) guarda em %APPDATA%\Shell\letras para abrir sem internet.
// Nada aqui desenha: a thread só acorda quando a música muda.
#include "shell.h"
#include <shellapi.h>
#include <objbase.h>
#include <shlobj.h>
#include <winhttp.h>
#include <algorithm>
#include <cmath>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

#pragma comment(lib, "winhttp.lib")

namespace {

struct Linha { double t = 0; std::wstring s; };

std::mutex g_mx;
std::condition_variable g_cv;
bool g_acordar = false, g_parar = false, g_rodando = false;
std::wstring g_pedT, g_pedA;      // o que a Ilha pediu (título e artista)
double g_pedDur = 0;              // a duração que a Ilha conhece (0 = não sabe)
std::wstring g_cargaT, g_cargaA;  // o que já está valendo ("" = nada)
std::vector<Linha> g_linhas;
double g_dur = 0;                 // duração da música (para a barra de progresso)

const std::wstring& Pasta() {
    static const std::wstring c = [] {
        std::wstring o;
        PWSTR p = nullptr;
        if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &p))) {
            o = std::wstring(p) + L"\\Shell";
            CoTaskMemFree(p);
        }
        return o;
    }();
    return c;
}

std::wstring Minus(const std::wstring& s) {
    std::wstring o = s;
    for (auto& c : o) if (c >= L'A' && c <= L'Z') c = (wchar_t)(c - L'A' + L'a');
    return o;
}

bool Contem(const std::wstring& onde, const std::wstring& o) {
    if (o.empty()) return false;
    return Minus(onde).find(Minus(o)) != std::wstring::npos;
}

// "如愿 (电影《我和我的父辈》主题曲)" -> "如愿": o parêntese atrapalha a busca
std::wstring Simples(const std::wstring& s) {
    std::wstring o;
    int dentro = 0;
    for (wchar_t c : s) {
        if (c == L'(' || c == L'[' || c == L'(') dentro++;
        else if (c == L')' || c == L']' || c == L')') { if (dentro) dentro--; }
        else if (!dentro && c != L' ' && c != L'\t') o.push_back(c);
    }
    return Minus(o);
}

std::string U(const std::wstring& s) {
    if (s.empty()) return std::string();
    int n = WideCharToMultiByte(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0, nullptr, nullptr);
    std::string o((size_t)n, 0);
    WideCharToMultiByte(CP_UTF8, 0, s.data(), (int)s.size(), &o[0], n, nullptr, nullptr);
    return o;
}

std::wstring W(const std::string& s, UINT cp = CP_UTF8) {
    if (s.empty()) return std::wstring();
    int n = MultiByteToWideChar(cp, 0, s.data(), (int)s.size(), nullptr, 0);
    if (n <= 0) return std::wstring();
    std::wstring o((size_t)n, 0);
    MultiByteToWideChar(cp, 0, s.data(), (int)s.size(), &o[0], n);
    return o;
}

// arquivo .lrc antigo costuma estar em GBK: se o UTF-8 der lixo, tenta o 936
std::wstring Decodifica(const std::string& b) {
    std::wstring o = W(b);
    size_t ruins = 0;
    for (wchar_t c : o) if (c == 0xFFFD) ruins++;
    if (!o.empty() && ruins * 8 > o.size()) {
        std::wstring g = W(b, 936);
        if (!g.empty()) return g;
    }
    return o;
}

bool LerArquivo(const std::wstring& p, std::wstring& out) {
    std::ifstream f(p.c_str(), std::ios::binary);
    if (!f) return false;
    std::string b((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
    if (b.empty() || b.size() > 4u * 1024 * 1024) return false;
    if (b.size() >= 3 && (unsigned char)b[0] == 0xEF && (unsigned char)b[1] == 0xBB && (unsigned char)b[2] == 0xBF) b.erase(0, 3);
    out = Decodifica(b);
    return !out.empty();
}

void GravaArquivo(const std::wstring& p, const std::wstring& txt) {
    std::ofstream f(p.c_str(), std::ios::binary | std::ios::trunc);
    if (f) { std::string b = U(txt); f.write(b.data(), (std::streamsize)b.size()); }
}

void CriaPasta(const std::wstring& p) { CreateDirectoryW(p.c_str(), nullptr); }

std::wstring NomeCache(const std::wstring& t, const std::wstring& a) {
    std::wstring k = Simples(t) + L"\x1f" + Minus(a);
    unsigned long long h = 1469598103934665603ULL;
    for (wchar_t c : k) { h ^= (unsigned long long)c; h *= 1099511628211ULL; }
    wchar_t b[32];
    swprintf_s(b, L"%016llx", h);
    return Pasta() + L"\\letras\\" + b + L".lrc";
}

// ---- LRC
bool LerTag(const std::wstring& s, double& t) {
    size_t c = s.find(L':');
    if (c == std::wstring::npos || c == 0) return false;
    for (size_t i = 0; i < s.size(); i++) {
        if (i == c) continue;
        if (s[i] < L'0' || s[i] > L'9') { if (s[i] != L'.') return false; }
    }
    double m = wcstod(s.substr(0, c).c_str(), nullptr);
    double g = wcstod(s.substr(c + 1).c_str(), nullptr);
    t = m * 60.0 + g;
    return true;
}

void ParseLRC(const std::wstring& txt, std::vector<Linha>& out) {
    size_t i = 0;
    while (i <= txt.size()) {
        size_t j = txt.find(L'\n', i);
        if (j == std::wstring::npos) j = txt.size();
        std::wstring ln = txt.substr(i, j - i);
        i = j + 1;
        while (!ln.empty() && (ln.back() == L'\r' || ln.back() == L'\t')) ln.pop_back();
        std::vector<double> ts;
        size_t k = 0;
        bool meta = false;
        while (k < ln.size() && ln[k] == L'[') {
            size_t e = ln.find(L']', k);
            if (e == std::wstring::npos) break;
            double t;
            if (!LerTag(ln.substr(k + 1, e - k - 1), t)) { meta = true; break; }  // [ar:] [ti:] [length:]
            ts.push_back(t);
            k = e + 1;
        }
        if (meta || ts.empty()) { if (j == txt.size()) break; continue; }
        std::wstring corpo = ln.substr(k);
        while (!corpo.empty() && (corpo.front() == L' ' || corpo.front() == L'\t')) corpo.erase(0, 1);
        while (!corpo.empty() && (corpo.back() == L' ' || corpo.back() == L'\t')) corpo.pop_back();
        for (double t : ts) out.push_back({ t, corpo });
        if (j == txt.size()) break;
    }
    std::stable_sort(out.begin(), out.end(), [](const Linha& a, const Linha& b) { return a.t < b.t; });
}

// ---- JSON mínimo (a resposta do NetEase é previsível: só preciso de algumas chaves)
void PulaEsp(const std::string& s, size_t& p) {
    while (p < s.size() && (s[p] == ' ' || s[p] == '\t' || s[p] == '\n' || s[p] == '\r')) p++;
}

void Utf8Add(std::string& o, unsigned cp) {
    if (cp < 0x80) o.push_back((char)cp);
    else if (cp < 0x800) { o.push_back((char)(0xC0 | (cp >> 6))); o.push_back((char)(0x80 | (cp & 0x3F))); }
    else if (cp < 0x10000) {
        o.push_back((char)(0xE0 | (cp >> 12)));
        o.push_back((char)(0x80 | ((cp >> 6) & 0x3F)));
        o.push_back((char)(0x80 | (cp & 0x3F)));
    } else {
        o.push_back((char)(0xF0 | (cp >> 18)));
        o.push_back((char)(0x80 | ((cp >> 12) & 0x3F)));
        o.push_back((char)(0x80 | ((cp >> 6) & 0x3F)));
        o.push_back((char)(0x80 | (cp & 0x3F)));
    }
}

bool PegaStr(const std::string& s, size_t& p, std::wstring& out) {
    PulaEsp(s, p);
    if (p >= s.size() || s[p] != '"') return false;
    p++;
    std::string b;
    unsigned par = 0;
    while (p < s.size()) {
        unsigned char c = (unsigned char)s[p++];
        if (c == '"') { out = W(b); return true; }
        if (c != '\\') { b.push_back((char)c); continue; }
        if (p >= s.size()) break;
        char e = s[p++];
        if (e == 'n') b.push_back('\n');
        else if (e == 't') b.push_back('\t');
        else if (e == 'r') b.push_back('\r');
        else if (e == 'u' && p + 4 <= s.size()) {
            unsigned v = (unsigned)strtoul(s.substr(p, 4).c_str(), nullptr, 16);
            p += 4;
            if (v >= 0xD800 && v <= 0xDBFF) { par = v; continue; }
            if (v >= 0xDC00 && v <= 0xDFFF && par) { Utf8Add(b, 0x10000 + ((par - 0xD800) << 10) + (v - 0xDC00)); par = 0; continue; }
            Utf8Add(b, v); par = 0;
        } else b.push_back(e);
    }
    return false;
}

bool Chave(const std::string& s, size_t from, const char* nome, size_t& depois) {
    size_t p = s.find(nome, from);
    if (p == std::string::npos) return false;
    p += strlen(nome);
    PulaEsp(s, p);
    if (p >= s.size() || s[p] != ':') return false;
    depois = p + 1;
    return true;
}

// As chaves do proprio objeto da musica: o primeiro "id" e o primeiro "name" que aparecem dentro dele
// sao os do album/artista (id 0 e nome vazio), nao os da musica. Aqui so valem as chaves do nivel de cima.
bool ChaveTop(const std::string& s, const char* nome, size_t& depois) {
    int d = 0;
    bool emStr = false;
    size_t n = strlen(nome);
    for (size_t i = 0; i < s.size(); i++) {
        char c = s[i];
        if (emStr) {
            if (c == '\\') { i++; continue; }
            if (c == '"') emStr = false;
            continue;
        }
        if (c == '"') {
            if (d == 1 && s.compare(i, n, nome) == 0) {
                size_t p = i + n;
                PulaEsp(s, p);
                if (p < s.size() && s[p] == ':') { depois = p + 1; return true; }
            }
            emStr = true;
            continue;
        }
        if (c == '{' || c == '[') d++;
        else if (c == '}' || c == ']') d--;
    }
    return false;
}

std::wstring StrTop(const std::string& s, const char* nome) {
    size_t p;
    std::wstring o;
    if (!ChaveTop(s, nome, p)) return o;
    if (!PegaStr(s, p, o)) o.clear();
    return o;
}

long long NumTop(const std::string& s, const char* nome) {
    size_t p;
    if (!ChaveTop(s, nome, p)) return 0;
    PulaEsp(s, p);
    return strtoll(s.c_str() + p, nullptr, 10);
}
std::wstring StrDe(const std::string& s, size_t from, const char* nome) {
    size_t p;
    std::wstring o;
    if (!Chave(s, from, nome, p)) return o;
    if (!PegaStr(s, p, o)) o.clear();
    return o;
}

long long NumDe(const std::string& s, size_t from, const char* nome) {
    size_t p;
    if (!Chave(s, from, nome, p)) return 0;
    PulaEsp(s, p);
    return strtoll(s.c_str() + p, nullptr, 10);
}

struct Achado { long long id = 0, dur = 0; std::wstring nome, artista; };

std::wstring ArtistaDe(const std::string& obj) {
    size_t p;
    if (!Chave(obj, 0, "\"artists\"", p)) return std::wstring();
    size_t q = obj.find('[', p);
    if (q == std::string::npos) return std::wstring();
    return StrDe(obj, q, "\"name\"");
}

std::wstring UrlEnc(const std::wstring& s) {
    std::string u = U(s);
    std::wstring o;
    wchar_t b[8];
    for (unsigned char c : u) {
        if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
            c == '-' || c == '_' || c == '.' || c == '~') o.push_back((wchar_t)c);
        else { swprintf_s(b, L"%%%02X", c); o += b; }
    }
    return o;
}

bool Http(const wchar_t* host, const std::wstring& caminho, std::string& corpo) {
    bool ok = false;
    HINTERNET ses = WinHttpOpen(L"WacOS/1.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
                                WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    if (!ses) { Log(L"letra: WinHttpOpen falhou"); return false; }
    WinHttpSetTimeouts(ses, 4000, 4000, 6000, 9000);
    HINTERNET con = WinHttpConnect(ses, host, INTERNET_DEFAULT_HTTPS_PORT, 0);
    if (!con) Log(L"letra: WinHttpConnect falhou (%lu)", GetLastError());
    HINTERNET req = con ? WinHttpOpenRequest(con, L"GET", caminho.c_str(), nullptr, WINHTTP_NO_REFERER,
                                             WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : nullptr;
    if (req) {
        const wchar_t* hdr = L"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\r\n"
                             L"Referer: https://music.163.com/\r\nAccept: application/json\r\n";
        if (WinHttpSendRequest(req, hdr, (DWORD)-1L, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) &&
            WinHttpReceiveResponse(req, nullptr)) {
            DWORD st = 0, n = sizeof(st);
            WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
                                WINHTTP_HEADER_NAME_BY_INDEX, &st, &n, WINHTTP_NO_HEADER_INDEX);
            if (st == 200) {
                corpo.clear();
                DWORD lido = 0;
                char buf[8192];
                while (WinHttpReadData(req, buf, sizeof(buf), &lido) && lido > 0) {
                    corpo.append(buf, lido);
                    if (corpo.size() > 4u * 1024 * 1024) break;
                }
                ok = !corpo.empty();
            }
        }
        if (!ok) Log(L"letra: nada de %ls%ls", host, caminho.substr(0, 90).c_str());
        WinHttpCloseHandle(req);
    }
    if (con) WinHttpCloseHandle(con);
    WinHttpCloseHandle(ses);
    return ok;
}
// ---- busca
// Tira o que vem entre parênteses/colchetes: "Rain (Live)" e "Rain" são a mesma faixa
std::wstring Limpo(const std::wstring& s) {
    std::wstring o;
    int nivel = 0;
    for (wchar_t c : s) {
        if (c == L'(' || c == L'(' || c == L'[' || c == L'【') { nivel++; continue; }
        if (c == L')' || c == L')' || c == L']' || c == L'】') { if (nivel) nivel--; continue; }
        if (!nivel) o.push_back(c);
    }
    while (!o.empty() && o.front() == L' ') o.erase(0, 1);
    while (!o.empty() && o.back() == L' ') o.pop_back();
    return o;
}

// A letra só serve quando o título e o artista batem; se a duração é conhecida, também tem de bater.
// Na dúvida fica sem letra: melhor nada do que a letra de outra gravação.
int Nota(const Achado& a, const std::wstring& t, const std::wstring& art, double durPedido) {
    std::wstring an = Simples(a.nome), at = Simples(t);
    if (an.empty() || at.empty()) return -1;
    std::wstring ln = Limpo(an), lt = Limpo(at);
    int s;
    if (an == at) s = 100;
    else if (!ln.empty() && ln == lt) s = 85;
    else if (an.find(at) != std::wstring::npos || at.find(an) != std::wstring::npos) s = 40;
    else return -1;
    std::wstring aa = Minus(a.artista), ra = Minus(art);
    if (!aa.empty() && !ra.empty()) {
        if (aa.find(ra) != std::wstring::npos || ra.find(aa) != std::wstring::npos) s += 50;
        else return -1;  // outro artista: recusa
    }
    if (durPedido > 1.0 && a.dur > 0) {
        double dif = durPedido - (double)a.dur / 1000.0;
        if (dif < 0) dif = -dif;
        if (dif <= 3.0) s += 25;
        else if (dif <= 8.0) s += 8;
        else return -1;  // a duração não bate: recusa
    }
    return s;
}

bool TemLetra(const std::wstring& txt) {
    std::vector<Linha> l;
    ParseLRC(txt, l);
    for (auto& x : l) if (!x.s.empty()) return true;
    return false;
}

bool DoArquivo(const std::wstring& caminho, std::vector<Linha>& ls, double& dur) {
    std::wstring txt;
    if (!LerArquivo(caminho, txt)) return false;
    ls.clear();
    ParseLRC(txt, ls);
    if (ls.empty()) return false;
    dur = ls.back().t + 6.0;
    return true;
}

// .lrc nosso próprio: a pasta de cache e as pastas do ajuste letra_pasta (separadas por ';')
bool Local(const std::wstring& t, const std::wstring& a, std::wstring& achou) {
    std::wstring chave = Simples(t);
    std::wstring art = Minus(a);
    if (chave.size() < 2) return false;
    std::vector<std::wstring> pastas;
    std::wstring cfg = shell::Setting(L"letra_pasta", L"");
    size_t i = 0;
    while (i <= cfg.size()) {
        size_t j = cfg.find(L';', i);
        if (j == std::wstring::npos) j = cfg.size();
        std::wstring d = cfg.substr(i, j - i);
        while (!d.empty() && (d.front() == L' ' || d.front() == L'"' || d.front() == L'\r')) d.erase(0, 1);
        while (!d.empty() && (d.back() == L' ' || d.back() == L'"')) d.pop_back();
        if (!d.empty()) pastas.push_back(d);
        i = j + 1;
        if (j == cfg.size()) break;
    }
    pastas.push_back(Pasta() + L"\\letras");
    for (auto& d : pastas) {
        WIN32_FIND_DATAW fd;
        HANDLE h = FindFirstFileW((d + L"\\*.lrc").c_str(), &fd);
        if (h == INVALID_HANDLE_VALUE) continue;
        std::wstring forte, fraco;
        do {
            if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
            if (!Contem(fd.cFileName, chave)) continue;
            std::wstring txt;
            if (!LerArquivo(d + L"\\" + fd.cFileName, txt) || !TemLetra(txt)) continue;
            // o ficheiro que também leva o nome do artista vale mais do que um homónimo
            if (!art.empty() && Contem(fd.cFileName, art)) { forte = txt; break; }
            if (fraco.empty()) fraco = txt;
        } while (FindNextFileW(h, &fd));
        FindClose(h);
        if (!forte.empty()) { achou = forte; return true; }
        if (!fraco.empty()) { achou = fraco; return true; }
    }
    return false;
}

bool Online(const std::wstring& t, const std::wstring& a, double durPedido, std::vector<Linha>& ls, double& dur) {
    std::wstring q = UrlEnc(a.empty() ? t : t + L" " + a);
    std::string js;
    if (!Http(L"music.163.com", L"/api/search/get/web?s=" + q + L"&type=1&limit=10", js)) {
        Log(L"letra: busca sem resposta");
        return false;
    }
    size_t p = js.find("\"songs\"");
    if (p == std::string::npos) {
        Log(L"letra: sem songs em %u bytes", (unsigned)js.size());
        return false;
    }
    std::vector<Achado> cand;
    while (p < js.size() && cand.size() < 10) {
        size_t ob = js.find('{', p);
        if (ob == std::string::npos) break;
        int d = 0;
        size_t k = ob;
        for (; k < js.size(); k++) {
            if (js[k] == '{') d++;
            else if (js[k] == '}') { d--; if (!d) break; }
        }
        if (k >= js.size()) break;
        std::string obj = js.substr(ob, k - ob + 1);
        Achado x;
        x.id = NumTop(obj, "\"id\"");
        x.dur = NumTop(obj, "\"duration\"");
        x.nome = StrTop(obj, "\"name\"");
        x.artista = ArtistaDe(obj);
        if (x.id > 0 && !x.nome.empty()) cand.push_back(x);
        p = k + 1;
    }
    int melhor = -1, nota = -1;
    for (size_t i = 0; i < cand.size(); i++) {
        int n = Nota(cand[(size_t)i], t, a, durPedido);
        if (n > nota) { nota = n; melhor = (int)i; }
    }
    if (melhor < 0 || nota < 0) {
        Log(L"letra: %u candidato(s), nenhum serve para %ls", (unsigned)cand.size(), t.c_str());
        return false;
    }
    wchar_t url[96];
    swprintf_s(url, L"/api/song/lyric?id=%lld&lv=1&kv=0&tv=0", cand[(size_t)melhor].id);
    if (!Http(L"music.163.com", url, js)) {
        Log(L"letra: sem resposta da letra");
        return false;
    }
    std::wstring lrc = StrDe(js, 0, "\"lyric\"");
    ls.clear();
    ParseLRC(lrc, ls);
    if (ls.empty()) {
        Log(L"letra: LRC vazio (%u chars)", (unsigned)lrc.size());
        return false;
    }
    dur = cand[(size_t)melhor].dur > 0 ? (double)cand[(size_t)melhor].dur / 1000.0 : ls.back().t + 6.0;
    return true;
}

bool Buscar(const std::wstring& t, const std::wstring& a, double durPedido, std::vector<Linha>& ls, double& dur) {
    std::wstring cache = NomeCache(t, a);
    if (DoArquivo(cache, ls, dur)) return true;
    std::wstring txt;
    if (Local(t, a, txt)) {
        ls.clear();
        ParseLRC(txt, ls);
        if (!ls.empty()) {
            dur = ls.back().t + 6.0;
            CriaPasta(Pasta() + L"\\letras");
            GravaArquivo(cache, txt);
            return true;
        }
    }
    if (!Online(t, a, durPedido, ls, dur)) return false;
    std::wstring saida;
    wchar_t b[40];
    for (auto& x : ls) {
        int m = (int)(x.t / 60.0);
        int s = (int)x.t - m * 60;
        int cs = (int)((x.t - (double)(int)x.t) * 100.0 + 0.5);
        if (cs > 99) cs = 99;
        swprintf_s(b, L"[%02d:%02d.%02d]", m, s, cs);
        saida += b;
        saida += x.s;
        saida += L"\n";
    }
    CriaPasta(Pasta() + L"\\letras");
    GravaArquivo(cache, saida);
    return true;
}

void Thread() {
    if (!Pasta().empty()) { CriaPasta(Pasta() + L"\\letras"); }
    for (;;) {
        std::wstring t, a; double durPedido = 0;
        {
            std::unique_lock<std::mutex> l(g_mx);
            g_cv.wait(l, [] { return g_acordar || g_parar; });
            if (g_parar) break;
            g_acordar = false;
            t = g_pedT; a = g_pedA; durPedido = g_pedDur;
            if (t == g_cargaT && a == g_cargaA) continue;
        }
        std::vector<Linha> ls;
        double dur = 0;
        bool ok = !t.empty() && Buscar(t, a, durPedido, ls, dur);
        size_t n = ls.size();
        {
            std::lock_guard<std::mutex> l(g_mx);
            if (g_pedT == t && g_pedA == a) {
                g_linhas = std::move(ls);
                g_dur = ok ? dur : 0.0;
                g_cargaT = t; g_cargaA = a;
            }
        }
        if (ok) Log(L"letra: %ls -> %u linha(s)", t.c_str(), (unsigned)n);
        else Log(L"letra: %ls sem letra", t.c_str());
    }
}

}  // namespace

namespace letra {

void Pedir(const std::wstring& t, const std::wstring& a, double dur) {
    if (t.empty() && a.empty()) return;
    std::lock_guard<std::mutex> l(g_mx);
    g_pedDur = dur;
    if (t == g_cargaT && a == g_cargaA) { g_pedT = t; g_pedA = a; return; }
    if (t != g_pedT || a != g_pedA) {
        g_pedT = t; g_pedA = a;
        g_linhas.clear();
        g_dur = 0;
        g_cargaT.clear(); g_cargaA.clear();
        g_acordar = true;
        if (!g_rodando) { g_rodando = true; std::thread(Thread).detach(); }
    }
    g_cv.notify_one();
}

bool Tem() {
    std::lock_guard<std::mutex> l(g_mx);
    for (auto& x : g_linhas) if (!x.s.empty()) return true;
    return false;
}

double Duracao() {
    std::lock_guard<std::mutex> l(g_mx);
    return g_linhas.empty() ? g_dur : std::max(g_dur, g_linhas.back().t + 1.0);
}

std::wstring Texto(double pos) {
    std::lock_guard<std::mutex> l(g_mx);
    if (g_linhas.empty()) return std::wstring();
    int lo = 0, hi = (int)g_linhas.size() - 1, at = -1;
    while (lo <= hi) {
        int m = (lo + hi) / 2;
        if (g_linhas[(size_t)m].t <= pos) { at = m; lo = m + 1; } else hi = m - 1;
    }
    if (at >= 0 && !g_linhas[(size_t)at].s.empty()) return g_linhas[(size_t)at].s;
    for (int i = at + 1; i < (int)g_linhas.size(); i++)
        if (!g_linhas[(size_t)i].s.empty()) return g_linhas[(size_t)i].s;  // intro: já mostra a 1ª frase
    return std::wstring();
}

void Parar() {
    std::lock_guard<std::mutex> l(g_mx);
    g_parar = true;
    g_cv.notify_all();
}

}  // namespace letra