-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
1657 lines (1428 loc) · 53.4 KB
/
Copy pathmain.cpp
File metadata and controls
1657 lines (1428 loc) · 53.4 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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// main.cpp - Main GUI application with custom names, pin/save, tray fix
#include <QAction>
#include <QApplication>
#include <QCheckBox>
#include <QCloseEvent>
#include <QComboBox>
#include <QCoreApplication>
#include <QDebug>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDir>
#include <QFile>
#include <QFormLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QIcon>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <QLineEdit>
#include <QMainWindow>
#include <QMap>
#include <QMenu>
#include <QMessageBox>
#include <QPixmap>
#include <QProcess>
#include <QPushButton>
#include <QRegularExpression>
#include <QSpinBox>
#include <QStandardPaths>
#include <QSystemTrayIcon>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
// ======================================================================
// Video Stream Configuration (with custom name)
// ======================================================================
struct VideoStreamConfig {
// Core
int width;
int height;
int bitrate;
QString host;
int port;
bool useVideoConvert;
QString customName; // user-provided stream name
// Encoder selection
QString encoder;
bool useHardware;
// x264 specific
QString speedPreset;
QString tune;
QString profile;
// Hardware encoder common
int qualityLevel;
QString rateControl;
QJsonObject toJson() const {
QJsonObject obj;
obj["width"] = width;
obj["height"] = height;
obj["bitrate"] = bitrate;
obj["host"] = host;
obj["port"] = port;
obj["useVideoConvert"] = useVideoConvert;
obj["customName"] = customName;
obj["encoder"] = encoder;
obj["speedPreset"] = speedPreset;
obj["tune"] = tune;
obj["profile"] = profile;
obj["qualityLevel"] = qualityLevel;
obj["rateControl"] = rateControl;
return obj;
}
static VideoStreamConfig fromJson(const QJsonObject &obj) {
VideoStreamConfig cfg;
cfg.width = obj["width"].toInt();
cfg.height = obj["height"].toInt();
cfg.bitrate = obj["bitrate"].toInt();
cfg.host = obj["host"].toString();
cfg.port = obj["port"].toInt();
cfg.useVideoConvert = obj["useVideoConvert"].toBool();
cfg.customName = obj["customName"].toString();
cfg.encoder = obj["encoder"].toString();
cfg.speedPreset = obj["speedPreset"].toString();
cfg.tune = obj["tune"].toString();
cfg.profile = obj["profile"].toString();
cfg.qualityLevel = obj["qualityLevel"].toInt();
cfg.rateControl = obj["rateControl"].toString();
return cfg;
}
};
// ======================================================================
// Audio Stream Configuration (with custom name + virtual sink)
// ======================================================================
struct AudioStreamConfig {
QString host;
int port;
QString codec;
int bitrate;
int channels;
int sampleRate;
QString opusApplication;
QString customName; // user-provided stream name
QString direction; // "outgoing" or "incoming"
QString sinkDevice; // PulseAudio sink name for incoming streams
int bufferSize; // bytes, 0 = default
int latencyTime; // ms, 0 = default
int bufferTime; // ms, 0 = default
bool virtualSink; // new: create a virtual sink
QString virtualSinkName; // new: name for the virtual sink
QJsonObject toJson() const {
QJsonObject obj;
obj["host"] = host;
obj["port"] = port;
obj["codec"] = codec;
obj["bitrate"] = bitrate;
obj["channels"] = channels;
obj["sampleRate"] = sampleRate;
obj["opusApplication"] = opusApplication;
obj["customName"] = customName;
obj["direction"] = direction;
obj["sinkDevice"] = sinkDevice;
obj["bufferSize"] = bufferSize;
obj["latencyTime"] = latencyTime;
obj["bufferTime"] = bufferTime;
obj["virtualSink"] = virtualSink;
obj["virtualSinkName"] = virtualSinkName;
return obj;
}
static AudioStreamConfig fromJson(const QJsonObject &obj) {
AudioStreamConfig cfg;
cfg.host = obj["host"].toString();
cfg.port = obj["port"].toInt();
cfg.codec = obj["codec"].toString();
cfg.bitrate = obj["bitrate"].toInt();
cfg.channels = obj["channels"].toInt();
cfg.sampleRate = obj["sampleRate"].toInt();
cfg.opusApplication = obj["opusApplication"].toString();
cfg.customName = obj["customName"].toString();
cfg.direction = obj["direction"].toString("outgoing");
cfg.sinkDevice = obj["sinkDevice"].toString();
cfg.bufferSize = obj["bufferSize"].toInt(0);
cfg.latencyTime = obj["latencyTime"].toInt(0);
cfg.bufferTime = obj["bufferTime"].toInt(0);
cfg.virtualSink = obj["virtualSink"].toBool(false);
cfg.virtualSinkName = obj["virtualSinkName"].toString();
return cfg;
}
static AudioStreamConfig defaultConfig() {
AudioStreamConfig cfg;
cfg.host = "192.168.178.91";
cfg.port = 5020;
cfg.codec = "opus";
cfg.bitrate = 128;
cfg.channels = 2;
cfg.sampleRate = 48000;
cfg.opusApplication = "audio";
cfg.direction = "outgoing";
cfg.sinkDevice = "";
cfg.bufferSize = 4096;
cfg.latencyTime = 100;
cfg.bufferTime = 2000;
cfg.virtualSink = false;
cfg.virtualSinkName = "";
return cfg;
}
};
// ======================================================================
// Stream Info (added nodeId and virtualSinkModule)
// ======================================================================
struct StreamInfo {
QString type;
QString name;
QProcess *workerProcess;
VideoStreamConfig videoConfig;
AudioStreamConfig audioConfig;
bool pinned; // is this stream saved for auto-start?
QString nodeId; // pipewire node id (video only)
int virtualSinkModule; // PulseAudio module index (audio only, -1 if none)
};
// ======================================================================
// Video Stream Configuration Dialog (with custom name field)
// ======================================================================
class VideoStreamDialog : public QDialog {
Q_OBJECT
public:
VideoStreamDialog(QWidget *parent = nullptr);
void setConfig(const VideoStreamConfig &config); // new
VideoStreamConfig getConfig() const;
private slots:
void onEncoderChanged(int index);
void onHardwareToggled(bool checked);
private:
// Core widgets
QSpinBox *spinWidth;
QSpinBox *spinHeight;
QSpinBox *spinBitrate;
QLineEdit *editHost;
QSpinBox *spinPort;
QCheckBox *checkVideoConvert;
QLineEdit *editCustomName;
// Encoder selection
QComboBox *comboEncoder;
QCheckBox *checkHardware;
// Software x264 widgets
QComboBox *comboSpeedPreset;
QComboBox *comboTune;
QComboBox *comboProfile;
QWidget *swX264Widget;
// Hardware encoder widgets
QSpinBox *spinQuality;
QComboBox *comboRateControl;
QWidget *hwWidget;
QVBoxLayout *mainLayout;
QFormLayout *formLayout;
};
VideoStreamDialog::VideoStreamDialog(QWidget *parent) : QDialog(parent) {
setWindowTitle("🎥 Video Stream Configuration");
setMinimumWidth(550);
mainLayout = new QVBoxLayout(this);
formLayout = new QFormLayout();
// ---- Custom stream name ----
editCustomName = new QLineEdit();
editCustomName->setPlaceholderText(
"Leave empty for auto-name (e.g. qt-caster-video-1)");
formLayout->addRow("📛 Stream Name:", editCustomName);
// ---- Resolution ----
QHBoxLayout *resLayout = new QHBoxLayout();
spinWidth = new QSpinBox();
spinWidth->setRange(320, 7680);
spinWidth->setValue(1920);
spinWidth->setSuffix(" px");
spinHeight = new QSpinBox();
spinHeight->setRange(240, 4320);
spinHeight->setValue(1080);
spinHeight->setSuffix(" px");
resLayout->addWidget(new QLabel("📏 Width:"));
resLayout->addWidget(spinWidth);
resLayout->addWidget(new QLabel("📏 Height:"));
resLayout->addWidget(spinHeight);
formLayout->addRow("Resolution:", resLayout);
// ---- Bitrate ----
spinBitrate = new QSpinBox();
spinBitrate->setRange(500, 100000);
spinBitrate->setValue(30000);
spinBitrate->setSuffix(" kbps");
formLayout->addRow("⚡ Bitrate:", spinBitrate);
// ---- Network ----
editHost = new QLineEdit("192.168.178.91");
formLayout->addRow("🌐 Destination Host:", editHost);
spinPort = new QSpinBox();
spinPort->setRange(1024, 65535);
spinPort->setValue(5010);
formLayout->addRow("🔌 Destination Port:", spinPort);
// ---- Video convert ----
checkVideoConvert = new QCheckBox("Use videoconvert");
checkVideoConvert->setChecked(true);
formLayout->addRow("🔄 Video Processing:", checkVideoConvert);
// ---- Hardware acceleration toggle ----
checkHardware = new QCheckBox("Use hardware acceleration (if available)");
checkHardware->setChecked(false);
connect(checkHardware, &QCheckBox::toggled, this,
&VideoStreamDialog::onHardwareToggled);
formLayout->addRow("⚙️ Acceleration:", checkHardware);
// ---- Encoder selection ----
comboEncoder = new QComboBox();
comboEncoder->addItem("Software (x264)", "x264enc");
comboEncoder->addItem("VAAPI H.264", "vaapih264enc");
comboEncoder->addItem("NVENC H.264", "nvh264enc");
comboEncoder->addItem("QSV H.264", "qsvh264enc");
connect(comboEncoder, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &VideoStreamDialog::onEncoderChanged);
formLayout->addRow("🎛 Encoder:", comboEncoder);
mainLayout->addLayout(formLayout);
// ---- Encoder-specific option panels ----
// Software x264 panel
swX264Widget = new QWidget();
QFormLayout *swLayout = new QFormLayout(swX264Widget);
comboSpeedPreset = new QComboBox();
comboSpeedPreset->addItems({"ultrafast", "superfast", "veryfast", "faster",
"fast", "medium", "slow", "slower", "veryslow"});
comboSpeedPreset->setCurrentText("ultrafast");
swLayout->addRow("⏩ Speed Preset:", comboSpeedPreset);
comboTune = new QComboBox();
comboTune->addItems({"zerolatency", "film", "animation", "grain",
"stillimage", "fastdecode"});
comboTune->setCurrentText("zerolatency");
swLayout->addRow("🎛 Tune:", comboTune);
comboProfile = new QComboBox();
comboProfile->addItems({"baseline", "main", "high"});
comboProfile->setCurrentText("high");
swLayout->addRow("📊 Profile:", comboProfile);
mainLayout->addWidget(swX264Widget);
// Hardware panel
hwWidget = new QWidget();
QFormLayout *hwLayout = new QFormLayout(hwWidget);
spinQuality = new QSpinBox();
spinQuality->setRange(0, 51);
spinQuality->setValue(20);
spinQuality->setSuffix(" (lower = better)");
hwLayout->addRow("🎚 Quality:", spinQuality);
comboRateControl = new QComboBox();
comboRateControl->addItem("CBR", "cbr");
comboRateControl->addItem("VBR", "vbr");
comboRateControl->addItem("CQP", "cqp");
comboRateControl->setCurrentText("cbr");
hwLayout->addRow("📈 Rate Control:", comboRateControl);
mainLayout->addWidget(hwWidget);
// ---- Button box ----
QDialogButtonBox *buttonBox =
new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
buttonBox->button(QDialogButtonBox::Ok)->setText("✅ Start");
buttonBox->button(QDialogButtonBox::Cancel)->setText("❌ Cancel");
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
mainLayout->addWidget(buttonBox);
// Initial state
onHardwareToggled(false);
onEncoderChanged(0);
}
void VideoStreamDialog::onHardwareToggled(bool checked) {
comboEncoder->setEnabled(checked);
if (!checked) {
comboEncoder->setCurrentIndex(0);
comboEncoder->setEnabled(false);
}
}
void VideoStreamDialog::onEncoderChanged(int index) {
QString encoder = comboEncoder->currentData().toString();
bool isSoftware = (encoder == "x264enc");
swX264Widget->setVisible(isSoftware);
hwWidget->setVisible(!isSoftware);
}
void VideoStreamDialog::setConfig(const VideoStreamConfig &cfg) {
editCustomName->setText(cfg.customName);
spinWidth->setValue(cfg.width);
spinHeight->setValue(cfg.height);
spinBitrate->setValue(cfg.bitrate);
editHost->setText(cfg.host);
spinPort->setValue(cfg.port);
checkVideoConvert->setChecked(cfg.useVideoConvert);
checkHardware->setChecked(cfg.useHardware);
// Find encoder index
int encoderIndex = comboEncoder->findData(cfg.encoder);
if (encoderIndex >= 0)
comboEncoder->setCurrentIndex(encoderIndex);
comboSpeedPreset->setCurrentText(cfg.speedPreset);
comboTune->setCurrentText(cfg.tune);
comboProfile->setCurrentText(cfg.profile);
spinQuality->setValue(cfg.qualityLevel);
int rcIndex = comboRateControl->findData(cfg.rateControl);
if (rcIndex >= 0)
comboRateControl->setCurrentIndex(rcIndex);
}
VideoStreamConfig VideoStreamDialog::getConfig() const {
VideoStreamConfig cfg;
cfg.customName = editCustomName->text().trimmed();
cfg.width = spinWidth->value();
cfg.height = spinHeight->value();
cfg.bitrate = spinBitrate->value();
cfg.host = editHost->text();
cfg.port = spinPort->value();
cfg.useVideoConvert = checkVideoConvert->isChecked();
cfg.encoder = comboEncoder->currentData().toString();
cfg.useHardware = checkHardware->isChecked();
cfg.speedPreset = comboSpeedPreset->currentText();
cfg.tune = comboTune->currentText();
cfg.profile = comboProfile->currentText();
cfg.qualityLevel = spinQuality->value();
cfg.rateControl = comboRateControl->currentData().toString();
return cfg;
}
// ======================================================================
// Audio Stream Configuration Dialog (with custom name field + virtual sink)
// ======================================================================
class AudioStreamDialog : public QDialog {
Q_OBJECT
public:
AudioStreamDialog(QWidget *parent = nullptr);
void setConfig(const AudioStreamConfig &config); // new
AudioStreamConfig getConfig() const;
private slots:
void onCodecChanged(int index);
void onDirectionChanged(int index);
void onVirtualSinkToggled(bool checked);
private:
QLineEdit *editCustomName;
QLineEdit *editHost;
QLabel *hostLabel;
QSpinBox *spinPort;
QComboBox *comboCodec;
QSpinBox *spinBitrate;
QSpinBox *spinChannels;
QComboBox *comboSampleRate; // fixed: capitalized S
QComboBox *comboOpusApplication;
QComboBox *comboDirection;
QLineEdit *editSinkDevice;
QSpinBox *spinBufferSize;
QSpinBox *spinLatencyTime;
QSpinBox *spinBufferTime;
QCheckBox *checkVirtualSink; // new
QLineEdit *editVirtualSinkName; // new
};
AudioStreamDialog::AudioStreamDialog(QWidget *parent) : QDialog(parent) {
setWindowTitle("🎤 Audio Stream Configuration");
setMinimumWidth(450);
QVBoxLayout *mainLayout = new QVBoxLayout(this);
QFormLayout *formLayout = new QFormLayout();
// ---- Advanced buffering options ----
QGroupBox *advancedGroup =
new QGroupBox("⚙️ Advanced Buffer Settings (0 = default)", this);
QFormLayout *advancedLayout = new QFormLayout(advancedGroup);
// ---- Custom stream name ----
editCustomName = new QLineEdit();
editCustomName->setPlaceholderText(
"Leave empty for auto-name (e.g. qt-caster-audio-1)");
formLayout->addRow("📛 Stream Name:", editCustomName);
// ---- Direction ----
comboDirection = new QComboBox();
comboDirection->addItem("📤 Outgoing (send microphone)", "outgoing");
comboDirection->addItem("📥 Incoming (receive & play)", "incoming");
connect(
comboDirection,
static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, &AudioStreamDialog::onDirectionChanged);
formLayout->addRow("🔄 Direction:", comboDirection);
// ---- Host / Listen Address ----
hostLabel = new QLabel("🌐 Destination Host:");
editHost = new QLineEdit();
editHost->setText("192.168.178.91");
formLayout->addRow(hostLabel, editHost);
// ---- Port ----
spinPort = new QSpinBox();
spinPort->setRange(1024, 65535);
spinPort->setValue(5020);
formLayout->addRow("🔌 Port:", spinPort);
// ---- Sink Device (only for incoming) ----
editSinkDevice = new QLineEdit();
editSinkDevice->setPlaceholderText(
"e.g. Virtual-Music (leave empty for default sink)");
editSinkDevice->setEnabled(false); // initially disabled
formLayout->addRow("🎧 Sink Device:", editSinkDevice);
// ---- Codec ----
comboCodec = new QComboBox();
comboCodec->addItem("🎵 Opus", "opus");
comboCodec->addItem("🎶 AAC", "aac");
formLayout->addRow("🎛 Codec:", comboCodec);
// ---- Bitrate ----
spinBitrate = new QSpinBox();
spinBitrate->setRange(16, 512);
spinBitrate->setValue(128);
spinBitrate->setSuffix(" kbps");
formLayout->addRow("⚡ Bitrate:", spinBitrate);
// ---- Channels ----
spinChannels = new QSpinBox();
spinChannels->setRange(1, 8);
spinChannels->setValue(2);
spinChannels->setSuffix(" ch");
formLayout->addRow("🎧 Channels:", spinChannels);
// ---- Sample Rate ----
comboSampleRate = new QComboBox();
comboSampleRate->addItem("48 kHz", 48000);
comboSampleRate->addItem("44.1 kHz", 44100);
comboSampleRate->addItem("96 kHz", 96000);
comboSampleRate->setCurrentIndex(0);
formLayout->addRow("⏱ Sample Rate:", comboSampleRate);
// ---- Opus Application (only for Opus) ----
comboOpusApplication = new QComboBox();
comboOpusApplication->addItem("🎼 Audio", "audio");
comboOpusApplication->addItem("🎤 VoIP", "voip");
comboOpusApplication->addItem("⚡ Low Delay", "lowdelay");
formLayout->addRow("📱 Application:", comboOpusApplication);
// ---- Virtual sink (new) ----
checkVirtualSink = new QCheckBox("Create virtual sink (for routing audio)");
checkVirtualSink->setChecked(false);
connect(checkVirtualSink, &QCheckBox::toggled, this,
&AudioStreamDialog::onVirtualSinkToggled);
formLayout->addRow("🎚️ Virtual Sink:", checkVirtualSink);
editVirtualSinkName = new QLineEdit();
editVirtualSinkName->setPlaceholderText(
"Leave empty for auto-generated name");
editVirtualSinkName->setEnabled(false);
formLayout->addRow("📛 Sink Name:", editVirtualSinkName);
// Advanced settings
spinBufferSize = new QSpinBox();
spinBufferSize->setRange(0, 1048576);
spinBufferSize->setValue(4096);
spinBufferSize->setSuffix(" bytes");
spinBufferSize->setSpecialValueText("Auto");
advancedLayout->addRow("📦 Buffer Size:", spinBufferSize);
spinLatencyTime = new QSpinBox();
spinLatencyTime->setRange(0, 10000);
spinLatencyTime->setValue(100);
spinLatencyTime->setSuffix(" ms");
spinLatencyTime->setSpecialValueText("Auto");
advancedLayout->addRow("⏱️ Latency Time:", spinLatencyTime);
spinBufferTime = new QSpinBox();
spinBufferTime->setRange(0, 10000);
spinBufferTime->setValue(2000);
spinBufferTime->setSuffix(" ms");
spinBufferTime->setSpecialValueText("Auto");
advancedLayout->addRow("⏱️ Buffer Time:", spinBufferTime);
connect(comboCodec, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
&AudioStreamDialog::onCodecChanged);
onCodecChanged(0);
mainLayout->addLayout(formLayout);
mainLayout->addWidget(advancedGroup);
QDialogButtonBox *buttonBox =
new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
buttonBox->button(QDialogButtonBox::Ok)->setText("✅ Start");
buttonBox->button(QDialogButtonBox::Cancel)->setText("❌ Cancel");
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
mainLayout->addWidget(buttonBox);
}
void AudioStreamDialog::onDirectionChanged(int index) {
bool incoming = (comboDirection->itemData(index).toString() == "incoming");
if (incoming) {
hostLabel->setText("🌐 Listen Address:");
editHost->setText("0.0.0.0");
editSinkDevice->setEnabled(true);
} else {
hostLabel->setText("🌐 Destination Host:");
editHost->setText("192.168.178.91");
editSinkDevice->setEnabled(false);
}
}
void AudioStreamDialog::onCodecChanged(int index) {
QString codec = comboCodec->itemData(index).toString();
comboOpusApplication->setEnabled(codec == "opus");
if (codec == "opus") {
spinBitrate->setRange(16, 512);
spinBitrate->setValue(128);
} else {
spinBitrate->setRange(32, 512);
spinBitrate->setValue(192);
}
}
void AudioStreamDialog::onVirtualSinkToggled(bool checked) {
editVirtualSinkName->setEnabled(checked);
if (!checked)
editVirtualSinkName->clear();
}
void AudioStreamDialog::setConfig(const AudioStreamConfig &cfg) {
editCustomName->setText(cfg.customName);
editHost->setText(cfg.host);
spinPort->setValue(cfg.port);
int codecIndex = comboCodec->findData(cfg.codec);
if (codecIndex >= 0)
comboCodec->setCurrentIndex(codecIndex);
spinBitrate->setValue(cfg.bitrate);
spinChannels->setValue(cfg.channels);
int srIndex = comboSampleRate->findData(cfg.sampleRate);
if (srIndex >= 0)
comboSampleRate->setCurrentIndex(srIndex);
int appIndex = comboOpusApplication->findData(cfg.opusApplication);
if (appIndex >= 0)
comboOpusApplication->setCurrentIndex(appIndex);
int dirIndex = comboDirection->findData(cfg.direction);
if (dirIndex >= 0)
comboDirection->setCurrentIndex(dirIndex);
editSinkDevice->setText(cfg.sinkDevice);
spinBufferSize->setValue(cfg.bufferSize);
spinLatencyTime->setValue(cfg.latencyTime);
spinBufferTime->setValue(cfg.bufferTime);
checkVirtualSink->setChecked(cfg.virtualSink);
editVirtualSinkName->setText(cfg.virtualSinkName);
onVirtualSinkToggled(cfg.virtualSink);
}
AudioStreamConfig AudioStreamDialog::getConfig() const {
AudioStreamConfig config;
config.customName = editCustomName->text().trimmed();
config.host = editHost->text();
config.port = spinPort->value();
config.codec = comboCodec->currentData().toString();
config.bitrate = spinBitrate->value();
config.channels = spinChannels->value();
config.sampleRate = comboSampleRate->currentData().toInt();
config.opusApplication = comboOpusApplication->currentData().toString();
config.direction = comboDirection->currentData().toString();
config.sinkDevice = editSinkDevice->text().trimmed();
config.bufferSize = spinBufferSize->value();
config.latencyTime = spinLatencyTime->value();
config.bufferTime = spinBufferTime->value();
config.virtualSink = checkVirtualSink->isChecked();
config.virtualSinkName = editVirtualSinkName->text().trimmed();
return config;
}
// ======================================================================
// StreamManager - Main Window
// ======================================================================
class StreamManager : public QMainWindow {
Q_OBJECT
public:
static StreamManager *instance; // for signal handler
static void signalHandler(int sig); // static signal handler
StreamManager(QWidget *parent = nullptr);
~StreamManager();
protected:
void closeEvent(QCloseEvent *event) override;
private slots:
void createVideoStream();
void createAudioStream();
void onStreamDoubleClicked(int row, int column);
void onTrayIconActivated(QSystemTrayIcon::ActivationReason reason);
void minimizeToTray();
void quitApplication();
void onWorkerOutput();
void onWorkerFinished(int exitCode, QProcess::ExitStatus exitStatus);
void updateStreamTable();
void stopStreamFromTray();
void updateTrayTooltip();
void onPinToggled(int row, int column);
void onTrayMenuAboutToShow();
void cleanupAndQuit();
// New context menu actions
void showContextMenu(const QPoint &pos);
void editStream();
void visualizeVideoStream();
private:
void setupSystemTray();
void setupTable();
void loadSavedStreams();
void saveStreamConfig(const StreamInfo &stream);
void removeSavedStream(const QString &name);
QString getConfigFilePath() const;
void terminateAllStreams();
void stopAndRemoveStream(int row);
QPushButton *btnCreateVideo;
QPushButton *btnCreateAudio;
QPushButton *btnMinimize;
QPushButton *btnQuit;
QTableWidget *streamTable;
QList<StreamInfo> activeStreams;
int videoStreamCounter;
int audioStreamCounter;
QSystemTrayIcon *trayIcon;
QMenu *trayMenu;
QTimer *statusTimer;
QMap<QAction *, int> trayStreamActions;
bool m_isQuitting;
int m_contextMenuRow; // added
};
// Static member definition
StreamManager *StreamManager::instance = nullptr;
StreamManager::StreamManager(QWidget *parent)
: QMainWindow(parent), videoStreamCounter(0), audioStreamCounter(0),
trayIcon(nullptr), trayMenu(nullptr), statusTimer(nullptr),
m_isQuitting(false), m_contextMenuRow(-1) {
instance = this;
setWindowTitle("🎬 Qt-Caster Stream Manager");
resize(950, 600);
QWidget *centralWidget = new QWidget(this);
setCentralWidget(centralWidget);
QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
QHBoxLayout *buttonLayout = new QHBoxLayout();
btnCreateVideo = new QPushButton("🎥 Create Video Stream", this);
btnCreateAudio = new QPushButton("🎤 Create Audio Stream", this);
buttonLayout->addWidget(btnCreateVideo);
buttonLayout->addWidget(btnCreateAudio);
streamTable = new QTableWidget(this);
setupTable();
QHBoxLayout *bottomButtonLayout = new QHBoxLayout();
btnMinimize = new QPushButton("⤵ Minimize to Tray", this);
btnQuit = new QPushButton("⏹ Quit Application", this);
bottomButtonLayout->addWidget(btnMinimize);
bottomButtonLayout->addWidget(btnQuit);
mainLayout->addLayout(buttonLayout);
mainLayout->addWidget(streamTable);
mainLayout->addLayout(bottomButtonLayout);
connect(btnCreateVideo, &QPushButton::clicked, this,
&StreamManager::createVideoStream);
connect(btnCreateAudio, &QPushButton::clicked, this,
&StreamManager::createAudioStream);
connect(btnMinimize, &QPushButton::clicked, this,
&StreamManager::minimizeToTray);
connect(btnQuit, &QPushButton::clicked, this,
&StreamManager::quitApplication);
connect(streamTable, &QTableWidget::cellDoubleClicked, this,
&StreamManager::onStreamDoubleClicked);
connect(streamTable, &QTableWidget::cellChanged, this,
&StreamManager::onPinToggled);
streamTable->setContextMenuPolicy(Qt::CustomContextMenu);
connect(streamTable, &QTableWidget::customContextMenuRequested, this,
&StreamManager::showContextMenu);
setupSystemTray();
statusTimer = new QTimer(this);
statusTimer->setInterval(1000);
connect(statusTimer, &QTimer::timeout, this,
&StreamManager::updateStreamTable);
statusTimer->start();
loadSavedStreams();
}
StreamManager::~StreamManager() {
if (instance == this)
instance = nullptr;
}
void StreamManager::setupTable() {
QStringList headers;
headers << "📛 Stream" << "🔄 Status" << "🌐 Destination" << "⚙️ Options"
<< "📊 Activity" << "📌 Pin";
streamTable->setColumnCount(headers.size());
streamTable->setHorizontalHeaderLabels(headers);
streamTable->verticalHeader()->setVisible(false);
streamTable->setAlternatingRowColors(false);
streamTable->setSelectionBehavior(QAbstractItemView::SelectRows);
streamTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
streamTable->horizontalHeader()->setSectionResizeMode(0,
QHeaderView::Stretch);
streamTable->horizontalHeader()->setSectionResizeMode(
1, QHeaderView::ResizeToContents);
streamTable->horizontalHeader()->setSectionResizeMode(
2, QHeaderView::ResizeToContents);
streamTable->horizontalHeader()->setSectionResizeMode(3,
QHeaderView::Stretch);
streamTable->horizontalHeader()->setSectionResizeMode(
4, QHeaderView::ResizeToContents);
streamTable->horizontalHeader()->setSectionResizeMode(
5, QHeaderView::ResizeToContents);
}
void StreamManager::setupSystemTray() {
if (!QSystemTrayIcon::isSystemTrayAvailable()) {
qWarning() << "⚠️ System tray not available – tray icon disabled.";
trayIcon = nullptr;
return;
}
QString iconPath = QCoreApplication::applicationDirPath() + "/icon.png";
QIcon icon;
if (QFile::exists(iconPath)) {
icon = QIcon(iconPath);
qDebug() << "✅ Loaded tray icon from:" << iconPath;
} else {
QPixmap pixmap(64, 64);
pixmap.fill(Qt::darkBlue);
icon = QIcon(pixmap);
qDebug() << "ℹ️ Using default tray icon (icon.png not found)";
}
trayIcon = new QSystemTrayIcon(icon, this);
connect(trayIcon, &QSystemTrayIcon::activated, this,
&StreamManager::onTrayIconActivated);
trayMenu = new QMenu(this);
trayIcon->setContextMenu(trayMenu);
connect(trayMenu, &QMenu::aboutToShow, this,
&StreamManager::onTrayMenuAboutToShow);
trayIcon->show();
updateTrayTooltip();
}
void StreamManager::onTrayMenuAboutToShow() {
if (!trayMenu)
return;
trayMenu->clear();
trayStreamActions.clear();
QAction *showAction = trayMenu->addAction("🪟 Show Window");
connect(showAction, &QAction::triggered, this, &QWidget::show);
trayMenu->addSeparator();
QAction *videoAction = trayMenu->addAction("🎥 Create Video Stream");
QAction *audioAction = trayMenu->addAction("🎤 Create Audio Stream");
connect(videoAction, &QAction::triggered, this,
&StreamManager::createVideoStream);
connect(audioAction, &QAction::triggered, this,
&StreamManager::createAudioStream);
trayMenu->addSeparator();
if (!activeStreams.isEmpty()) {
QMenu *streamsMenu = trayMenu->addMenu("📡 Active Streams");
for (int i = 0; i < activeStreams.size(); ++i) {
const StreamInfo &stream = activeStreams[i];
bool isRunning = stream.workerProcess &&
stream.workerProcess->state() == QProcess::Running;
QString statusIcon = isRunning ? "🟢" : "🔴";
QString text = QString("%1 %2").arg(statusIcon).arg(stream.name);
QAction *streamAction = streamsMenu->addAction(text);
streamAction->setData(i);
connect(streamAction, &QAction::triggered, this,
&StreamManager::stopStreamFromTray);
trayStreamActions[streamAction] = i;
}
}
trayMenu->addSeparator();
QAction *quitAction = trayMenu->addAction("⏹ Quit");
connect(quitAction, &QAction::triggered, this,
&StreamManager::quitApplication);
}
void StreamManager::stopStreamFromTray() {
QAction *action = qobject_cast<QAction *>(sender());
if (!action)
return;
int index = action->data().toInt();
if (index < 0 || index >= activeStreams.size())
return;
stopAndRemoveStream(index);
}
void StreamManager::updateTrayTooltip() {
if (!trayIcon)
return;
QString tooltip = "🎬 Qt-Caster Stream Manager\n";
if (activeStreams.isEmpty()) {
tooltip += "📡 No active streams";
} else {
tooltip += "━━━━━━━━━━━━━━━━━━━━\n";
for (const StreamInfo &stream : activeStreams) {
bool isRunning = stream.workerProcess &&
stream.workerProcess->state() == QProcess::Running;
QString statusIcon = isRunning ? "🟢" : "🔴";
tooltip += QString("%1 %2\n").arg(statusIcon).arg(stream.name);
}
}
trayIcon->setToolTip(tooltip);
}
void StreamManager::closeEvent(QCloseEvent *event) {
if (m_isQuitting) {
event->accept();
return;
}
event->ignore();
hide();
if (trayIcon) {
trayIcon->showMessage(
"🎬 Qt-Caster",
"Application minimized to tray. Right-click the tray icon for options.",
QSystemTrayIcon::Information, 2000);
}
}
void StreamManager::onTrayIconActivated(
QSystemTrayIcon::ActivationReason reason) {
if (reason == QSystemTrayIcon::Trigger ||
reason == QSystemTrayIcon::DoubleClick) {
show();
raise();
activateWindow();
}
}
void StreamManager::minimizeToTray() {
hide();
if (trayIcon) {
trayIcon->showMessage("🎬 Qt-Caster", "Application minimized to tray.",
QSystemTrayIcon::Information, 2000);
}
}
// ----------------------------------------------------------------------
// Common cleanup logic
// ----------------------------------------------------------------------
void StreamManager::terminateAllStreams() {
qDebug() << "🧹 Terminating all active streams...";
// Step 1: Collect all worker processes into a separate list
QList<QProcess *> processes;
for (const StreamInfo &stream : activeStreams) {
if (stream.workerProcess)
processes.append(stream.workerProcess);
}
// Step 2: Terminate each process (no reliance on activeStreams)
for (QProcess *proc : processes) {
if (proc->state() == QProcess::Running) {
qDebug() << " Stopping process";
proc->terminate();
if (!proc->waitForFinished(2000)) {
proc->kill();
proc->waitForFinished(1000);
}
}
proc->deleteLater();
}
// Step 3: Clear the list and update UI
activeStreams.clear();
updateStreamTable();
updateTrayTooltip();
qDebug() << "✅ All streams terminated.";
}
void StreamManager::cleanupAndQuit() {
if (m_isQuitting)
return;
m_isQuitting = true;
qDebug() << "🛑 Starting graceful shutdown...";
if (trayIcon) {