-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi_server.cpp
More file actions
635 lines (572 loc) · 25.8 KB
/
Copy pathapi_server.cpp
File metadata and controls
635 lines (572 loc) · 25.8 KB
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
#include "api_server.h"
#include "loiacono_rolling.h"
#include "spectrogram_widget.h"
#include <QImage>
#include <QStandardPaths>
#include <QWidget>
#include <QMainWindow>
#include <QLayout>
#include <QWindow>
#include <QScreen>
static const char* APP_VERSION = "1.0.0";
ApiServer::ApiServer(LoiaconoRolling* transform, SpectrogramWidget* spectrogram,
QObject* parent)
: QTcpServer(parent), transform_(transform), spectrogram_(spectrogram)
{
}
bool ApiServer::startListening(quint16 port)
{
if (!listen(QHostAddress::LocalHost, port)) {
qWarning("API server failed to listen on port %d: %s",
port, qPrintable(errorString()));
return false;
}
// MJPEG stream timer — push frames to all connected stream clients
connect(&streamTimer_, &QTimer::timeout, this, &ApiServer::pushMjpegFrame);
qInfo("API server listening on http://localhost:%d", port);
return true;
}
void ApiServer::updateCurrentSettings(int multiple, int bins, int freqMin, int freqMax, double baseAFreq)
{
curMultiple_ = multiple;
curBins_ = bins;
curFreqMin_ = freqMin;
curFreqMax_ = freqMax;
curBaseAFreq_ = baseAFreq;
}
void ApiServer::incomingConnection(qintptr socketDescriptor)
{
auto* socket = new QTcpSocket(this);
socket->setSocketDescriptor(socketDescriptor);
connect(socket, &QTcpSocket::readyRead, this, [this, socket]() {
handleRequest(socket);
});
connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
}
void ApiServer::handleRequest(QTcpSocket* socket)
{
auto data = socket->readAll();
QString request = QString::fromUtf8(data);
auto lines = request.split("\r\n");
if (lines.isEmpty()) { sendError(socket, 400, "Bad request"); return; }
auto parts = lines[0].split(" ");
if (parts.size() < 2) { sendError(socket, 400, "Bad request"); return; }
QString method = parts[0];
QString fullPath = parts[1];
// Strip query string for route matching
QString path = fullPath.section('?', 0, 0);
// Parse body for PUT/POST
QJsonObject body;
int bodyStart = request.indexOf("\r\n\r\n");
if (bodyStart >= 0) {
QByteArray bodyData = data.mid(bodyStart + 4);
QJsonParseError err;
auto doc = QJsonDocument::fromJson(bodyData, &err);
if (doc.isObject()) body = doc.object();
}
// ── Route ──
if (method == "GET" && path == "/api/version") {
sendJson(socket, 200, {
{"app", "Loiacono Spectrogram"},
{"version", APP_VERSION},
{"qt", qVersion()},
{"platform", QSysInfo::prettyProductName()},
{"arch", QSysInfo::currentCpuArchitecture()},
});
} else if (method == "GET" && path == "/api/status") {
std::vector<float> spectrum;
transform_->getSpectrum(spectrum);
float peak = 0; int peakIdx = 0;
for (int i = 0; i < (int)spectrum.size(); i++) {
if (spectrum[i] > peak) { peak = spectrum[i]; peakIdx = i; }
}
double peakHz = transform_->numBins() > 0 ? transform_->binFreqHz(peakIdx) : 0;
sendJson(socket, 200, {
{"peakFrequencyHz", peakHz},
{"peakAmplitude", static_cast<double>(peak)},
{"numBins", transform_->numBins()},
{"sampleRate", transform_->sampleRate()},
{"multiple", curMultiple_},
{"freqMin", curFreqMin_},
{"freqMax", curFreqMax_},
{"baseAFrequency", transform_->baseAFrequency()},
});
} else if (method == "GET" && path == "/api/screenshot") {
// Capture the full app window UI when possible (controls + spectrogram).
// Fallback to spectrogram-only render if a top-level window is unavailable.
QImage img;
if (spectrogram_ && spectrogram_->window() && spectrogram_->window()->isVisible()) {
img = spectrogram_->window()->grab().toImage();
} else {
img = spectrogram_->renderToImage();
}
QByteArray pngData;
QBuffer buf(&pngData);
buf.open(QIODevice::WriteOnly);
img.save(&buf, "PNG");
sendPng(socket, pngData);
} else if (method == "GET" && path == "/api/spectrum") {
std::vector<float> spectrum;
transform_->getSpectrum(spectrum);
QJsonArray arr;
for (int i = 0; i < (int)spectrum.size(); i++) {
QJsonObject bin;
bin["hz"] = transform_->binFreqHz(i);
bin["amplitude"] = static_cast<double>(spectrum[i]);
arr.append(bin);
}
sendJsonArray(socket, 200, arr);
} else if (method == "GET" && path == "/api/profile") {
sendJson(socket, 200, {
{"multiple", curMultiple_},
{"bins", curBins_},
{"freqMin", curFreqMin_},
{"freqMax", curFreqMax_},
{"sampleRate", transform_->sampleRate()},
{"baseAFrequency", transform_->baseAFrequency()},
});
} else if (method == "PUT" && path == "/api/profile") {
int m = body.value("multiple").toInt(curMultiple_);
int b = body.value("bins").toInt(curBins_);
int fmin = body.value("freqMin").toInt(curFreqMin_);
int fmax = body.value("freqMax").toInt(curFreqMax_);
if (fmin >= fmax - 50) fmax = fmin + 50;
curMultiple_ = m; curBins_ = b; curFreqMin_ = fmin; curFreqMax_ = fmax;
transform_->configure(transform_->sampleRate(), fmin, fmax, b, m);
if (settingsCallback_) settingsCallback_(m, b, fmin, fmax);
sendJson(socket, 200, {
{"status", "ok"},
{"multiple", m}, {"bins", b}, {"freqMin", fmin}, {"freqMax", fmax},
});
} else if (method == "GET" && path == "/api/profiles") {
QDir dir(profileDir());
QJsonArray names;
for (auto& f : dir.entryList({"*.json"}, QDir::Files)) {
names.append(f.chopped(5)); // strip .json
}
sendJsonArray(socket, 200, names);
} else if (method == "GET" && path.startsWith("/api/profiles/")) {
QString name = path.mid(QString("/api/profiles/").length()); // after "/api/profiles/"
QFile file(profileDir() + "/" + name + ".json");
if (!file.open(QIODevice::ReadOnly)) {
sendError(socket, 404, "Profile not found: " + name);
} else {
auto doc = QJsonDocument::fromJson(file.readAll());
sendJson(socket, 200, doc.object());
}
} else if (method == "POST" && path.startsWith("/api/profiles/")) {
QString name = path.mid(QString("/api/profiles/").length());
QDir().mkpath(profileDir());
QFile file(profileDir() + "/" + name + ".json");
QJsonObject profile = {
{"name", name},
{"multiple", curMultiple_},
{"bins", curBins_},
{"freqMin", curFreqMin_},
{"freqMax", curFreqMax_},
{"baseAFrequency", transform_->baseAFrequency()},
{"savedAt", QDateTime::currentDateTime().toString(Qt::ISODate)},
};
if (!file.open(QIODevice::WriteOnly)) {
sendError(socket, 500, "Failed to save profile");
} else {
file.write(QJsonDocument(profile).toJson(QJsonDocument::Compact));
sendJson(socket, 201, profile);
}
} else if (method == "DELETE" && path.startsWith("/api/profiles/")) {
QString name = path.mid(QString("/api/profiles/").length());
QFile file(profileDir() + "/" + name + ".json");
if (!file.exists()) {
sendError(socket, 404, "Profile not found: " + name);
} else {
file.remove();
sendOk(socket, "Deleted profile: " + name);
}
} else if (method == "GET" && path == "/api/runtime") {
auto stats = transform_->getStats();
auto fs = spectrogram_->frameStats();
sendJson(socket, 200, {
{"fps", fs.fps},
{"peakFrequencyHz", fs.peakHz},
{"peakAmplitude", static_cast<double>(fs.peakAmp)},
{"maxAmplitude", static_cast<double>(fs.maxAmp)},
{"totalSamples", static_cast<qint64>(stats.totalSamples)},
{"totalChunks", static_cast<qint64>(stats.totalChunks)},
{"uptimeSeconds", stats.uptimeSeconds},
{"samplesPerSecond", stats.samplesPerSecond},
{"avgChunkMicros", stats.avgChunkMicros},
{"peakChunkMicros", stats.peakChunkMicros},
{"cpuLoadPercent", stats.cpuLoadPercent},
{"currentBins", stats.currentBins},
{"currentMultiple", stats.currentMultiple},
{"freqMin", stats.freqMin},
{"freqMax", stats.freqMax},
{"gain", static_cast<double>(spectrogram_->gain())},
{"gamma", static_cast<double>(spectrogram_->gamma())},
{"floor", static_cast<double>(spectrogram_->floor())},
});
} else if (method == "GET" && path == "/api/devices") {
if (deviceListCb_) {
sendJsonArray(socket, 200, deviceListCb_());
} else {
sendError(socket, 500, "Device listing not available");
}
} else if (method == "PUT" && path == "/api/device") {
if (deviceSwitchCb_) {
QString deviceKey = body.value("id").toString();
if (deviceKey.isEmpty()) {
sendError(socket, 400, "Missing 'id' field");
} else {
QString result = deviceSwitchCb_(deviceKey);
if (result.startsWith("Error")) {
sendError(socket, 500, result);
} else {
sendJson(socket, 200, {{"status", "ok"}, {"device", result}});
}
}
} else {
sendError(socket, 500, "Device switching not available");
}
} else if (method == "GET" && path == "/api/stream") {
startMjpegStream(socket);
return; // don't close the socket — it stays open for streaming
} else if (method == "GET" && (path == "/" || path == "/index.html")) {
// Landing page with live spectrogram and API links
std::vector<float> spectrum;
transform_->getSpectrum(spectrum);
float peak = 0; int peakIdx = 0;
for (int i = 0; i < (int)spectrum.size(); i++) {
if (spectrum[i] > peak) { peak = spectrum[i]; peakIdx = i; }
}
double peakHz = transform_->numBins() > 0 ? transform_->binFreqHz(peakIdx) : 0;
QByteArray html = R"HTML(<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Loiacono Spectrogram</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{background:#0a0a0f;color:#d0d0e0;font-family:-apple-system,BlinkMacSystemFont,monospace;padding:24px;max-width:960px;margin:0 auto}
h1{color:#a0c0ff;font-weight:400;font-size:1.5rem;margin-bottom:4px}
.subtitle{color:#505070;font-size:.8rem;margin-bottom:20px}
.spectrogram{background:#000;border:1px solid #1a1a2a;border-radius:6px;width:100%;margin-bottom:16px}
.spectrogram img{width:100%;display:block;border-radius:5px;image-rendering:pixelated}
.status{display:flex;gap:20px;flex-wrap:wrap;margin-bottom:20px;padding:12px;background:#0e0e18;border:1px solid #1a1a2a;border-radius:6px}
.stat{display:flex;flex-direction:column}
.stat .label{font-size:.65rem;color:#505070;text-transform:uppercase;letter-spacing:.05em}
.stat .value{font-size:1.1rem;color:#a0c0ff;font-weight:600}
h2{color:#708090;font-size:.9rem;font-weight:400;margin:16px 0 8px;text-transform:uppercase;letter-spacing:.08em}
.endpoints{display:grid;grid-template-columns:1fr 1fr;gap:6px}
.ep{display:flex;gap:8px;padding:8px 12px;background:#0e0e18;border:1px solid #1a1a2a;border-radius:4px;text-decoration:none;transition:border-color .15s}
.ep:hover{border-color:#2a3a5a}
.method{font-size:.7rem;font-weight:700;padding:2px 6px;border-radius:3px;min-width:48px;text-align:center;flex-shrink:0}
.get .method{background:#1a2a1a;color:#60c060}
.put .method{background:#2a2a1a;color:#c0a040}
.post .method{background:#1a1a2a;color:#6080c0}
.delete .method{background:#2a1a1a;color:#c06060}
.ep .path{color:#a0c0ff;font-size:.85rem}
.ep .desc{color:#505070;font-size:.7rem}
.ep-info{display:flex;flex-direction:column}
.refresh-note{color:#404060;font-size:.7rem;text-align:center;margin-top:8px}
</style>
</head>
<body>
<h1>Loiacono Transform</h1>
<p class="subtitle">Rolling spectrogram — )HTML";
html += QString("v%1 | Qt %2 | %3")
.arg(APP_VERSION).arg(qVersion())
.arg(QSysInfo::currentCpuArchitecture()).toUtf8();
html += R"HTML(</p>
<div class="spectrogram">
<img id="spec" src="/api/stream" alt="Live Spectrogram">
</div>
<div class="status">
<div class="stat"><span class="label">Peak</span><span class="value" id="peak">)HTML";
html += QString("%1 Hz").arg(peakHz, 0, 'f', 0).toUtf8();
html += R"HTML(</span></div>
<div class="stat"><span class="label">Bins</span><span class="value" id="bins">)HTML";
html += QString::number(curBins_).toUtf8();
html += R"HTML(</span></div>
<div class="stat"><span class="label">Multiple</span><span class="value" id="mult">)HTML";
html += QString::number(curMultiple_).toUtf8();
html += R"HTML(</span></div>
<div class="stat"><span class="label">Range</span><span class="value" id="range">)HTML";
html += QString("%1-%2 Hz").arg(curFreqMin_).arg(curFreqMax_).toUtf8();
html += R"HTML(</span></div>
<div class="stat"><span class="label">Sample Rate</span><span class="value">48000</span></div>
</div>
<h2>API Endpoints</h2>
<div class="endpoints">
<a class="ep get" href="/api/version"><span class="method">GET</span><div class="ep-info"><span class="path">/api/version</span><span class="desc">App version, platform, architecture</span></div></a>
<a class="ep get" href="/api/status"><span class="method">GET</span><div class="ep-info"><span class="path">/api/status</span><span class="desc">Peak frequency, amplitude, settings</span></div></a>
<a class="ep get" href="/api/screenshot"><span class="method">GET</span><div class="ep-info"><span class="path">/api/screenshot</span><span class="desc">Spectrogram as PNG image</span></div></a>
<a class="ep get" href="/api/stream" target="_blank"><span class="method">GET</span><div class="ep-info"><span class="path">/api/stream</span><span class="desc">Live MJPEG video stream (~30fps)</span></div></a>
<a class="ep get" href="/api/spectrum"><span class="method">GET</span><div class="ep-info"><span class="path">/api/spectrum</span><span class="desc">All frequency bins as JSON</span></div></a>
<a class="ep get" href="/api/profile"><span class="method">GET</span><div class="ep-info"><span class="path">/api/profile</span><span class="desc">Current transform settings</span></div></a>
<a class="ep put" href="#"><span class="method">PUT</span><div class="ep-info"><span class="path">/api/profile</span><span class="desc">Update settings {multiple, bins, freqMin, freqMax}</span></div></a>
<a class="ep get" href="/api/profiles"><span class="method">GET</span><div class="ep-info"><span class="path">/api/profiles</span><span class="desc">List saved profiles</span></div></a>
<a class="ep post" href="#"><span class="method">POST</span><div class="ep-info"><span class="path">/api/profiles/:name</span><span class="desc">Save current settings as profile</span></div></a>
</div>
<script>
setInterval(async()=>{
try{
const s=await(await fetch('/api/status')).json();
document.getElementById('peak').textContent=Math.round(s.peakFrequencyHz)+' Hz';
document.getElementById('bins').textContent=s.numBins;
document.getElementById('mult').textContent=s.multiple;
document.getElementById('range').textContent=s.freqMin+'-'+s.freqMax+' Hz';
}catch(e){}
},500);
</script>
<p class="refresh-note">Live MJPEG stream at ~30fps | Status refreshes every 500ms</p>
</body>
</html>)HTML";
sendHtml(socket, html);
} else if (method == "GET" && path == "/api/debug/sizes") {
// Recursively collect widget size information
std::function<QJsonObject(QWidget*)> collectWidgetInfo = [&](QWidget* widget) -> QJsonObject {
if (!widget) return QJsonObject{{"error", "null widget"}};
QJsonObject info;
info["class"] = widget->metaObject()->className();
info["objectName"] = widget->objectName().isEmpty() ? "(unnamed)" : widget->objectName();
QRect geo = widget->geometry();
QRect frame = widget->frameGeometry();
QSize min = widget->minimumSize();
QSize max = widget->maximumSize();
QSizePolicy policy = widget->sizePolicy();
info["geometry"] = QJsonObject{
{"x", geo.x()}, {"y", geo.y()},
{"width", geo.width()}, {"height", geo.height()}
};
info["frameGeometry"] = QJsonObject{
{"x", frame.x()}, {"y", frame.y()},
{"width", frame.width()}, {"height", frame.height()}
};
info["sizeHint"] = QJsonObject{
{"width", widget->sizeHint().width()},
{"height", widget->sizeHint().height()}
};
info["minimumSize"] = QJsonObject{{"width", min.width()}, {"height", min.height()}};
info["maximumSize"] = QJsonObject{{"width", max.width()}, {"height", max.height()}};
info["sizePolicy"] = QJsonObject{
{"horizontal", policy.horizontalPolicy()},
{"vertical", policy.verticalPolicy()},
{"expanding", policy.horizontalPolicy() == QSizePolicy::Expanding ||
policy.verticalPolicy() == QSizePolicy::Expanding}
};
info["isVisible"] = widget->isVisible();
info["isEnabled"] = widget->isEnabled();
// Handle OpenGL widget specially
if (QString(widget->metaObject()->className()).contains("GL", Qt::CaseInsensitive) ||
QString(widget->metaObject()->className()).contains("OpenGL", Qt::CaseInsensitive)) {
info["type"] = "opengl";
}
// Recursively collect children
QJsonArray children;
for (QObject* child : widget->children()) {
if (QWidget* childWidget = qobject_cast<QWidget*>(child)) {
children.append(collectWidgetInfo(childWidget));
}
}
if (!children.isEmpty()) {
info["children"] = children;
info["childCount"] = children.size();
}
// Add layout info if present
if (QLayout* layout = widget->layout()) {
info["layout"] = QJsonObject{
{"type", layout->metaObject()->className()},
{"margin", layout->contentsMargins().left()}, // same for all sides usually
{"spacing", layout->spacing()}
};
QJsonArray layoutItems;
for (int i = 0; i < layout->count(); ++i) {
QLayoutItem* item = layout->itemAt(i);
QJsonObject itemInfo;
if (item->widget()) {
itemInfo["type"] = "widget";
itemInfo["widget"] = collectWidgetInfo(item->widget());
} else if (item->layout()) {
itemInfo["type"] = "layout";
itemInfo["class"] = item->layout()->metaObject()->className();
} else {
itemInfo["type"] = "spacer";
}
layoutItems.append(itemInfo);
}
info["layoutItems"] = layoutItems;
}
return info;
};
// Find the main window by traversing up from spectrogram
QJsonObject hierarchy;
QWidget* root = spectrogram_;
while (root && !qobject_cast<QMainWindow*>(root)) {
root = root->parentWidget();
}
if (!root) root = spectrogram_; // fallback
hierarchy["root"] = collectWidgetInfo(root);
// Also include spectrogram-specific info
hierarchy["spectrogram"] = QJsonObject{
{"size", QJsonObject{{"width", spectrogram_->width()}, {"height", spectrogram_->height()}}},
{"canvasSize", QJsonObject{{"width", spectrogram_->width()}, {"height", spectrogram_->height()}}},
{"isVisible", spectrogram_->isVisible()}
};
// Get screen info
if (QWindow* window = root->window()->windowHandle()) {
QScreen* screen = window->screen();
if (screen) {
hierarchy["screen"] = QJsonObject{
{"name", screen->name()},
{"geometry", QJsonObject{
{"width", screen->geometry().width()},
{"height", screen->geometry().height()}
}},
{"devicePixelRatio", screen->devicePixelRatio()}
};
}
}
sendJson(socket, 200, hierarchy);
} else {
sendError(socket, 404, "Not found: " + path);
}
}
// ── Response helpers ──
void ApiServer::sendJson(QTcpSocket* socket, int status, const QJsonObject& obj)
{
QByteArray body = QJsonDocument(obj).toJson(QJsonDocument::Compact);
QString statusText = (status == 200) ? "OK" : (status == 201) ? "Created" : "Error";
QByteArray response;
response += QString("HTTP/1.1 %1 %2\r\n").arg(status).arg(statusText).toUtf8();
response += "Content-Type: application/json\r\n";
response += "Access-Control-Allow-Origin: *\r\n";
response += QString("Content-Length: %1\r\n").arg(body.size()).toUtf8();
response += "\r\n";
response += body;
socket->write(response);
socket->flush();
socket->disconnectFromHost();
}
void ApiServer::sendJsonArray(QTcpSocket* socket, int status, const QJsonArray& arr)
{
QByteArray body = QJsonDocument(arr).toJson(QJsonDocument::Compact);
QByteArray response;
response += QString("HTTP/1.1 %1 OK\r\n").arg(status).toUtf8();
response += "Content-Type: application/json\r\n";
response += "Access-Control-Allow-Origin: *\r\n";
response += QString("Content-Length: %1\r\n").arg(body.size()).toUtf8();
response += "\r\n";
response += body;
socket->write(response);
socket->flush();
socket->disconnectFromHost();
}
void ApiServer::sendHtml(QTcpSocket* socket, const QByteArray& html)
{
QByteArray response;
response += "HTTP/1.1 200 OK\r\n";
response += "Content-Type: text/html; charset=utf-8\r\n";
response += QString("Content-Length: %1\r\n").arg(html.size()).toUtf8();
response += "\r\n";
response += html;
socket->write(response);
socket->flush();
socket->disconnectFromHost();
}
void ApiServer::sendPng(QTcpSocket* socket, const QByteArray& data)
{
QByteArray response;
response += "HTTP/1.1 200 OK\r\n";
response += "Content-Type: image/png\r\n";
response += "Access-Control-Allow-Origin: *\r\n";
response += QString("Content-Length: %1\r\n").arg(data.size()).toUtf8();
response += "\r\n";
response += data;
socket->write(response);
socket->flush();
socket->disconnectFromHost();
}
void ApiServer::sendError(QTcpSocket* socket, int status, const QString& msg)
{
sendJson(socket, status, {{"error", msg}});
}
void ApiServer::sendOk(QTcpSocket* socket, const QString& msg)
{
sendJson(socket, 200, {{"status", "ok"}, {"message", msg}});
}
// ── MJPEG Streaming ──
// The browser <img src="/api/stream"> natively handles multipart JPEG streams.
// No JavaScript needed — the browser decodes each JPEG frame as it arrives.
static constexpr char MJPEG_BOUNDARY[] = "loiaconoframe";
void ApiServer::startMjpegStream(QTcpSocket* socket)
{
// Send the multipart header — connection stays open
QByteArray header;
header += "HTTP/1.1 200 OK\r\n";
header += "Content-Type: multipart/x-mixed-replace; boundary=";
header += MJPEG_BOUNDARY;
header += "\r\n";
header += "Cache-Control: no-cache, no-store\r\n";
header += "Access-Control-Allow-Origin: *\r\n";
header += "Connection: keep-alive\r\n";
header += "\r\n";
socket->write(header);
socket->flush();
streamClients_.insert(socket);
// Remove client on disconnect
connect(socket, &QTcpSocket::disconnected, this, [this, socket]() {
streamClients_.remove(socket);
socket->deleteLater();
if (streamClients_.isEmpty()) {
streamTimer_.stop();
}
});
// Start the frame timer if not already running (~30 fps)
if (!streamTimer_.isActive()) {
streamTimer_.start(33);
}
}
void ApiServer::pushMjpegFrame()
{
if (streamClients_.isEmpty()) {
streamTimer_.stop();
return;
}
// Render the spectrogram to JPEG
QImage img = spectrogram_->renderToImage();
QByteArray jpegData;
QBuffer buf(&jpegData);
buf.open(QIODevice::WriteOnly);
img.save(&buf, "JPEG", 80); // quality 80 — good balance of size vs clarity
// Build the multipart frame
QByteArray frame;
frame += "--";
frame += MJPEG_BOUNDARY;
frame += "\r\n";
frame += "Content-Type: image/jpeg\r\n";
frame += QString("Content-Length: %1\r\n").arg(jpegData.size()).toUtf8();
frame += "\r\n";
frame += jpegData;
frame += "\r\n";
// Push to all connected clients
QSet<QTcpSocket*> dead;
for (auto* client : streamClients_) {
if (client->state() != QAbstractSocket::ConnectedState) {
dead.insert(client);
continue;
}
client->write(frame);
client->flush();
}
for (auto* d : dead) {
streamClients_.remove(d);
d->deleteLater();
}
if (streamClients_.isEmpty()) {
streamTimer_.stop();
}
}
QString ApiServer::profileDir() const
{
return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/profiles";
}