File size: 7,722 Bytes
8fb6238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Logging;

namespace ClipForge.Infrastructure.Services;

/// <summary>
/// Edge TTS implementation using Microsoft Edge's speech synthesis WebSocket API.
/// Free, no API key required, high quality voices in multiple languages.
/// Based on https://github.com/rany2/edge-tts
/// </summary>
public class EdgeTtsService
{
    private const string TrustedClientToken = "6A5AA1D4EAFF4E9FB37E23D68491D6F4";
    private const string ChromiumFullVersion = "143.0.3650.75";
    private const string ChromiumMajor = "143";
    private const long WinEpoch = 11644473600;
    private const double SToNs = 1e9;

    private static string WssUrl =>
        $"wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1?TrustedClientToken={TrustedClientToken}&Sec-MS-GEC={GenerateSecMsGec()}&Sec-MS-GEC-Version=1-{ChromiumFullVersion}";

    private readonly ILogger<EdgeTtsService> _logger;

    public static class Voices
    {
        public const string FranciscaPtBr = "pt-BR-FranciscaNeural";
        public const string AntonioNeural = "pt-BR-AntonioNeural";
        public const string ThalitaNeural = "pt-BR-ThalitaNeural";
    }

    public EdgeTtsService(ILogger<EdgeTtsService> logger)
    {
        _logger = logger;
    }

    public async Task<byte[]> SynthesizeSpeechAsync(string text, string voice = "pt-BR-FranciscaNeural", CancellationToken ct = default)
    {
        _logger.LogInformation("Generating TTS with Edge voice '{Voice}', text length: {Length}", voice, text.Length);

        // Retry up to 3 times
        for (int attempt = 1; attempt <= 3; attempt++)
        {
            try
            {
                var result = await TrySynthesizeAsync(text, voice, ct);
                if (result.Length > 0)
                    return result;
            }
            catch (Exception ex) when (attempt < 3)
            {
                _logger.LogWarning(ex, "Edge TTS attempt {Attempt} failed, retrying...", attempt);
                await Task.Delay(1000 * attempt, ct);
            }
        }

        // Final attempt - let it throw
        return await TrySynthesizeAsync(text, voice, ct);
    }

    private async Task<byte[]> TrySynthesizeAsync(string text, string voice, CancellationToken ct)
    {
        _logger.LogInformation("Generating TTS with Edge voice '{Voice}', text length: {Length}", voice, text.Length);

        using var ws = new ClientWebSocket();

        // Headers matching edge-tts Python library
        ws.Options.SetRequestHeader("Pragma", "no-cache");
        ws.Options.SetRequestHeader("Cache-Control", "no-cache");
        ws.Options.SetRequestHeader("Origin", "chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold");
        ws.Options.SetRequestHeader("User-Agent",
            $"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{ChromiumMajor}.0.0.0 Safari/537.36 Edg/{ChromiumMajor}.0.0.0");
        ws.Options.SetRequestHeader("Accept-Encoding", "gzip, deflate, br, zstd");
        ws.Options.SetRequestHeader("Accept-Language", "en-US,en;q=0.9");

        // MUID cookie
        var muid = GenerateMuid();
        ws.Options.SetRequestHeader("Cookie", $"muid={muid};");

        var url = WssUrl;
        _logger.LogDebug("Connecting to Edge TTS WebSocket");

        await ws.ConnectAsync(new Uri(url), ct);

        var requestId = Guid.NewGuid().ToString("N");

        // Send configuration
        var configMessage =
            $"X-Timestamp:{GetTimestamp()}\r\n" +
            "Content-Type:application/json; charset=utf-8\r\n" +
            "Path:speech.config\r\n\r\n" +
            "{\"context\":{\"synthesis\":{\"audio\":{\"metadataoptions\":{\"sentenceBoundaryEnabled\":\"false\",\"wordBoundaryEnabled\":\"false\"},\"outputFormat\":\"audio-24khz-48kbitrate-mono-mp3\"}}}}";

        await SendTextAsync(ws, configMessage, ct);

        // Send SSML
        var ssml = $"<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='pt-BR'>" +
                   $"<voice name='{voice}'><prosody pitch='+0Hz' rate='+0%' volume='+0%'>{EscapeXml(text)}</prosody></voice></speak>";

        var ssmlMessage =
            $"X-RequestId:{requestId}\r\n" +
            "Content-Type:application/ssml+xml\r\n" +
            $"X-Timestamp:{GetTimestamp()}\r\n" +
            "Path:ssml\r\n\r\n" +
            ssml;

        await SendTextAsync(ws, ssmlMessage, ct);

        // Receive audio data
        var audioData = new List<byte>();
        var buffer = new byte[32768];

        while (ws.State == WebSocketState.Open)
        {
            var result = await ws.ReceiveAsync(buffer, ct);

            if (result.MessageType == WebSocketMessageType.Close)
                break;

            if (result.MessageType == WebSocketMessageType.Binary)
            {
                // Binary messages: first 2 bytes are header length (big-endian)
                if (result.Count > 2)
                {
                    int headerLen = (buffer[0] << 8) | buffer[1];
                    int audioStart = 2 + headerLen;
                    if (audioStart < result.Count)
                    {
                        var audioChunk = new byte[result.Count - audioStart];
                        Array.Copy(buffer, audioStart, audioChunk, 0, audioChunk.Length);
                        audioData.AddRange(audioChunk);
                    }
                }
            }
            else if (result.MessageType == WebSocketMessageType.Text)
            {
                var msg = Encoding.UTF8.GetString(buffer, 0, result.Count);
                if (msg.Contains("Path:turn.end"))
                    break;
            }
        }

        if (ws.State == WebSocketState.Open)
        {
            try { await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "done", ct); }
            catch { /* ignore close errors */ }
        }

        _logger.LogInformation("Edge TTS generated {Bytes} bytes of audio", audioData.Count);
        return audioData.ToArray();
    }

    /// <summary>
    /// Generates the Sec-MS-GEC token value (SHA256 hash of rounded timestamp + token).
    /// Matches the Python edge-tts DRM implementation.
    /// </summary>
    private static string GenerateSecMsGec()
    {
        // Get current Unix timestamp
        var ticks = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

        // Convert to Windows file time epoch
        ticks += WinEpoch;

        // Round down to nearest 5 minutes (300 seconds)
        ticks -= ticks % 300;

        // Convert to 100-nanosecond intervals (Windows file time format)
        var nsValue = (long)(ticks * SToNs / 100);

        // Hash: "{ticks}{TrustedClientToken}"
        var strToHash = $"{nsValue}{TrustedClientToken}";
        var hashBytes = SHA256.HashData(Encoding.ASCII.GetBytes(strToHash));

        return Convert.ToHexString(hashBytes);
    }

    private static string GenerateMuid()
    {
        var bytes = new byte[16];
        RandomNumberGenerator.Fill(bytes);
        return Convert.ToHexString(bytes);
    }

    private static async Task SendTextAsync(ClientWebSocket ws, string message, CancellationToken ct)
    {
        var bytes = Encoding.UTF8.GetBytes(message);
        await ws.SendAsync(bytes, WebSocketMessageType.Text, true, ct);
    }

    private static string GetTimestamp()
        => DateTime.UtcNow.ToString("ddd MMM dd yyyy HH:mm:ss") + " GMT+0000 (Coordinated Universal Time)";

    private static string EscapeXml(string text)
        => text.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");
}