Repository navigation
Expand file tree
/
Copy pathtransmit.c
More file actions
1431 lines (1282 loc) · 57 KB
/
Copy pathtransmit.c
File metadata and controls
1431 lines (1282 loc) · 57 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
/*
* FILE: transmit.c
* AUTHOR: Colin Perkins <csp@csperkins.org>
* Ladan Gharai
* Martin Benes <martinbenesh@gmail.com>
* Lukas Hejtmanek <xhejtman@ics.muni.cz>
* Petr Holub <hopet@ics.muni.cz>
* Milos Liska <xliska@fi.muni.cz>
* Jiri Matela <matela@ics.muni.cz>
* Dalibor Matura <255899@mail.muni.cz>
* Ian Wesley-Smith <iwsmith@cct.lsu.edu>
* David Cassany <david.cassany@i2cat.net>
* Ignacio Contreras <ignacio.contreras@i2cat.net>
* Gerard Castillo <gerard.castillo@i2cat.net>
* Jordi "Txor" Casas Ríos <txorlings@gmail.com>
* Martin Pulec <pulec@cesnet.cz>
*
* Copyright (c) 2005-2010 Fundació i2CAT, Internet I Innovació Digital a Catalunya
* Copyright (c) 2001-2004 University of Southern California
* Copyright (c) 2005-2026 CESNET, zájmové sdružení právických osob
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
*
* This product includes software developed by the University of Southern
* California Information Sciences Institute. This product also includes
* software developed by CESNET z.s.p.o.
*
* 4. Neither the name of the University, Institute, CESNET nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "transmit.h"
#include <assert.h>
#include <math.h>
#include <stdio.h> // for snprintf, fprintf, stderr
#include <stdlib.h>
#include <string.h> // for memcpy, strlen, strchr, strstr
#include <strings.h> // for strcasecmp
#include <time.h>
#ifdef _WIN32
#include <windef.h> // for LARGE_INTEGER
#endif
#include "audio/codec.h"
#include "audio/types.h"
#include "audio/utils.h"
#include "compat/c23.h" // IWYU pragma: keep
#include "compat/net.h" // for htonl etc.
#include "control_socket.h"
#include "crypto/openssl_encrypt.h"
#include "debug.h"
#include "host.h" // for exit_uv
#include "lib_common.h"
#include "messaging.h" // for check_message...
#include "module.h"
#include "rtp/fec.h"
#include "rtp/rtp.h"
#include "rtp/rtp_types.h" // for fec_payload_hdr_t, crypto_payloa...
#include "rtp/rtpdec_h264.h" // for hevc_nal_type
#include "rtp/rtpenc_h264.h"
#include "tv.h"
#include "types.h"
#include "utils/color_out.h"
#include "utils/jpeg_reader.h"
#include "utils/macros.h"
#include "utils/misc.h" // unit_evaluate
#include "utils/random.h"
#include "video_codec.h"
#include "video_frame.h" // for vf_get_tile
struct audio_frame2;
#define MOD_NAME "[transmit] "
#define TRANSMIT_MAGIC 0xe80ab15f
#define FEC_MAX_MULT 10
#define RATE_MIN RATE_DYNAMIC
#define CONTROL_PORT_BANDWIDTH_REPORT_INTERVAL_NS NS_IN_SEC
#define GET_STARTTIME clock_gettime(CLOCK_MONOTONIC, &start)
#define GET_STOPTIME clock_gettime(CLOCK_MONOTONIC, &stop)
#define GET_DELTA delta = (stop.tv_sec - start.tv_sec) * 1000000000l + stop.tv_nsec - start.tv_nsec
static void tx_update(struct tx *tx, struct video_frame *frame, int substream);
static uint32_t format_interl_fps_hdr_row(enum interlacing_t interlacing, double input_fps);
static void
tx_send_base(struct tx *tx, struct video_frame *frame, struct rtp *rtp_session,
uint32_t ts, int send_m,
unsigned int substream,
int fragment_offset);
static bool set_fec(struct tx *tx, const char *fec);
static void fec_check_messages(struct tx *tx);
struct rate_limit_dyn {
unsigned long avg_frame_size; ///< moving average
long long last_excess; ///< nr of frames last excessive frame was emitted
};
enum { EXCESS_GAP = 4 }; ///< minimal gap between excessive frames
struct tx {
struct module mod;
uint32_t magic;
enum tx_media_type media_type;
unsigned mtu;
double max_loss;
uint32_t last_ts;
int last_frame_fragment_id;
unsigned int buffer:22;
unsigned long int sent_frames;
int32_t avg_len;
int32_t avg_len_last;
enum fec_type fec_scheme;
bool fec_dup_1st_pkt;
int mult_count;
int last_fragment;
struct control_state *control;
size_t sent_since_report;
uint64_t last_stat_report;
const struct openssl_encrypt_info *enc_funcs;
struct openssl_encrypt *encryption;
long long int bitrate;
struct rate_limit_dyn dyn_rate_limit_state;
char tmp_packet[RTP_MAX_MTU];
};
static void tx_update(struct tx *tx, struct video_frame *frame, int substream)
{
if(!frame) {
return;
}
uint64_t tmp_avg = tx->avg_len * tx->sent_frames + frame->tiles[substream].data_len *
(frame->fec_params.type != FEC_NONE ?
(double) frame->fec_params.k / (frame->fec_params.k + frame->fec_params.m) :
1);
tx->sent_frames++;
tx->avg_len = tmp_avg / tx->sent_frames;
if(tx->sent_frames >= 100) {
if(tx->fec_scheme == FEC_LDGM && tx->max_loss > 0.0) {
if(abs(tx->avg_len_last - tx->avg_len) > tx->avg_len / 3) {
int data_len = tx->mtu - (40 + (sizeof(fec_payload_hdr_t)));
data_len = (data_len / 48) * 48;
//void *fec_state_old = tx->fec_state;
struct msg_sender *msg = (struct msg_sender *)
new_message(sizeof(struct msg_sender));
snprintf(msg->fec_cfg, sizeof(msg->fec_cfg), "LDGM percents %d %d %f",
data_len, tx->avg_len, tx->max_loss);
msg->type = SENDER_MSG_CHANGE_FEC;
struct response *resp = send_message_to_receiver(get_parent_module(&tx->mod),
(struct message *) msg);
free_response(resp);
tx->avg_len_last = tx->avg_len;
}
}
tx->avg_len = 0;
tx->sent_frames = 0;
}
}
static bool
check_print_bitrate(long long int bitrate)
{
if (bitrate < RATE_MIN) {
MSG(ERROR,
"Invalid bitrate value %lld passed (either positive "
"bitrate or magic values from %d supported)!\n",
bitrate, RATE_MIN);
return false;
}
if (log_level < LOG_LEVEL_VERBOSE) {
return true;
}
char buf[100];
char *num = buf;
switch (bitrate) {
case RATE_UNLIMITED:
num = "unlimited";
break;
case RATE_AUTO :
num = "auto";
break;
case RATE_DYNAMIC :
num = "dynamic";
break;
default:
snprintf_ch(buf, "%lld%s", bitrate & ~RATE_FLAG_FIXED_RATE,
bitrate & RATE_FLAG_FIXED_RATE ? " (fixed)" : "");
}
MSG(VERBOSE, "Using bitrate limit: %s\n", num);
return true;
}
/**
* @brief initializes transmission
*
* @param encryption passcode to be used to encrypt the data; NULL or an empty
* string can be passed
*/
struct tx *tx_init(struct module *parent, unsigned mtu, enum tx_media_type media_type,
const char *fec, const char *encryption, long long int bitrate)
{
if (mtu > RTP_MAX_MTU) {
log_msg(LOG_LEVEL_ERROR, "Requested MTU exceeds maximal value allowed by RTP library (%d B).\n", RTP_MAX_MTU);
return NULL;
}
if (!check_print_bitrate(bitrate)) {
return NULL;
}
struct tx *tx = (struct tx *) calloc(1, sizeof(struct tx));
if (tx == nullptr) {
return tx;
}
module_init_default(&tx->mod);
tx->mod.cls = MODULE_CLASS_TX;
tx->mod.priv_data = tx;
module_register(&tx->mod, parent);
tx->magic = TRANSMIT_MAGIC;
tx->media_type = media_type;
tx->mult_count = 1;
tx->max_loss = 0.0;
tx->mtu = mtu;
tx->buffer = ug_rand() & 0x3fffff;
tx->avg_len = tx->avg_len_last = tx->sent_frames = 0u;
tx->fec_scheme = FEC_NONE;
tx->last_frame_fragment_id = -1;
if (fec) {
if(!set_fec(tx, fec)) {
tx_done(tx);
return NULL;
}
}
if (encryption != nullptr && strlen(encryption) > 0) {
tx->enc_funcs =
(const struct openssl_encrypt_info *) load_library(
"openssl_encrypt", LIBRARY_CLASS_UNDEFINED,
OPENSSL_ENCRYPT_ABI_VERSION);
if (!tx->enc_funcs) {
fprintf(stderr, "UltraGrid was build without OpenSSL support!\n");
tx_done(tx);
return NULL;
}
if (tx->enc_funcs->init(&tx->encryption,
encryption) != 0) {
log_msg(LOG_LEVEL_ERROR, MOD_NAME "Unable to initialize encryption\n");
tx_done(tx);
return NULL;
}
}
tx->bitrate = bitrate;
tx->control = get_control_state(parent);
return tx;
}
static bool set_fec(struct tx *tx, const char *fec_const)
{
char *fec = strdup(fec_const);
bool ret = true;
bool req_1st_pkt_dup = true;
// handle ...[:]nodup
char *end = fec + MAX(strlen(fec), 5) - 5;
if (strcmp(end, "nodup") == 0) {
req_1st_pkt_dup = true;
*end = '\0';
if (end > fec) { // ':'
end[-1] = '\0';
}
}
const char *fec_cfg = "";
if(strchr(fec, ':')) {
char *delim = strchr(fec, ':');
*delim = '\0';
fec_cfg = delim + 1;
}
struct msg_sender *msg = (struct msg_sender *)
new_message(sizeof(struct msg_sender));
msg->type = SENDER_MSG_CHANGE_FEC;
snprintf(msg->fec_cfg, sizeof(msg->fec_cfg), "flush");
tx->mult_count = 1; // default
if (strcasecmp(fec, "none") == 0) {
tx->fec_scheme = FEC_NONE;
} else if(strcasecmp(fec, "mult") == 0) {
tx->fec_scheme = FEC_MULT;
tx->mult_count = atoi(fec_cfg);
if (tx->mult_count <= 0 || tx->mult_count > FEC_MAX_MULT) {
MSG(ERROR,
"mult count must be between 1 and %d (%d given)!\n",
FEC_MAX_MULT, tx->mult_count);
ret = false;
}
} else if(strcasecmp(fec, "LDGM") == 0) {
tx->fec_dup_1st_pkt = req_1st_pkt_dup;
if(tx->media_type == TX_MEDIA_AUDIO) {
fprintf(stderr, "LDGM is not currently supported for audio!\n");
ret = false;
} else {
if (strlen(fec_cfg) == 0 ||
(strlen(fec_cfg) > 0 &&
strchr(fec_cfg, '%') == nullptr)) {
snprintf(msg->fec_cfg, sizeof(msg->fec_cfg),
"LDGM cfg %s", fec_cfg);
} else { // delay creation until we have average frame size
tx->max_loss = atof(fec_cfg);
}
tx->fec_scheme = FEC_LDGM;
}
} else if(strcasecmp(fec, "RS") == 0) {
tx->fec_dup_1st_pkt = req_1st_pkt_dup;
snprintf(msg->fec_cfg, sizeof(msg->fec_cfg), "RS cfg %s",
fec_cfg);
tx->fec_scheme = FEC_RS;
} else if(strcasecmp(fec, "help") == 0) {
fec_usage();
ret = false;
} else {
fprintf(stderr, "Unknown FEC: %s\n", fec);
ret = false;
}
if (tx->fec_dup_1st_pkt) {
MSG(VERBOSE, "Duplicating 1st packet of every frame for better "
"error resiliency.\n");
}
if (ret) {
struct response *resp = send_message_to_receiver(get_parent_module(&tx->mod),
(struct message *) msg);
free_response(resp);
} else {
free_message((struct message *) msg, NULL);
}
free(fec);
return ret;
}
static void fec_check_messages(struct tx *tx)
{
struct message *msg;
while ((msg = check_message(&tx->mod))) {
struct msg_universal *data = (struct msg_universal *) msg;
const char *text = data->text;
if (strstr(text, MSG_UNIVERSAL_TAG_TX) != text) {
MSG(ERROR, "Unexpected TX message: %s\n", text);
free_message(msg, new_response(RESPONSE_BAD_REQUEST, "Unexpected message"));
continue;
}
text += strlen(MSG_UNIVERSAL_TAG_TX);
struct response *r = nullptr;
if (strstr(text, "fec ") == text) {
text += strlen("fec ");
if (set_fec(tx, text)) {
r = new_response(RESPONSE_OK, nullptr);
MSG(NOTICE, "FEC set to new setting: %s\n", text);
} else {
r = new_response(RESPONSE_INT_SERV_ERR, "cannot set FEC");
MSG(ERROR, "Unable to reconfiure FEC to: %s\n", text);
}
} else if (strstr(text, "rate ") == text) {
text += strlen("rate ");
long long new_rate = unit_evaluate(text, nullptr);
if (new_rate >= RATE_MIN) {
tx->bitrate = new_rate;
r = new_response(RESPONSE_OK, nullptr);
MSG(NOTICE, "Bitrate set to: %s%s\n", text, new_rate > 0 ? "B" : "");
} else {
r = new_response(RESPONSE_BAD_REQUEST, "Wrong value for bitrate");
MSG(ERROR, "Wrong bitrate: %s\n", text);
}
} else {
r = new_response(RESPONSE_BAD_REQUEST, "Unknown TX message");
MSG(ERROR, "Unknown TX message: %s\n", text);
}
free_message(msg, r);
}
}
void tx_done(struct tx *tx_session)
{
assert(tx_session->magic == TRANSMIT_MAGIC);
module_done(&tx_session->mod);
free(tx_session);
}
/*
* sends one or more frames (tiles) with same TS in one RTP stream. Only one m-bit is set.
*/
void
tx_send(struct tx *tx, struct video_frame *frame, struct rtp *rtp_session)
{
unsigned int i;
assert(!frame->fragment || tx->fec_scheme == FEC_NONE); // currently no support for FEC with fragments
assert(!frame->fragment || frame->tile_count); // multiple tile are not currently supported for fragmented send
fec_check_messages(tx);
uint32_t ts =
(frame->flags & TIMESTAMP_VALID) == 0
? get_local_mediatime()
: get_local_mediatime_offset() + frame->timestamp;
if(frame->fragment &&
tx->last_frame_fragment_id == frame->frame_fragment_id) {
ts = tx->last_ts;
} else {
tx->last_frame_fragment_id = frame->frame_fragment_id;
tx->last_ts = ts;
}
for(i = 0; i < frame->tile_count; ++i)
{
bool last = false;
int fragment_offset = 0;
if (i == frame->tile_count - 1) {
if(!frame->fragment || frame->last_fragment)
last = true;
}
if(frame->fragment)
fragment_offset = vf_get_tile(frame, i)->offset;
tx_send_base(tx, frame, rtp_session, ts, last,
i, fragment_offset);
}
tx->buffer++;
}
void
format_video_header(const struct video_frame *frame, int tile_idx,
int buffer_idx, uint32_t *video_hdr)
{
uint32_t tmp;
video_hdr[3] = htonl(frame->tiles[tile_idx].width << 16 | frame->tiles[tile_idx].height);
video_hdr[4] = get_fourcc(frame->color_spec);
video_hdr[2] = htonl(frame->tiles[tile_idx].data_len);
tmp = tile_idx << 22;
tmp |= 0x3fffff & buffer_idx;
video_hdr[0] = htonl(tmp);
/* word 6 */
video_hdr[5] = format_interl_fps_hdr_row(frame->interlacing, frame->fps);
}
void format_audio_header(const struct audio_frame2 *frame, int channel, int buffer_idx, uint32_t *audio_hdr)
{
uint32_t tmp = 0;
tmp = channel << 22U; /* bits 0-9 */
tmp |= buffer_idx; /* bits 10-31 */
audio_hdr[0] = htonl(tmp);
audio_hdr[2] = htonl(audio_frame2_get_data_len(frame, channel));
/* fourth word */
tmp = (audio_frame2_get_bps(frame) * 8) << 26U;
tmp |= audio_frame2_get_sample_rate(frame);
audio_hdr[3] = htonl(tmp);
/* fifth word */
audio_hdr[4] = htonl(get_audio_tag(audio_frame2_get_codec(frame)));
}
static uint32_t format_interl_fps_hdr_row(enum interlacing_t interlacing, double input_fps)
{
unsigned int fpsd, fd, fps, fi;
uint32_t tmp;
tmp = interlacing << 29;
fps = round(input_fps);
fpsd = 1; /// @todo make use of this value (for now it is always one)
fd = 0;
fi = 0;
if (input_fps > 1.0 && fabs(input_fps - round(input_fps) / 1.001) < 0.005) { // 29.97 etc.
fd = 1;
} else if (fps < 1.0) {
fps = round(1.0 / input_fps);
fi = 1;
}
tmp |= fps << 19;
tmp |= fpsd << 15;
tmp |= fd << 14;
tmp |= fi << 13;
return htonl(tmp);
}
static inline void check_symbol_size(int fec_symbol_size, int payload_len)
{
_Thread_local static bool status_printed = false;
if (status_printed && log_level < LOG_LEVEL_DEBUG2) {
return;
}
if (fec_symbol_size > payload_len) {
MSG(WARNING,
"Warning: FEC symbol size exceeds payload size! "
"FEC symbol size: %d\n", fec_symbol_size);
} else {
const int ll =
status_printed ? LOG_LEVEL_DEBUG2 : LOG_LEVEL_INFO;
log_msg(ll,
MOD_NAME "FEC symbol size: %d, symbols per packet: %d, "
"payload size: %d\n",
fec_symbol_size, payload_len / fec_symbol_size,
payload_len / fec_symbol_size * fec_symbol_size);
}
status_printed = true;
}
/**
* Splits symbol (FEC symbol or uncompressed line) to 1 or more MTUs. Symbol starts
* always on beginning of packet.
*
* If symbol_size is longer than MTU (more symbols fit one packet), the aligned
* packet size is always the same.
*
* @param symbol_size FEC symbol size or linesize for uncompressed
*/
static inline int get_video_pkt_len(int mtu,
int symbol_size, int *symbol_offset)
{
if (symbol_size > mtu) {
if (symbol_size - *symbol_offset <= mtu) {
mtu = symbol_size - *symbol_offset;
*symbol_offset = 0;
} else {
*symbol_offset += mtu;
}
return mtu;
}
return mtu / symbol_size * symbol_size;
}
int gso_force; ///< do not enforce line alignment (rcv should display tx pixfmt)
/// @param mtu is tx->mtu - hdrs_len
static size_t
get_packet_sizes(struct video_frame *frame, unsigned substream, int mtu,
size_t max_count, uint16_t pkt_sz[static max_count])
{
if (frame->fec_params.type != FEC_NONE) {
check_symbol_size(frame->fec_params.symbol_size, mtu);
}
unsigned int symbol_size = 1;
int symbol_offset = 0;
if (frame->fec_params.type == FEC_NONE && !is_codec_opaque(frame->color_spec)) {
symbol_size = vc_get_linesize(frame->tiles[substream].width, frame->color_spec);
int pf_block_size = PIX_BLOCK_LCM / get_pf_block_pixels(frame->color_spec) * get_pf_block_bytes(frame->color_spec);
assert(pf_block_size <= mtu);
if (symbol_size % pf_block_size == 0 || gso_force) {
symbol_size = pf_block_size;
}
mtu = mtu / pf_block_size * pf_block_size;
} else if (frame->fec_params.type != FEC_NONE) {
symbol_size = frame->fec_params.symbol_size;
}
size_t pkt_cnt = 0;
unsigned pos = 0;
do {
int len = symbol_size == 1
? mtu
: get_video_pkt_len(mtu, symbol_size, &symbol_offset);
pos += len;
assert(pkt_cnt < max_count);
pkt_sz[pkt_cnt++] = len;
} while (pos < frame->tiles[substream].data_len);
if (pos > frame->tiles[substream].data_len) {
pkt_sz[pkt_cnt - 1] -=
(int) (pos - frame->tiles[substream].data_len);
}
return pkt_cnt;
}
static void
report_stats(struct tx *tx, struct rtp *rtp_session, long data_sent)
{
if (!tx->control || !control_stats_enabled(tx->control)) {
return;
}
tx->sent_since_report += data_sent;
const time_ns_t current_time_ns = get_time_in_ns();
if (current_time_ns - tx->last_stat_report <
CONTROL_PORT_BANDWIDTH_REPORT_INTERVAL_NS) {
return;
}
const char *media =
tx->media_type == TX_MEDIA_VIDEO ? "video" : "audio";
char buf[STR_LEN];
snprintf_ch(buf, "tx_send %x %s %zu", rtp_my_ssrc(rtp_session), media,
tx->sent_since_report);
control_report_stats(tx->control, buf);
tx->last_stat_report = current_time_ns;
tx->sent_since_report = 0;
}
/**
* Returns inter-packet interval in nanoseconds.
*/
static long
get_packet_rate(struct tx *tx, struct video_frame *frame, int substream, long packet_count)
{
if (tx->bitrate == RATE_UNLIMITED) {
return 0;
}
double time_for_frame = 1.0 / frame->fps / frame->tile_count;
double interval_between_pkts = time_for_frame / tx->mult_count / packet_count;
// use only 75% of the time - we less likely overshot the frame time and
// can minimize risk of swapping packets between 2 frames (out-of-order ones)
interval_between_pkts = interval_between_pkts * 0.75;
// prevent bitrate to be "too low", here 1 Mbps at minimum
interval_between_pkts = MIN(interval_between_pkts, tx->mtu / (1000.0 * 1000.0));
long packet_rate_auto = interval_between_pkts * 1000L * 1000 * 1000;
if (tx->bitrate == RATE_AUTO) { // adaptive (spread packets to 75% frame time)
return packet_rate_auto;
}
if (tx->bitrate == RATE_DYNAMIC) {
if (frame->tiles[substream].data_len > 2 * tx->dyn_rate_limit_state.avg_frame_size
&& tx->dyn_rate_limit_state.last_excess > EXCESS_GAP) {
packet_rate_auto /= 2; // double packet rate for this frame
tx->dyn_rate_limit_state.last_excess = 0;
} else {
tx->dyn_rate_limit_state.last_excess += 1;
}
tx->dyn_rate_limit_state.avg_frame_size = (9 * tx->dyn_rate_limit_state.avg_frame_size + frame->tiles[substream].data_len) / 10;
return packet_rate_auto;
}
long long int bitrate = tx->bitrate & ~RATE_FLAG_FIXED_RATE;
int avg_packet_size = frame->tiles[substream].data_len / packet_count;
long packet_rate = 1000L * 1000 * 1000L * avg_packet_size * 8 / bitrate; // fixed rate
if ((tx->bitrate & RATE_FLAG_FIXED_RATE) == 0) { // adaptive capped rate
packet_rate = MAX(packet_rate, packet_rate_auto);
}
return packet_rate;
}
static int
get_tx_hdr_len(bool is_ipv6)
{
return (is_ipv6 ? IPV6_HDR_LEN : IPV4_HDR_LEN) + UDP_HDR_LEN +
RTP_HDR_LEN;
}
static void
tx_send_base(struct tx *tx, struct video_frame *frame, struct rtp *rtp_session,
uint32_t ts, int send_m,
unsigned int substream,
int fragment_offset)
{
assert(fragment_offset == 0); // no longer supported
if (!rtp_has_receiver(rtp_session)) {
return;
}
struct tile *tile = &frame->tiles[substream];
// see definition in rtp_callback.h
uint32_t rtp_hdr[100];
int rtp_hdr_len;
int pt = fec_pt_from_fec_type(TX_MEDIA_VIDEO, frame->fec_params.type, tx->encryption); /* A value specified in our packet format */
struct timespec start, stop;
long delta, overslept = 0;
int hdrs_len = get_tx_hdr_len(rtp_is_ipv6(rtp_session));
assert(tx->magic == TRANSMIT_MAGIC);
tx_update(tx, frame, substream);
if (frame->fec_params.type == FEC_NONE) {
hdrs_len += (sizeof(video_payload_hdr_t));
rtp_hdr_len = sizeof(video_payload_hdr_t);
format_video_header(frame, substream, tx->buffer, rtp_hdr);
} else {
hdrs_len += (sizeof(fec_payload_hdr_t));
rtp_hdr_len = sizeof(fec_payload_hdr_t);
uint32_t tmp = substream << 22;
tmp |= 0x3fffff & tx->buffer;
// see definition in rtp_callback.h
rtp_hdr[0] = htonl(tmp);
rtp_hdr[2] = htonl(tile->data_len);
rtp_hdr[3] = htonl(
frame->fec_params.k << 19 |
frame->fec_params.m << 6 |
frame->fec_params.c);
rtp_hdr[4] = htonl(frame->fec_params.seed);
}
if (tx->encryption) {
hdrs_len += sizeof(crypto_payload_hdr_t) + tx->enc_funcs->get_overhead(tx->encryption);
rtp_hdr[rtp_hdr_len / sizeof(uint32_t)] =
htonl(tx->enc_funcs->get_cipher(tx->encryption) << 24);
rtp_hdr_len += sizeof(crypto_payload_hdr_t);
}
int netto_len = tx->mtu - hdrs_len;
uint16_t
packet_sizes[1000 + ((size_t) 4 * frame->tiles[substream].data_len /
netto_len)];
const size_t nr_packets = get_packet_sizes(
frame, substream, netto_len, countof(packet_sizes), packet_sizes);
size_t mult_pkt_cnt = nr_packets * tx->mult_count;
const long packet_rate =
get_packet_rate(tx, frame, (int) substream, mult_pkt_cnt);
// initialize header array with values (except offset which is different among
// different packts)
void *rtp_headers = malloc((mult_pkt_cnt + 1) * rtp_hdr_len);
uint32_t *rtp_hdr_packet = (uint32_t *) rtp_headers;
for (int m = 0; m < tx->mult_count; ++m) {
unsigned pos = 0;
for (unsigned i = 0; i < nr_packets; ++i) {
memcpy(rtp_hdr_packet, rtp_hdr, rtp_hdr_len);
rtp_hdr_packet[1] = htonl(pos);
rtp_hdr_packet += rtp_hdr_len / sizeof(uint32_t);
pos += packet_sizes[i];
}
}
if (tx->fec_dup_1st_pkt) { // dup 1st pkt with RS/LDGM
mult_pkt_cnt += 1;
memcpy(rtp_hdr_packet, rtp_hdr, rtp_hdr_len);
rtp_hdr_packet[1] = htonl(0);
}
if (!tx->encryption) {
rtp_async_start(rtp_session, mult_pkt_cnt, tx->mtu);
}
rtp_hdr_packet = (uint32_t *) rtp_headers;
for (unsigned i = 0; i < mult_pkt_cnt; ++i) {
GET_STARTTIME;
const int m = i == mult_pkt_cnt - 1 ? send_m : 0;
char *data = tile->data + ntohl(rtp_hdr_packet[1]);
int data_len = packet_sizes[i % nr_packets];
char encrypted_data[RTP_MAX_PACKET_LEN + MAX_CRYPTO_EXCEED];
if (tx->encryption != nullptr) {
data_len = tx->enc_funcs->encrypt(
tx->encryption, data, data_len,
(char *) rtp_hdr_packet,
frame->fec_params.type != FEC_NONE
? sizeof(fec_payload_hdr_t)
: sizeof(video_payload_hdr_t),
encrypted_data);
if (data_len <= 0) {
return;
}
data = encrypted_data;
}
rtp_send_data_hdr(rtp_session, ts, pt, m, 0, nullptr,
(char *) rtp_hdr_packet, rtp_hdr_len, data,
data_len, nullptr, 0, 0);
rtp_hdr_packet += rtp_hdr_len / sizeof(uint32_t);
// TRAFFIC SHAPER
if (m != 1) { // wait for all but last packet
do {
GET_STOPTIME;
GET_DELTA;
} while (packet_rate - delta - overslept > 0);
overslept = -(packet_rate - delta - overslept);
//fprintf(stdout, "%ld ", overslept);
}
}
const long data_sent = tile->data_len + rtp_hdr_len * mult_pkt_cnt;
report_stats(tx, rtp_session, data_sent);
if (!tx->encryption) {
rtp_async_wait(rtp_session);
}
free(rtp_headers);
}
static void audio_tx_send_chan(struct tx *tx, struct rtp *rtp_session,
uint32_t timestamp, const struct audio_frame2 *buffer,
int channel, bool send_m);
/*
* This multiplication scheme relies upon the fact, that our RTP/pbuf implementation is
* not sensitive to packet duplication. Otherwise, we can get into serious problems.
*/
void
audio_tx_send(struct tx *tx, struct rtp *rtp_session,
const struct audio_frame2 *buffer)
{
if (!rtp_has_receiver(rtp_session)) {
return;
}
fec_check_messages(tx);
const uint32_t timestamp =
audio_frame2_get_timestamp(buffer) == -1
? get_local_mediatime()
: get_local_mediatime_offset() + audio_frame2_get_timestamp(buffer);
for (int iter = 0; iter < tx->mult_count; ++iter) {
for (int chan = 0; chan < audio_frame2_get_channel_count(buffer); ++chan) {
bool send_m = iter == tx->mult_count - 1 &&
chan == audio_frame2_get_channel_count(buffer) - 1;
audio_tx_send_chan(tx, rtp_session, timestamp, buffer,
chan, send_m);
}
}
tx->buffer++;
}
static void
audio_tx_send_chan(struct tx *tx, struct rtp *rtp_session, uint32_t timestamp,
const struct audio_frame2 *buffer, int channel, bool send_m)
{
const struct fec_desc fec_desc =
audio_frame2_get_fec_params(buffer, channel);
int pt = fec_pt_from_fec_type(
TX_MEDIA_AUDIO, fec_desc.type,
tx->encryption); /* PT set for audio in our packet format */
unsigned m = 0U;
// see definition in rtp_callback.h
uint32_t rtp_hdr[100];
int rtp_hdr_len = 0;
int hdrs_len = get_tx_hdr_len(rtp_is_ipv6(rtp_session));
unsigned int fec_symbol_size = fec_desc.symbol_size;
const char *chan_data = audio_frame2_get_data(buffer, channel);
unsigned pos = 0U;
if (fec_desc.type == FEC_NONE) {
hdrs_len += (sizeof(audio_payload_hdr_t));
rtp_hdr_len = sizeof(audio_payload_hdr_t);
format_audio_header(buffer, channel, tx->buffer, rtp_hdr);
} else {
hdrs_len += (sizeof(fec_payload_hdr_t));
rtp_hdr_len = sizeof(fec_payload_hdr_t);
uint32_t tmp = channel << 22;
tmp |= 0x3fffff & tx->buffer;
// see definition in rtp_callback.h
rtp_hdr[0] = htonl(tmp);
rtp_hdr[2] = htonl(audio_frame2_get_data_len(buffer, channel));
rtp_hdr[3] = htonl(fec_desc.k << 19 |
fec_desc.m << 6 |
fec_desc.c);
rtp_hdr[4] = htonl(fec_desc.seed);
}
if (tx->encryption) {
hdrs_len += sizeof(crypto_payload_hdr_t) +
tx->enc_funcs->get_overhead(tx->encryption);
rtp_hdr[rtp_hdr_len / sizeof(uint32_t)] =
htonl(tx->enc_funcs->get_cipher(tx->encryption) << 24);
rtp_hdr_len += sizeof(crypto_payload_hdr_t);
}
if (fec_desc.type != FEC_NONE) {
check_symbol_size(fec_symbol_size, tx->mtu - hdrs_len);
}
long data_sent = 0;
const int max_len = tx->mtu - hdrs_len;
do {
const char *data_c = chan_data + pos;
char *data = CONST_CAST(char *, data, data_c);
int data_len = max_len;
if (pos + data_len >=
(unsigned int) audio_frame2_get_data_len(buffer, channel)) {
data_len = audio_frame2_get_data_len(buffer, channel) - pos;
if (send_m) {
m = 1;
}
}
rtp_hdr[1] = htonl(pos);
pos += data_len;
char encrypted_data[RTP_MAX_PACKET_LEN + MAX_CRYPTO_EXCEED];
if (tx->encryption) {
data_len = tx->enc_funcs->encrypt(
tx->encryption, data, data_len,
(char *) rtp_hdr,
rtp_hdr_len - sizeof(crypto_payload_hdr_t),
encrypted_data);
if (data_len <= 0) {
return;
}
data = encrypted_data;
}
data_sent += data_len + rtp_hdr_len;
rtp_send_data_hdr(rtp_session, timestamp, pt, m,
0, /* contributing sources */
0, /* contributing sources length */
(char *) rtp_hdr, rtp_hdr_len,
data, data_len, 0, 0, 0);
} while (pos < audio_frame2_get_data_len(buffer, channel));
report_stats(tx, rtp_session, data_sent);
if (fec_desc.type == FEC_NONE) {
return;
}
// issue a warning if R-S is inadequate
const int packet_count =
(audio_frame2_get_data_len(buffer, channel) + max_len - 1) /
max_len;
if (packet_count > 3) {
return;
}
const char *pl_suffix = packet_count == 1 ? "" : "s";
MSG_ONCE(WARNING,
"[audio] %d packet%s per audio channel may be too low "
"for Reed Solomon, consider mult instead!%s\n",
packet_count, pl_suffix,
packet_count == 3 ? " (Or increase the redundancy.)" : "");
}
static bool
validate_std_audio(const struct audio_frame2 * buffer, size_t payload_size)
{
const audio_codec_t audio_codec = audio_frame2_get_codec(buffer);
if ((audio_codec == AC_MP3 ||
audio_codec == AC_OPUS) &&
audio_frame2_get_channel_count(buffer) > 1) { // we cannot interleave Opus here
MSG_ONCE(ERROR, "%s can currently have only 1 channel in "
"RFC-compliant mode! Discarding channels but the "
"first one...\n",
get_audio_codec_name(audio_codec));
}
if (audio_codec == AC_OPUS &&
payload_size < audio_frame2_get_data_len(buffer, 0)) {
MSG(ERROR, "Opus frame larger than packet! Discarding...\n");
return false;
}
return true;
}
/**
* audio_tx_send_standard - Send interleaved channels from the audio_frame2,
* as the mulaw and A-law standards (dynamic or std PT).
*/
void audio_tx_send_standard(struct tx* tx, struct rtp *rtp_session,
const struct audio_frame2 * buffer) {
const audio_codec_t audio_codec = audio_frame2_get_codec(buffer);
const int ch_count = audio_frame2_get_channel_count(buffer);