-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsendrecv.cpp
1364 lines (1107 loc) · 40 KB
/
sendrecv.cpp
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
#include "sendrecv.h"
#include "isendrecv.h"
/*
* Demo gstreamer app for negotiating and streaming a sendrecv webrtc stream
* with a browser JS app.
*
* gcc webrtc-sendrecv.c $(pkg-config --cflags --libs gstreamer-webrtc-1.0 gstreamer-sdp-1.0 libsoup-2.4 json-glib-1.0) -o webrtc-sendrecv
*
* Author: Nirbheek Chauhan <[email protected]>
*/
#include <gst/gst.h>
#include <gst/sdp/sdp.h>
#include <gst/rtp/rtp.h>
#define GST_USE_UNSTABLE_API
#include <gst/webrtc/webrtc.h>
#include <gst/video/videooverlay.h>
/* For signalling */
#include "signaling_connection.h"
#include <json-glib/json-glib.h>
#include "globals.h"
#include "makeguard.h"
#include <QSettings>
#include <QDateTime>
#include <QFile>
#include <QSlider>
#include <cstring>
#include <string>
#include <string_view>
#include <atomic>
#include <memory>
#include <mutex>
#define GST_CAT_DEFAULT webrtc_sendrecv_debug
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
static gchar*
get_string_from_json_object(JsonObject* object)
{
/* Make it the root node */
auto root = json_node_init_object(json_node_alloc(), object);
auto generator = json_generator_new();
json_generator_set_root(generator, root);
auto text = json_generator_to_data(generator, nullptr);
/* Release everything */
g_object_unref(generator);
json_node_free(root);
return text;
}
#ifdef _WIN64
#define DEFAULT_VIDEOSINK "d3d11videosink"
#else
#define DEFAULT_VIDEOSINK "d3dvideosink"
#endif
/* slightly convoluted way to find a working video sink that's not a bin,
* one could use autovideosink from gst-plugins-good instead
*/
static GstElement*
find_video_sink()
{
GstElement* sink;
if ((sink = gst_element_factory_make("xvimagesink", nullptr))) {
auto sret = gst_element_set_state(sink, GST_STATE_READY);
if (sret == GST_STATE_CHANGE_SUCCESS)
return sink;
gst_element_set_state(sink, GST_STATE_NULL);
gst_object_unref(sink);
}
if ((sink = gst_element_factory_make("ximagesink", nullptr))) {
auto sret = gst_element_set_state(sink, GST_STATE_READY);
if (sret == GST_STATE_CHANGE_SUCCESS)
return sink;
gst_element_set_state(sink, GST_STATE_NULL);
gst_object_unref(sink);
}
if (strcmp(DEFAULT_VIDEOSINK, "xvimagesink") == 0 ||
strcmp(DEFAULT_VIDEOSINK, "ximagesink") == 0)
return nullptr;
if ((sink = gst_element_factory_make(DEFAULT_VIDEOSINK, nullptr))) {
if (GST_IS_BIN(sink)) {
gst_object_unref(sink);
return nullptr;
}
auto sret = gst_element_set_state(sink, GST_STATE_READY);
if (sret == GST_STATE_CHANGE_SUCCESS)
return sink;
gst_element_set_state(sink, GST_STATE_NULL);
gst_object_unref(sink);
}
return nullptr;
}
static GstPadProbeReturn
static_rtp_packet_loss_probe(GstPad* opad, GstPadProbeInfo* p_info, gpointer /*p_data*/)
{
if (G_UNLIKELY((p_info->type & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM) == 0))
return GST_PAD_PROBE_OK;
GstEvent* event = gst_pad_probe_info_get_event(p_info);
switch (GST_EVENT_TYPE(event))
{
case GST_EVENT_GAP:
{
static GstClockTime prev_ts{};
GstClockTime ts, dur;
gst_event_parse_gap(event, &ts, &dur);
if (prev_ts != ts)
{
prev_ts = ts;
GstClockTime end = ts;
if (ts != GST_CLOCK_TIME_NONE && dur != GST_CLOCK_TIME_NONE)
end += dur;
g_print("%s:%s Gap TS: %" GST_TIME_FORMAT " dur %" GST_TIME_FORMAT
" (to %" GST_TIME_FORMAT ")\n", GST_DEBUG_PAD_NAME(opad),
GST_TIME_ARGS(ts), GST_TIME_ARGS(dur), GST_TIME_ARGS(end));
}
break;
}
default:
break;
}
return GST_PAD_PROBE_OK;
}
static void
disconnect(gpointer data,
GObject* where_the_object_was)
{
auto c = static_cast<QMetaObject::Connection*>(data);
auto ok = QObject::disconnect(*c);
g_assert_true(ok);
delete c;
}
class GObjHandle
{
public:
GObjHandle(gpointer p)
{
g_weak_ref_init(&m_ref, p);
}
~GObjHandle()
{
g_weak_ref_clear(&m_ref);
}
GObjHandle(const GObjHandle&) = delete;
GObjHandle operator =(const GObjHandle&) = delete;
auto get() const
{
auto ptr = g_weak_ref_get(&m_ref);
return MakeGuard(ptr, g_object_unref);
}
private:
mutable GWeakRef m_ref;
};
static auto prepare_next_file_name()
{
QDateTime now = QDateTime::currentDateTime();
const auto name = now.toString("yyMMddhhmmss");
auto path = QSettings().value(SETTING_SAVE_PATH).toString() + '/' + name + ".webm";
int i = 0;
while (QFile::exists(path))
{
++i;
path = QSettings().value(SETTING_SAVE_PATH).toString() + '/' + name + '(' + QString::number(i) + ").webm";
}
return QFile::encodeName(path);
}
static gchar* splitmuxsink_on_format_location_full(GstElement* splitmux,
guint fragment_id,
GstSample* first_sample,
gpointer user_data)
{
auto nextfilename = prepare_next_file_name();
g_print("New file name generated for recording as %s \n", nextfilename.constData());
return g_strdup_printf("%s", nextfilename.constData());
}
static gboolean
check_plugins()
{
const gchar* needed[] = { "opus", "vpx", "nice", "webrtc", "dtls", "srtp",
"rtpmanager", "videotestsrc", "audiotestsrc", nullptr
};
auto registry = gst_registry_get();
gboolean ret = TRUE;
for (guint i = 0; i < g_strv_length((gchar**)needed); i++) {
auto plugin = gst_registry_find_plugin(registry, needed[i]);
if (!plugin) {
gst_print("Required gstreamer plugin '%s' not found\n", needed[i]);
ret = FALSE;
continue;
}
gst_object_unref(plugin);
}
return ret;
}
////////////////////////////////////////////////////////////////////
enum AppState
{
APP_STATE_UNKNOWN = 0,
APP_STATE_ERROR = 1, /* generic error */
SERVER_CONNECTING = 1000,
SERVER_CONNECTION_ERROR,
SERVER_CONNECTED, /* Ready to register */
SERVER_REGISTERING = 2000,
SERVER_REGISTRATION_ERROR,
SERVER_REGISTERED, /* Ready to call a peer */
SERVER_CLOSED, /* server connection closed by us or the server */
PEER_CONNECTING = 3000,
PEER_CONNECTION_ERROR,
PEER_CONNECTED,
PEER_CALL_NEGOTIATING = 4000,
PEER_CALL_STARTED,
PEER_CALL_STOPPING,
PEER_CALL_STOPPED,
PEER_CALL_ERROR,
HANG_UP
};
const static gboolean remote_is_offerer = FALSE;
////////////////////////////////////////////////////////////////////
class SendRecv
{
GMainLoop *loop = nullptr;
GstElement *pipe1 = nullptr;
GstElement *webrtc1 = nullptr;
AppState app_state = APP_STATE_UNKNOWN;
guint webrtcbin_get_stats_id = 0;
std::vector<std::pair<int, std::string>> ice_candidates;
guintptr xwinid{};
ISendRecv* p_sendrecv = nullptr;
std::unique_ptr<ISignalingConnection> signaling_connection;
GThread* gthread = nullptr;
GstClockTime last_video_pts{};
std::mutex mtx;
public:
bool set_connected()
{
if (app_state < PEER_CONNECTED) {
app_state = PEER_CONNECTED;
return true;
}
return false;
}
gboolean cleanup_and_quit_loop (const gchar * msg, enum AppState state)
{
if (msg)
gst_printerr ("%s\n", msg);
if (state > 0)
app_state = state;
if (webrtcbin_get_stats_id)
g_source_remove(webrtcbin_get_stats_id);
webrtcbin_get_stats_id = 0;
if (signaling_connection)
signaling_connection->close();
if (loop) {
g_main_loop_quit (loop);
g_clear_pointer (&loop, g_main_loop_unref);
}
if (p_sendrecv)
{
p_sendrecv->onQuit();
p_sendrecv = nullptr;
}
/* To allow usage as a GSourceFunc */
return G_SOURCE_REMOVE;
}
void cleanup_and_quit_loop(const gchar* msg, bool is_error)
{
cleanup_and_quit_loop(msg, is_error ? PEER_CALL_ERROR : HANG_UP);
}
void handle_media_stream(GstPad* pad, GstElement* pipe, const char* convert_name,
GstElement* sink)
{
auto q = gst_element_factory_make("queue", nullptr);
g_assert_nonnull(q);
auto conv = gst_element_factory_make(convert_name, nullptr);
g_assert_nonnull(conv);
g_assert_nonnull(sink);
if (g_strcmp0(convert_name, "audioconvert") == 0) {
/* Might also need to resample, so add it just in case.
* Will be a no-op if it's not required. */
auto resample = gst_element_factory_make("audioresample", nullptr);
g_assert_nonnull(resample);
auto volume = gst_element_factory_make("volume", nullptr);
auto lam = [ptr = std::make_shared<GObjHandle>(volume)](int v) {
if (auto obj = ptr->get())
g_object_set(obj.get(), "volume", v / 100., NULL);
};
auto c = new QMetaObject::Connection(p_sendrecv->setAudioVolumeLambda(std::move(lam)));
g_object_weak_ref(G_OBJECT(volume), disconnect, c);
gst_bin_add_many(GST_BIN(pipe), q, conv, resample, volume, sink, NULL);
gst_element_sync_state_with_parent(q);
gst_element_sync_state_with_parent(conv);
gst_element_sync_state_with_parent(resample);
gst_element_sync_state_with_parent(volume);
gst_element_sync_state_with_parent(sink);
gst_element_link_many(q, conv, resample, volume, sink, NULL);
}
else {
// adding a probe for handling loss messages from rtpbin
gst_pad_add_probe(pad,
GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
static_rtp_packet_loss_probe,
nullptr,
nullptr);
gst_bin_add_many(GST_BIN(pipe), q, conv, sink, NULL);
gst_element_sync_state_with_parent(q);
gst_element_sync_state_with_parent(conv);
gst_element_sync_state_with_parent(sink);
gst_element_link_many(q, conv, sink, NULL);
}
auto qpad = gst_element_get_static_pad(q, "sink");
auto ret = gst_pad_link(pad, qpad);
g_assert_cmphex(ret, == , GST_PAD_LINK_OK);
}
static void
on_incoming_decodebin_stream (GstElement * decodebin, GstPad * pad,
gpointer user_data)
{
auto self = static_cast<SendRecv*>(user_data);
if (!gst_pad_has_current_caps (pad)) {
gst_printerr ("Pad '%s' has no caps, can't do anything, ignoring\n",
GST_PAD_NAME (pad));
return;
}
auto caps = gst_pad_get_current_caps (pad);
auto name = gst_structure_get_name (gst_caps_get_structure (caps, 0));
auto str = gst_caps_to_string(caps);
g_print("on_incoming_decodebin_stream pad caps: %s\n", str);
g_free(str);
if (g_str_has_prefix (name, "video")) {
auto sink = find_video_sink();
self->handle_media_stream (pad, self->pipe1, "videoconvert", sink);
gst_video_overlay_set_window_handle (GST_VIDEO_OVERLAY (sink), self->xwinid);
} else if (g_str_has_prefix (name, "audio")) {
self->handle_media_stream (pad, self->pipe1, "audioconvert", gst_element_factory_make("autoaudiosink", nullptr));
} else {
gst_printerr ("Unknown pad %s, ignoring", GST_PAD_NAME (pad));
}
}
GstElement* get_file_sink(GstBin* pipe)
{
std::unique_lock<std::mutex> lock(mtx);
const char file_sink_name[] = "file_sink";
if (auto result = gst_bin_get_by_name(pipe, file_sink_name))
return result;
const char muxerName[] = "webmmux";
const int sliceDurationSecs = getSliceDurationSecs();
if (sliceDurationSecs > 0)
{
auto splitmuxsink = gst_element_factory_make("splitmuxsink", file_sink_name);
auto s = gst_structure_new("properties",
"streamable", G_TYPE_BOOLEAN, TRUE,
nullptr);
g_object_set(G_OBJECT(splitmuxsink),
"async-finalize", TRUE,
"max-size-time", GST_SECOND * sliceDurationSecs,
"muxer-factory", muxerName,
"muxer-properties", s,
NULL);
g_signal_connect(splitmuxsink, "format-location-full",
G_CALLBACK(splitmuxsink_on_format_location_full), NULL);
auto ok = gst_bin_add(GST_BIN(pipe), splitmuxsink);
g_assert_true(ok);
ok = gst_element_sync_state_with_parent(splitmuxsink);
g_assert_true(ok);
return splitmuxsink;
}
auto muxer = gst_element_factory_make(muxerName, file_sink_name);
auto ok = gst_bin_add(GST_BIN(pipe), muxer);
g_assert_true(ok);
ok = gst_element_sync_state_with_parent(muxer);
g_assert_true(ok);
auto filesink = gst_element_factory_make("filesink", nullptr);
ok = gst_bin_add(GST_BIN(pipe), filesink);
g_assert_true(ok);
auto nextfilename = prepare_next_file_name();
g_object_set(G_OBJECT(filesink),
"location", nextfilename.constData(),
NULL);
ok = gst_element_sync_state_with_parent(filesink);
g_assert_true(ok);
ok = gst_element_link_many(
muxer,
filesink,
NULL);
g_assert_true(ok);
return muxer;
}
// https://stackoverflow.com/questions/29107370/gstreamer-timestamps-pts-are-not-monotonically-increasing-for-captured-frames
static GstPadProbeReturn
gst_pad_probe_callback(GstPad * pad,
GstPadProbeInfo * info,
gpointer user_data)
{
auto self = static_cast<SendRecv*>(user_data);
auto buffer = gst_pad_probe_info_get_buffer(info);
auto pts = buffer->pts;
if (pts <= self->last_video_pts)
{
g_print("Out-of-order pts: %lld; the last pts: %lld.\n", pts, self->last_video_pts);
buffer->pts = self->last_video_pts;
return GST_PAD_PROBE_OK;
}
self->last_video_pts = pts;
return GST_PAD_PROBE_OK;
}
static void
on_incoming_stream (GstElement * webrtc, GstPad * pad, gpointer user_data)
{
if (GST_PAD_DIRECTION (pad) != GST_PAD_SRC)
return;
auto self = static_cast<SendRecv*>(user_data);
auto decodebin = gst_element_factory_make ("decodebin", nullptr);
g_signal_connect (decodebin, "pad-added",
G_CALLBACK (on_incoming_decodebin_stream), self);
gst_bin_add (GST_BIN (self->pipe1), decodebin);
gst_element_sync_state_with_parent (decodebin);
auto caps = gst_pad_get_current_caps(pad);
auto str = gst_caps_to_string(caps);
g_print("on_incoming_stream pad caps: %s\n", str);
g_free(str);
int payload = 0;
if (QSettings().value(SETTING_DO_SAVE).toBool())
{
GstStructure *s = gst_caps_get_structure(caps, 0);
auto ok = gst_structure_get_int(s, "payload", &payload);
g_assert_true(ok);
}
if (payload == 96 || payload == 97)
{
auto tee = gst_element_factory_make("tee", nullptr);
gst_bin_add(GST_BIN(self->pipe1), tee);
gst_element_sync_state_with_parent(tee);
{
auto sinkpad = gst_element_get_static_pad(tee, "sink");
auto ret = gst_pad_link(pad, sinkpad);
g_assert_cmphex(ret, == , GST_PAD_LINK_OK);
gst_object_unref(sinkpad);
}
{
auto srcpad = gst_element_request_pad_simple(tee, "src_%u");
auto sinkpad = gst_element_get_static_pad(decodebin, "sink");
auto ret = gst_pad_link(srcpad, sinkpad);
g_assert_cmphex(ret, == , GST_PAD_LINK_OK);
gst_object_unref(srcpad);
gst_object_unref(sinkpad);
}
auto rtpvp8depay = gst_element_factory_make(
(payload == 96) ? "rtpvp8depay" : "rtpopusdepay", nullptr);
auto ok = gst_bin_add(GST_BIN(self->pipe1), rtpvp8depay);
g_assert_true(ok);
ok = gst_element_sync_state_with_parent(rtpvp8depay);
g_assert_true(ok);
auto queue = gst_element_factory_make("queue", nullptr);
ok = gst_bin_add(GST_BIN(self->pipe1), queue);
g_assert_true(ok);
ok = gst_element_sync_state_with_parent(queue);
g_assert_true(ok);
auto sink = self->get_file_sink(GST_BIN(self->pipe1));
if (payload == 96)
{
self->last_video_pts = {};
auto srcpad = gst_element_get_static_pad(rtpvp8depay, "src");
gst_pad_add_probe(srcpad, GST_PAD_PROBE_TYPE_BUFFER, gst_pad_probe_callback, self, nullptr);
ok = gst_element_link_many(tee,
rtpvp8depay,
queue,
NULL);
g_assert_true(ok);
}
else
{
auto opusdec = gst_element_factory_make("opusdec", nullptr);
ok = gst_bin_add(GST_BIN(self->pipe1), opusdec);
g_assert_true(ok);
ok = gst_element_sync_state_with_parent(opusdec);
g_assert_true(ok);
//audiorate
auto audiorate = gst_element_factory_make("audiorate", nullptr);
ok = gst_bin_add(GST_BIN(self->pipe1), audiorate);
g_assert_true(ok);
ok = gst_element_sync_state_with_parent(audiorate);
g_assert_true(ok);
//opusenc
auto opusenc = gst_element_factory_make("opusenc", nullptr);
ok = gst_bin_add(GST_BIN(self->pipe1), opusenc);
g_assert_true(ok);
ok = gst_element_sync_state_with_parent(opusenc);
g_assert_true(ok);
ok = gst_element_link_many(tee,
rtpvp8depay,
opusdec,
audiorate,
opusenc,
queue,
NULL);
g_assert_true(ok);
}
auto srcpad = gst_element_get_static_pad(queue, "src");
auto sinkpad = gst_element_request_pad_simple(sink,
(payload == 97) ? "audio_%u" : ((getSliceDurationSecs() > 0) ? "video" : "video_%u"));
auto ret = gst_pad_link(srcpad, sinkpad);
g_assert_cmphex(ret, == , GST_PAD_LINK_OK);
gst_object_unref(srcpad);
gst_object_unref(sinkpad);
}
else
{
auto sinkpad = gst_element_get_static_pad(decodebin, "sink");
gst_pad_link(pad, sinkpad);
gst_object_unref(sinkpad);
}
}
static void
send_ice_candidate_message(GstElement * webrtc G_GNUC_UNUSED, guint mlineindex,
gchar * candidate, gpointer user_data)
{
auto self = static_cast<SendRecv*>(user_data);
self->ice_candidates.emplace_back( mlineindex, candidate );
}
void send_candidates()
{
auto ar = json_array_new();
for (const auto& candidate : ice_candidates)
{
auto ice = json_object_new();
json_object_set_string_member(ice, "candidate", candidate.second.c_str());
json_object_set_int_member(ice, "sdpMLineIndex", candidate.first);
json_array_add_object_element(ar, ice);
}
ice_candidates.clear();
auto msg = json_object_new();
json_object_set_array_member(msg, "ice", ar);
auto text = get_string_from_json_object(msg);
json_object_unref(msg);
signaling_connection->send_text(text);
g_free(text);
}
void send_sdp_to_peer (GstWebRTCSessionDescription * desc)
{
if (app_state < PEER_CALL_NEGOTIATING) {
cleanup_and_quit_loop ("Can't send SDP to peer, not in call",
APP_STATE_ERROR);
return;
}
auto text = gst_sdp_message_as_text (desc->sdp);
auto sdp = json_object_new ();
if (desc->type == GST_WEBRTC_SDP_TYPE_OFFER) {
gst_print ("Sending offer:\n%s\n", text);
json_object_set_string_member (sdp, "type", "offer");
} else if (desc->type == GST_WEBRTC_SDP_TYPE_ANSWER) {
gst_print ("Sending answer:\n%s\n", text);
json_object_set_string_member (sdp, "type", "answer");
} else {
g_assert_not_reached ();
}
json_object_set_string_member (sdp, "sdp", text);
g_free (text);
auto msg = json_object_new ();
json_object_set_object_member (msg, "sdp", sdp);
text = get_string_from_json_object (msg);
json_object_unref (msg);
signaling_connection->send_text(text);
g_free (text);
}
/* Offer created by our pipeline, to be sent to the peer */
static void
on_offer_created (GstPromise * promise, gpointer user_data)
{
auto self = static_cast<SendRecv*>(user_data);
GstWebRTCSessionDescription *offer = nullptr;
g_assert_cmphex (self->app_state, ==, PEER_CALL_NEGOTIATING);
g_assert_cmphex (gst_promise_wait (promise), ==, GST_PROMISE_RESULT_REPLIED);
auto reply = gst_promise_get_reply (promise);
gst_structure_get (reply, "offer",
GST_TYPE_WEBRTC_SESSION_DESCRIPTION, &offer, NULL);
gst_promise_unref (promise);
promise = gst_promise_new ();
g_signal_emit_by_name (self->webrtc1, "set-local-description", offer, promise);
gst_promise_interrupt (promise);
gst_promise_unref (promise);
/* Send offer to peer */
self->send_sdp_to_peer (offer);
gst_webrtc_session_description_free (offer);
}
void on_negotiation_needed (GstElement * element, bool create_offer)
{
app_state = PEER_CALL_NEGOTIATING;
if (remote_is_offerer) {
signaling_connection->send_text("OFFER_REQUEST");
} else if (create_offer) {
GstPromise *promise =
gst_promise_new_with_change_func (on_offer_created, this, nullptr);
g_signal_emit_by_name (webrtc1, "create-offer", NULL, promise);
}
}
static void
on_negotiation_needed_true(GstElement* element, gpointer user_data)
{
auto self = static_cast<SendRecv*>(user_data);
self->on_negotiation_needed(element, true);
}
static void
on_negotiation_needed_false(GstElement* element, gpointer user_data)
{
auto self = static_cast<SendRecv*>(user_data);
self->on_negotiation_needed(element, false);
}
#define STUN_SERVER " stun-server=stun://stun.l.google.com:19302 "
#define RTP_CAPS_OPUS "application/x-rtp,media=audio,encoding-name=OPUS,payload="
#define RTP_CAPS_VP8 "application/x-rtp,media=video,encoding-name=VP8,payload="
static void
data_channel_on_error (GObject * dc, gpointer user_data)
{
auto self = static_cast<SendRecv*>(user_data);
self->cleanup_and_quit_loop ("Data channel error", APP_STATE_UNKNOWN);
}
static void
data_channel_on_close (GObject * dc, gpointer user_data)
{
auto self = static_cast<SendRecv*>(user_data);
self->cleanup_and_quit_loop ("Data channel closed", APP_STATE_UNKNOWN);
}
static void
data_channel_on_message_string (GObject * dc, gchar * str, gpointer user_data)
{
auto self = static_cast<SendRecv*>(user_data);
if (self->p_sendrecv)
self->p_sendrecv->handleRecv((uintptr_t)(void*) dc, str);
}
void connect_data_channel_signals (GObject * data_channel)
{
g_signal_connect (data_channel, "on-error",
G_CALLBACK (data_channel_on_error), this);
g_signal_connect (data_channel, "on-close",
G_CALLBACK (data_channel_on_close), this);
g_signal_connect (data_channel, "on-message-string",
G_CALLBACK (data_channel_on_message_string), this);
}
static void
on_data_channel (GstElement * webrtc, GObject * data_channel,
gpointer user_data)
{
auto self = static_cast<SendRecv*>(user_data);
self->connect_data_channel_signals (data_channel);
if (self->p_sendrecv)
{
auto lam = [ptr = std::make_shared<GObjHandle>(data_channel)](const QString& s) {
auto line = s.toStdString();
if (line.empty())
return;
if (auto obj = ptr->get())
g_signal_emit_by_name(obj.get(), "send-string", line.c_str());
};
auto c = new QMetaObject::Connection(self->p_sendrecv->setSendLambda(std::move(lam)));
g_object_weak_ref(G_OBJECT(data_channel), disconnect, c);
}
}
static void
on_ice_gathering_state_notify (GstElement * webrtcbin, GParamSpec * pspec,
gpointer user_data)
{
auto self = static_cast<SendRecv*>(user_data);
GstWebRTCICEGatheringState ice_gather_state;
const gchar *new_state = "unknown";
g_object_get (webrtcbin, "ice-gathering-state", &ice_gather_state, NULL);
switch (ice_gather_state) {
case GST_WEBRTC_ICE_GATHERING_STATE_NEW:
new_state = "new";
break;
case GST_WEBRTC_ICE_GATHERING_STATE_GATHERING:
new_state = "gathering";
break;
case GST_WEBRTC_ICE_GATHERING_STATE_COMPLETE:
new_state = "complete";
self->send_candidates();
break;
}
gst_print ("ICE gathering state changed to %s\n", new_state);
}
static void
on_ice_connection_state_notify(GstElement * webrtcbin, GParamSpec * pspec,
gpointer user_data)
{
GstWebRTCICEConnectionState ice_connection_state;
const gchar *new_state = "unknown";
g_object_get(webrtcbin, "ice-connection-state", &ice_connection_state, NULL);
switch (ice_connection_state) {
case GST_WEBRTC_ICE_CONNECTION_STATE_NEW:
new_state = "new";
break;
case GST_WEBRTC_ICE_CONNECTION_STATE_CHECKING:
new_state = "checking";
break;
case GST_WEBRTC_ICE_CONNECTION_STATE_CONNECTED:
new_state = "connected";
break;
case GST_WEBRTC_ICE_CONNECTION_STATE_COMPLETED:
new_state = "completed";
break;
case GST_WEBRTC_ICE_CONNECTION_STATE_FAILED:
new_state = "failed";
break;
case GST_WEBRTC_ICE_CONNECTION_STATE_DISCONNECTED:
new_state = "disconnected";
break;
case GST_WEBRTC_ICE_CONNECTION_STATE_CLOSED:
new_state = "closed";
break;
}
gst_print("ICE connection state changed to %s\n", new_state);
}
static gboolean
on_webrtcbin_stat (GQuark field_id, const GValue * value, gpointer unused)
{
if (GST_VALUE_HOLDS_STRUCTURE (value)) {
GST_DEBUG ("stat: \'%s\': %" GST_PTR_FORMAT, g_quark_to_string (field_id),
gst_value_get_structure (value));
} else {
GST_FIXME ("unknown field \'%s\' value type: \'%s\'",
g_quark_to_string (field_id), g_type_name (G_VALUE_TYPE (value)));
}
return TRUE;
}
static void
on_webrtcbin_get_stats (GstPromise * promise, void* user_data)
{
auto self = static_cast<SendRecv*>(user_data);
g_return_if_fail (gst_promise_wait (promise) == GST_PROMISE_RESULT_REPLIED);
auto stats = gst_promise_get_reply (promise);
gst_structure_foreach (stats, on_webrtcbin_stat, nullptr);
self->webrtcbin_get_stats_id = g_timeout_add (100, (GSourceFunc) webrtcbin_get_stats, self);
}
static gboolean
webrtcbin_get_stats (void* user_data)
{
auto self = static_cast<SendRecv*>(user_data);
GstPromise *promise =
gst_promise_new_with_change_func (
(GstPromiseChangeFunc) on_webrtcbin_get_stats, self, nullptr);
GST_TRACE ("emitting get-stats on %" GST_PTR_FORMAT, self->webrtc1);
g_signal_emit_by_name (self->webrtc1, "get-stats", NULL, promise);
gst_promise_unref (promise);
return G_SOURCE_REMOVE;
}
static void
on_new_transceiver(GstElement * webrtc, GstWebRTCRTPTransceiver * trans)
{
/* If we expected more than one transceiver, we would take a look at
* trans->mline, and compare it with webrtcbin's local description */
g_object_set(trans, "fec-type", GST_WEBRTC_FEC_TYPE_ULP_RED, "do-nack", TRUE, NULL);
}
static gboolean bus_call(GstBus * /*bus*/, GstMessage *msg, void *user_data)
{
auto self = static_cast<SendRecv*>(user_data);
switch (GST_MESSAGE_TYPE(msg))
{
case GST_MESSAGE_ERROR:
{
GError *err;
gchar *debug;
gst_message_parse_error(msg, &err, &debug);
g_print("GOT ERROR %s\n", err->message);
g_error_free(err);
g_free(debug);
if (auto srcName = GST_MESSAGE_SRC_NAME(msg))
{
g_print("ERROR SOURCE %s\n", srcName);
// could get and handle source: GST_MESSAGE_SRC(msg);
}
break;
}
case GST_MESSAGE_LATENCY:
{
// when pipeline latency is changed, this msg is posted on the bus. we then have
// to explicitly tell the pipeline to recalculate its latency
if (self->pipe1 && !gst_bin_recalculate_latency(GST_BIN(self->pipe1)))
g_print("Could not reconfigure latency.\n");
else
g_print("Reconfigured latency.\n");
break;
}
default:
break;
}
return TRUE;
}
#define RTP_TWCC_URI "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"
gboolean
start_pipeline (gboolean create_offer)
{
GstStateChangeReturn ret;
GError *error = nullptr;
std::string turnServer;
if (QSettings().value(SETTING_USE_TURN).toBool())
{
turnServer = QSettings().value(SETTING_TURN).toString().trimmed().toStdString();
if (!turnServer.empty())
{
turnServer = " turn-server=turn://" + turnServer + ' ';
}
}
const auto pipeline_description = "webrtcbin bundle-policy=max-bundle name=sendrecv "
STUN_SERVER + turnServer
+ QSettings().value(SETTING_VIDEO_LAUNCH_LINE, VIDEO_LAUNCH_LINE_DEFAULT).toString().toStdString() +
" ! videoconvert ! queue ! "
// https://developer.ridgerun.com/wiki/index.php/GstKinesisWebRTC/Getting_Started/C_Example_Application
"vp8enc error-resilient=partitions keyframe-max-dist=10 deadline=1 ! "
// picture-id-mode=15-bit seems to make TWCC stats behave better
"rtpvp8pay name=videopay picture-id-mode=15-bit ! "
"queue ! " RTP_CAPS_VP8 "96 ! sendrecv. "
+ QSettings().value(SETTING_AUDIO_LAUNCH_LINE, AUDIO_LAUNCH_LINE_DEFAULT).toString().toStdString() +
" ! audioconvert ! audioresample ! queue ! opusenc ! rtpopuspay name=audiopay ! "
"queue ! " RTP_CAPS_OPUS "97 ! sendrecv. ";
pipe1 = gst_parse_launch (pipeline_description.c_str(), &error);
if (error) {