-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmoqt_session.cpp
More file actions
1831 lines (1667 loc) · 80.7 KB
/
Copy pathmoqt_session.cpp
File metadata and controls
1831 lines (1667 loc) · 80.7 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
#include "openmoq/publisher/transport/moqt_session.h"
#include "openmoq/publisher/transport/moqt_control_messages.h"
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <thread>
#include <vector>
namespace openmoq::publisher::transport {
namespace {
bool trace_enabled() {
static const bool enabled = std::getenv("OPENMOQ_PICOQUIC_TRACE") != nullptr;
return enabled;
}
bool is_idle_subscribe_exit(std::string_view message) {
return message == "timed out waiting for stream data" ||
message == "no queued read for stream" ||
message == "webtransport connection closed";
}
std::string hex_dump(std::span<const std::uint8_t> bytes);
TransportStatus try_read_wt_session_stream(PublisherTransport& transport,
bool& saw_bytes,
bool& fin) {
std::vector<std::uint8_t> session_chunk;
bool session_fin = false;
const TransportStatus session_status =
transport.read_stream(0, session_chunk, session_fin, std::chrono::milliseconds(0));
if (!session_status.ok) {
return session_status;
}
saw_bytes = !session_chunk.empty();
if (trace_enabled()) {
std::cerr << "[moqt-session] setup fallback read stream=0 bytes=" << session_chunk.size()
<< " fin=" << (session_fin ? 1 : 0)
<< " bytes=[" << hex_dump(session_chunk) << "]" << std::endl;
}
fin = session_fin;
return TransportStatus::success();
}
const char* control_message_type_name(std::uint64_t message_type) {
switch (message_type) {
case 0x02:
return "SUBSCRIBE_UPDATE";
case 0x03:
return "SUBSCRIBE";
case 0x04:
return "SUBSCRIBE_OK";
case 0x05:
return "SUBSCRIBE_ERROR";
case 0x06:
return "PUBLISH_NAMESPACE";
case 0x07:
return "PUBLISH_NAMESPACE_OK";
case 0x08:
return "PUBLISH_NAMESPACE_ERROR";
case 0x09:
return "PUBLISH_NAMESPACE_DONE";
case 0x0b:
return "PUBLISH_DONE";
case 0x11:
return "SUBSCRIBE_NAMESPACE";
case 0x12:
return "SUBSCRIBE_NAMESPACE_OK";
case 0x15:
return "MAX_REQUEST_ID";
case 0x1d:
return "PUBLISH";
case 0x1e:
return "PUBLISH_OK";
case 0x1f:
return "PUBLISH_ERROR";
case 0x20:
return "CLIENT_SETUP";
case 0x21:
return "SERVER_SETUP";
case 0x0a:
return "UNSUBSCRIBE";
case 0x10:
return "GOAWAY";
case 0x13:
return "SUBSCRIBE_NAMESPACE_ERROR";
case 0x14:
return "SUBSCRIBE_DONE";
case 0x16:
return "FETCH";
case 0x17:
return "FETCH_OK";
case 0x18:
return "FETCH_CANCEL";
case 0x1a:
return "REQUESTS_BLOCKED";
case 0x1b:
return "UNSUBSCRIBE_NAMESPACE";
default:
return "UNKNOWN";
}
}
std::string hex_dump(std::span<const std::uint8_t> bytes) {
std::ostringstream out;
out << std::hex << std::setfill('0');
for (std::size_t index = 0; index < bytes.size(); ++index) {
if (index != 0) {
out << ' ';
}
out << std::setw(2) << static_cast<unsigned int>(bytes[index]);
}
return out.str();
}
void trace_control_message(std::span<const std::uint8_t> message_bytes, openmoq::publisher::DraftVersion draft) {
if (!trace_enabled()) {
return;
}
std::size_t offset = 0;
std::uint64_t message_type = 0;
if (!decode_varint(message_bytes, offset, message_type)) {
std::cerr << "[moqt-session] control message parse error bytes=[" << hex_dump(message_bytes) << "]"
<< std::endl;
return;
}
std::cerr << "[moqt-session] control message type=0x" << std::hex << message_type << std::dec << " "
<< control_message_type_name(message_type);
if (message_type == 0x07) {
PublishNamespaceOk message;
if (decode_request_ok(message_bytes, draft, message)) {
std::cerr << " request_id=" << message.request_id;
}
} else if (message_type == 0x08) {
PublishNamespaceError message;
if (decode_publish_namespace_error(message_bytes, message)) {
std::cerr << " request_id=" << message.request_id << " error_code=" << message.error_code
<< " reason=" << message.reason;
}
} else if (message_type == 0x05 && draft == openmoq::publisher::DraftVersion::kDraft16) {
RequestError message;
if (decode_request_error(message_bytes, draft, message)) {
std::cerr << " request_id=" << message.request_id << " error_code=" << message.error_code
<< " reason=" << message.reason;
}
} else if (message_type == 0x02) {
SubscribeUpdateMessage message;
if (decode_subscribe_update_message(message_bytes, message)) {
std::cerr << " request_id=" << message.request_id
<< " subscription_request_id=" << message.subscription_request_id
<< " start_group=" << message.start_group_id
<< " start_object=" << message.start_object_id
<< " end_group_plus_one=" << message.end_group_plus_one
<< " forward=" << static_cast<unsigned int>(message.forward);
}
} else if (message_type == 0x11) {
SubscribeNamespaceMessage message;
if (decode_subscribe_namespace_message(message_bytes, message)) {
std::cerr << " request_id=" << message.request_id;
if (!message.track_namespace_prefix.empty()) {
std::cerr << " prefix=" << message.track_namespace_prefix.front();
} else {
std::cerr << " prefix=<empty>";
}
}
} else if (message_type == 0x03) {
SubscribeMessage message;
if (decode_subscribe_message(message_bytes, message)) {
std::cerr << " request_id=" << message.request_id << " track=" << message.track_name
<< " forward=" << static_cast<unsigned int>(message.forward)
<< " filter_type=" << message.filter_type;
}
} else if (message_type == 0x1e) {
PublishOk message;
if (decode_publish_ok(message_bytes, draft, message)) {
std::cerr << " request_id=" << message.request_id
<< " forward=" << static_cast<unsigned int>(message.forward)
<< " subscriber_priority=" << static_cast<unsigned int>(message.subscriber_priority)
<< " group_order=" << static_cast<unsigned int>(message.group_order)
<< " filter_type=" << message.filter_type;
}
} else if (message_type == 0x1f) {
PublishError message;
if (decode_publish_error(message_bytes, draft, message)) {
std::cerr << " request_id=" << message.request_id << " error_code=" << message.error_code
<< " reason=" << message.reason;
}
}
std::cerr << " bytes=[" << hex_dump(message_bytes) << "]" << std::endl;
}
std::span<const std::uint8_t> object_payload(const openmoq::publisher::CmsfObject& object) {
if (!object.owned_payload.empty()) {
return object.owned_payload;
}
return {};
}
std::size_t object_payload_size(const openmoq::publisher::CmsfObject& object) {
if (!object.owned_payload.empty()) {
return object.owned_payload.size();
}
return object.payload.size;
}
void pace_until(std::chrono::steady_clock::time_point start_time,
std::uint64_t first_media_time_us,
const openmoq::publisher::CmsfObject& object,
bool paced) {
if (!paced || object.kind != openmoq::publisher::CmsfObjectKind::kMedia) {
return;
}
if (object.media_time_us < first_media_time_us) {
return;
}
std::this_thread::sleep_until(start_time + std::chrono::microseconds(object.media_time_us - first_media_time_us));
}
struct TrackLoopInfo {
std::size_t group_span = 0;
std::size_t first_loop_object_index = 0;
bool has_loopable_objects = false;
};
struct LoopState {
bool enabled = false;
std::uint64_t cycle_duration_us = 0;
std::map<std::string, TrackLoopInfo> tracks;
};
struct PublishedTrack {
std::string name;
std::uint64_t alias = 0;
std::size_t largest_group_id = 0;
std::size_t largest_object_id = 0;
bool content_exists = false;
};
struct ActiveSubscription {
SubscribeMessage subscribe;
PublishedTrack track;
std::uint64_t stream_count = 0;
std::size_t loop_cycle = 0;
std::size_t next_object_index = 0;
bool completed = false;
};
struct DormantPublishedTrack {
SubscribeMessage subscribe;
PublishedTrack track;
};
LoopState build_loop_state(const openmoq::publisher::PublishPlan& plan, bool loop_enabled) {
LoopState state;
state.enabled = loop_enabled;
if (!loop_enabled) {
return state;
}
for (std::size_t index = 0; index < plan.objects.size(); ++index) {
const auto& object = plan.objects[index];
auto& track = state.tracks[object.track_name];
track.group_span = std::max(track.group_span, object.group_id + 1);
if (object.kind == openmoq::publisher::CmsfObjectKind::kInitialization) {
continue;
}
if (!track.has_loopable_objects) {
track.first_loop_object_index = index;
track.has_loopable_objects = true;
}
if (object.kind == openmoq::publisher::CmsfObjectKind::kMedia) {
state.cycle_duration_us = std::max(state.cycle_duration_us, object.media_time_us + object.media_duration_us);
}
}
return state;
}
const TrackLoopInfo* find_track_loop_info(const LoopState& loop_state, std::string_view track_name) {
const auto it = loop_state.tracks.find(std::string(track_name));
return it == loop_state.tracks.end() ? nullptr : &it->second;
}
bool track_can_loop(const LoopState& loop_state, std::string_view track_name) {
const TrackLoopInfo* info = find_track_loop_info(loop_state, track_name);
return info != nullptr && info->has_loopable_objects;
}
openmoq::publisher::CmsfObject make_looped_object(const openmoq::publisher::CmsfObject& object,
const LoopState& loop_state,
std::size_t loop_cycle) {
if (!loop_state.enabled || loop_cycle == 0) {
return object;
}
const TrackLoopInfo* info = find_track_loop_info(loop_state, object.track_name);
if (info == nullptr || !info->has_loopable_objects || object.kind == openmoq::publisher::CmsfObjectKind::kInitialization) {
return object;
}
openmoq::publisher::CmsfObject adjusted = object;
adjusted.group_id += info->group_span * loop_cycle;
adjusted.media_time_us += loop_state.cycle_duration_us * loop_cycle;
return adjusted;
}
std::vector<PublishedTrack> build_published_tracks(const openmoq::publisher::PublishPlan& plan) {
std::map<std::string, PublishedTrack> tracks;
std::uint64_t next_alias = 0;
for (const auto& object : plan.objects) {
auto [it, inserted] = tracks.emplace(object.track_name,
PublishedTrack{
.name = object.track_name,
.alias = next_alias,
});
if (inserted) {
++next_alias;
}
it->second.content_exists = true;
if (object.group_id > it->second.largest_group_id ||
(object.group_id == it->second.largest_group_id && object.object_id > it->second.largest_object_id)) {
it->second.largest_group_id = object.group_id;
it->second.largest_object_id = object.object_id;
}
}
std::vector<PublishedTrack> ordered_tracks;
ordered_tracks.reserve(tracks.size());
for (auto& [name, track] : tracks) {
static_cast<void>(name);
ordered_tracks.push_back(track);
}
return ordered_tracks;
}
TransportStatus collect_control_acknowledgements(PublisherTransport& transport,
std::uint64_t control_stream_id,
openmoq::publisher::DraftVersion draft,
std::size_t expected_namespace_responses,
std::size_t expected_publish_responses,
std::vector<std::uint8_t>& pending_control_bytes,
std::map<std::uint64_t, PublishOk>* publish_ok_by_request_id = nullptr) {
std::vector<std::uint8_t> buffer = std::move(pending_control_bytes);
std::vector<std::uint8_t> deferred_messages;
pending_control_bytes.clear();
std::size_t namespace_responses = 0;
std::size_t publish_responses = 0;
bool fin = false;
while (namespace_responses < expected_namespace_responses || publish_responses < expected_publish_responses) {
std::size_t consumed = 0;
std::size_t message_size = 0;
while (next_control_message(std::span<const std::uint8_t>(buffer).subspan(consumed), message_size)) {
const std::vector<std::uint8_t> message_bytes(buffer.begin() + static_cast<std::ptrdiff_t>(consumed),
buffer.begin() + static_cast<std::ptrdiff_t>(consumed + message_size));
std::size_t offset = 0;
std::uint64_t message_type = 0;
if (!decode_varint(message_bytes, offset, message_type)) {
return TransportStatus::failure("failed to parse control response type");
}
trace_control_message(message_bytes, draft);
bool handled = false;
if (message_type == 0x07 && namespace_responses < expected_namespace_responses) {
PublishNamespaceOk message;
if (!decode_request_ok(message_bytes, draft, message)) {
return TransportStatus::failure(draft == openmoq::publisher::DraftVersion::kDraft16
? "received invalid REQUEST_OK"
: "received invalid PUBLISH_NAMESPACE_OK");
}
++namespace_responses;
handled = true;
} else if (namespace_responses < expected_namespace_responses &&
((draft == openmoq::publisher::DraftVersion::kDraft14 && message_type == 0x08) ||
(draft == openmoq::publisher::DraftVersion::kDraft16 && message_type == 0x05))) {
RequestError message;
if (!decode_request_error(message_bytes, draft, message)) {
return TransportStatus::failure(draft == openmoq::publisher::DraftVersion::kDraft16
? "received invalid REQUEST_ERROR"
: "received invalid PUBLISH_NAMESPACE_ERROR");
}
return TransportStatus::failure("peer rejected namespace publish: " + message.reason);
} else if (message_type == 0x1e && publish_responses < expected_publish_responses) {
PublishOk message;
if (!decode_publish_ok(message_bytes, draft, message)) {
return TransportStatus::failure("received invalid PUBLISH_OK");
}
if (publish_ok_by_request_id != nullptr) {
publish_ok_by_request_id->insert_or_assign(message.request_id, message);
}
++publish_responses;
handled = true;
} else if (message_type == 0x1f && publish_responses < expected_publish_responses) {
PublishError message;
if (!decode_publish_error(message_bytes, draft, message)) {
return TransportStatus::failure("received invalid PUBLISH_ERROR");
}
return TransportStatus::failure("peer rejected track publish: " + message.reason);
}
if (!handled) {
deferred_messages.insert(deferred_messages.end(), message_bytes.begin(), message_bytes.end());
}
consumed += message_size;
}
buffer.erase(buffer.begin(), buffer.begin() + static_cast<std::ptrdiff_t>(consumed));
if (namespace_responses >= expected_namespace_responses && publish_responses >= expected_publish_responses) {
break;
}
if (fin) {
break;
}
std::vector<std::uint8_t> chunk;
const TransportStatus status = transport.read_stream(control_stream_id, chunk, fin, std::chrono::seconds(2));
if (!status.ok) {
return status;
}
if (trace_enabled()) {
std::cerr << "[moqt-session] control chunk fin=" << (fin ? 1 : 0) << " bytes=[" << hex_dump(chunk)
<< "]" << std::endl;
}
buffer.insert(buffer.end(), chunk.begin(), chunk.end());
}
if (namespace_responses < expected_namespace_responses || publish_responses < expected_publish_responses) {
if (trace_enabled() && (!buffer.empty() || !deferred_messages.empty())) {
if (!deferred_messages.empty()) {
std::cerr << "[moqt-session] deferred control bytes=[" << hex_dump(deferred_messages) << "]" << std::endl;
}
if (!buffer.empty()) {
std::cerr << "[moqt-session] unparsed control bytes=[" << hex_dump(buffer) << "]" << std::endl;
}
}
return TransportStatus::failure("timed out waiting for publish acknowledgements");
}
deferred_messages.insert(deferred_messages.end(), buffer.begin(), buffer.end());
pending_control_bytes = std::move(deferred_messages);
return TransportStatus::success();
}
bool namespace_matches(std::span<const std::string> track_namespace, std::string_view expected) {
std::size_t component_count = 0;
std::size_t start = 0;
for (; start <= expected.size(); ++component_count) {
const std::size_t slash = expected.find('/', start);
const std::size_t end = slash == std::string_view::npos ? expected.size() : slash;
if (component_count >= track_namespace.size() || track_namespace[component_count] != expected.substr(start, end - start)) {
return false;
}
if (slash == std::string_view::npos) {
return component_count + 1 == track_namespace.size();
}
start = slash + 1;
}
return false;
}
bool namespace_prefix_matches(std::span<const std::string> track_namespace_prefix, std::string_view expected) {
if (track_namespace_prefix.empty()) {
return true;
}
std::size_t component_index = 0;
std::size_t start = 0;
while (start <= expected.size()) {
const std::size_t slash = expected.find('/', start);
const std::size_t end = slash == std::string_view::npos ? expected.size() : slash;
if (component_index >= track_namespace_prefix.size() ||
track_namespace_prefix[component_index] != expected.substr(start, end - start)) {
return false;
}
++component_index;
if (slash == std::string_view::npos) {
return component_index == track_namespace_prefix.size();
}
start = slash + 1;
}
return false;
}
std::vector<std::string> split_track_namespace_components(std::string_view ns) {
std::vector<std::string> components;
std::size_t start = 0;
while (start <= ns.size()) {
const std::size_t slash = ns.find('/', start);
const std::size_t end = slash == std::string_view::npos ? ns.size() : slash;
components.emplace_back(ns.substr(start, end - start));
if (slash == std::string_view::npos) {
break;
}
start = slash + 1;
}
return components;
}
bool object_matches_filter(const openmoq::publisher::CmsfObject& object, const SubscribeMessage& subscribe) {
switch (subscribe.filter_type) {
case 0x01:
case 0x02:
return true;
case 0x03:
return object.group_id > subscribe.start_group_id ||
(object.group_id == subscribe.start_group_id && object.object_id >= subscribe.start_object_id);
case 0x04:
return (object.group_id > subscribe.start_group_id ||
(object.group_id == subscribe.start_group_id && object.object_id >= subscribe.start_object_id)) &&
object.group_id <= subscribe.end_group_id;
default:
return true;
}
}
bool apply_subscribe_update(SubscribeMessage& subscribe, const SubscribeUpdateMessage& update) {
const bool start_increases = update.start_group_id > subscribe.start_group_id ||
(update.start_group_id == subscribe.start_group_id &&
update.start_object_id >= subscribe.start_object_id);
if (!start_increases) {
return false;
}
const std::size_t updated_end_group_id =
update.end_group_plus_one == 0 ? 0 : (update.end_group_plus_one - 1);
if (subscribe.filter_type == 0x04) {
if (update.end_group_plus_one == 0 || updated_end_group_id > subscribe.end_group_id) {
return false;
}
}
subscribe.start_group_id = update.start_group_id;
subscribe.start_object_id = update.start_object_id;
subscribe.subscriber_priority = update.subscriber_priority;
subscribe.forward = update.forward;
if (update.end_group_plus_one != 0) {
subscribe.filter_type = 0x04;
subscribe.end_group_id = updated_end_group_id;
} else if (subscribe.filter_type != 0x04) {
subscribe.end_group_id = 0;
}
return true;
}
bool decode_legacy_subscribe_update_message(std::span<const std::uint8_t> bytes,
const std::map<std::string, PublishedTrack>& tracks_by_name,
const std::map<std::uint64_t, SubscribeMessage>& pending_subscriptions,
const std::map<std::uint64_t, std::uint64_t>* request_id_by_track_alias,
SubscribeUpdateMessage& message) {
std::size_t offset = 0;
std::uint64_t message_type = 0;
if (!decode_varint(bytes, offset, message_type) || message_type != 0x02 || offset + 2 > bytes.size()) {
return false;
}
const std::size_t payload_length =
(static_cast<std::size_t>(bytes[offset]) << 8) | static_cast<std::size_t>(bytes[offset + 1]);
offset += 2;
if (offset + payload_length != bytes.size() || payload_length != 7) {
return false;
}
std::size_t payload_offset = offset;
std::uint64_t track_alias = 0;
std::uint64_t start_group_id = 0;
std::uint64_t start_object_id = 0;
if (!decode_varint(bytes, payload_offset, track_alias) ||
!decode_varint(bytes, payload_offset, start_group_id) ||
!decode_varint(bytes, payload_offset, start_object_id) ||
payload_offset + 4 != bytes.size()) {
return false;
}
const std::uint8_t subscriber_priority = bytes[payload_offset++];
const std::uint8_t group_order = bytes[payload_offset++];
const std::uint8_t parameter_or_filter = bytes[payload_offset++];
const std::uint8_t forward = bytes[payload_offset++];
if (group_order > 2 || forward > 1) {
return false;
}
static_cast<void>(parameter_or_filter);
for (const auto& [request_id, subscribe] : pending_subscriptions) {
const auto track_it = tracks_by_name.find(subscribe.track_name);
if (track_it == tracks_by_name.end() || track_it->second.alias != track_alias) {
continue;
}
message.request_id = 0;
message.subscription_request_id = request_id;
message.start_group_id = static_cast<std::size_t>(start_group_id);
message.start_object_id = static_cast<std::size_t>(start_object_id);
message.end_group_plus_one = subscribe.filter_type == 0x04 ? (subscribe.end_group_id + 1) : 0;
message.subscriber_priority = subscriber_priority;
message.forward = forward;
return true;
}
if (request_id_by_track_alias != nullptr) {
const auto request_id_it = request_id_by_track_alias->find(track_alias);
if (request_id_it != request_id_by_track_alias->end()) {
message.request_id = 0;
message.subscription_request_id = request_id_it->second;
message.start_group_id = static_cast<std::size_t>(start_group_id);
message.start_object_id = static_cast<std::size_t>(start_object_id);
message.end_group_plus_one = 0;
message.subscriber_priority = subscriber_priority;
message.forward = forward;
return true;
}
}
return false;
}
bool find_next_matching_object_index(const openmoq::publisher::PublishPlan& plan,
const SubscribeMessage& subscribe,
std::size_t start_index,
std::size_t& object_index) {
for (std::size_t index = start_index; index < plan.objects.size(); ++index) {
const auto& object = plan.objects[index];
if (object.track_name == subscribe.track_name && object_matches_filter(object, subscribe)) {
object_index = index;
return true;
}
}
return false;
}
bool advance_subscription_to_next_loop_object(const openmoq::publisher::PublishPlan& plan,
const LoopState& loop_state,
ActiveSubscription& active) {
if (!loop_state.enabled || !track_can_loop(loop_state, active.track.name)) {
return false;
}
const TrackLoopInfo* info = find_track_loop_info(loop_state, active.track.name);
if (info == nullptr || !info->has_loopable_objects) {
return false;
}
std::size_t next_object_index = 0;
if (!find_next_matching_object_index(plan, active.subscribe, info->first_loop_object_index, next_object_index)) {
return false;
}
++active.loop_cycle;
active.next_object_index = next_object_index;
active.completed = false;
return true;
}
bool is_final_object_in_group(const openmoq::publisher::PublishPlan& plan, std::size_t object_index) {
const auto& object = plan.objects.at(object_index);
for (std::size_t index = object_index + 1; index < plan.objects.size(); ++index) {
const auto& candidate = plan.objects[index];
if (candidate.track_name == object.track_name && candidate.group_id == object.group_id &&
candidate.object_id > object.object_id) {
return false;
}
}
return true;
}
TransportStatus finalize_subscription(PublisherTransport& transport,
std::uint64_t control_stream_id,
std::uint64_t request_id,
std::uint64_t stream_count,
std::set<std::uint64_t>& completed_request_ids) {
const TransportStatus write_status = transport.write_stream(
control_stream_id, encode_publish_done_message(request_id, stream_count), false);
if (!write_status.ok) {
return write_status;
}
completed_request_ids.insert(request_id);
return TransportStatus::success();
}
TransportStatus serve_subscriptions(PublisherTransport& transport,
std::uint64_t control_stream_id,
const openmoq::publisher::PublishPlan& plan,
const LoopState& loop_state,
const std::map<std::string, PublishedTrack>& tracks_by_name,
openmoq::publisher::DraftVersion draft,
std::string_view track_namespace,
bool paced,
std::chrono::milliseconds subscriber_timeout,
std::vector<std::uint8_t>& pending_control_bytes,
bool send_namespace_done = true,
std::map<std::uint64_t, DormantPublishedTrack>* dormant_published_tracks = nullptr,
const std::map<std::uint64_t, std::uint64_t>* request_id_by_track_alias = nullptr) {
std::vector<std::uint8_t> buffer = std::move(pending_control_bytes);
pending_control_bytes.clear();
std::set<std::uint64_t> completed_request_ids;
std::map<std::uint64_t, SubscribeMessage> pending_subscriptions;
std::deque<std::uint64_t> pending_subscription_order;
std::map<std::uint64_t, ActiveSubscription> active_subscriptions;
bool fin = false;
bool served_any_subscription = false;
std::uint64_t first_media_time_us = 0;
bool first_media_time_set = false;
const auto pacing_start = std::chrono::steady_clock::now();
NamespaceMessage namespace_message{
.draft = draft,
.track_namespace = std::string(track_namespace),
.request_id = 0,
};
while (true) {
std::size_t message_size = 0;
while (next_control_message(buffer, message_size)) {
const std::vector<std::uint8_t> message_bytes(buffer.begin(), buffer.begin() + message_size);
std::size_t offset = 0;
std::uint64_t message_type = 0;
if (!decode_varint(message_bytes, offset, message_type)) {
return TransportStatus::failure("failed to parse control request type");
}
trace_control_message(message_bytes, draft);
// Discard messages we don't act on (acknowledged responses,
// FETCH, GOAWAY, UNSUBSCRIBE, and any future message types) so they
// never block the control-stream buffer. Log them for visibility.
const bool is_handled_type =
message_type == 0x02 || // SUBSCRIBE_UPDATE
message_type == 0x11 || // SUBSCRIBE_NAMESPACE
message_type == 0x03; // SUBSCRIBE
if (!is_handled_type) {
std::cerr << "[moqt-session] skipping unhandled control message type=0x"
<< std::hex << message_type << std::dec
<< " (" << control_message_type_name(message_type) << ")"
<< " size=" << message_size << '\n';
buffer.erase(buffer.begin(), buffer.begin() + message_size);
continue;
}
if (message_type == 0x02) {
SubscribeUpdateMessage subscribe_update;
if (!decode_subscribe_update_message(message_bytes, subscribe_update) &&
!decode_legacy_subscribe_update_message(message_bytes,
tracks_by_name,
pending_subscriptions,
request_id_by_track_alias,
subscribe_update)) {
return TransportStatus::failure("received invalid SUBSCRIBE_UPDATE");
}
auto remapped_request_id = subscribe_update.subscription_request_id;
if (request_id_by_track_alias != nullptr && !pending_subscriptions.contains(remapped_request_id) &&
!active_subscriptions.contains(remapped_request_id) &&
(dormant_published_tracks == nullptr || !dormant_published_tracks->contains(remapped_request_id))) {
const auto alias_it = request_id_by_track_alias->find(remapped_request_id);
if (alias_it != request_id_by_track_alias->end()) {
remapped_request_id = alias_it->second;
subscribe_update.subscription_request_id = remapped_request_id;
}
}
if (completed_request_ids.contains(remapped_request_id)) {
return TransportStatus::failure("received invalid SUBSCRIBE_UPDATE state transition");
}
auto pending_it = pending_subscriptions.find(remapped_request_id);
if (pending_it != pending_subscriptions.end()) {
if (!apply_subscribe_update(pending_it->second, subscribe_update)) {
return TransportStatus::failure("received invalid SUBSCRIBE_UPDATE state transition");
}
buffer.erase(buffer.begin(), buffer.begin() + message_size);
continue;
}
auto active_it = active_subscriptions.find(remapped_request_id);
if (active_it != active_subscriptions.end()) {
if (!apply_subscribe_update(active_it->second.subscribe, subscribe_update)) {
return TransportStatus::failure("received invalid SUBSCRIBE_UPDATE state transition");
}
std::size_t next_object_index = 0;
if (find_next_matching_object_index(plan,
active_it->second.subscribe,
active_it->second.next_object_index,
next_object_index)) {
active_it->second.next_object_index = next_object_index;
active_it->second.completed = false;
} else {
active_it->second.next_object_index = plan.objects.size();
active_it->second.completed =
!advance_subscription_to_next_loop_object(plan, loop_state, active_it->second);
}
buffer.erase(buffer.begin(), buffer.begin() + message_size);
continue;
}
if (dormant_published_tracks != nullptr) {
auto dormant_it = dormant_published_tracks->find(remapped_request_id);
if (dormant_it != dormant_published_tracks->end()) {
ActiveSubscription active{
.subscribe = dormant_it->second.subscribe,
.track = dormant_it->second.track,
.stream_count = 0,
.loop_cycle = 0,
.next_object_index = 0,
.completed = false,
};
if (!apply_subscribe_update(active.subscribe, subscribe_update)) {
return TransportStatus::failure("received invalid SUBSCRIBE_UPDATE state transition");
}
std::size_t next_object_index = 0;
if (find_next_matching_object_index(plan, active.subscribe, 0, next_object_index)) {
active.next_object_index = next_object_index;
active_subscriptions.insert_or_assign(remapped_request_id, std::move(active));
} else {
if (advance_subscription_to_next_loop_object(plan, loop_state, active)) {
active_subscriptions.insert_or_assign(remapped_request_id, std::move(active));
} else {
const TransportStatus finalize_status = finalize_subscription(
transport, control_stream_id, remapped_request_id, 0, completed_request_ids);
if (!finalize_status.ok) {
return finalize_status;
}
served_any_subscription = true;
}
}
dormant_published_tracks->erase(dormant_it);
buffer.erase(buffer.begin(), buffer.begin() + message_size);
continue;
}
}
return TransportStatus::failure("received invalid SUBSCRIBE_UPDATE state transition");
}
if (message_type == 0x11) {
SubscribeNamespaceMessage subscribe_namespace;
if (!decode_subscribe_namespace_message(message_bytes, subscribe_namespace)) {
return TransportStatus::failure("received invalid SUBSCRIBE_NAMESPACE");
}
if (!namespace_prefix_matches(subscribe_namespace.track_namespace_prefix, track_namespace)) {
return TransportStatus::failure("peer requested unsupported namespace prefix");
}
const TransportStatus write_status =
transport.write_stream(control_stream_id,
encode_subscribe_namespace_ok_message(draft, subscribe_namespace.request_id),
false);
if (!write_status.ok) {
return write_status;
}
buffer.erase(buffer.begin(), buffer.begin() + message_size);
continue;
}
if (message_type == 0x03) {
SubscribeMessage subscribe;
if (!decode_subscribe_message(message_bytes, subscribe)) {
return TransportStatus::failure("received invalid SUBSCRIBE");
}
if (!namespace_matches(subscribe.track_namespace, track_namespace)) {
return TransportStatus::failure("peer requested unsupported track namespace");
}
pending_subscriptions.insert_or_assign(subscribe.request_id, subscribe);
pending_subscription_order.push_back(subscribe.request_id);
buffer.erase(buffer.begin(), buffer.begin() + message_size);
continue;
}
}
if (!fin && !pending_subscription_order.empty()) {
std::vector<std::uint8_t> chunk;
bool immediate_fin = false;
const TransportStatus read_status =
transport.read_stream(control_stream_id, chunk, immediate_fin, std::chrono::milliseconds(0));
if (read_status.ok) {
if (trace_enabled()) {
std::cerr << "[moqt-session] control chunk fin=" << (immediate_fin ? 1 : 0) << " bytes=["
<< hex_dump(chunk) << "]" << std::endl;
}
buffer.insert(buffer.end(), chunk.begin(), chunk.end());
fin = immediate_fin;
continue;
}
if (read_status.message != "timed out waiting for stream data") {
return read_status;
}
}
while (!pending_subscription_order.empty()) {
const std::uint64_t request_id = pending_subscription_order.front();
pending_subscription_order.pop_front();
auto pending_it = pending_subscriptions.find(request_id);
if (pending_it == pending_subscriptions.end()) {
continue;
}
const SubscribeMessage subscribe = pending_it->second;
pending_subscriptions.erase(pending_it);
const auto track_it = tracks_by_name.find(subscribe.track_name);
if (track_it == tracks_by_name.end()) {
const TransportStatus write_status =
transport.write_stream(control_stream_id,
encode_subscribe_error_message(subscribe.request_id, 0x2, "track does not exist"),
false);
if (!write_status.ok) {
return write_status;
}
continue;
}
const TransportStatus write_status =
transport.write_stream(control_stream_id,
encode_subscribe_ok_message(draft,
subscribe.request_id,
track_it->second.alias,
subscribe.subscriber_priority,
0,
0,
false),
false);
if (!write_status.ok) {
return write_status;
}
std::cerr << "[moqt-session] accepted subscribe track=" << subscribe.track_name
<< " request_id=" << subscribe.request_id << '\n';
ActiveSubscription active{
.subscribe = subscribe,
.track = track_it->second,
.stream_count = 0,
.loop_cycle = 0,
.next_object_index = 0,
.completed = false,
};
std::size_t next_object_index = 0;
if (find_next_matching_object_index(plan, active.subscribe, 0, next_object_index)) {
active.next_object_index = next_object_index;
active_subscriptions.insert_or_assign(request_id, std::move(active));
continue;
}
const TransportStatus finalize_status =
finalize_subscription(transport, control_stream_id, request_id, 0, completed_request_ids);
if (!finalize_status.ok) {
return finalize_status;
}
served_any_subscription = true;
}
if (!active_subscriptions.empty()) {
std::vector<std::uint8_t> chunk;
bool immediate_fin = false;
const TransportStatus read_status =
transport.read_stream(control_stream_id, chunk, immediate_fin, std::chrono::milliseconds(0));
if (read_status.ok) {
if (trace_enabled()) {
std::cerr << "[moqt-session] control chunk fin=" << (immediate_fin ? 1 : 0) << " bytes=["
<< hex_dump(chunk) << "]" << std::endl;
}
buffer.insert(buffer.end(), chunk.begin(), chunk.end());
fin = immediate_fin;
continue;
}
if (read_status.message != "timed out waiting for stream data") {
return read_status;
}
std::size_t next_plan_index = plan.objects.size();
std::size_t next_loop_cycle = 0;
for (const auto& [request_id, active] : active_subscriptions) {
static_cast<void>(request_id);
if (active.completed) {
continue;
}
if (next_plan_index == plan.objects.size() ||
active.loop_cycle < next_loop_cycle ||
(active.loop_cycle == next_loop_cycle && active.next_object_index < next_plan_index)) {
next_plan_index = active.next_object_index;
next_loop_cycle = active.loop_cycle;
}
}
if (next_plan_index < plan.objects.size()) {
const auto& source_object = plan.objects[next_plan_index];
const openmoq::publisher::CmsfObject object =
make_looped_object(source_object, loop_state, next_loop_cycle);
const auto payload = object_payload(source_object);