FreeSWITCH API Documentation  1.7.0
switch_rtp.c
Go to the documentation of this file.
1 /*
2  * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
3  * Copyright (C) 2005-2014, Anthony Minessale II <anthm@freeswitch.org>
4  *
5  * Version: MPL 1.1
6  *
7  * The contents of this file are subject to the Mozilla Public License Version
8  * 1.1 (the "License"); you may not use this file except in compliance with
9  * the License. You may obtain a copy of the License at
10  * http://www.mozilla.org/MPL/
11  *
12  * Software distributed under the License is distributed on an "AS IS" basis,
13  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14  * for the specific language governing rights and limitations under the
15  * License.
16  *
17  * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
18  *
19  * The Initial Developer of the Original Code is
20  * Anthony Minessale II <anthm@freeswitch.org>
21  * Portions created by the Initial Developer are Copyright (C)
22  * the Initial Developer. All Rights Reserved.
23  *
24  * Contributor(s):
25  *
26  * Anthony Minessale II <anthm@freeswitch.org>
27  * Marcel Barbulescu <marcelbarbulescu@gmail.com>
28  * Seven Du <dujinfang@gmail.com>
29  *
30  * switch_rtp.c -- RTP
31  *
32  */
33 //#define DEBUG_2833
34 //#define RTP_DEBUG_WRITE_DELTA
35 //#define DEBUG_MISSED_SEQ
36 //#define DEBUG_EXTRA
37 //#define DEBUG_RTCP
38 
39 #include <switch.h>
40 #ifndef _MSC_VER
41 #include <switch_private.h>
42 #endif
43 #include <switch_stun.h>
44 #include <apr_network_io.h>
45 #undef PACKAGE_NAME
46 #undef PACKAGE_STRING
47 #undef PACKAGE_TARNAME
48 #undef PACKAGE_VERSION
49 #undef PACKAGE_BUGREPORT
50 #undef VERSION
51 #undef PACKAGE
52 #undef inline
53 #include <datatypes.h>
54 #include <srtp.h>
55 #include <srtp_priv.h>
56 #include <switch_ssl.h>
57 #include <switch_jitterbuffer.h>
58 
59 #define JITTER_LEAD_FRAMES 10
60 #define READ_INC(rtp_session) switch_mutex_lock(rtp_session->read_mutex); rtp_session->reading++
61 #define READ_DEC(rtp_session) switch_mutex_unlock(rtp_session->read_mutex); rtp_session->reading--
62 #define WRITE_INC(rtp_session) switch_mutex_lock(rtp_session->write_mutex); rtp_session->writing++
63 #define WRITE_DEC(rtp_session) switch_mutex_unlock(rtp_session->write_mutex); rtp_session->writing--
64 
65 #define RTP_STUN_FREQ 1000000
66 #define rtp_header_len 12
67 #define RTP_START_PORT 16384
68 #define RTP_END_PORT 32768
69 #define MASTER_KEY_LEN 30
70 #define RTP_MAGIC_NUMBER 42
71 #define WARN_SRTP_ERRS 10
72 #define MAX_SRTP_ERRS 100
73 #define NTP_TIME_OFFSET 2208988800UL
74 #define ZRTP_MAGIC_COOKIE 0x5a525450
75 static const switch_payload_t INVALID_PT = 255;
76 
77 #define DTMF_SANITY (rtp_session->one_second * 30)
78 
79 #define rtp_session_name(_rtp_session) _rtp_session->session ? switch_core_session_get_name(_rtp_session->session) : "-"
80 
83 static switch_mutex_t *port_lock = NULL;
84 static switch_size_t do_flush(switch_rtp_t *rtp_session, int force, switch_size_t bytes_in);
85 
86 typedef srtp_hdr_t rtp_hdr_t;
87 
88 #ifdef ENABLE_ZRTP
89 #include "zrtp.h"
90 static zrtp_global_t *zrtp_global;
91 #ifndef WIN32
92 static zrtp_zid_t zid = { "FreeSWITCH01" };
93 #else
94 static zrtp_zid_t zid = { "FreeSWITCH0" };
95 #endif
96 static int zrtp_on = 0;
97 #define ZRTP_MITM_TRIES 100
98 #endif
99 
100 #ifdef _MSC_VER
101 #pragma pack(4)
102 #endif
103 
104 #ifdef _MSC_VER
105 #pragma pack()
106 #define ENABLE_SRTP
107 #endif
108 
109 static switch_hash_t *alloc_hash = NULL;
110 
111 typedef struct {
112  srtp_hdr_t header;
115  char *ebody;
116 } rtp_msg_t;
117 
118 #define RTP_BODY(_s) (char *) (_s->recv_msg.ebody ? _s->recv_msg.ebody : _s->recv_msg.body)
119 
120 typedef struct {
121  uint32_t ssrc;
122  uint8_t seq;
123  uint8_t r1;
124  uint8_t r2;
125  uint8_t r3;
126 } rtcp_fir_t;
127 
128 #ifdef _MSC_VER
129 #pragma pack(push, r1, 1)
130 #endif
131 
132 typedef struct switch_rtcp_sdes_unit_s {
133  unsigned char type;
134  unsigned char length;
135  char value[];
137 
138 typedef struct {
139  uint32_t ssrc;
140  uint8_t parts[4];
141 } rtcp_tmmbx_t;
142 
143 #if SWITCH_BYTE_ORDER == __BIG_ENDIAN
144 
145 typedef struct {
146  unsigned version:2;
147  unsigned p:1;
148  unsigned fmt:5;
149  unsigned pt:8;
150  unsigned length:16;
151  uint32_t send_ssrc;
152  uint32_t recv_ssrc;
154 
155 #else /* BIG_ENDIAN */
156 
157 typedef struct {
158  unsigned fmt:5;
159  unsigned p:1;
160  unsigned version:2;
161  unsigned pt:8;
162  unsigned length:16;
163  uint32_t send_ssrc;
164  uint32_t recv_ssrc;
166 
167 #endif
168 
169 #ifdef _MSC_VER
170 #pragma pack(pop, r1)
171 #endif
172 
173 
174 typedef struct {
178 
179 typedef struct {
182 } rtcp_msg_t;
183 
184 
185 typedef enum {
186  VAD_FIRE_TALK = (1 << 0),
187  VAD_FIRE_NOT_TALK = (1 << 1)
189 
194  uint32_t bg_level;
195  uint32_t bg_count;
196  uint32_t bg_len;
197  uint32_t diff_level;
198  uint8_t hangunder;
199  uint8_t hangunder_hits;
200  uint8_t hangover;
201  uint8_t hangover_hits;
202  uint8_t cng_freq;
203  uint8_t cng_count;
205  uint32_t ts;
206  uint8_t start;
207  uint8_t start_count;
208  uint8_t scan_freq;
209  time_t next_scan;
214 };
215 
218  char out_digit;
219  unsigned char out_digit_packet[4];
220  unsigned int out_digit_sofar;
221  unsigned int out_digit_sub_sofar;
222  unsigned int out_digit_dur;
223  uint16_t in_digit_seq;
224  uint32_t in_digit_ts;
226  uint32_t in_digit_sanity;
227  uint32_t in_interleaved;
228  uint32_t timestamp_dtmf;
229  uint16_t last_duration;
230  uint32_t flip;
236 };
237 
238 typedef struct {
239  char *ice_user;
240  char *user_ice;
241  char *luser_ice;
242  char *pass;
243  char *rpass;
245  uint32_t funny_stun;
250  uint8_t sending;
251  uint8_t ready;
252  uint8_t rready;
254  char last_sent_id[13];
257 
258 struct switch_rtp;
259 
260 typedef struct switch_dtls_s {
261  /* DTLS */
262  SSL_CTX *ssl_ctx;
263  SSL *ssl;
264  BIO *read_bio;
265  BIO *write_bio;
270  uint8_t new_state;
273  void *data;
276  char *rsa;
277  char *pvt;
278  char *ca;
279  char *pem;
281 } switch_dtls_t;
282 
284 
285 
286 static int dtls_state_handshake(switch_rtp_t *rtp_session, switch_dtls_t *dtls);
287 static int dtls_state_ready(switch_rtp_t *rtp_session, switch_dtls_t *dtls);
288 static int dtls_state_setup(switch_rtp_t *rtp_session, switch_dtls_t *dtls);
289 static int dtls_state_fail(switch_rtp_t *rtp_session, switch_dtls_t *dtls);
290 
292 
293 typedef struct ts_normalize_s {
294  uint32_t last_ssrc;
295  uint32_t last_frame;
296  uint32_t ts;
297  uint32_t delta;
298  uint32_t delta_ct;
299  uint32_t delta_ttl;
301 
302 struct switch_rtp {
303  /*
304  * Two sockets are needed because we might be transcoding protocol families
305  * (e.g. receive over IPv4 and send over IPv6). In case the protocol
306  * families are equal, sock_input == sock_output and only one socket is
307  * used.
308  */
312 
317 
318  uint8_t fir_seq;
319  uint16_t fir_count;
320  uint16_t pli_count;
321  uint32_t cur_tmmbr;
322  uint32_t tmmbr;
323  uint32_t tmmbn;
324 
330 
331  uint32_t autoadj_window;
333  uint32_t autoadj_tally;
334 
335  srtp_ctx_t *send_ctx[2];
336  srtp_ctx_t *recv_ctx[2];
337 
338  srtp_policy_t send_policy[2];
339  srtp_policy_t recv_policy[2];
340 
341  uint32_t srtp_errs[2];
342  uint32_t srctp_errs[2];
343 
344 
347 
350 
352 
353  uint16_t seq;
354  uint32_t ssrc;
355  uint32_t remote_ssrc;
357  int8_t sending_dtmf;
358  uint8_t need_mark;
362  uint32_t ts;
363  uint32_t last_write_ts;
364  uint32_t last_read_ts;
365  uint32_t last_cng_ts;
367  uint32_t delay_samples;
370  uint32_t queue_delay;
375  char *rx_host;
379  char *timer_name;
385  uint32_t wrong_addrs;
391  uint32_t ms_per_packet;
392  uint32_t one_second;
394  uint32_t jitter_lead;
395  double old_mean;
401 
412  uint8_t ready;
413  uint8_t cn;
418  uint32_t missed_count;
421  int reading;
422  int writing;
423  char *stun_ip;
426  uint32_t cng_count;
429  uint32_t clean_stream;
430  uint32_t bad_stream;
432 
433  uint32_t hot_hits;
434  uint32_t sync_packets;
438 
441  uint8_t pause_jb;
442  uint16_t last_seq;
449  int ice_adj;
450  uint8_t has_rtp;
451  uint8_t has_rtcp;
452  uint8_t has_ice;
453  uint8_t punts;
454  uint8_t clean;
455 #ifdef ENABLE_ZRTP
456  zrtp_session_t *zrtp_session;
457  zrtp_profile_t *zrtp_profile;
458  zrtp_stream_t *zrtp_stream;
459  int zrtp_mitm_tries;
460  int zinit;
461 #endif
462 
463 };
464 
466  uint32_t ssrc; /* The SSRC identifier of the source to which the information in this reception report block pertains. */
467  unsigned int fraction :8; /* The fraction of RTP data packets from source SSRC_n lost since the previous SR or RR packet was sent */
468  int lost :24; /* The total number of RTP data packets from source SSRC_n that have been lost since the beginning of reception */
470  uint32_t jitter; /* An estimate of the statistical variance of the RTP data packet interarrival time, measured in timestamp units and expressed as an unsigned integer. */
471  uint32_t lsr; /* The middle 32 bits out of 64 in the NTP timestamp */
472  uint32_t dlsr; /* The delay, expressed in units of 1/65536 seconds, between receiving the last SR packet from source SSRC_n and sending this reception report block */
473 };
474 
476  uint32_t ssrc;
477  uint32_t ntp_msw;
478  uint32_t ntp_lsw;
479  uint32_t ts;
480  uint32_t pc;
481  uint32_t oc;
482 };
483 
485  uint32_t ntp_msw;
486  uint32_t ntp_lsw;
487  uint32_t ts;
488  uint32_t pc;
489  uint32_t oc;
490 };
491 
493  uint32_t ssrc;
496 };
497 
499  uint32_t ssrc;
501 };
502 
503 typedef enum {
509 
510 static void do_2833(switch_rtp_t *rtp_session);
511 
512 
513 #define rtp_type(rtp_session) rtp_session->flags[SWITCH_RTP_FLAG_VIDEO] ? "video" : "audio"
514 
515 
516 static void switch_rtp_change_ice_dest(switch_rtp_t *rtp_session, switch_rtp_ice_t *ice, const char *host, switch_port_t port)
517 {
518  int is_rtcp = ice == &rtp_session->rtcp_ice;
519  const char *err = "";
520 
521  ice->ice_params->cands[ice->ice_params->chosen[ice->proto]][ice->proto].con_addr = switch_core_strdup(rtp_session->pool, host);
522  ice->ice_params->cands[ice->ice_params->chosen[ice->proto]][ice->proto].con_port = port;
523  ice->missed_count = 0;
524 
525  if (is_rtcp) {
526  ice->addr = rtp_session->rtcp_remote_addr;
527  } else {
528  switch_rtp_set_remote_address(rtp_session, host, port, 0, SWITCH_FALSE, &err);
529 
530  if (rtp_session->flags[SWITCH_RTP_FLAG_RTCP_MUX]) {
531  ice->addr = rtp_session->remote_addr;
532  }
533  }
534 
535 }
536 
537 
538 
539 static handle_rfc2833_result_t handle_rfc2833(switch_rtp_t *rtp_session, switch_size_t bytes, int *do_cng)
540 {
541 
542  if (rtp_session->flags[SWITCH_RTP_FLAG_DTMF_ON]) {
543  rtp_session->flags[SWITCH_RTP_FLAG_DTMF_ON]++;
544 
545  if (rtp_session->flags[SWITCH_RTP_FLAG_DTMF_ON] > DTMF_SANITY) {
546  rtp_session->flags[SWITCH_RTP_FLAG_DTMF_ON] = 0;
547  } else {
548  rtp_session->stats.inbound.last_processed_seq = 0;
549  }
550  }
551 
552 
553 #ifdef DEBUG_2833
554  if (rtp_session->dtmf_data.in_digit_sanity && !(rtp_session->dtmf_data.in_digit_sanity % 100)) {
555  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "sanity %d %ld\n", rtp_session->dtmf_data.in_digit_sanity, bytes);
556  }
557 #endif
558 
559  if (rtp_session->dtmf_data.in_digit_sanity && !--rtp_session->dtmf_data.in_digit_sanity) {
560 
561  rtp_session->dtmf_data.last_digit = 0;
562  rtp_session->dtmf_data.in_digit_ts = 0;
563  rtp_session->dtmf_data.in_digit_queued = 0;
564  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "Failed DTMF sanity check.\n");
565  }
566 
567  /* RFC2833 ... like all RFC RE: VoIP, guaranteed to drive you to insanity!
568  We know the real rules here, but if we enforce them, it's an interop nightmare so,
569  we put up with as much as we can so we don't have to deal with being punished for
570  doing it right. Nice guys finish last!
571  */
572 
573  if (bytes > rtp_header_len && !rtp_session->flags[SWITCH_RTP_FLAG_PROXY_MEDIA] &&
574  rtp_session->last_rtp_hdr.pt == rtp_session->recv_te) {
575  switch_size_t len = bytes - rtp_header_len;
576  unsigned char *packet = (unsigned char *) RTP_BODY(rtp_session);
577  int end;
578  uint16_t duration;
579  char key;
580  uint16_t in_digit_seq;
581  uint32_t ts;
582 
583  rtp_session->stats.inbound.last_processed_seq = 0;
584 
585  if (!(packet[0] || packet[1] || packet[2] || packet[3]) && len >= 8) {
586  packet += 4;
587  len -= 4;
588  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_WARNING, "DTMF payload offset by 4 bytes.\n");
589  }
590 
591  if (!(packet[0] || packet[1] || packet[2] || packet[3]) && rtp_session->dtmf_data.in_digit_ts) {
592  switch_core_session_t *session = switch_core_memory_pool_get_data(rtp_session->pool, "__session");
593  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "Failed DTMF payload check.\n");
594  rtp_session->dtmf_data.last_digit = 0;
595  rtp_session->dtmf_data.in_digit_ts = 0;
596  rtp_session->dtmf_data.in_digit_sanity = 0;
597  rtp_session->dtmf_data.in_digit_queued = 0;
598  }
599 
600  end = packet[1] & 0x80 ? 1 : 0;
601  duration = (packet[2] << 8) + packet[3];
602  key = switch_rfc2833_to_char(packet[0]);
603  in_digit_seq = ntohs((uint16_t) rtp_session->last_rtp_hdr.seq);
604  ts = htonl(rtp_session->last_rtp_hdr.ts);
605 
606  if (rtp_session->flags[SWITCH_RTP_FLAG_PASS_RFC2833]) {
607 
608  if (end) {
609  rtp_session->flags[SWITCH_RTP_FLAG_DTMF_ON] = DTMF_SANITY - 3;
610  } else if (!rtp_session->flags[SWITCH_RTP_FLAG_DTMF_ON]) {
611  rtp_session->flags[SWITCH_RTP_FLAG_DTMF_ON] = 1;
612  }
613 
614  return RESULT_CONTINUE;
615  }
616 
617  if (in_digit_seq < rtp_session->dtmf_data.in_digit_seq) {
618  if (rtp_session->dtmf_data.in_digit_seq - in_digit_seq > 100) {
619  rtp_session->dtmf_data.in_digit_seq = 0;
620  }
621  }
622 #ifdef DEBUG_2833
623  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "packet[%d]: %02x %02x %02x %02x\n", (int) len, (unsigned char) packet[0], (unsigned char) packet[1], (unsigned char) packet[2], (unsigned char) packet[3]);
624 #endif
625 
626  if (in_digit_seq > rtp_session->dtmf_data.in_digit_seq) {
627 
628  rtp_session->dtmf_data.in_digit_seq = in_digit_seq;
629 #ifdef DEBUG_2833
630 
631  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "read: %c %u %u %u %u %d %d %s\n",
632  key, in_digit_seq, rtp_session->dtmf_data.in_digit_seq,
633  ts, duration, rtp_session->last_rtp_hdr.m, end, end && !rtp_session->dtmf_data.in_digit_ts ? "ignored" : "");
634 #endif
635 
636 
637  if (rtp_session->dtmf_data.in_digit_ts && rtp_session->dtmf_data.in_digit_ts != ts) {
638  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "TS changed from last packet, resetting....\n");
639  rtp_session->dtmf_data.last_digit = 0;
640  rtp_session->dtmf_data.in_digit_ts = 0;
641  rtp_session->dtmf_data.in_digit_sanity = 0;
642  rtp_session->dtmf_data.in_digit_queued = 0;
643  }
644 
645 
646  if (!rtp_session->dtmf_data.in_digit_queued && rtp_session->dtmf_data.in_digit_ts) {
647  if ((rtp_session->rtp_bugs & RTP_BUG_IGNORE_DTMF_DURATION)) {
649 #ifdef DEBUG_2833
650  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Early Queuing digit %c:%d\n", dtmf.digit, dtmf.duration / 8);
651 #endif
652  switch_rtp_queue_rfc2833_in(rtp_session, &dtmf);
653  rtp_session->dtmf_data.in_digit_queued = 1;
654  }
655 
656  if (rtp_session->jb && (rtp_session->rtp_bugs & RTP_BUG_FLUSH_JB_ON_DTMF)) {
657  switch_jb_reset(rtp_session->jb);
658  }
659 
660  }
661 
662  /* only set sanity if we do NOT ignore the packet */
663  if (rtp_session->dtmf_data.in_digit_ts) {
664  rtp_session->dtmf_data.in_digit_sanity = 2000;
665  }
666 
667  if (rtp_session->dtmf_data.last_duration > duration &&
668  rtp_session->dtmf_data.last_duration > 0xFC17 && ts == rtp_session->dtmf_data.in_digit_ts) {
669  rtp_session->dtmf_data.flip++;
670  }
671 
672  if (end) {
673  if (!rtp_session->dtmf_data.in_digit_ts && rtp_session->dtmf_data.last_in_digit_ts != ts) {
674 #ifdef DEBUG_2833
675  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "start with end packet %d\n", ts);
676 #endif
677  rtp_session->dtmf_data.last_in_digit_ts = ts;
678  rtp_session->dtmf_data.in_digit_ts = ts;
679  rtp_session->dtmf_data.first_digit = key;
680  rtp_session->dtmf_data.in_digit_sanity = 2000;
681  }
682  if (rtp_session->dtmf_data.in_digit_ts) {
683  switch_dtmf_t dtmf = { key, duration, 0, SWITCH_DTMF_RTP };
684 
685  if (ts > rtp_session->dtmf_data.in_digit_ts) {
686  dtmf.duration += (ts - rtp_session->dtmf_data.in_digit_ts);
687  }
688  if (rtp_session->dtmf_data.flip) {
689  dtmf.duration += rtp_session->dtmf_data.flip * 0xFFFF;
690  rtp_session->dtmf_data.flip = 0;
691 #ifdef DEBUG_2833
693 #endif
694  }
695 #ifdef DEBUG_2833
696  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "done digit=%c ts=%u start_ts=%u dur=%u ddur=%u\n",
697  dtmf.digit, ts, rtp_session->dtmf_data.in_digit_ts, duration, dtmf.duration);
698 #endif
699 
700  if (!(rtp_session->rtp_bugs & RTP_BUG_IGNORE_DTMF_DURATION) && !rtp_session->dtmf_data.in_digit_queued) {
701 #ifdef DEBUG_2833
702  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Queuing digit %c:%d\n", dtmf.digit, dtmf.duration / 8);
703 #endif
704  switch_rtp_queue_rfc2833_in(rtp_session, &dtmf);
705  }
706 
707  rtp_session->dtmf_data.last_digit = rtp_session->dtmf_data.first_digit;
708 
709  rtp_session->dtmf_data.in_digit_ts = 0;
710  rtp_session->dtmf_data.in_digit_sanity = 0;
711  rtp_session->dtmf_data.in_digit_queued = 0;
712  *do_cng = 1;
713  } else {
714  if (!switch_rtp_ready(rtp_session)) {
715  return RESULT_GOTO_END;
716  }
718  return RESULT_GOTO_RECVFROM;
719  }
720 
721  } else if (!rtp_session->dtmf_data.in_digit_ts) {
722 #ifdef DEBUG_2833
723  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "start %d [%c]\n", ts, key);
724 #endif
725  rtp_session->dtmf_data.in_digit_ts = ts;
726  rtp_session->dtmf_data.last_in_digit_ts = ts;
727  rtp_session->dtmf_data.first_digit = key;
728  rtp_session->dtmf_data.in_digit_sanity = 2000;
729  }
730 
731  rtp_session->dtmf_data.last_duration = duration;
732  } else {
733 #ifdef DEBUG_2833
734  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "drop: %c %u %u %u %u %d %d\n",
735  key, in_digit_seq, rtp_session->dtmf_data.in_digit_seq, ts, duration, rtp_session->last_rtp_hdr.m, end);
736 #endif
738  return RESULT_GOTO_RECVFROM;
739  }
740  }
741 
742  if (bytes && rtp_session->dtmf_data.in_digit_ts) {
743  if (!switch_rtp_ready(rtp_session)) {
744  return RESULT_GOTO_END;
745  }
746 
747  if (!rtp_session->dtmf_data.in_interleaved && rtp_session->last_rtp_hdr.pt != rtp_session->recv_te) {
748  /* Drat, they are sending audio still as well as DTMF ok fine..... *sigh* */
749  rtp_session->dtmf_data.in_interleaved = 1;
750  }
751 
752  if (rtp_session->dtmf_data.in_interleaved || (rtp_session->rtp_bugs & RTP_BUG_IGNORE_DTMF_DURATION)) {
753  if (rtp_session->last_rtp_hdr.pt == rtp_session->recv_te) {
754  return RESULT_GOTO_RECVFROM;
755  }
756  } else {
757  *do_cng = 1;
758  return RESULT_GOTO_TIMERCHECK;
759  }
760  }
761 
762  return RESULT_CONTINUE;
763 }
764 
765 static int rtp_write_ready(switch_rtp_t *rtp_session, uint32_t bytes, int line);
766 static int global_init = 0;
767 static int rtp_common_write(switch_rtp_t *rtp_session,
768  rtp_msg_t *send_msg, void *data, uint32_t datalen, switch_payload_t payload, uint32_t timestamp, switch_frame_flag_t *flags);
769 
770 
771 static switch_status_t ice_out(switch_rtp_t *rtp_session, switch_rtp_ice_t *ice)
772 {
773  uint8_t buf[256] = { 0 };
774  switch_stun_packet_t *packet;
775  unsigned int elapsed;
776  switch_size_t bytes;
778  //switch_sockaddr_t *remote_addr = rtp_session->remote_addr;
779  switch_socket_t *sock_output = rtp_session->sock_output;
781 
782  if (ice->next_run && ice->next_run > now) {
783  return SWITCH_STATUS_BREAK;
784  }
785 
786  ice->next_run = now + RTP_STUN_FREQ;
787 
788  if (ice == &rtp_session->rtcp_ice && rtp_session->rtcp_sock_output) {
789  sock_output = rtp_session->rtcp_sock_output;
790  }
791 
792  if (!sock_output) {
793  return SWITCH_STATUS_FALSE;
794  }
795 
796  switch_assert(rtp_session != NULL);
797  switch_assert(ice->ice_user != NULL);
798 
799  READ_INC(rtp_session);
800 
801  if (rtp_session->last_stun) {
802  elapsed = (unsigned int) ((switch_micro_time_now() - rtp_session->last_stun) / 1000);
803 
804  if (elapsed > 30000) {
805  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "No %s stun for a long time!\n", rtp_type(rtp_session));
806  rtp_session->last_stun = switch_micro_time_now();
807  //status = SWITCH_STATUS_GENERR;
808  //goto end;
809  }
810  }
811 
813  switch_stun_packet_attribute_add_username(packet, ice->ice_user, (uint16_t)strlen(ice->ice_user));
814 
815  memcpy(ice->last_sent_id, packet->header.id, 12);
816 
817  //if (ice->pass && ice->type == ICE_GOOGLE_JINGLE) {
818  // switch_stun_packet_attribute_add_password(packet, ice->pass, (uint16_t)strlen(ice->pass));
819  //}
820 
821  if ((ice->type & ICE_VANILLA)) {
822  char sw[128] = "";
823 
825 
826  switch_snprintf(sw, sizeof(sw), "FreeSWITCH (%s)", switch_version_revision_human());
827  switch_stun_packet_attribute_add_software(packet, sw, (uint16_t)strlen(sw));
828 
829  if ((ice->type & ICE_CONTROLLED)) {
831  } else {
834  }
835 
838  }
839 
840 
841  bytes = switch_stun_packet_length(packet);
842 
843 #ifdef DEBUG_EXTRA
844  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_CRIT, "%s send %s stun\n", rtp_session_name(rtp_session), rtp_type(rtp_session));
845 #endif
846  switch_socket_sendto(sock_output, ice->addr, 0, (void *) packet, &bytes);
847 
848  ice->sending = 3;
849 
850  // end:
851  READ_DEC(rtp_session);
852 
853  return status;
854 }
855 
856 int icecmp(const char *them, switch_rtp_ice_t *ice)
857 {
858  if (strchr(them, ':')) {
859  return strcmp(them, ice->user_ice);
860  }
861 
862  return strcmp(them, ice->luser_ice);
863 }
864 
865 static void handle_ice(switch_rtp_t *rtp_session, switch_rtp_ice_t *ice, void *data, switch_size_t len)
866 {
867  switch_stun_packet_t *packet;
869  void *end_buf;
870  char username[34] = { 0 };
871  unsigned char buf[512] = { 0 };
872  switch_size_t cpylen = len;
873  int xlen = 0;
874  int ok = 1;
875  uint32_t *pri = NULL;
876  int is_rtcp = ice == &rtp_session->rtcp_ice;
877  uint32_t elapsed;
878  switch_time_t ref_point;
879 
880  //if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
881  // switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_WARNING, "WTF OK %s CALL\n", rtp_type(rtp_session));
882  //}
883 
884  if (!switch_rtp_ready(rtp_session) || zstr(ice->user_ice) || zstr(ice->ice_user)) {
885  return;
886  }
887 
888  switch_mutex_lock(rtp_session->ice_mutex);
889 
890  READ_INC(rtp_session);
891  WRITE_INC(rtp_session);
892 
893  if (!switch_rtp_ready(rtp_session)) {
894  goto end;
895  }
896 
897  if (cpylen > sizeof(buf)) {
898  cpylen = sizeof(buf);
899  }
900 
901 
902  memcpy(buf, data, cpylen);
903  packet = switch_stun_packet_parse(buf, (uint32_t)cpylen);
904  if (!packet) {
905  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "Invalid STUN/ICE packet received %ld bytes\n", (long)cpylen);
906  goto end;
907 
908  }
909 
910  rtp_session->last_stun = switch_micro_time_now();
911 
912  if (!rtp_session->first_stun) {
913  rtp_session->first_stun = rtp_session->last_stun;
914  }
915 
916  if (ice->last_ok) {
917  ref_point = ice->last_ok;
918  } else {
919  ref_point = rtp_session->first_stun;
920  }
921 
922  elapsed = (unsigned int) ((switch_micro_time_now() - ref_point) / 1000);
923 
924 
925  end_buf = buf + ((sizeof(buf) > packet->header.length) ? packet->header.length : sizeof(buf));
926 
928  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG8, "%s STUN PACKET TYPE: %s\n",
930  do {
931  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG8, "|---: %s STUN ATTR %d %x %s\n", rtp_type(rtp_session), attr->type, attr->type,
933 
934  switch (attr->type) {
936  {
937  ice->rready = 1;
938  }
939  break;
941  {
943  uint32_t code = (err->code * 100) + err->number;
944 
945  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_WARNING, "%s got %s stun binding response %u %s\n",
946  rtp_session_name(rtp_session),
947  rtp_type(rtp_session),
948  code,
949  err->reason
950  );
951 
952  if ((ice->type & ICE_VANILLA) && code == 487) {
953  if ((ice->type & ICE_CONTROLLED)) {
954  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_WARNING, "%s STUN Changing role to CONTROLLING\n", rtp_type(rtp_session));
955  ice->type &= ~ICE_CONTROLLED;
956  } else {
957  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_WARNING, "%s STUN Changing role to CONTROLLED\n", rtp_type(rtp_session));
958  ice->type |= ICE_CONTROLLED;
959  }
961  }
962 
963  }
964  break;
966  if (attr->type) {
967  char ip[50];
968  uint16_t port;
969  switch_stun_packet_attribute_get_mapped_address(attr, ip, sizeof(ip), &port);
970  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG8, "|------: %s:%d\n", ip, port);
971  }
972  break;
974  if (attr->type) {
975  char ip[50];
976  uint16_t port;
977  switch_stun_packet_attribute_get_xor_mapped_address(attr, &packet->header, ip, sizeof(ip), &port);
978  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG8, "|------: %s:%d\n", ip, port);
979  }
980  break;
982  if (attr->type) {
983  switch_stun_packet_attribute_get_username(attr, username, sizeof(username));
984  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG8, "|------: %s\n", username);
985  }
986  break;
987 
989  {
990  uint32_t priority = 0;
991  pri = (uint32_t *) attr->value;
992  priority = ntohl(*pri);
993  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG8, "|------: %u\n", priority);
994  ok = priority == ice->ice_params->cands[ice->ice_params->chosen[ice->proto]][ice->proto].priority;
995  }
996  break;
997  }
998 
999  if (!switch_stun_packet_next_attribute(attr, end_buf)) {
1000  break;
1001  }
1002 
1003  xlen += 4 + switch_stun_attribute_padded_length(attr);
1004  } while (xlen <= packet->header.length);
1005 
1006  if ((ice->type & ICE_GOOGLE_JINGLE) && ok) {
1007  ok = !strcmp(ice->user_ice, username);
1008  }
1009 
1011  goto end;
1012  }
1013 
1014  if ((ice->type & ICE_VANILLA)) {
1015  char foo1[13] = "", foo2[13] = "";
1016  if (!ok) ok = !memcmp(packet->header.id, ice->last_sent_id, 12);
1017 
1018  if (packet->header.type == SWITCH_STUN_BINDING_RESPONSE) {
1019  ok = 1;
1020  if (!ice->rready) {
1021  if (rtp_session->flags[SWITCH_RTP_FLAG_RTCP_MUX]) {
1022  rtp_session->ice.rready = 1;
1023  rtp_session->rtcp_ice.rready = 1;
1024  } else {
1025  ice->rready = 1;
1026  }
1027 
1028  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
1030  }
1031  }
1032  }
1033 
1034  memcpy(foo1, packet->header.id, 12);
1035  memcpy(foo2, ice->last_sent_id, 12);
1036 
1037  if (!ok && ice == &rtp_session->ice && rtp_session->rtcp_ice.ice_params && pri &&
1038  *pri == rtp_session->rtcp_ice.ice_params->cands[rtp_session->rtcp_ice.ice_params->chosen[1]][1].priority) {
1039  ice = &rtp_session->rtcp_ice;
1040  ok = 1;
1041  }
1042 
1043  if (!zstr(username)) {
1044  if (!icecmp(username, ice)) {
1045  ok = 1;
1046  } else if(!zstr(rtp_session->rtcp_ice.user_ice) && !icecmp(username, &rtp_session->rtcp_ice)) {
1047  ice = &rtp_session->rtcp_ice;
1048  ok = 1;
1049  }
1050  }
1051 
1052  if (ok) {
1053  ice->missed_count = 0;
1054  } else {
1055  switch_rtp_ice_t *icep[2] = { &rtp_session->ice, &rtp_session->rtcp_ice };
1056  switch_port_t port = 0;
1057  char *host = NULL;
1058 
1059  if (elapsed > 20000 && pri) {
1060  int i, j;
1061  uint32_t old;
1062  //const char *tx_host;
1063  const char *old_host, *err = NULL;
1064  //char bufa[50];
1065  char bufb[50];
1066  char adj_port[6];
1067  switch_channel_t *channel = NULL;
1068 
1069 
1070  ice->missed_count++;
1072 
1073 
1074  if (rtp_session->session) {
1075  channel = switch_core_session_get_channel(rtp_session->session);
1076  }
1077 
1078  //ice->ice_params->cands[ice->ice_params->chosen][ice->proto].priority;
1079  for (j = 0; j < 2; j++) {
1080  if (!icep[j] || !icep[j]->ice_params) {
1081  continue;
1082  }
1083  for (i = 0; i < icep[j]->ice_params->cand_idx[icep[j]->proto]; i++) {
1084  if (icep[j]->ice_params && icep[j]->ice_params->cands[i][icep[j]->proto].priority == *pri) {
1085  if (j == IPR_RTP) {
1086  icep[j]->ice_params->chosen[j] = i;
1087  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_INFO, "Change candidate index to %d\n", i);
1088  }
1089 
1090  ice = icep[j];
1091  ok = 1;
1092 
1093  if (j != IPR_RTP) {
1094  break;
1095  }
1096 
1097  old = rtp_session->remote_port;
1098 
1099  //tx_host = switch_get_addr(bufa, sizeof(bufa), rtp_session->from_addr);
1100  old_host = switch_get_addr(bufb, sizeof(bufb), rtp_session->remote_addr);
1101 
1102  host = ice->ice_params->cands[ice->ice_params->chosen[ice->proto]][ice->proto].con_addr;
1103  port = ice->ice_params->cands[ice->ice_params->chosen[ice->proto]][ice->proto].con_port;
1104 
1105  if (!host || !port) {
1106  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "Error setting remote host!\n");
1107  return;
1108  }
1109 
1111  "%s ICE Auto Changing port from %s:%u to %s:%u\n", rtp_type(rtp_session), old_host, old, host, port);
1112 
1113 
1114  if (channel) {
1115  switch_channel_set_variable(channel, "remote_media_ip_reported", switch_channel_get_variable(channel, "remote_media_ip"));
1116  switch_channel_set_variable(channel, "remote_media_ip", host);
1117  switch_channel_set_variable(channel, "rtp_auto_adjust_ip", host);
1118  switch_snprintf(adj_port, sizeof(adj_port), "%u", port);
1119  switch_channel_set_variable(channel, "remote_media_port_reported", switch_channel_get_variable(channel, "remote_media_port"));
1120  switch_channel_set_variable(channel, "remote_media_port", adj_port);
1121  switch_channel_set_variable(channel, "rtp_auto_adjust_port", adj_port);
1122  switch_channel_set_variable(channel, "rtp_auto_candidate_adjust", "true");
1123  }
1124  rtp_session->auto_adj_used = 1;
1125 
1126 
1127  switch_rtp_set_remote_address(rtp_session, host, port, 0, SWITCH_FALSE, &err);
1128  if (switch_sockaddr_info_get(&ice->addr, host, SWITCH_UNSPEC, port, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS ||
1129  !ice->addr) {
1130  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "Error setting remote host!\n");
1131  return;
1132  }
1133 
1134  if ((rtp_session->rtp_bugs & RTP_BUG_ALWAYS_AUTO_ADJUST)) {
1136  } else {
1138  }
1139 
1140  }
1141  }
1142  }
1143  }
1144  }
1145  }
1146 
1147  if (ice->missed_count > 5 && !(ice->type & ICE_GOOGLE_JINGLE)) {
1148  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_WARNING, "missed too many: %d, looking for new ICE dest.\n",
1149  ice->missed_count);
1150  ice->rready = 0;
1151  ok = 1;
1152  }
1153 
1154 
1155  //if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO] || 1) {
1156  // switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_WARNING, "WTF OK %s %d\n", rtp_type(rtp_session), ok);
1157  //}
1158 
1159  if (ok) {
1160  const char *host = NULL, *host2 = NULL;
1161  switch_port_t port = 0, port2 = 0;
1162  char buf[80] = "";
1163  char buf2[80] = "";
1164 
1165  if (packet->header.type == SWITCH_STUN_BINDING_REQUEST) {
1166  uint8_t stunbuf[512];
1167  switch_stun_packet_t *rpacket;
1168  const char *remote_ip;
1169  switch_size_t bytes;
1170  char ipbuf[50];
1171  switch_sockaddr_t *from_addr = rtp_session->from_addr;
1172  switch_socket_t *sock_output = rtp_session->sock_output;
1173  uint8_t do_adj = 0;
1175  int cmp = 0;
1176 
1177  if (is_rtcp) {
1178  from_addr = rtp_session->rtcp_from_addr;
1179  sock_output = rtp_session->rtcp_sock_output;
1180  }
1181 
1182  if (!ice->ready) {
1183  ice->ready = 1;
1184  }
1185 
1186  memset(stunbuf, 0, sizeof(stunbuf));
1188 
1189  if ((ice->type & ICE_GOOGLE_JINGLE)) {
1190  switch_stun_packet_attribute_add_username(rpacket, username, (uint16_t)strlen(username));
1191  }
1192 
1193  remote_ip = switch_get_addr(ipbuf, sizeof(ipbuf), from_addr);
1194 
1195  switch_stun_packet_attribute_add_xor_binded_address(rpacket, (char *) remote_ip, switch_sockaddr_get_port(from_addr), from_addr->family);
1196 
1197  if ((ice->type & ICE_VANILLA)) {
1200  }
1201 
1202  bytes = switch_stun_packet_length(rpacket);
1203 
1204  host = switch_get_addr(buf, sizeof(buf), from_addr);
1205  port = switch_sockaddr_get_port(from_addr);
1206  host2 = switch_get_addr(buf2, sizeof(buf2), ice->addr);
1207  port2 = switch_sockaddr_get_port(ice->addr);
1208  cmp = switch_cmp_addr(from_addr, ice->addr);
1209 
1211  "STUN from %s:%d %s\n", host, port, cmp ? "EXPECTED" : "IGNORED");
1212 
1213  if (cmp) {
1214  ice->last_ok = now;
1215  rtp_session->wrong_addrs = 0;
1216  } else {
1217  if (((rtp_session->dtls && rtp_session->dtls->state != DS_READY) || !ice->ready || !ice->rready) &&
1218  rtp_session->wrong_addrs > 2 && rtp_session->ice_adj == 0) {
1219  do_adj++;
1220  rtp_session->ice_adj = 1;
1221  rtp_session->wrong_addrs = 0;
1222  } else if (rtp_session->wrong_addrs > 10 || elapsed >= 10000) {
1223  do_adj++;
1224  }
1225 
1226  if (!do_adj) {
1227  rtp_session->wrong_addrs++;
1228  }
1229  }
1230 
1231  if ((ice->type & ICE_VANILLA) && ice->ice_params && do_adj) {
1232  int i = 0;
1233 
1234  ice->missed_count = 0;
1235  ice->rready = 1;
1236 
1237  for (i = 0; i <= ice->ice_params->cand_idx[ice->proto]; i++) {
1238  if (ice->ice_params->cands[i][ice->proto].con_port == port) {
1239  if (!strcmp(ice->ice_params->cands[i][ice->proto].con_addr, host) &&
1240  !strcmp(ice->ice_params->cands[i][ice->proto].cand_type, "relay")) {
1241 
1242  if (elapsed < 1000) {
1244  "Skiping RELAY stun/%s/dtls port change from %s:%u to %s:%u\n", is_rtcp ? "rtcp" : "rtp",
1245  host2, port2,
1246  host, port);
1247 
1248  goto end;
1249  }
1250 
1251  break;
1252  }
1253  }
1254  }
1255 
1257  "Auto Changing %s stun/%s/dtls port from %s:%u to %s:%u\n", rtp_type(rtp_session), is_rtcp ? "rtcp" : "rtp",
1258  host2, port2,
1259  host, port);
1260 
1261  switch_rtp_change_ice_dest(rtp_session, ice, host, port);
1262  ice->last_ok = now;
1263  rtp_session->wrong_addrs = 0;
1264  }
1265  if (cmp) {
1266  switch_socket_sendto(sock_output, from_addr, 0, (void *) rpacket, &bytes);
1267  }
1268  }
1269  } else if (packet->header.type == SWITCH_STUN_BINDING_ERROR_RESPONSE) {
1270 
1271  if (rtp_session->session) {
1272  switch_core_session_message_t msg = { 0 };
1273  msg.from = __FILE__;
1274  msg.numeric_arg = packet->header.type;
1275  msg.pointer_arg = packet;
1277  switch_core_session_receive_message(rtp_session->session, &msg);
1279  "STUN/ICE binding error received on %s channel\n", rtp_session->flags[SWITCH_RTP_FLAG_VIDEO] ? "video" : "audio");
1280  }
1281 
1282  }
1283 
1284 
1285 
1286 
1287  end:
1288  switch_mutex_unlock(rtp_session->ice_mutex);
1289  READ_DEC(rtp_session);
1290  WRITE_DEC(rtp_session);
1291 }
1292 
1293 #ifdef ENABLE_ZRTP
1294 SWITCH_STANDARD_SCHED_FUNC(zrtp_cache_save_callback)
1295 {
1296  zrtp_status_t status = zrtp_status_ok;
1297 
1298  status = zrtp_def_cache_store(zrtp_global);
1299  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Saving ZRTP cache: %s\n", zrtp_status_ok == status ? "OK" : "FAIL");
1300  task->runtime = switch_epoch_time_now(NULL) + 900;
1301 }
1302 
1303 static int zrtp_send_rtp_callback(const zrtp_stream_t *stream, char *rtp_packet, unsigned int rtp_packet_length)
1304 {
1305  switch_rtp_t *rtp_session = zrtp_stream_get_userdata(stream);
1306  switch_size_t len = rtp_packet_length;
1307  zrtp_status_t status = zrtp_status_ok;
1308 
1309  switch_socket_sendto(rtp_session->sock_output, rtp_session->remote_addr, 0, rtp_packet, &len);
1310  return status;
1311 }
1312 
1313 static void zrtp_event_callback(zrtp_stream_t *stream, unsigned event)
1314 {
1315  switch_rtp_t *rtp_session = zrtp_stream_get_userdata(stream);
1316  zrtp_session_info_t zrtp_session_info;
1317 
1318  switch_channel_t *channel = switch_core_session_get_channel(rtp_session->session);
1319  switch_event_t *fsevent = NULL;
1320  const char *type;
1321 
1322  type = rtp_type(rtp_session);
1323 
1324  switch (event) {
1325  case ZRTP_EVENT_IS_SECURE:
1326  {
1327  rtp_session->flags[SWITCH_ZRTP_FLAG_SECURE_SEND] = 1;
1328  rtp_session->flags[SWITCH_ZRTP_FLAG_SECURE_RECV] = 1;
1329  if (!rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
1330  rtp_session->flags[SWITCH_ZRTP_FLAG_SECURE_MITM_SEND] = 1;
1331  rtp_session->flags[SWITCH_ZRTP_FLAG_SECURE_MITM_RECV] = 1;
1332  }
1333  if (zrtp_status_ok == zrtp_session_get(stream->session, &zrtp_session_info)) {
1334  if (zrtp_session_info.sas_is_ready) {
1335 
1336  switch_channel_set_variable_name_printf(channel, "true", "zrtp_secure_media_confirmed_%s", type);
1337  switch_channel_set_variable_name_printf(channel, stream->session->sas1.buffer, "zrtp_sas1_string_%s", type);
1338  switch_channel_set_variable_name_printf(channel, stream->session->sas2.buffer, "zrtp_sas2_string", type);
1339  zrtp_verified_set(zrtp_global, &stream->session->zid, &stream->session->peer_zid, (uint8_t)1);
1340  }
1341  }
1342 
1343  if (!rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
1344 
1345 
1346  if (rtp_session->session) {
1347  switch_channel_t *channel = switch_core_session_get_channel(rtp_session->session);
1348  switch_rtp_t *video_rtp_session = switch_channel_get_private(channel, "__zrtp_video_rtp_session");
1349 
1350  if (!video_rtp_session) {
1351  video_rtp_session = switch_channel_get_private_partner(channel, "__zrtp_video_rtp_session");
1352  }
1353 
1354  if (video_rtp_session) {
1355  if (zrtp_status_ok != zrtp_stream_attach(stream->session, &video_rtp_session->zrtp_stream)) {
1356  abort();
1357  }
1358  zrtp_stream_set_userdata(video_rtp_session->zrtp_stream, video_rtp_session);
1359  if (switch_true(switch_channel_get_variable(channel, "zrtp_enrollment"))) {
1360  zrtp_stream_registration_start(video_rtp_session->zrtp_stream, video_rtp_session->ssrc);
1361  } else {
1362  zrtp_stream_start(video_rtp_session->zrtp_stream, video_rtp_session->ssrc);
1363  }
1364  }
1365  }
1366  }
1367 
1369  switch_event_add_header(fsevent, SWITCH_STACK_BOTTOM, "secure_media_type", "%s", type);
1370  switch_event_add_header(fsevent, SWITCH_STACK_BOTTOM, "secure_type", "zrtp:%s:%s", stream->session->sas1.buffer,
1371  stream->session->sas2.buffer);
1372  switch_event_add_header_string(fsevent, SWITCH_STACK_BOTTOM, "caller-unique-id", switch_channel_get_uuid(channel));
1373  switch_event_fire(&fsevent);
1374  }
1375  }
1376  break;
1377 #if 0
1378  case ZRTP_EVENT_NO_ZRTP_QUICK:
1379  {
1380  if (stream != NULL) {
1381  zrtp_stream_stop(stream);
1382  }
1383  }
1384  break;
1385 #endif
1386  case ZRTP_EVENT_IS_CLIENT_ENROLLMENT:
1387  {
1388  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG, "Enrolled complete!\n");
1389  switch_channel_set_variable_name_printf(channel, "true", "zrtp_enroll_complete_%s", type);
1390  }
1391  break;
1392 
1393  case ZRTP_EVENT_USER_ALREADY_ENROLLED:
1394  {
1395  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG, "User already enrolled!\n");
1396  switch_channel_set_variable_name_printf(channel, "true", "zrtp_already_enrolled_%s", type);
1397  }
1398  break;
1399 
1400  case ZRTP_EVENT_NEW_USER_ENROLLED:
1401  {
1402  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG, "New user enrolled!\n");
1403  switch_channel_set_variable_name_printf(channel, "true", "zrtp_new_user_enrolled_%s", type);
1404  }
1405  break;
1406 
1407  case ZRTP_EVENT_USER_UNENROLLED:
1408  {
1409  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG, "User unenrolled!\n");
1410  switch_channel_set_variable_name_printf(channel, "true", "zrtp_user_unenrolled_%s", type);
1411  }
1412  break;
1413 
1414  case ZRTP_EVENT_IS_PENDINGCLEAR:
1415  {
1416  switch_channel_set_variable_name_printf(channel, "false", "zrtp_secure_media_confirmed_%s", type);
1417  rtp_session->flags[SWITCH_ZRTP_FLAG_SECURE_SEND] = 0;
1418  rtp_session->flags[SWITCH_ZRTP_FLAG_SECURE_RECV] = 0;
1419  rtp_session->flags[SWITCH_ZRTP_FLAG_SECURE_MITM_SEND] = 0;
1420  rtp_session->flags[SWITCH_ZRTP_FLAG_SECURE_MITM_RECV] = 0;
1421  rtp_session->zrtp_mitm_tries = 0;
1422  }
1423  break;
1424 
1425  case ZRTP_EVENT_NO_ZRTP:
1426  {
1427  switch_channel_set_variable_name_printf(channel, "false", "zrtp_secure_media_confirmed_%s", type);
1428  }
1429  break;
1430 
1431  default:
1432  break;
1433  }
1434 }
1435 
1436 static void zrtp_logger(int level, const char *data, int len, int offset)
1437 {
1439 }
1440 #endif
1441 
1443 {
1444 #ifdef ENABLE_ZRTP
1445  const char *zid_string = switch_core_get_variable_pdup("switch_serial", pool);
1446  const char *zrtp_enabled = switch_core_get_variable_pdup("zrtp_enabled", pool);
1447  zrtp_config_t zrtp_config;
1448  char zrtp_cache_path[256] = "";
1449  zrtp_on = zrtp_enabled ? switch_true(zrtp_enabled) : 0;
1450 #endif
1451  if (global_init) {
1452  return;
1453  }
1454  switch_core_hash_init(&alloc_hash);
1455 #ifdef ENABLE_ZRTP
1456  if (zrtp_on) {
1457  uint32_t cache_len;
1458  zrtp_config_defaults(&zrtp_config);
1459  strcpy(zrtp_config.client_id, "FreeSWITCH");
1460  zrtp_config.is_mitm = 1;
1461  zrtp_config.lic_mode = ZRTP_LICENSE_MODE_ACTIVE;
1462  switch_snprintf(zrtp_cache_path, sizeof(zrtp_cache_path), "%s%szrtp.dat", SWITCH_GLOBAL_dirs.db_dir, SWITCH_PATH_SEPARATOR);
1463  cache_len=(uint32_t)strlen(zrtp_cache_path);
1464  ZSTR_SET_EMPTY(zrtp_config.def_cache_path);
1465  zrtp_config.def_cache_path.length = cache_len > zrtp_config.def_cache_path.max_length ? zrtp_config.def_cache_path.max_length : (uint16_t)cache_len;
1466  strncpy(zrtp_config.def_cache_path.buffer, zrtp_cache_path, zrtp_config.def_cache_path.max_length);
1467  zrtp_config.cb.event_cb.on_zrtp_protocol_event = (void (*)(zrtp_stream_t*,zrtp_protocol_event_t))zrtp_event_callback;
1468  zrtp_config.cb.misc_cb.on_send_packet = zrtp_send_rtp_callback;
1469  zrtp_config.cb.event_cb.on_zrtp_security_event = (void (*)(zrtp_stream_t*,zrtp_security_event_t))zrtp_event_callback;
1470  zrtp_log_set_log_engine((zrtp_log_engine *) zrtp_logger);
1471  zrtp_log_set_level(4);
1472  if (zrtp_status_ok == zrtp_init(&zrtp_config, &zrtp_global)) {
1473  memcpy(zid, zid_string, 12);
1474  switch_scheduler_add_task(switch_epoch_time_now(NULL) + 900, zrtp_cache_save_callback, "zrtp_cache_save", "core", 0, NULL,
1476  } else {
1477  switch_core_set_variable("zrtp_enabled", NULL);
1478  zrtp_on = 0;
1479  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "ZRTP init failed!\n");
1480  }
1481  }
1482 #endif
1483 #ifdef ENABLE_SRTP
1484  srtp_init();
1485 #endif
1487  global_init = 1;
1488 }
1489 
1490 static uint8_t get_next_write_ts(switch_rtp_t *rtp_session, uint32_t timestamp)
1491 {
1492  uint8_t m = 0;
1493 
1494  if (rtp_session->rtp_bugs & RTP_BUG_SEND_LINEAR_TIMESTAMPS) {
1495  rtp_session->ts += rtp_session->samples_per_interval;
1496  if (rtp_session->ts <= rtp_session->last_write_ts && rtp_session->ts > 0) {
1497  rtp_session->ts = rtp_session->last_write_ts + rtp_session->samples_per_interval;
1498  }
1499  } else if (timestamp) {
1500  rtp_session->ts = (uint32_t) timestamp;
1501  /* Send marker bit if timestamp is lower/same as before (resetted/new timer) */
1502  if (rtp_session->ts <= rtp_session->last_write_ts && !(rtp_session->rtp_bugs & RTP_BUG_NEVER_SEND_MARKER)) {
1503  m++;
1504  }
1505  } else if (switch_rtp_test_flag(rtp_session, SWITCH_RTP_FLAG_USE_TIMER)) {
1506  rtp_session->ts = rtp_session->timer.samplecount;
1507 
1508  if (rtp_session->ts <= rtp_session->last_write_ts && rtp_session->ts > 0) {
1509  rtp_session->ts = rtp_session->last_write_ts + rtp_session->samples_per_interval;
1510  }
1511  } else {
1512  rtp_session->ts += rtp_session->samples_per_interval;
1513  if (rtp_session->ts <= rtp_session->last_write_ts && rtp_session->ts > 0) {
1514  rtp_session->ts = rtp_session->last_write_ts + rtp_session->samples_per_interval;
1515  }
1516  }
1517 
1518  return m;
1519 }
1520 
1521 static void do_mos(switch_rtp_t *rtp_session, int force) {
1522 
1523  if ((switch_size_t)rtp_session->stats.inbound.recved < rtp_session->stats.inbound.flaws) {
1524  rtp_session->stats.inbound.flaws = 0;
1525  }
1526 
1527  if (rtp_session->stats.inbound.recved > 0 &&
1528  rtp_session->stats.inbound.flaws && (force || rtp_session->stats.inbound.last_flaw != rtp_session->stats.inbound.flaws)) {
1529  int R;
1530 
1531  if (rtp_session->consecutive_flaws++) {
1532  int diff, penalty;
1533 
1534  diff = (rtp_session->stats.inbound.flaws - rtp_session->stats.inbound.last_flaw);
1535 
1536  if (diff < 1) diff = 1;
1537 
1538  penalty = diff * 2;
1539 
1540  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG3, "%s %s %d consecutive flaws, adding %d flaw penalty\n",
1541  rtp_session_name(rtp_session), rtp_type(rtp_session),
1542  rtp_session->consecutive_flaws, penalty);
1543  rtp_session->bad_stream++;
1544  rtp_session->stats.inbound.flaws += penalty;
1545  }
1546 
1547  R = (int)((double)((double)(rtp_session->stats.inbound.recved - rtp_session->stats.inbound.flaws) / (double)rtp_session->stats.inbound.recved) * 100.0);
1548 
1549  if (R < 0 || R > 100) R = 100;
1550 
1551  rtp_session->stats.inbound.R = R;
1552  rtp_session->stats.inbound.mos = 1 + (0.035) * R + (.000007) * R * (R-60) * (100-R);
1553  rtp_session->stats.inbound.last_flaw = rtp_session->stats.inbound.flaws;
1554  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG3, "%s %s stat %0.2f %ld/%d flaws: %ld mos: %0.2f v: %0.2f %0.2f/%0.2f\n",
1555  rtp_session_name(rtp_session),
1556  rtp_type(rtp_session),
1557  rtp_session->stats.inbound.R,
1558  (long int)(rtp_session->stats.inbound.recved - rtp_session->stats.inbound.flaws), rtp_session->stats.inbound.recved,
1559  (long int)rtp_session->stats.inbound.flaws,
1560  rtp_session->stats.inbound.mos,
1561  rtp_session->stats.inbound.variance,
1562  rtp_session->stats.inbound.min_variance,
1563  rtp_session->stats.inbound.max_variance
1564  );
1565  } else {
1566  rtp_session->consecutive_flaws = 0;
1567  }
1568 }
1569 
1570 void burstr_calculate ( int loss[], int received, double *burstr, double *lossr )
1571 {
1572  int lost = 0;
1573  int bursts = 0;
1574  int i;
1575 
1576  for ( i = 0; i < LOST_BURST_ANALYZE; i++ ) {
1577  lost += i * loss[i];
1578  bursts += loss[i];
1579  }
1580  if (received > 0 && bursts > 0) {
1581  *burstr = (double)((double)lost / (double)bursts) / (double)(1.0 / ( 1.0 - (double)lost / (double)received ));
1582  if (*burstr < 0) {
1583  *burstr = - *burstr;
1584  }
1585  } else {
1586  *burstr = 0;
1587  }
1588  if (received > 0) {
1589  *lossr = (double)((double)lost / (double)received);
1590  } else {
1591  *lossr = 0;
1592  }
1593 }
1594 
1595 static void reset_jitter_seq(switch_rtp_t *rtp_session)
1596 {
1597  rtp_session->stats.inbound.last_proc_time = 0;
1598  rtp_session->stats.inbound.last_processed_seq = 0;
1599  rtp_session->jitter_lead = 0;
1600  rtp_session->consecutive_flaws = 0;
1601  rtp_session->stats.inbound.last_flaw = 0;
1602 }
1603 
1604 static void check_jitter(switch_rtp_t *rtp_session)
1605 {
1606  switch_time_t current_time;
1607  int64_t diff_time = 0, cur_diff = 0;
1608  int seq;
1609 
1610  current_time = switch_micro_time_now() / 1000;
1611 
1612  if (rtp_session->flags[SWITCH_RTP_FLAG_PAUSE] || rtp_session->flags[SWITCH_RTP_FLAG_DTMF_ON] || rtp_session->dtmf_data.in_digit_ts) {
1613  reset_jitter_seq(rtp_session);
1614  return;
1615  }
1616 
1617  if (++rtp_session->jitter_lead < JITTER_LEAD_FRAMES || !rtp_session->stats.inbound.last_proc_time) {
1618  rtp_session->stats.inbound.last_proc_time = current_time;
1619  return;
1620  }
1621 
1622  diff_time = (current_time - rtp_session->stats.inbound.last_proc_time);
1623  seq = (int)(uint16_t) ntohs((uint16_t) rtp_session->last_rtp_hdr.seq);
1624 
1625  /* Burst and Packet Loss */
1626  rtp_session->stats.inbound.recved++;
1627 
1628  if (rtp_session->stats.inbound.last_processed_seq > 0 && seq > (int)(rtp_session->stats.inbound.last_processed_seq + 1)) {
1629  int lost = (seq - rtp_session->stats.inbound.last_processed_seq - 1);
1630 
1631  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG1, "%s Got: %s seq %d but expected: %d lost: %d\n",
1632  rtp_session_name(rtp_session),
1633  rtp_type(rtp_session),
1634  seq,
1635  (rtp_session->stats.inbound.last_processed_seq + 1), lost);
1636  rtp_session->stats.inbound.last_loss++;
1637 
1638  if (rtp_session->stats.inbound.last_loss > 0 && rtp_session->stats.inbound.last_loss < LOST_BURST_CAPTURE) {
1639  rtp_session->stats.inbound.loss[rtp_session->stats.inbound.last_loss] += lost;
1640  }
1641 
1642  rtp_session->bad_stream++;
1643  rtp_session->stats.inbound.flaws += lost;
1644  } else {
1645  rtp_session->stats.inbound.last_loss = 0;
1646  }
1647 
1648  rtp_session->stats.inbound.last_processed_seq = seq;
1649 
1650  /* Burst and Packet Loss */
1651 
1652  if (current_time > rtp_session->next_stat_check_time) {
1653  rtp_session->next_stat_check_time = current_time + 5000;
1654  burstr_calculate(rtp_session->stats.inbound.loss, rtp_session->stats.inbound.recved,
1655  &(rtp_session->stats.inbound.burstrate), &(rtp_session->stats.inbound.lossrate));
1656  do_mos(rtp_session, SWITCH_TRUE);
1657  } else {
1658  do_mos(rtp_session, SWITCH_FALSE);
1659  }
1660 
1661  if (rtp_session->stats.inbound.last_loss || rtp_session->bad_stream) {
1662  if (rtp_session->session && (!rtp_session->stats.inbound.error_log || rtp_session->stats.inbound.error_log->stop)) {
1663  struct error_period *error = switch_core_session_alloc(rtp_session->session, sizeof(*error));
1664  error->start = switch_micro_time_now();
1665  error->next = rtp_session->stats.inbound.error_log;
1666  rtp_session->stats.inbound.error_log = error;
1667  }
1668 
1669  if (!rtp_session->stats.inbound.last_loss) {
1670  if (++rtp_session->recovering_stream > (rtp_session->one_second * 3)) {
1671  if (rtp_session->session && rtp_session->stats.inbound.error_log) {
1672  rtp_session->stats.inbound.error_log->stop = switch_micro_time_now();
1673  }
1674 
1675  rtp_session->bad_stream = 0;
1676  }
1677  } else {
1678  rtp_session->recovering_stream = 0;
1679  rtp_session->bad_stream++;
1680  }
1681  } else {
1682  rtp_session->recovering_stream = 0;
1683  rtp_session->clean_stream++;
1684  }
1685 
1686 
1687  if ( diff_time < 0 ) {
1688  diff_time = -diff_time;
1689  }
1690 
1691  rtp_session->stats.inbound.jitter_n++;
1692  rtp_session->stats.inbound.jitter_add += diff_time;
1693 
1694  cur_diff = (int64_t)(diff_time - rtp_session->stats.inbound.mean_interval);
1695 
1696  rtp_session->stats.inbound.jitter_addsq += (cur_diff * cur_diff);
1697  rtp_session->stats.inbound.last_proc_time = current_time;
1698 
1699  if (rtp_session->stats.inbound.jitter_n > 0) {
1700  double ipdv;
1701 
1702  rtp_session->stats.inbound.mean_interval = (double)rtp_session->stats.inbound.jitter_add / (double)rtp_session->stats.inbound.jitter_n;
1703 
1704  if (!rtp_session->old_mean) {
1705  rtp_session->old_mean = rtp_session->stats.inbound.mean_interval;
1706  }
1707 
1708  rtp_session->stats.inbound.variance = (double)rtp_session->stats.inbound.jitter_addsq / (double)rtp_session->stats.inbound.jitter_n;
1709 
1710  //printf("CHECK %d +%ld +%ld %f %f\n", rtp_session->timer.samplecount, diff_time, (diff_time * diff_time), rtp_session->stats.inbound.mean_interval, rtp_session->stats.inbound.variance);
1711 
1712  ipdv = rtp_session->old_mean - rtp_session->stats.inbound.mean_interval;
1713 
1714  if ( ipdv > IPDV_THRESHOLD ) { /* It shows Increasing Delays */
1715  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG3, "Calculated Instantaneous Packet Delay Variation: %s packet %lf\n",
1716  rtp_type(rtp_session), ipdv);
1717  }
1718 
1719  if ( rtp_session->stats.inbound.variance < rtp_session->stats.inbound.min_variance || rtp_session->stats.inbound.min_variance == 0 ) {
1720  rtp_session->stats.inbound.min_variance = rtp_session->stats.inbound.variance;
1721  }
1722 
1723  if ( rtp_session->stats.inbound.variance > rtp_session->stats.inbound.max_variance ) {
1724  rtp_session->stats.inbound.max_variance = rtp_session->stats.inbound.variance;
1725  }
1726 
1727  rtp_session->old_mean = rtp_session->stats.inbound.mean_interval;
1728  }
1729 }
1730 
1731 static void rtcp_generate_sender_info(switch_rtp_t *rtp_session, struct switch_rtcp_sender_info *sr){
1732  switch_core_session_t *session = switch_core_memory_pool_get_data(rtp_session->pool, "__session");
1733  switch_time_t now;
1734  uint32_t sec, ntp_sec, ntp_usec;
1735  switch_time_exp_t now_hr;
1736  now = switch_time_now();
1737  sec = (uint32_t)(now/1000000); /* convert to seconds */
1738  ntp_sec = sec+NTP_TIME_OFFSET; /* convert to NTP seconds */
1739  sr->ntp_msw = htonl(ntp_sec); /* store result in "most significant word" */
1740  ntp_usec = (uint32_t)(now - (sec*1000000)); /* remove seconds to keep only the microseconds */
1741  sr->ntp_lsw = htonl((u_long)(ntp_usec*(double)(((uint64_t)1)<<32)*1.0e-6)); /* convert microseconds to fraction of 32bits and store result in "least significatn word" */
1742 
1743  sr->ts = htonl(rtp_session->last_write_ts);
1744  sr->pc = htonl(rtp_session->stats.outbound.packet_count);
1745  sr->oc = htonl((rtp_session->stats.outbound.raw_bytes - rtp_session->stats.outbound.packet_count * sizeof(srtp_hdr_t)));
1746 
1747  switch_time_exp_gmt(&now_hr,now);
1748  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG10,"Sending an RTCP packet[%04d-%02d-%02d %02d:%02d:%02d.%d] lsr[%u] msw[%u] lsw[%u] stats_ssrc[%u]\n",
1749  1900 + now_hr.tm_year, now_hr.tm_mday, now_hr.tm_mon, now_hr.tm_hour, now_hr.tm_min, now_hr.tm_sec, now_hr.tm_usec,
1750  (ntohl(sr->ntp_lsw)&0xffff0000)>>16 | (ntohl(sr->ntp_msw)&0x0000ffff)<<16,
1751  ntohl(sr->ntp_msw),ntohl(sr->ntp_lsw), rtp_session->stats.rtcp.ssrc
1752  );
1753 }
1754 
1755 //#define DEBUG_RTCP
1756 static void rtcp_generate_report_block(switch_rtp_t *rtp_session, struct switch_rtcp_report_block *rtcp_report_block){
1757 #ifdef DEBUG_RTCP
1758  switch_core_session_t *session = switch_core_memory_pool_get_data(rtp_session->pool, "__session");
1759 #endif
1760  switch_rtcp_numbers_t * stats=&rtp_session->stats.rtcp;
1761  switch_time_t now;
1762  uint32_t expected_pkt, dlsr;
1763  int32_t pkt_lost;
1764  uint32_t ntp_sec, ntp_usec, lsr_now, sec;
1765  now = switch_time_now();
1766  sec = (uint32_t)(now/1000000); /* convert to seconds */
1767  ntp_sec = sec+NTP_TIME_OFFSET; /* convert to NTP seconds */
1768  ntp_usec = (uint32_t)(now - (sec*1000000)); /* remove seconds to keep only the microseconds */
1769 
1770  /* Packet loss */
1771  if (stats->rtcp_rtp_count == 0) {
1772  expected_pkt = stats->high_ext_seq_recv - stats->base_seq + 1;
1773  } else {
1774  expected_pkt = stats->high_ext_seq_recv - stats->last_rpt_ext_seq;
1775  }
1776 
1777  pkt_lost = expected_pkt - stats->period_pkt_count;
1778  stats->cum_lost=stats->cum_lost+pkt_lost;
1779  if (expected_pkt > 0 && pkt_lost > 0) {
1780  rtcp_report_block->fraction = (uint8_t) (pkt_lost * 256 / expected_pkt);
1781  } else {
1782  rtcp_report_block->fraction = 0;
1783  }
1784 #if SWITCH_BYTE_ORDER != __BIG_ENDIAN
1785  /* Reversing byte order for 24bits */
1786  rtcp_report_block->lost = (((stats->cum_lost&0x0000FF)<<16) | ((stats->cum_lost&0x00FF00)) | ((stats->cum_lost&0xFF0000)>>16));
1787 #endif
1788 
1789 #ifdef DEBUG_RTCP
1790  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO])
1791  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_CRIT, "rtcp_generate_sr: stats_ssrc[%u]\nreceived[%d]\nexpected[%d]\ncum[%d]\nlost[%d|%d/256]pkt\nlast_seq[%d]\ncyc[%d]\nlast_rpt_seq[%d]\ncyc[%d]\nssrc[%d]\n",
1792  rtp_session->remote_ssrc, stats->period_pkt_count, expected_pkt,
1793  stats->cum_lost, pkt_lost, rtcp_report_block->fraction, stats->high_ext_seq_recv&0x0000ffff,
1794  stats->cycle, stats->last_rpt_ext_seq&0x0000ffff, stats->last_rpt_cycle, rtp_session->stats.rtcp.peer_ssrc
1795  );
1796 #endif
1797  rtcp_report_block->highest_sequence_number_received = htonl(stats->high_ext_seq_recv);
1798 
1799  /* Jitter */
1800  rtcp_report_block->jitter = htonl((uint32_t)stats->inter_jitter);
1801 
1802  /* Delay since Last Sender Report (DLSR) : 32bits, 1/65536 seconds */
1803  lsr_now = (uint32_t)(ntp_usec*0.065536) | (ntp_sec&0x0000ffff)<<16; /* 0.065536 is used for convertion from useconds to fraction of 65536 (x65536/1000000) */
1804 
1805  if (stats->last_recv_lsr_local) {
1806  dlsr = lsr_now - stats->last_recv_lsr_local;
1807  } else {
1808  dlsr = 0;
1809  }
1810  rtcp_report_block->lsr = stats->last_recv_lsr_peer;
1811  rtcp_report_block->dlsr = htonl(dlsr);
1812  rtcp_report_block->ssrc = htonl(rtp_session->stats.rtcp.peer_ssrc);
1813  stats->rtcp_rtp_count++;
1814 }
1815 
1816 static void rtcp_stats_init(switch_rtp_t *rtp_session)
1817 {
1818  switch_rtcp_numbers_t * stats = &rtp_session->stats.rtcp;
1819  srtp_hdr_t * hdr = &rtp_session->last_rtp_hdr;
1820  switch_core_session_t *session = switch_core_memory_pool_get_data(rtp_session->pool, "__session");
1821  stats->ssrc = ntohl(hdr->ssrc);
1822  stats->last_rpt_ts = rtp_session->timer.samplecount;
1823  stats->init = 1;
1824  stats->last_rpt_ext_seq = 0;
1825  stats->last_rpt_cycle = 0;
1826  stats->last_pkt_tsdiff = 0;
1827  stats->inter_jitter = 0;
1828  stats->cycle = 0;
1829  stats->high_ext_seq_recv = ntohs((uint16_t)hdr->seq);
1830  stats->base_seq = ntohs((uint16_t)hdr->seq);
1831  stats->bad_seq = (1<<16) + 1; /* Make sure we wont missmatch 2 consecutive packets, so seq == bad_seq is false */
1832  stats->cum_lost = 0;
1833  stats->period_pkt_count = 0;
1834  stats->sent_pkt_count = 0;
1835  stats->pkt_count = 0;
1836  stats->rtcp_rtp_count = 0;
1837 
1838  if (!rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP]) {
1839  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "rtcp_stats_init: %s rtcp disabled\n", rtp_type(rtp_session));
1840  } else if (!rtp_session->rtcp_sock_output) {
1841  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_WARNING, "rtcp_stats_init: %s no rtcp socket\n", rtp_type(rtp_session));
1842  } else if (rtp_session->flags[SWITCH_RTP_FLAG_RTCP_PASSTHRU]) {
1843  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "rtcp_stats_init: %s rtcp passthru\n", rtp_type(rtp_session));
1844  } else {
1845  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "rtcp_stats_init: %s ssrc[%u] base_seq[%u]\n", rtp_type(rtp_session), stats->ssrc, stats->base_seq);
1846  }
1847 }
1848 
1849 static int rtcp_stats(switch_rtp_t *rtp_session)
1850 {
1851  switch_core_session_t *session = switch_core_memory_pool_get_data(rtp_session->pool, "__session");
1852  srtp_hdr_t * hdr = &rtp_session->last_rtp_hdr;
1853  switch_rtcp_numbers_t * stats = &rtp_session->stats.rtcp;
1854  uint32_t packet_spacing_diff = 0, pkt_tsdiff, pkt_extended_seq;
1855  uint16_t pkt_seq, seq_diff, max_seq;
1856  const int MAX_DROPOUT = 3000;
1857  const int MAX_MISORDER = 100;
1858  const int RTP_SEQ_MOD = (1<<16);
1859 
1860  if(!rtp_session->rtcp_sock_output || !rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP] || rtp_session->flags[SWITCH_RTP_FLAG_RTCP_PASSTHRU] || !rtp_session->rtcp_interval)
1861  return 0; /* do not process RTCP in current state */
1862 
1863  pkt_seq = (uint16_t) ntohs((uint16_t) rtp_session->last_rtp_hdr.seq);
1864 
1865  /* Detect sequence number cycle change */
1866  max_seq = stats->high_ext_seq_recv&0x0000ffff;
1867  seq_diff = pkt_seq - max_seq;
1868 
1869  if (seq_diff < MAX_DROPOUT) { /* in order, with permissible gap */
1870  if (pkt_seq < max_seq) {
1871  stats->cycle++;
1872  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "rtcp_stats:[cycle change] pkt_seq[%d] cycle[%d] max_seq[%d] stats_ssrc[%u] local_ts[%u]\n",
1873  pkt_seq, stats->cycle, max_seq, stats->ssrc, rtp_session->timer.samplecount);
1874  }
1875  pkt_extended_seq = stats->cycle << 16 | pkt_seq; /* getting the extended packet extended sequence ID */
1876  if (pkt_extended_seq > stats->high_ext_seq_recv) {
1877  stats->high_ext_seq_recv = pkt_extended_seq;
1878  }
1879  }
1880  else if (seq_diff <= (RTP_SEQ_MOD - MAX_MISORDER)) { /* the sequence number made a very large jump */
1881  if (pkt_seq == stats->bad_seq) {
1882  rtcp_stats_init(rtp_session);
1883  } else {
1884  stats->bad_seq = (pkt_seq + 1) & (RTP_SEQ_MOD-1);
1885  }
1886  return 0; /* no stats, packet is out of sync and will be accounted as lost */
1887  } else {
1888  /* duplicate or reordered packet */
1889  }
1890 
1891  /* Verify that we are on the same stream source (we do not support multiple sources) */
1892  if (ntohl(hdr->ssrc) != stats->ssrc || !stats->init) {
1893  rtcp_stats_init(rtp_session);
1894  }
1895 
1896  stats->period_pkt_count++;
1897  stats->pkt_count++;
1898 #ifdef DEBUG_RTCP
1899  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG10, "rtcp_stats: period_pkt_count[%d]last_seq[%d]cycle[%d]stats_ssrc[%u]local_ts[%u]\n",
1900  stats->period_pkt_count, pkt_seq, stats->cycle, stats->ssrc, rtp_session->timer.samplecount);
1901 #endif
1902  /* Interarrival jitter calculation */
1903  pkt_tsdiff = abs((int)rtp_session->timer.samplecount - (int)ntohl(hdr->ts)); /* relative transit times for this packet */
1904  if (stats->pkt_count < 2) { /* Can not compute Jitter with only one packet */
1905  stats->last_pkt_tsdiff = pkt_tsdiff;
1906  } else {
1907  packet_spacing_diff = abs((int)pkt_tsdiff - (int)stats->last_pkt_tsdiff); /* Jitter : difference of relative transit times for the two packets */
1908  stats->last_pkt_tsdiff = pkt_tsdiff;
1909  /* Interarrival jitter estimation, "J(i) = J(i-1) + ( |D(i-1,i)| - J(i-1) )/16" */
1910  stats->inter_jitter = (stats->inter_jitter + (((double)packet_spacing_diff - stats->inter_jitter) /16.));
1911  }
1912 
1913 #ifdef DEBUG_RTCP
1914  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG10, "rtcp_stats: pkt_ts[%d]local_ts[%d]diff[%d]pkt_spacing[%d]inter_jitter[%f]seq[%d]stats_ssrc[%d]",
1915  ntohl(hdr->ts), rtp_session->timer.samplecount, pkt_tsdiff, packet_spacing_diff, stats->inter_jitter, ntohs(hdr->seq), stats->ssrc);
1916 #endif
1917  return 1;
1918 }
1919 
1920 static void calc_bw_exp(uint32_t bps, uint8_t bits, rtcp_tmmbx_t *tmmbx)
1921 {
1922  uint32_t mantissa_max, i = 0;
1923  uint8_t exp = 0;
1924  uint32_t mantissa = 0;
1925  uint16_t overhead = 60;
1926 
1927  switch_assert(bits<=32);
1928 
1929  mantissa_max = (1 << bits) - 1;
1930 
1931  for (i = 0; i < 32; ++i) {
1932  if (bps <= (mantissa_max << i)) {
1933  exp = i;
1934  break;
1935  }
1936  }
1937 
1938  mantissa = (bps >> exp);
1939 
1940  tmmbx->parts[0] = (uint8_t) ((exp << 2) + ((mantissa >> 15) & 0x03));
1941  tmmbx->parts[1] = (uint8_t) (mantissa >> 7);
1942  tmmbx->parts[2] = (uint8_t) ((mantissa >> 1) + ((overhead >> 8) & 0x01));
1943  tmmbx->parts[3] = (uint8_t) (overhead);
1944 }
1945 
1946 static int using_ice(switch_rtp_t *rtp_session)
1947 {
1948  if (rtp_session->ice.ice_user || rtp_session->rtcp_ice.ice_user) {
1949  return 1;
1950  }
1951 
1952  return 0;
1953 }
1954 
1955 #define MAX_NACK 10
1956 static int check_rtcp_and_ice(switch_rtp_t *rtp_session)
1957 {
1958  int ret = 0;
1959  int rtcp_ok = 0, rtcp_fb = 0;
1961  int rate = 0, nack_ttl = 0;
1962  uint32_t cur_nack[MAX_NACK] = { 0 };
1963 
1964  if (!rtp_session->flags[SWITCH_RTP_FLAG_UDPTL] &&
1965  rtp_session->flags[SWITCH_RTP_FLAG_AUTO_CNG] &&
1966  rtp_session->send_msg.header.ts &&
1967  rtp_session->cng_pt != INVALID_PT &&
1968  (rtp_session->timer.samplecount - rtp_session->last_write_samplecount >= rtp_session->samples_per_interval * 60)) {
1969  uint8_t data[10] = { 0 };
1970  switch_frame_flag_t frame_flags = SFF_NONE;
1971  data[0] = 65;
1972  rtp_session->cn++;
1973 
1974  get_next_write_ts(rtp_session, 0);
1975  rtp_session->send_msg.header.ts = htonl(rtp_session->ts);
1976 
1977  switch_rtp_write_manual(rtp_session, (void *) data, 2, 0, rtp_session->cng_pt, ntohl(rtp_session->send_msg.header.ts), &frame_flags);
1978 
1979  if (switch_rtp_test_flag(rtp_session, SWITCH_RTP_FLAG_USE_TIMER)) {
1980  rtp_session->last_write_samplecount = rtp_session->timer.samplecount;
1981  }
1982  }
1983 
1984  rate = rtp_session->rtcp_interval;
1985 
1986  if (rtp_session->flags[SWITCH_RTP_FLAG_NACK] && rtp_session->vb) {
1987  int n;
1988  for (n = 0; n < MAX_NACK; n++) {
1989  uint32_t nack = switch_jb_pop_nack(rtp_session->vb);
1990 
1991  if (!nack) break;
1992 
1993  cur_nack[nack_ttl++] = nack;
1994  }
1995  }
1996 
1997 
1998 
1999  if (rtp_session->rtcp_sent_packets < 4) {
2000  rate = 4000;
2001  } else {
2002  if (rtp_session->pli_count || rtp_session->fir_count || nack_ttl || rtp_session->tmmbr || rtp_session->tmmbn) {
2003  //switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "MARK BW/FIR ETC %d %d\n", rtp_session->pli_count, rtp_session->fir_count);
2004  rtcp_ok = 1;
2005  rtcp_fb = 1;
2006  }
2007  }
2008 
2009  //switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "TIME CHECK %d > %d\n", (int)((now - rtp_session->rtcp_last_sent) / 1000), rate);
2010 
2011  if (!rtcp_ok && (!rtp_session->rtcp_last_sent || (int)((now - rtp_session->rtcp_last_sent) / 1000) > rate)) {
2012  //switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "TIME UP\n");
2013  rtcp_ok = 1;
2014  }
2015 
2016  if (rtcp_ok && using_ice(rtp_session)) {
2017  if (rtp_session->flags[SWITCH_RTP_FLAG_RTCP_MUX]) {
2018  if (!rtp_session->ice.rready) {
2019  rtcp_ok = 0;
2020  }
2021  } else {
2022  if (!rtp_session->rtcp_ice.rready) {
2023  rtcp_ok = 0;
2024  }
2025  }
2026  }
2027 
2028  //switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "WTF %d %d %d %d\n", rate, rtp_session->rtcp_sent_packets, rtcp_ok, nack_ttl);
2029 
2030  if (rtp_session->rtcp_sock_output && rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP] && !rtp_session->flags[SWITCH_RTP_FLAG_RTCP_PASSTHRU] && rtcp_ok) {
2031  switch_rtcp_numbers_t * stats = &rtp_session->stats.rtcp;
2032  struct switch_rtcp_receiver_report *rr;
2033  struct switch_rtcp_sender_report *sr;
2034  struct switch_rtcp_report_block *rtcp_report_block;
2035  switch_size_t rtcp_bytes = sizeof(struct switch_rtcp_hdr_s)+sizeof(uint32_t); /* add size of the packet header and the ssrc */
2036  switch_rtcp_hdr_t *sdes;
2037  uint8_t *p;
2038  switch_size_t sdes_bytes = sizeof(struct switch_rtcp_hdr_s);
2039  uint32_t *ssrc;
2041 
2042  if (!rtcp_fb) {
2043  rtp_session->rtcp_last_sent = now;
2044  rtp_session->rtcp_sent_packets++;
2045  }
2046 
2047  rtp_session->rtcp_send_msg.header.version = 2;
2048  rtp_session->rtcp_send_msg.header.p = 0;
2049  rtp_session->rtcp_send_msg.header.count = 1;
2050 
2051 
2052  if (!rtp_session->stats.rtcp.sent_pkt_count) {
2053  rtp_session->rtcp_send_msg.header.type = _RTCP_PT_RR; /* Receiver report */
2054  rr=(struct switch_rtcp_receiver_report*) rtp_session->rtcp_send_msg.body;
2055  rr->ssrc = htonl(rtp_session->ssrc);
2056  rtcp_report_block = &rr->report_block;
2057  rtcp_bytes += sizeof(struct switch_rtcp_report_block);
2058  } else {
2059  struct switch_rtcp_sender_info *rtcp_sender_info;
2060  rtp_session->rtcp_send_msg.header.type = _RTCP_PT_SR; /* Sender report */
2061  sr = (struct switch_rtcp_sender_report*) rtp_session->rtcp_send_msg.body;
2062  sr->ssrc = htonl(rtp_session->ssrc);
2063  rtcp_sender_info = &sr->sender_info;
2064  rtcp_generate_sender_info(rtp_session, rtcp_sender_info);
2065  rtcp_report_block = &sr->report_block;
2066  rtcp_bytes += sizeof(struct switch_rtcp_sender_info) + sizeof(struct switch_rtcp_report_block);
2067  }
2068  rtcp_generate_report_block(rtp_session, rtcp_report_block);
2069 
2070  rtp_session->rtcp_send_msg.header.length = htons((uint16_t)(rtcp_bytes / 4) - 1);
2071 
2072  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
2073  //if (rtp_session->remote_ssrc == 0) {
2074  // rtp_session->remote_ssrc = rtp_session->stats.rtcp.peer_ssrc;
2075  //}
2076 
2077  //if (rtp_session->remote_ssrc == 0) {
2078  // rtp_session->remote_ssrc = ntohl(rtp_session->last_rtp_hdr.ssrc);
2079  //}
2080 
2081 
2082  if (rtp_session->pli_count) {
2083  switch_rtcp_ext_hdr_t *ext_hdr;
2084 
2085  p = (uint8_t *) (&rtp_session->rtcp_send_msg) + rtcp_bytes;
2086  ext_hdr = (switch_rtcp_ext_hdr_t *) p;
2087 
2088  ext_hdr->version = 2;
2089  ext_hdr->p = 0;
2090  ext_hdr->fmt = _RTCP_PSFB_PLI;
2091  ext_hdr->pt = _RTCP_PT_PSFB;
2092 
2093  ext_hdr->send_ssrc = htonl(rtp_session->ssrc);
2094  ext_hdr->recv_ssrc = htonl(rtp_session->remote_ssrc);
2095 
2096  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG1, "Sending RTCP PLI\n");
2097 
2098  ext_hdr->length = htons((uint8_t)(sizeof(switch_rtcp_ext_hdr_t) / 4) - 1);
2099  rtcp_bytes += sizeof(switch_rtcp_ext_hdr_t);
2100  rtp_session->pli_count = 0;
2101  }
2102 
2103  if (rtp_session->flags[SWITCH_RTP_FLAG_NACK] && nack_ttl > 0) {
2104  int n = 0;
2105 
2106  for (n = 0; n < nack_ttl; n++) {
2107  switch_rtcp_ext_hdr_t *ext_hdr;
2108  uint32_t *nack;
2109  p = (uint8_t *) (&rtp_session->rtcp_send_msg) + rtcp_bytes;
2110  ext_hdr = (switch_rtcp_ext_hdr_t *) p;
2111 
2112  ext_hdr->version = 2;
2113  ext_hdr->p = 0;
2114  ext_hdr->fmt = _RTCP_RTPFB_NACK;
2115  ext_hdr->pt = _RTCP_PT_RTPFB;
2116  ext_hdr->send_ssrc = htonl(rtp_session->ssrc);
2117  ext_hdr->recv_ssrc = htonl(rtp_session->remote_ssrc);
2118  ext_hdr->length = htons(3);
2119  p += sizeof(switch_rtcp_ext_hdr_t);
2120  nack = (uint32_t *) p;
2121  *nack = cur_nack[n];
2122 
2123  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG1, "Sending RTCP NACK %u\n",
2124  ntohs(*nack & 0xFFFF));
2125 
2126  rtcp_bytes += sizeof(switch_rtcp_ext_hdr_t) + sizeof(cur_nack[n]);
2127  cur_nack[n] = 0;
2128  }
2129 
2130  nack_ttl = 0;
2131  }
2132 
2133  if (rtp_session->fir_count) {
2134  switch_rtcp_ext_hdr_t *ext_hdr;
2135  rtcp_fir_t *fir;
2136 
2137  p = (uint8_t *) (&rtp_session->rtcp_send_msg) + rtcp_bytes;
2138  ext_hdr = (switch_rtcp_ext_hdr_t *) p;
2139 
2140  p += sizeof(switch_rtcp_ext_hdr_t);
2141  fir = (rtcp_fir_t *) p;
2142 
2143  ext_hdr->version = 2;
2144  ext_hdr->p = 0;
2145  ext_hdr->fmt = _RTCP_PSFB_FIR;
2146  ext_hdr->pt = _RTCP_PT_PSFB;
2147 
2148  ext_hdr->send_ssrc = htonl(rtp_session->ssrc);
2149  ext_hdr->recv_ssrc = 0;
2150 
2151  fir->ssrc = htonl(rtp_session->remote_ssrc);
2152  fir->seq = rtp_session->fir_seq;
2153  fir->r1 = fir->r2 = fir->r3 = 0;
2154 
2155  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG1, "Sending RTCP FIR SEQ %d\n", rtp_session->fir_seq);
2156 
2157  rtp_session->fir_seq++;
2158 
2159  ext_hdr->length = htons((uint8_t)((sizeof(switch_rtcp_ext_hdr_t) + sizeof(rtcp_fir_t)) / 4) - 1);
2160  rtcp_bytes += sizeof(switch_rtcp_ext_hdr_t) + sizeof(rtcp_fir_t);
2161  rtp_session->fir_count = 0;
2162  }
2163 
2164  //if (!rtp_session->tmmbr && rtp_session->cur_tmmbr) {
2165  // rtp_session->tmmbr = rtp_session->cur_tmmbr;
2166  //}
2167 
2168  while (rtp_session->tmmbr || rtp_session->tmmbn) {
2169  switch_rtcp_ext_hdr_t *ext_hdr;
2170  rtcp_tmmbx_t *tmmbx;
2171  uint32_t bps = 0;
2172  p = (uint8_t *) (&rtp_session->rtcp_send_msg) + rtcp_bytes;
2173  ext_hdr = (switch_rtcp_ext_hdr_t *) p;
2174 
2175  p += sizeof(switch_rtcp_ext_hdr_t);
2176  tmmbx = (rtcp_tmmbx_t *) p;
2177 
2178  ext_hdr->version = 2;
2179  ext_hdr->p = 0;
2180  ext_hdr->pt = _RTCP_PT_RTPFB;
2181  ext_hdr->send_ssrc = htonl(rtp_session->ssrc);
2182  ext_hdr->recv_ssrc = 0;
2183 
2184  if (rtp_session->tmmbr) {
2185  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG1, "Sending RTCP TMMBR %u\n", rtp_session->tmmbr);
2186  ext_hdr->fmt = _RTCP_RTPFB_TMMBR;
2187  bps = rtp_session->tmmbr;
2188  rtp_session->tmmbr = 0;
2189  } else {
2190  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG1, "Sending RTCP TMMBN %u\n", rtp_session->tmmbr);
2191  ext_hdr->fmt = _RTCP_RTPFB_TMMBN;
2192  bps = rtp_session->tmmbn;
2193  rtp_session->tmmbn = 0;
2194  }
2195 
2196  tmmbx->ssrc = htonl(rtp_session->remote_ssrc);
2197  calc_bw_exp(bps, 17, tmmbx);
2198 
2199  ext_hdr->length = htons((uint8_t)((sizeof(switch_rtcp_ext_hdr_t) + sizeof(rtcp_tmmbx_t)) / 4) - 1);
2200  rtcp_bytes += sizeof(switch_rtcp_ext_hdr_t) + sizeof(rtcp_tmmbx_t);
2201  }
2202 
2203  }
2204 
2205  //SDES + CNAME
2206  p = (uint8_t *) (&rtp_session->rtcp_send_msg) + rtcp_bytes;
2207  sdes = (switch_rtcp_hdr_t *) p;
2208  sdes->version = 2;
2209  sdes->type = _RTCP_PT_SDES;
2210  sdes->count = 1;
2211  sdes->p = 0;
2212  p = (uint8_t *) (sdes) + sdes_bytes;
2213  ssrc = (uint32_t *) p;
2214  *ssrc = htonl(rtp_session->ssrc);
2215  sdes_bytes += sizeof(uint32_t);
2216 
2217 
2218  p = (uint8_t *) (sdes) + sdes_bytes;
2219  unit = (switch_rtcp_sdes_unit_t *) p;
2220  unit->type = _RTCP_SDES_CNAME;
2221  snprintf((char *)unit->value, 80, "%x", rtp_session->ssrc);
2222  unit->length = strlen((char *)unit->value);
2223  sdes_bytes += sizeof(switch_rtcp_sdes_unit_t) + unit->length;
2224 
2225 
2226  p += sizeof(switch_rtcp_sdes_unit_t) + unit->length;
2227  unit = (switch_rtcp_sdes_unit_t *) p;
2228  unit->type = _RTCP_SDES_NOTE;
2229  snprintf((char *)unit->value, 80, "FreeSWITCH.org -- Come to ClueCon.com");
2230  unit->length = strlen((char *)unit->value);
2231  sdes_bytes += sizeof(switch_rtcp_sdes_unit_t) + unit->length;
2232 
2233  sdes_bytes ++;//END
2234 
2235  sdes_bytes += 4 - (sdes_bytes % 4);
2236 
2237  sdes->length = htons((uint16_t)(sdes_bytes / 4) - 1);
2238  rtcp_bytes += sdes_bytes;
2239 
2240  /* Prepare next report */
2241 
2242  stats->last_rpt_cycle = stats->cycle;
2243  stats->last_rpt_ext_seq = stats->high_ext_seq_recv;
2244  stats->last_rpt_ts = rtp_session->timer.samplecount;
2245  stats->period_pkt_count = 0;
2246  stats->sent_pkt_count = 0;
2247 
2248 
2249 
2250 #ifdef ENABLE_SRTP
2251  if (rtp_session->flags[SWITCH_RTP_FLAG_SECURE_SEND]) {
2252  int sbytes = (int) rtcp_bytes;
2253  int stat = srtp_protect_rtcp(rtp_session->send_ctx[rtp_session->srtp_idx_rtcp], &rtp_session->rtcp_send_msg.header, &sbytes);
2254 
2255  if (stat) {
2256  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "Error: SRTP RTCP protection failed with code %d\n", stat);
2257  goto end;
2258  } else {
2259  rtcp_bytes = sbytes;
2260  }
2261 
2262  }
2263 #endif
2264 
2265 #ifdef ENABLE_ZRTP
2266  /* ZRTP Send */
2267  if (zrtp_on && !rtp_session->flags[SWITCH_RTP_FLAG_PROXY_MEDIA]) {
2268  unsigned int sbytes = (int) rtcp_bytes;
2269  zrtp_status_t stat = zrtp_status_fail;
2270 
2271  stat = zrtp_process_rtcp(rtp_session->zrtp_stream, (void *) &rtp_session->rtcp_send_msg, &sbytes);
2272 
2273  switch (stat) {
2274  case zrtp_status_ok:
2275  break;
2276  case zrtp_status_drop:
2277  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error: zRTP protection drop with code %d\n", stat);
2278  ret = (int)rtcp_bytes;
2279  goto end;
2280  break;
2281  case zrtp_status_fail:
2282  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error: zRTP protection fail with code %d\n", stat);
2283  break;
2284  default:
2285  break;
2286  }
2287 
2288  rtcp_bytes = sbytes;
2289  }
2290 #endif
2291  //#define DEBUG_EXTRA
2292 #ifdef DEBUG_EXTRA
2293  {
2294  const char *old_host;
2295  char bufb[50];
2296  old_host = switch_get_addr(bufb, sizeof(bufb), rtp_session->rtcp_remote_addr);
2297  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_CRIT, "%s SEND %s RTCP %s:%d %ld\n",
2298  rtp_session_name(rtp_session),
2299  rtp_type(rtp_session),
2300  old_host,
2302  rtcp_bytes);
2303  }
2304 #endif
2305  if (switch_socket_sendto(rtp_session->rtcp_sock_output, rtp_session->rtcp_remote_addr, 0, (void *)&rtp_session->rtcp_send_msg, &rtcp_bytes ) != SWITCH_STATUS_SUCCESS) {
2306  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG,"RTCP packet not written\n");
2307  } else {
2308  rtp_session->stats.inbound.period_packet_count = 0;
2309  }
2310  }
2311 
2312  if (rtp_session->ice.ice_user) {
2313  if (ice_out(rtp_session, &rtp_session->ice) == SWITCH_STATUS_GENERR) {
2314  ret = -1;
2315  goto end;
2316  }
2317  }
2318 
2319  if (!rtp_session->flags[SWITCH_RTP_FLAG_RTCP_MUX]) {
2320  if (rtp_session->rtcp_ice.ice_user) {
2321  if (ice_out(rtp_session, &rtp_session->rtcp_ice) == SWITCH_STATUS_GENERR) {
2322  ret = -1;
2323  goto end;
2324  }
2325  }
2326  }
2327 
2328  end:
2329 
2330  return ret;
2331 }
2332 
2333 SWITCH_DECLARE(void) switch_rtp_ping(switch_rtp_t *rtp_session)
2334 {
2335  check_rtcp_and_ice(rtp_session);
2336 }
2337 
2338 SWITCH_DECLARE(void) switch_rtp_get_random(void *buf, uint32_t len)
2339 {
2340 #ifdef ENABLE_SRTP
2341  crypto_get_random(buf, len);
2342 #else
2343  switch_stun_random_string(buf, len, NULL);
2344 #endif
2345 }
2346 
2347 
2349 {
2350  switch_core_port_allocator_t *alloc = NULL;
2351  switch_hash_index_t *hi;
2352  const void *var;
2353  void *val;
2354 
2355  if (!global_init) {
2356  return;
2357  }
2358 
2360 
2361  for (hi = switch_core_hash_first(alloc_hash); hi; hi = switch_core_hash_next(&hi)) {
2362  switch_core_hash_this(hi, &var, NULL, &val);
2363  if ((alloc = (switch_core_port_allocator_t *) val)) {
2364  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Destroy port allocator for %s\n", (char *) var);
2366  }
2367  }
2368 
2369  switch_core_hash_destroy(&alloc_hash);
2371 
2372 #ifdef ENABLE_ZRTP
2373  if (zrtp_on) {
2374  zrtp_status_t status = zrtp_status_ok;
2375 
2376  status = zrtp_def_cache_store(zrtp_global);
2377  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Saving ZRTP cache: %s\n", zrtp_status_ok == status ? "OK" : "FAIL");
2378  zrtp_down(zrtp_global);
2379  }
2380 #endif
2381 #ifdef ENABLE_SRTP
2382  crypto_kernel_shutdown();
2383 #endif
2384 
2385 }
2386 
2388 {
2389  if (port) {
2390  if (port_lock) {
2392  }
2393  START_PORT = port;
2394  if (port_lock) {
2396  }
2397  }
2398  return START_PORT;
2399 }
2400 
2402 {
2403  if (port) {
2404  if (port_lock) {
2406  }
2407  END_PORT = port;
2408  if (port_lock) {
2410  }
2411  }
2412  return END_PORT;
2413 }
2414 
2416 {
2417  switch_core_port_allocator_t *alloc = NULL;
2418 
2419  if (!ip || !port) {
2420  return;
2421  }
2422 
2424  if ((alloc = switch_core_hash_find(alloc_hash, ip))) {
2426  }
2428 
2429 }
2430 
2432 {
2433  switch_port_t port = 0;
2434  switch_core_port_allocator_t *alloc = NULL;
2435 
2437  alloc = switch_core_hash_find(alloc_hash, ip);
2438  if (!alloc) {
2440  abort();
2441  }
2442 
2443  switch_core_hash_insert(alloc_hash, ip, alloc);
2444  }
2445 
2447  port = 0;
2448  }
2449 
2451  return port;
2452 }
2453 
2455 {
2456 
2457  if (rtp_session) {
2458  switch_mutex_lock(rtp_session->flag_mutex);
2459  rtp_session->pmaps = pmap;
2460  switch_mutex_unlock(rtp_session->flag_mutex);
2461  return SWITCH_STATUS_SUCCESS;
2462  }
2463 
2464  return SWITCH_STATUS_FALSE;
2465 }
2466 
2468 {
2469  rtp_session->rtp_bugs = bugs;
2470 
2471  if ((rtp_session->rtp_bugs & RTP_BUG_START_SEQ_AT_ZERO)) {
2472  rtp_session->seq = 0;
2473  }
2474 
2475 }
2476 
2477 
2478 static switch_status_t enable_remote_rtcp_socket(switch_rtp_t *rtp_session, const char **err) {
2479 
2481 
2482  if (rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP]) {
2483 
2485  rtp_session->remote_rtcp_port, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS || !rtp_session->rtcp_remote_addr) {
2486  *err = "RTCP Remote Address Error!";
2487  return SWITCH_STATUS_FALSE;
2488  } else {
2489  const char *host;
2490  char bufa[50];
2491 
2492  host = switch_get_addr(bufa, sizeof(bufa), rtp_session->rtcp_remote_addr);
2493 
2495  "Setting RTCP remote addr to %s:%d %d\n", host, rtp_session->remote_rtcp_port, rtp_session->rtcp_remote_addr->family);
2496  }
2497 
2498  if (rtp_session->rtcp_sock_input && switch_sockaddr_get_family(rtp_session->rtcp_remote_addr) ==
2500  rtp_session->rtcp_sock_output = rtp_session->rtcp_sock_input;
2501  } else {
2502 
2503  if (rtp_session->rtcp_sock_output && rtp_session->rtcp_sock_output != rtp_session->rtcp_sock_input) {
2504  switch_socket_close(rtp_session->rtcp_sock_output);
2505  }
2506 
2507  if ((status = switch_socket_create(&rtp_session->rtcp_sock_output,
2509  SOCK_DGRAM, 0, rtp_session->pool)) != SWITCH_STATUS_SUCCESS) {
2510  *err = "RTCP Socket Error!";
2511  }
2512  }
2513 
2514  } else {
2515  *err = "RTCP NOT ACTIVE!";
2516  }
2517 
2518  return status;
2519 
2520 }
2521 
2522 static switch_status_t enable_local_rtcp_socket(switch_rtp_t *rtp_session, const char **err) {
2523 
2524  const char *host = rtp_session->local_host_str;
2525  switch_port_t port = rtp_session->local_port;
2526  switch_socket_t *rtcp_new_sock = NULL, *rtcp_old_sock = NULL;
2528  char bufa[50];
2529 
2530  if (rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP]) {
2531  if (switch_sockaddr_info_get(&rtp_session->rtcp_local_addr, host, SWITCH_UNSPEC, port+1, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS) {
2532  *err = "RTCP Local Address Error!";
2533  goto done;
2534  }
2535 
2536  if (switch_socket_create(&rtcp_new_sock, switch_sockaddr_get_family(rtp_session->rtcp_local_addr), SOCK_DGRAM, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS) {
2537  *err = "RTCP Socket Error!";
2538  goto done;
2539  }
2540 
2542  *err = "RTCP Socket Error!";
2543  goto done;
2544  }
2545 
2546  if (switch_socket_bind(rtcp_new_sock, rtp_session->rtcp_local_addr) != SWITCH_STATUS_SUCCESS) {
2547  *err = "RTCP Bind Error!";
2548  goto done;
2549  }
2550 
2551  if (switch_sockaddr_info_get(&rtp_session->rtcp_from_addr, switch_get_addr(bufa, sizeof(bufa), rtp_session->from_addr),
2552  SWITCH_UNSPEC, switch_sockaddr_get_port(rtp_session->from_addr) + 1, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS) {
2553  *err = "RTCP From Address Error!";
2554  goto done;
2555  }
2556 
2557  rtcp_old_sock = rtp_session->rtcp_sock_input;
2558  rtp_session->rtcp_sock_input = rtcp_new_sock;
2559  rtcp_new_sock = NULL;
2560 
2561  switch_socket_create_pollset(&rtp_session->rtcp_read_pollfd, rtp_session->rtcp_sock_input, SWITCH_POLLIN | SWITCH_POLLERR, rtp_session->pool);
2562 
2563  done:
2564 
2565  if (*err) {
2566 
2567  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "Error allocating rtcp [%s]\n", *err);
2568  status = SWITCH_STATUS_FALSE;
2569  }
2570 
2571  if (rtcp_new_sock) {
2572  switch_socket_close(rtcp_new_sock);
2573  }
2574 
2575  if (rtcp_old_sock) {
2576  switch_socket_close(rtcp_old_sock);
2577  }
2578  } else {
2579  status = SWITCH_STATUS_FALSE;
2580  }
2581 
2582  return status;
2583 }
2584 
2585 SWITCH_DECLARE(switch_status_t) switch_rtp_set_local_address(switch_rtp_t *rtp_session, const char *host, switch_port_t port, const char **err)
2586 {
2587  switch_socket_t *new_sock = NULL, *old_sock = NULL;
2589  int j = 0;
2590 #ifndef WIN32
2591  char o[5] = "TEST", i[5] = "";
2592  switch_size_t len, ilen = 0;
2593  int x;
2594 #endif
2595 
2596  if (rtp_session->ready != 1) {
2597  if (!switch_rtp_ready(rtp_session)) {
2598  return SWITCH_STATUS_FALSE;
2599  }
2600 
2601  WRITE_INC(rtp_session);
2602  READ_INC(rtp_session);
2603 
2604  if (!switch_rtp_ready(rtp_session)) {
2605  goto done;
2606  }
2607  }
2608 
2609 
2610  *err = NULL;
2611 
2612  if (zstr(host) || !port) {
2613  *err = "Address Error";
2614  goto done;
2615  }
2616 
2617 
2618  rtp_session->local_host_str = switch_core_strdup(rtp_session->pool, host);
2619  rtp_session->local_port = port;
2620 
2621 
2622  if (switch_sockaddr_info_get(&rtp_session->local_addr, host, SWITCH_UNSPEC, port, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS) {
2623  *err = "Local Address Error!";
2624  goto done;
2625  }
2626 
2627 
2628  if (rtp_session->sock_input) {
2629  switch_rtp_kill_socket(rtp_session);
2630  }
2631 
2632  if (switch_socket_create(&new_sock, switch_sockaddr_get_family(rtp_session->local_addr), SOCK_DGRAM, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS) {
2633  *err = "Socket Error!";
2634  goto done;
2635  }
2636 
2638  *err = "Socket Error!";
2639  goto done;
2640  }
2641 
2642  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
2643  switch_socket_opt_set(new_sock, SWITCH_SO_RCVBUF, 1572864);
2644  switch_socket_opt_set(new_sock, SWITCH_SO_SNDBUF, 1572864);
2645  }
2646 
2647  if (switch_socket_bind(new_sock, rtp_session->local_addr) != SWITCH_STATUS_SUCCESS) {
2648  char *em = switch_core_sprintf(rtp_session->pool, "Bind Error! %s:%d", host, port);
2649  *err = em;
2650  goto done;
2651  }
2652 
2653 
2654  if ((j = atoi(host)) && j > 223 && j < 240) { /* mcast */
2655  if (switch_mcast_interface(new_sock, rtp_session->local_addr) != SWITCH_STATUS_SUCCESS) {
2656  *err = "Multicast Socket interface Error";
2657  goto done;
2658  }
2659 
2660  if (switch_mcast_join(new_sock, rtp_session->local_addr, NULL, NULL) != SWITCH_STATUS_SUCCESS) {
2661  *err = "Multicast Error";
2662  goto done;
2663  }
2664 
2665  if (rtp_session->session) {
2666  switch_channel_t *channel = switch_core_session_get_channel(rtp_session->session);
2667  const char *var;
2668 
2669  if ((var = switch_channel_get_variable(channel, "multicast_ttl"))) {
2670  int ttl = atoi(var);
2671 
2672  if (ttl > 0 && ttl < 256) {
2673  if (switch_mcast_hops(new_sock, (uint8_t) ttl) != SWITCH_STATUS_SUCCESS) {
2674  *err = "Mutlicast TTL set failed";
2675  goto done;
2676  }
2677 
2678  }
2679  }
2680 
2681  }
2682 
2683  }
2684 
2685 
2686 
2687 #ifndef WIN32
2688  len = sizeof(i);
2690 
2691  switch_socket_sendto(new_sock, rtp_session->local_addr, 0, (void *) o, &len);
2692 
2693  x = 0;
2694  while (!ilen) {
2695  switch_status_t status;
2696  ilen = len;
2697  status = switch_socket_recvfrom(rtp_session->from_addr, new_sock, 0, (void *) i, &ilen);
2698 
2699  if (status != SWITCH_STATUS_SUCCESS && status != SWITCH_STATUS_BREAK) {
2700  break;
2701  }
2702 
2703  if (++x > 1000) {
2704  break;
2705  }
2706  switch_cond_next();
2707  }
2709 
2710 #endif
2711 
2712  old_sock = rtp_session->sock_input;
2713  rtp_session->sock_input = new_sock;
2714  new_sock = NULL;
2715 
2716  if (rtp_session->flags[SWITCH_RTP_FLAG_USE_TIMER] || rtp_session->flags[SWITCH_RTP_FLAG_NOBLOCK] || rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
2717  switch_socket_opt_set(rtp_session->sock_input, SWITCH_SO_NONBLOCK, TRUE);
2719  }
2720 
2721  switch_socket_create_pollset(&rtp_session->read_pollfd, rtp_session->sock_input, SWITCH_POLLIN | SWITCH_POLLERR, rtp_session->pool);
2722 
2723  if (rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP]) {
2724  if ((status = enable_local_rtcp_socket(rtp_session, err)) == SWITCH_STATUS_SUCCESS) {
2725  *err = "Success";
2726  }
2727  } else {
2728  status = SWITCH_STATUS_SUCCESS;
2729  *err = "Success";
2730  }
2731 
2733 
2734  done:
2735 
2736  if (new_sock) {
2737  switch_socket_close(new_sock);
2738  }
2739 
2740  if (old_sock) {
2741  switch_socket_close(old_sock);
2742  }
2743 
2744 
2745  if (rtp_session->ready != 1) {
2746  WRITE_DEC(rtp_session);
2747  READ_DEC(rtp_session);
2748  }
2749 
2750  return status;
2751 }
2752 
2753 SWITCH_DECLARE(void) switch_rtp_set_max_missed_packets(switch_rtp_t *rtp_session, uint32_t max)
2754 {
2755  if (!switch_rtp_ready(rtp_session) || rtp_session->flags[SWITCH_RTP_FLAG_UDPTL]) {
2756  return;
2757  }
2758 
2759  if (rtp_session->missed_count >= max) {
2760 
2762  "new max missed packets(%d->%d) greater than current missed packets(%d). RTP will timeout.\n",
2763  rtp_session->missed_count, max, rtp_session->missed_count);
2764  }
2765 
2766  rtp_session->max_missed_packets = max;
2767 }
2768 
2769 SWITCH_DECLARE(void) switch_rtp_reset_jb(switch_rtp_t *rtp_session)
2770 {
2771  if (switch_rtp_ready(rtp_session)) {
2772  if (rtp_session->jb) {
2773  switch_jb_reset(rtp_session->jb);
2774  }
2775  }
2776 }
2777 
2778 SWITCH_DECLARE(void) switch_rtp_reset_vb(switch_rtp_t *rtp_session)
2779 {
2780  if (rtp_session->vb) {
2781  switch_jb_reset(rtp_session->vb);
2782  }
2783 
2784  if (rtp_session->vbw) {
2785  switch_jb_reset(rtp_session->vbw);
2786  }
2787 }
2788 
2789 SWITCH_DECLARE(void) switch_rtp_reset(switch_rtp_t *rtp_session)
2790 {
2791  if (!rtp_session) {
2792  return;
2793  }
2794 
2795  rtp_session->seq = (uint16_t) rand();
2796  rtp_session->ts = 0;
2797  memset(&rtp_session->ts_norm, 0, sizeof(rtp_session->ts_norm));
2798 
2799  rtp_session->last_stun = rtp_session->first_stun = 0;
2800  rtp_session->wrong_addrs = 0;
2801  rtp_session->rtcp_sent_packets = 0;
2802  rtp_session->rtcp_last_sent = 0;
2803  rtp_session->ice_adj = 0;
2804 
2805  //switch_rtp_del_dtls(rtp_session, DTLS_TYPE_RTP|DTLS_TYPE_RTCP);
2808  rtcp_stats_init(rtp_session);
2809 
2810  if (rtp_session->ice.ready) {
2811  switch_rtp_reset_vb(rtp_session);
2812  rtp_session->ice.ready = rtp_session->ice.rready = 0;
2813  }
2814 
2815 }
2816 
2817 SWITCH_DECLARE(void) switch_rtp_reset_media_timer(switch_rtp_t *rtp_session)
2818 {
2819  rtp_session->missed_count = 0;
2820 }
2821 
2822 SWITCH_DECLARE(char *) switch_rtp_get_remote_host(switch_rtp_t *rtp_session)
2823 {
2824  return zstr(rtp_session->remote_host_str) ? "0.0.0.0" : rtp_session->remote_host_str;
2825 }
2826 
2828 {
2829  return rtp_session->remote_port;
2830 }
2831 
2832 static void ping_socket(switch_rtp_t *rtp_session)
2833 {
2834  uint32_t o = UINT_MAX;
2835  switch_size_t len = sizeof(o);
2836  switch_socket_sendto(rtp_session->sock_input, rtp_session->local_addr, 0, (void *) &o, &len);
2837 
2838  if (rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP] && rtp_session->rtcp_sock_input) {
2839  switch_socket_sendto(rtp_session->rtcp_sock_input, rtp_session->rtcp_local_addr, 0, (void *) &o, &len);
2840  }
2841 }
2842 
2844 {
2845  switch_socket_t *sock;
2846 
2847  if (!switch_rtp_ready(rtp_session)) {
2848  return SWITCH_STATUS_FALSE;
2849  }
2850 
2852  ping_socket(rtp_session);
2853  }
2854 
2855  READ_INC(rtp_session);
2856  WRITE_INC(rtp_session);
2857 
2858  if (rtp_session->flags[SWITCH_RTP_FLAG_USE_TIMER] || rtp_session->timer.timer_interface) {
2859  switch_core_timer_destroy(&rtp_session->timer);
2860  memset(&rtp_session->timer, 0, sizeof(rtp_session->timer));
2862  }
2863 
2864  rtp_session->missed_count = 0;
2865  rtp_session->max_missed_packets = 0;
2866 
2867  rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP] = 0;
2868 
2869  if (rtp_session->rtcp_sock_input) {
2870  ping_socket(rtp_session);
2871  switch_socket_shutdown(rtp_session->rtcp_sock_input, SWITCH_SHUTDOWN_READWRITE);
2872  }
2873 
2874  if (rtp_session->rtcp_sock_output && rtp_session->rtcp_sock_output != rtp_session->rtcp_sock_input) {
2875  switch_socket_shutdown(rtp_session->rtcp_sock_output, SWITCH_SHUTDOWN_READWRITE);
2876  }
2877 
2878  if (rtp_session->flags[SWITCH_RTP_FLAG_RTCP_MUX]) {
2879  rtp_session->rtcp_sock_input = NULL;
2880  rtp_session->rtcp_sock_output = NULL;
2881  } else {
2882  if ((sock = rtp_session->rtcp_sock_input)) {
2883  rtp_session->rtcp_sock_input = NULL;
2884  switch_socket_close(sock);
2885 
2886  if (rtp_session->rtcp_sock_output && rtp_session->rtcp_sock_output != sock) {
2887  if ((sock = rtp_session->rtcp_sock_output)) {
2888  rtp_session->rtcp_sock_output = NULL;
2889  switch_socket_close(sock);
2890  }
2891  }
2892  }
2893  }
2894 
2897  switch_socket_opt_set(rtp_session->sock_input, SWITCH_SO_NONBLOCK, FALSE);
2899 
2900  WRITE_DEC(rtp_session);
2901  READ_DEC(rtp_session);
2902 
2905 
2906  switch_rtp_break(rtp_session);
2907 
2908  return SWITCH_STATUS_SUCCESS;
2909 
2910 }
2911 
2912 
2913 SWITCH_DECLARE(switch_status_t) switch_rtp_set_remote_address(switch_rtp_t *rtp_session, const char *host, switch_port_t port, switch_port_t remote_rtcp_port,
2914  switch_bool_t change_adv_addr, const char **err)
2915 {
2916  switch_sockaddr_t *remote_addr;
2918  *err = "Success";
2919 
2920  if (switch_sockaddr_info_get(&remote_addr, host, SWITCH_UNSPEC, port, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS || !remote_addr) {
2921  *err = "Remote Address Error!";
2922  return SWITCH_STATUS_FALSE;
2923  }
2924 
2925 
2926  switch_mutex_lock(rtp_session->write_mutex);
2927 
2928  rtp_session->remote_addr = remote_addr;
2929  switch_cp_addr(rtp_session->rtp_from_addr, rtp_session->remote_addr);
2930 
2931  if (change_adv_addr) {
2932  rtp_session->remote_host_str = switch_core_strdup(rtp_session->pool, host);
2933  rtp_session->remote_port = port;
2934  }
2935 
2936  rtp_session->eff_remote_host_str = switch_core_strdup(rtp_session->pool, host);
2937  rtp_session->eff_remote_port = port;
2938 
2939  if (rtp_session->sock_input && switch_sockaddr_get_family(rtp_session->remote_addr) == switch_sockaddr_get_family(rtp_session->local_addr)) {
2940  rtp_session->sock_output = rtp_session->sock_input;
2941  } else {
2942  if (rtp_session->sock_output && rtp_session->sock_output != rtp_session->sock_input) {
2943  switch_socket_close(rtp_session->sock_output);
2944  }
2945  if ((status = switch_socket_create(&rtp_session->sock_output,
2946  switch_sockaddr_get_family(rtp_session->remote_addr),
2947  SOCK_DGRAM, 0, rtp_session->pool)) != SWITCH_STATUS_SUCCESS) {
2948 
2949  *err = "Socket Error!";
2950  }
2951  }
2952 
2953  if (rtp_session->dtls) {
2954  rtp_session->dtls->sock_output = rtp_session->sock_output;
2955 
2956  if (rtp_session->flags[SWITCH_RTP_FLAG_RTCP_MUX]) {
2957  switch_sockaddr_info_get(&rtp_session->dtls->remote_addr, host, SWITCH_UNSPEC, port, 0, rtp_session->pool);
2958  }
2959  }
2960 
2961 
2962  if (rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP]) {
2963  if (rtp_session->flags[SWITCH_RTP_FLAG_RTCP_MUX]) {
2964  rtp_session->rtcp_remote_addr = rtp_session->remote_addr;
2965  rtp_session->rtcp_sock_output = rtp_session->sock_output;
2966  } else {
2967  if (remote_rtcp_port) {
2968  rtp_session->remote_rtcp_port = remote_rtcp_port;
2969  } else {
2970  rtp_session->remote_rtcp_port = rtp_session->eff_remote_port + 1;
2971  }
2972  status = enable_remote_rtcp_socket(rtp_session, err);
2973 
2974  if (rtp_session->rtcp_dtls) {
2975  //switch_sockaddr_info_get(&rtp_session->rtcp_dtls->remote_addr, host, SWITCH_UNSPEC, port, 0, rtp_session->pool);
2976  rtp_session->rtcp_dtls->remote_addr = rtp_session->rtcp_remote_addr;
2977  rtp_session->rtcp_dtls->sock_output = rtp_session->rtcp_sock_output;
2978  }
2979  }
2980  }
2981 
2982  switch_mutex_unlock(rtp_session->write_mutex);
2983 
2984  return status;
2985 }
2986 
2987 
2988 static const char *dtls_state_names_t[] = {"OFF", "HANDSHAKE", "SETUP", "READY", "FAIL", "INVALID"};
2989 static const char *dtls_state_names(dtls_state_t s)
2990 {
2991  if (s > DS_INVALID) {
2992  s = DS_INVALID;
2993  }
2994 
2995  return dtls_state_names_t[s];
2996 }
2997 
2998 
2999 #define dtls_set_state(_dtls, _state) switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_INFO, "Changing %s DTLS state from %s to %s\n", rtp_type(rtp_session), dtls_state_names(_dtls->state), dtls_state_names(_state)); _dtls->new_state = 1; _dtls->last_state = _dtls->state; _dtls->state = _state
3000 
3001 #define cr_keylen 16
3002 #define cr_saltlen 14
3003 #define cr_kslen 30
3004 
3005 static int dtls_state_setup(switch_rtp_t *rtp_session, switch_dtls_t *dtls)
3006 {
3007  X509 *cert;
3008  int r = 0;
3009 
3010  if ((dtls->type & DTLS_TYPE_SERVER)) {
3011  r = 1;
3012  } else if ((cert = SSL_get_peer_certificate(dtls->ssl))) {
3015  X509_free(cert);
3016  }
3017 
3018  if (!r) {
3019  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "%s Fingerprint Verification Failed!\n", rtp_type(rtp_session));
3020  dtls_set_state(dtls, DS_FAIL);
3021  return -1;
3022  } else {
3023  uint8_t raw_key_data[cr_kslen*2] = { 0 };
3024  unsigned char *local_key, *remote_key, *local_salt, *remote_salt;
3025  unsigned char local_key_buf[cr_kslen] = {0}, remote_key_buf[cr_kslen] = {0};
3026 
3027  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_INFO, "%s Fingerprint Verified.\n", rtp_type(rtp_session));
3028 
3029 #ifdef HAVE_OPENSSL_DTLS_SRTP
3030  if (!SSL_export_keying_material(dtls->ssl, raw_key_data, sizeof(raw_key_data), "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
3031  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "%s Key material export failure\n", rtp_type(rtp_session));
3032  dtls_set_state(dtls, DS_FAIL);
3033  return -1;
3034  }
3035 #else
3036  return -1;
3037 #endif
3038 
3039  if ((dtls->type & DTLS_TYPE_CLIENT)) {
3040  local_key = raw_key_data;
3041  remote_key = local_key + cr_keylen;
3042  local_salt = remote_key + cr_keylen;
3043  remote_salt = local_salt + cr_saltlen;
3044 
3045  } else {
3046  remote_key = raw_key_data;
3047  local_key = remote_key + cr_keylen;
3048  remote_salt = local_key + cr_keylen;
3049  local_salt = remote_salt + cr_saltlen;
3050  }
3051 
3052  memcpy(local_key_buf, local_key, cr_keylen);
3053  memcpy(local_key_buf + cr_keylen, local_salt, cr_saltlen);
3054 
3055  memcpy(remote_key_buf, remote_key, cr_keylen);
3056  memcpy(remote_key_buf + cr_keylen, remote_salt, cr_saltlen);
3057 
3058  if (dtls == rtp_session->rtcp_dtls && rtp_session->rtcp_dtls != rtp_session->dtls) {
3061  } else {
3064  }
3065  }
3066 
3067  dtls_set_state(dtls, DS_READY);
3068 
3069  return 0;
3070 }
3071 
3072 static int dtls_state_ready(switch_rtp_t *rtp_session, switch_dtls_t *dtls)
3073 {
3074 
3075  if (dtls->new_state) {
3076  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
3077  switch_core_session_t *other_session;
3078 
3079  if (rtp_session->session && switch_core_session_get_partner(rtp_session->session, &other_session) == SWITCH_STATUS_SUCCESS) {
3081  switch_core_session_rwunlock(other_session);
3082  }
3083  }
3084  dtls->new_state = 0;
3085  }
3086  return 0;
3087 }
3088 
3089 static int dtls_state_fail(switch_rtp_t *rtp_session, switch_dtls_t *dtls)
3090 {
3091  if (rtp_session->session) {
3092  switch_channel_t *channel = switch_core_session_get_channel(rtp_session->session);
3094  }
3095 
3096  return -1;
3097 }
3098 
3099 
3100 static int dtls_state_handshake(switch_rtp_t *rtp_session, switch_dtls_t *dtls)
3101 {
3102  int ret;
3103 
3104  if ((ret = SSL_do_handshake(dtls->ssl)) != 1){
3105  switch((ret = SSL_get_error(dtls->ssl, ret))){
3106  case SSL_ERROR_WANT_READ:
3107  case SSL_ERROR_WANT_WRITE:
3108  case SSL_ERROR_NONE:
3109  break;
3110  default:
3111  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "%s Handshake failure %d\n", rtp_type(rtp_session), ret);
3112  dtls_set_state(dtls, DS_FAIL);
3113  return -1;
3114  }
3115  }
3116 
3117  if (SSL_is_init_finished(dtls->ssl)) {
3118  dtls_set_state(dtls, DS_SETUP);
3119  }
3120 
3121  return 0;
3122 }
3123 
3124 static void free_dtls(switch_dtls_t **dtlsp)
3125 {
3126  switch_dtls_t *dtls;
3127 
3128  if (!dtlsp) {
3129  return;
3130  }
3131 
3132  dtls = *dtlsp;
3133  *dtlsp = NULL;
3134 
3135  if (dtls->ssl) {
3136  SSL_free(dtls->ssl);
3137  }
3138 
3139  if (dtls->ssl_ctx) {
3140  SSL_CTX_free(dtls->ssl_ctx);
3141  }
3142 }
3143 
3144 static int do_dtls(switch_rtp_t *rtp_session, switch_dtls_t *dtls)
3145 {
3146  int r = 0, ret = 0, len;
3147  switch_size_t bytes;
3148  unsigned char buf[4096] = "";
3149  int ready = rtp_session->ice.ice_user ? (rtp_session->ice.rready && rtp_session->ice.ready) : 1;
3150 
3151 
3152  if (!dtls->bytes && !ready) {
3153  return 0;
3154  }
3155 
3156  if ((ret = BIO_write(dtls->read_bio, dtls->data, (int)dtls->bytes)) != (int)dtls->bytes && dtls->bytes > 0) {
3157  ret = SSL_get_error(dtls->ssl, ret);
3158  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "%s DTLS packet read err %d\n", rtp_type(rtp_session), ret);
3159  }
3160 
3161  if (dtls_states[dtls->state]) {
3162  r = dtls_states[dtls->state](rtp_session, dtls);
3163  }
3164 
3165  if ((len = BIO_read(dtls->write_bio, buf, sizeof(buf))) > 0) {
3166  bytes = len;
3167 
3168  if (switch_socket_sendto(dtls->sock_output, dtls->remote_addr, 0, (void *)buf, &bytes ) != SWITCH_STATUS_SUCCESS) {
3169  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "%s DTLS packet not written\n", rtp_type(rtp_session));
3170  }
3171  }
3172 
3173 
3174 
3175  return r;
3176 }
3177 
3178 #if VERIFY
3179 static int cb_verify_peer(int preverify_ok, X509_STORE_CTX *ctx)
3180 {
3181  SSL *ssl = NULL;
3182  switch_dtls_t *dtls;
3183  X509 *cert;
3184  int r = 0;
3185 
3186  ssl = X509_STORE_CTX_get_app_data(ctx);
3187  dtls = (switch_dtls_t *) SSL_get_app_data(ssl);
3188 
3189  if (!(ssl && dtls)) {
3190  return 0;
3191  }
3192 
3193  if ((cert = SSL_get_peer_certificate(dtls->ssl))) {
3195 
3197 
3198  X509_free(cert);
3199  } else {
3201  }
3202 
3203  return r;
3204 }
3205 #endif
3206 
3208 #ifdef HAVE_OPENSSL_DTLS_SRTP
3209  return 1;
3210 #else
3211  return 0;
3212 #endif
3213 }
3214 
3216 {
3217  if (!rtp_session || (!rtp_session->dtls && !rtp_session->rtcp_dtls)) {
3218  return DS_OFF;
3219  }
3220 
3221  if ((type == DTLS_TYPE_RTP) && rtp_session->dtls) {
3222  return rtp_session->dtls->state;
3223  }
3224 
3225  if ((type == DTLS_TYPE_RTCP) && rtp_session->rtcp_dtls) {
3226  return rtp_session->rtcp_dtls->state;
3227  }
3228 
3229  return DS_OFF;
3230 }
3231 
3233 {
3234 
3235  if (!rtp_session || (!rtp_session->dtls && !rtp_session->rtcp_dtls)) {
3236  return SWITCH_STATUS_FALSE;
3237  }
3238 
3239  if ((type & DTLS_TYPE_RTP)) {
3240  if (rtp_session->dtls && rtp_session->dtls == rtp_session->rtcp_dtls) {
3241  rtp_session->rtcp_dtls = NULL;
3242  }
3243 
3244  if (rtp_session->dtls) {
3245  free_dtls(&rtp_session->dtls);
3246  }
3247 
3248  if (rtp_session->jb) {
3249  switch_jb_reset(rtp_session->jb);
3250  }
3251 
3252  if (rtp_session->vb) {
3253  switch_jb_reset(rtp_session->vb);
3254  }
3255 
3256  if (rtp_session->vbw) {
3257  switch_jb_reset(rtp_session->vbw);
3258  }
3259 
3260  }
3261 
3262  if ((type & DTLS_TYPE_RTCP) && rtp_session->rtcp_dtls) {
3263  free_dtls(&rtp_session->rtcp_dtls);
3264  }
3265 
3266 
3267 #ifdef ENABLE_SRTP
3268  if (rtp_session->flags[SWITCH_RTP_FLAG_SECURE_SEND]) {
3269  int x;
3270  for(x = 0; x < 2; x++) {
3271  if (rtp_session->send_ctx[x]) {
3272  srtp_dealloc(rtp_session->send_ctx[x]);
3273  rtp_session->send_ctx[x] = NULL;
3274  }
3275  }
3276  rtp_session->flags[SWITCH_RTP_FLAG_SECURE_SEND] = 0;
3277  }
3278 
3279  if (rtp_session->flags[SWITCH_RTP_FLAG_SECURE_RECV]) {
3280  int x;
3281  for (x = 0; x < 2; x++) {
3282  if (rtp_session->recv_ctx[x]) {
3283  srtp_dealloc(rtp_session->recv_ctx[x]);
3284  rtp_session->recv_ctx[x] = NULL;
3285  }
3286  }
3287  rtp_session->flags[SWITCH_RTP_FLAG_SECURE_RECV] = 0;
3288  }
3289 #endif
3290 
3291  return SWITCH_STATUS_SUCCESS;
3292 }
3293 
3295 {
3296  switch_dtls_t *dtls;
3297  int ret;
3298  const char *kind = "";
3299  BIO *bio;
3300  DH *dh;
3301 #ifndef OPENSSL_NO_EC
3302  EC_KEY* ecdh;
3303 #endif
3304 
3305 #ifndef HAVE_OPENSSL_DTLS_SRTP
3306  return SWITCH_STATUS_FALSE;
3307 #endif
3308 
3309  if (!switch_rtp_ready(rtp_session)) {
3310  return SWITCH_STATUS_FALSE;
3311  }
3312 
3313  if (!((type & DTLS_TYPE_RTP) || (type & DTLS_TYPE_RTCP)) || !((type & DTLS_TYPE_CLIENT) || (type & DTLS_TYPE_SERVER))) {
3314  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_CRIT, "INVALID TYPE!\n");
3315  }
3316 
3317  switch_rtp_del_dtls(rtp_session, type);
3318 
3319  if ((type & DTLS_TYPE_RTP) && (type & DTLS_TYPE_RTCP)) {
3320  kind = "RTP/RTCP";
3321  } else if ((type & DTLS_TYPE_RTP)) {
3322  kind = "RTP";
3323  } else {
3324  kind = "RTCP";
3325  }
3326 
3328  "Activate %s %s DTLS %s\n", kind, rtp_type(rtp_session), (type & DTLS_TYPE_SERVER) ? "server" : "client");
3329 
3330  if (((type & DTLS_TYPE_RTP) && rtp_session->dtls) || ((type & DTLS_TYPE_RTCP) && rtp_session->rtcp_dtls)) {
3331  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_WARNING, "DTLS ALREADY INIT\n");
3332  return SWITCH_STATUS_FALSE;
3333  }
3334 
3335  dtls = switch_core_alloc(rtp_session->pool, sizeof(*dtls));
3336 
3337  dtls->pem = switch_core_sprintf(rtp_session->pool, "%s%s%s.pem", SWITCH_GLOBAL_dirs.certs_dir, SWITCH_PATH_SEPARATOR, DTLS_SRTP_FNAME);
3338 
3339  if (switch_file_exists(dtls->pem, rtp_session->pool) == SWITCH_STATUS_SUCCESS) {
3340  dtls->pvt = dtls->rsa = dtls->pem;
3341  } else {
3342  dtls->pvt = switch_core_sprintf(rtp_session->pool, "%s%s%s.key", SWITCH_GLOBAL_dirs.certs_dir, SWITCH_PATH_SEPARATOR, DTLS_SRTP_FNAME);
3343  dtls->rsa = switch_core_sprintf(rtp_session->pool, "%s%s%s.crt", SWITCH_GLOBAL_dirs.certs_dir, SWITCH_PATH_SEPARATOR, DTLS_SRTP_FNAME);
3344  }
3345 
3346  dtls->ca = switch_core_sprintf(rtp_session->pool, "%s%sca-bundle.crt", SWITCH_GLOBAL_dirs.certs_dir, SWITCH_PATH_SEPARATOR);
3347 
3348  dtls->ssl_ctx = SSL_CTX_new((type & DTLS_TYPE_SERVER) ? DTLSv1_server_method() : DTLSv1_client_method());
3349  switch_assert(dtls->ssl_ctx);
3350 
3351  bio = BIO_new_file(dtls->pem, "r");
3352  dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3353  BIO_free(bio);
3354  if (dh) {
3355  SSL_CTX_set_tmp_dh(dtls->ssl_ctx, dh);
3356  DH_free(dh);
3357  }
3358 
3359  SSL_CTX_set_mode(dtls->ssl_ctx, SSL_MODE_AUTO_RETRY);
3360 
3361  //SSL_CTX_set_verify(dtls->ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
3362  SSL_CTX_set_verify(dtls->ssl_ctx, SSL_VERIFY_NONE, NULL);
3363 
3364  SSL_CTX_set_cipher_list(dtls->ssl_ctx, "ALL");
3365 
3366 #ifdef HAVE_OPENSSL_DTLS_SRTP
3367  //SSL_CTX_set_tlsext_use_srtp(dtls->ssl_ctx, "SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32");
3368  SSL_CTX_set_tlsext_use_srtp(dtls->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
3369 #endif
3370 
3371  dtls->type = type;
3372  dtls->read_bio = BIO_new(BIO_s_mem());
3373  switch_assert(dtls->read_bio);
3374 
3375  dtls->write_bio = BIO_new(BIO_s_mem());
3376  switch_assert(dtls->write_bio);
3377 
3378  BIO_set_mem_eof_return(dtls->read_bio, -1);
3379  BIO_set_mem_eof_return(dtls->write_bio, -1);
3380 
3381  if ((ret=SSL_CTX_use_certificate_file(dtls->ssl_ctx, dtls->rsa, SSL_FILETYPE_PEM)) != 1) {
3382  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "%s DTLS cert err [%d]\n", rtp_type(rtp_session), SSL_get_error(dtls->ssl, ret));
3383  return SWITCH_STATUS_FALSE;
3384  }
3385 
3386  if ((ret=SSL_CTX_use_PrivateKey_file(dtls->ssl_ctx, dtls->pvt, SSL_FILETYPE_PEM)) != 1) {
3387  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "%s DTLS key err [%d]\n", rtp_type(rtp_session), SSL_get_error(dtls->ssl, ret));
3388  return SWITCH_STATUS_FALSE;
3389  }
3390 
3391  if (SSL_CTX_check_private_key(dtls->ssl_ctx) == 0) {
3392  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "%s DTLS check key failed\n", rtp_type(rtp_session));
3393  return SWITCH_STATUS_FALSE;
3394  }
3395 
3396  if (!zstr(dtls->ca) && switch_file_exists(dtls->ca, rtp_session->pool) == SWITCH_STATUS_SUCCESS
3397  && (ret = SSL_CTX_load_verify_locations(dtls->ssl_ctx, dtls->ca, NULL)) != 1) {
3398  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "%s DTLS check chain cert failed [%d]\n",
3399  rtp_type(rtp_session) ,
3400  SSL_get_error(dtls->ssl, ret));
3401  return SWITCH_STATUS_FALSE;
3402  }
3403 
3404  dtls->ssl = SSL_new(dtls->ssl_ctx);
3405 
3406  SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
3407  SSL_set_mode(dtls->ssl, SSL_MODE_AUTO_RETRY);
3408  SSL_set_read_ahead(dtls->ssl, 1);
3409  //SSL_set_verify(dtls->ssl, (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT), cb_verify_peer);
3410 
3411 #ifndef OPENSSL_NO_EC
3412  ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3413  if (!ecdh) {
3414  return SWITCH_STATUS_FALSE;
3415  }
3416  SSL_set_options(dtls->ssl, SSL_OP_SINGLE_ECDH_USE);
3417  SSL_set_tmp_ecdh(dtls->ssl, ecdh);
3418  EC_KEY_free(ecdh);
3419 #endif
3420 
3421  SSL_set_verify(dtls->ssl, SSL_VERIFY_NONE, NULL);
3422  SSL_set_app_data(dtls->ssl, dtls);
3423 
3424  BIO_ctrl(dtls->read_bio, BIO_CTRL_DGRAM_SET_MTU, 1400, NULL);
3425  BIO_ctrl(dtls->write_bio, BIO_CTRL_DGRAM_SET_MTU, 1400, NULL);
3426  SSL_set_mtu(dtls->ssl, 1400);
3427  BIO_ctrl(dtls->write_bio, BIO_C_SET_BUFF_SIZE, 1400, NULL);
3428  BIO_ctrl(dtls->read_bio, BIO_C_SET_BUFF_SIZE, 1400, NULL);
3429 
3430 
3431 
3432  dtls->local_fp = local_fp;
3433  dtls->remote_fp = remote_fp;
3434  dtls->rtp_session = rtp_session;
3435 
3436  switch_core_cert_expand_fingerprint(remote_fp, remote_fp->str);
3437 
3438  if ((type & DTLS_TYPE_RTP)) {
3439  rtp_session->dtls = dtls;
3440  dtls->sock_output = rtp_session->sock_output;
3441  dtls->remote_addr = rtp_session->remote_addr;
3442  }
3443 
3444  if ((type & DTLS_TYPE_RTCP)) {
3445  rtp_session->rtcp_dtls = dtls;
3446  if (!(type & DTLS_TYPE_RTP)) {
3447  dtls->sock_output = rtp_session->rtcp_sock_output;
3448  dtls->remote_addr = rtp_session->rtcp_remote_addr;
3449  }
3450  }
3451 
3452  if ((type & DTLS_TYPE_SERVER)) {
3453  SSL_set_accept_state(dtls->ssl);
3454  } else {
3455  SSL_set_connect_state(dtls->ssl);
3456  }
3457 
3459 
3460  rtp_session->flags[SWITCH_RTP_FLAG_VIDEO_BREAK] = 1;
3461  switch_rtp_break(rtp_session);
3462 
3463  return SWITCH_STATUS_SUCCESS;
3464 
3465 }
3466 
3467 
3470  uint32_t index, switch_rtp_crypto_key_type_t type, unsigned char *key, switch_size_t keylen)
3471 {
3472 #ifndef ENABLE_SRTP
3473  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_CRIT, "SRTP NOT SUPPORTED IN THIS BUILD!\n");
3474  return SWITCH_STATUS_FALSE;
3475 #else
3476  switch_rtp_crypto_key_t *crypto_key;
3477  srtp_policy_t *policy;
3478  err_status_t stat;
3480 
3481  switch_channel_t *channel = switch_core_session_get_channel(rtp_session->session);
3482  switch_event_t *fsevent = NULL;
3483  int idx = 0;
3484  const char *var;
3485  unsigned char b64_key[512] = "";
3486 
3487  if (direction >= SWITCH_RTP_CRYPTO_MAX || keylen > SWITCH_RTP_MAX_CRYPTO_LEN) {
3488  return SWITCH_STATUS_FALSE;
3489  }
3490 
3491  switch_b64_encode(key, keylen, b64_key, sizeof(b64_key));
3492 
3493  if (switch_true(switch_core_get_variable("rtp_retain_crypto_keys"))) {
3494  switch(direction) {
3496  switch_channel_set_variable(channel, "srtp_local_crypto_key", (const char *)b64_key);
3497  break;
3499  switch_channel_set_variable(channel, "srtp_remote_crypto_key", (const char *)b64_key);
3500  break;
3502  switch_channel_set_variable(channel, "srtcp_local_crypto_key", (const char *)b64_key);
3503  break;
3505  switch_channel_set_variable(channel, "srtcp_remote_crypto_key", (const char *)b64_key);
3506  break;
3507  default:
3508  break;
3509  }
3510  }
3511 
3512  crypto_key = switch_core_alloc(rtp_session->pool, sizeof(*crypto_key));
3513 
3514  if (direction == SWITCH_RTP_CRYPTO_RECV_RTCP) {
3515  direction = SWITCH_RTP_CRYPTO_RECV;
3516  rtp_session->srtp_idx_rtcp = idx = 1;
3517  } else if (direction == SWITCH_RTP_CRYPTO_SEND_RTCP) {
3518  direction = SWITCH_RTP_CRYPTO_SEND;
3519  rtp_session->srtp_idx_rtcp = idx = 1;
3520  }
3521 
3522  if (direction == SWITCH_RTP_CRYPTO_RECV) {
3523  policy = &rtp_session->recv_policy[idx];
3524  } else {
3525  policy = &rtp_session->send_policy[idx];
3526  }
3527 
3528  crypto_key->type = type;
3529  crypto_key->index = index;
3530  memcpy(crypto_key->key, key, keylen);
3531  crypto_key->next = rtp_session->crypto_keys[direction];
3532  rtp_session->crypto_keys[direction] = crypto_key;
3533 
3534  memset(policy, 0, sizeof(*policy));
3535 
3536  /* many devices can't handle gaps in SRTP streams */
3537  if (!((var = switch_channel_get_variable(channel, "srtp_allow_idle_gaps"))
3538  && switch_true(var))
3539  && (!(var = switch_channel_get_variable(channel, "send_silence_when_idle"))
3540  || !(atoi(var)))) {
3541  switch_channel_set_variable(channel, "send_silence_when_idle", "-1");
3542  }
3543 
3544  switch (crypto_key->type) {
3546  crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy->rtp);
3547  crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy->rtcp);
3548 
3550  switch_channel_set_variable(channel, "rtp_has_crypto", "AES_CM_128_HMAC_SHA1_80");
3551  }
3552  break;
3554  crypto_policy_set_aes_cm_128_hmac_sha1_32(&policy->rtp);
3555  crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy->rtcp);
3556 
3557 
3559  switch_channel_set_variable(channel, "rtp_has_crypto", "AES_CM_128_HMAC_SHA1_32");
3560  }
3561  break;
3562 
3563  case AEAD_AES_256_GCM_8:
3564  crypto_policy_set_aes_gcm_256_8_auth(&policy->rtp);
3565  crypto_policy_set_aes_gcm_256_8_auth(&policy->rtcp);
3566 
3568  switch_channel_set_variable(channel, "rtp_has_crypto", "AEAD_AES_256_GCM_8");
3569  }
3570  break;
3571 
3572  case AEAD_AES_128_GCM_8:
3573  crypto_policy_set_aes_gcm_128_8_auth(&policy->rtp);
3574  crypto_policy_set_aes_gcm_128_8_auth(&policy->rtcp);
3575 
3577  switch_channel_set_variable(channel, "rtp_has_crypto", "AEAD_AES_128_GCM_8");
3578  }
3579  break;
3580 
3582  crypto_policy_set_aes_cm_256_hmac_sha1_80(&policy->rtp);
3583  crypto_policy_set_aes_cm_256_hmac_sha1_80(&policy->rtcp);
3585  switch_channel_set_variable(channel, "rtp_has_crypto", "AES_CM_256_HMAC_SHA1_80");
3586  }
3587  break;
3588  case AES_CM_128_NULL_AUTH:
3589  crypto_policy_set_aes_cm_128_null_auth(&policy->rtp);
3590  crypto_policy_set_aes_cm_128_null_auth(&policy->rtcp);
3591 
3593  switch_channel_set_variable(channel, "rtp_has_crypto", "AES_CM_128_NULL_AUTH");
3594  }
3595  break;
3596  default:
3597  break;
3598  }
3599 
3600  policy->key = (uint8_t *) crypto_key->key;
3601  policy->next = NULL;
3602 
3603  policy->window_size = 1024;
3604  policy->allow_repeat_tx = 1;
3605 
3606  //policy->rtp.sec_serv = sec_serv_conf_and_auth;
3607  //policy->rtcp.sec_serv = sec_serv_conf_and_auth;
3608 
3609  switch (direction) {
3611  policy->ssrc.type = ssrc_any_inbound;
3612 
3613  if (rtp_session->flags[SWITCH_RTP_FLAG_SECURE_RECV] && idx == 0 && rtp_session->recv_ctx[idx]) {
3614  rtp_session->flags[SWITCH_RTP_FLAG_SECURE_RECV_RESET] = 1;
3615  } else {
3616  if ((stat = srtp_create(&rtp_session->recv_ctx[idx], policy)) || !rtp_session->recv_ctx[idx]) {
3617  status = SWITCH_STATUS_FALSE;
3618  }
3619 
3620  if (status == SWITCH_STATUS_SUCCESS) {
3621  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_INFO, "Activating %s Secure %s RECV\n",
3622  rtp_session->flags[SWITCH_RTP_FLAG_VIDEO] ? "Video" : "Audio", idx ? "RTCP" : "RTP");
3623  rtp_session->flags[SWITCH_RTP_FLAG_SECURE_RECV] = 1;
3624  } else {
3625  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "Error allocating srtp [%d]\n", stat);
3626  return status;
3627  }
3628  }
3629  break;
3631  policy->ssrc.type = ssrc_any_outbound;
3632  //policy->ssrc.type = ssrc_specific;
3633  //policy->ssrc.value = rtp_session->ssrc;
3634 
3635  if (rtp_session->flags[SWITCH_RTP_FLAG_SECURE_SEND] && idx == 0 && rtp_session->send_ctx[idx]) {
3636  rtp_session->flags[SWITCH_RTP_FLAG_SECURE_SEND_RESET] = 1;
3637  } else {
3638  if ((stat = srtp_create(&rtp_session->send_ctx[idx], policy)) || !rtp_session->send_ctx[idx]) {
3639  status = SWITCH_STATUS_FALSE;
3640  }
3641 
3642  if (status == SWITCH_STATUS_SUCCESS) {
3643  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_INFO, "Activating %s Secure %s SEND\n",
3644  rtp_session->flags[SWITCH_RTP_FLAG_VIDEO] ? "Video" : "Audio", idx ? "RTCP" : "RTP");
3645  rtp_session->flags[SWITCH_RTP_FLAG_SECURE_SEND] = 1;
3646  } else {
3647  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "Error allocating SRTP [%d]\n", stat);
3648  return status;
3649  }
3650  }
3651 
3652  break;
3653  default:
3654  abort();
3655  break;
3656  }
3657 
3659  if (rtp_session->dtls) {
3660  switch_event_add_header(fsevent, SWITCH_STACK_BOTTOM, "secure_type", "srtp:dtls:AES_CM_128_HMAC_SHA1_80");
3661  switch_channel_set_variable(channel, "rtp_has_crypto", "srtp:dtls:AES_CM_128_HMAC_SHA1_80");
3662  } else {
3663  switch_event_add_header(fsevent, SWITCH_STACK_BOTTOM, "secure_type", "srtp:sdes:%s", switch_channel_get_variable(channel, "rtp_has_crypto"));
3664  }
3665  switch_event_add_header_string(fsevent, SWITCH_STACK_BOTTOM, "caller-unique-id", switch_channel_get_uuid(channel));
3666  switch_event_fire(&fsevent);
3667  }
3668 
3669 
3670  return SWITCH_STATUS_SUCCESS;
3671 #endif
3672 }
3673 
3674 SWITCH_DECLARE(switch_status_t) switch_rtp_set_interval(switch_rtp_t *rtp_session, uint32_t ms_per_packet, uint32_t samples_per_interval)
3675 {
3676  rtp_session->ms_per_packet = ms_per_packet;
3677  rtp_session->samples_per_interval = rtp_session->conf_samples_per_interval = samples_per_interval;
3678  rtp_session->missed_count = 0;
3679  rtp_session->samples_per_second =
3680  (uint32_t) ((double) (1000.0f / (double) (rtp_session->ms_per_packet / 1000)) * (double) rtp_session->samples_per_interval);
3681 
3682  rtp_session->one_second = (rtp_session->samples_per_second / rtp_session->samples_per_interval);
3683 
3684  return SWITCH_STATUS_SUCCESS;
3685 }
3686 
3687 SWITCH_DECLARE(switch_status_t) switch_rtp_change_interval(switch_rtp_t *rtp_session, uint32_t ms_per_packet, uint32_t samples_per_interval)
3688 {
3690  int change_timer = 0;
3691 
3692  if (rtp_session->ms_per_packet && rtp_session->ms_per_packet != ms_per_packet) {
3693  change_timer = 1;
3694  }
3695 
3696  switch_rtp_set_interval(rtp_session, ms_per_packet, samples_per_interval);
3697 
3698  if (change_timer && rtp_session->timer_name) {
3699  READ_INC(rtp_session);
3700  WRITE_INC(rtp_session);
3701 
3702  if (rtp_session->timer.timer_interface) {
3703  switch_core_timer_destroy(&rtp_session->timer);
3704  }
3705  if ((status = switch_core_timer_init(&rtp_session->timer,
3706  rtp_session->timer_name, ms_per_packet / 1000,
3707  samples_per_interval, rtp_session->pool)) == SWITCH_STATUS_SUCCESS) {
3708 
3710  "RE-Starting timer [%s] %d bytes per %dms\n", rtp_session->timer_name, samples_per_interval, ms_per_packet / 1000);
3711  } else {
3712 
3713  memset(&rtp_session->timer, 0, sizeof(rtp_session->timer));
3715  "Problem RE-Starting timer [%s] %d bytes per %dms\n", rtp_session->timer_name, samples_per_interval, ms_per_packet / 1000);
3716  }
3717 
3718  WRITE_DEC(rtp_session);
3719  READ_DEC(rtp_session);
3720  }
3721 
3722  return status;
3723 }
3724 
3725 SWITCH_DECLARE(switch_status_t) switch_rtp_set_ssrc(switch_rtp_t *rtp_session, uint32_t ssrc)
3726 {
3727  rtp_session->ssrc = ssrc;
3728  rtp_session->send_msg.header.ssrc = htonl(rtp_session->ssrc);
3729 
3730  return SWITCH_STATUS_SUCCESS;
3731 }
3732 
3733 SWITCH_DECLARE(switch_status_t) switch_rtp_set_remote_ssrc(switch_rtp_t *rtp_session, uint32_t ssrc)
3734 {
3735  rtp_session->remote_ssrc = ssrc;
3736 
3737  return SWITCH_STATUS_SUCCESS;
3738 }
3739 
3740 SWITCH_DECLARE(switch_status_t) switch_rtp_create(switch_rtp_t **new_rtp_session,
3741  switch_payload_t payload,
3742  uint32_t samples_per_interval,
3743  uint32_t ms_per_packet,
3744  switch_rtp_flag_t flags[SWITCH_RTP_FLAG_INVALID], char *timer_name, const char **err, switch_memory_pool_t *pool)
3745 {
3746  switch_rtp_t *rtp_session = NULL;
3747  switch_core_session_t *session = switch_core_memory_pool_get_data(pool, "__session");
3748  switch_channel_t *channel = NULL;
3749 
3750  if (session) channel = switch_core_session_get_channel(session);
3751 
3752  *new_rtp_session = NULL;
3753 
3754  if (samples_per_interval > SWITCH_RTP_MAX_BUF_LEN) {
3755  *err = "Packet Size Too Large!";
3756  return SWITCH_STATUS_FALSE;
3757  }
3758 
3759  if (!(rtp_session = switch_core_alloc(pool, sizeof(*rtp_session)))) {
3760  *err = "Memory Error!";
3761  return SWITCH_STATUS_MEMERR;
3762  }
3763 
3764  rtp_session->pool = pool;
3765  rtp_session->te = INVALID_PT;
3766  rtp_session->recv_te = INVALID_PT;
3767  rtp_session->cng_pt = INVALID_PT;
3768  rtp_session->session = session;
3769 
3770  switch_mutex_init(&rtp_session->flag_mutex, SWITCH_MUTEX_NESTED, pool);
3771  switch_mutex_init(&rtp_session->read_mutex, SWITCH_MUTEX_NESTED, pool);
3772  switch_mutex_init(&rtp_session->write_mutex, SWITCH_MUTEX_NESTED, pool);
3773  switch_mutex_init(&rtp_session->ice_mutex, SWITCH_MUTEX_NESTED, pool);
3775  switch_queue_create(&rtp_session->dtmf_data.dtmf_queue, 100, rtp_session->pool);
3776  switch_queue_create(&rtp_session->dtmf_data.dtmf_inqueue, 100, rtp_session->pool);
3777 
3778  switch_rtp_set_flags(rtp_session, flags);
3779 
3780  /* for from address on recvfrom calls */
3781  switch_sockaddr_create(&rtp_session->from_addr, pool);
3782  switch_sockaddr_create(&rtp_session->rtp_from_addr, pool);
3783 
3784  if (rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP]) {
3785  switch_sockaddr_create(&rtp_session->rtcp_from_addr, pool);
3786  }
3787  rtp_session->seq = (uint16_t) rand();
3788  rtp_session->ssrc = (uint32_t) ((intptr_t) rtp_session + (uint32_t) switch_epoch_time_now(NULL));
3789 
3790  rtp_session->stats.inbound.R = 100.0;
3791  rtp_session->stats.inbound.mos = 4.5;
3792  rtp_session->send_msg.header.ssrc = htonl(rtp_session->ssrc);
3793  rtp_session->send_msg.header.ts = 0;
3794  rtp_session->send_msg.header.m = 0;
3795  rtp_session->send_msg.header.pt = (switch_payload_t) htonl(payload);
3796  rtp_session->send_msg.header.version = 2;
3797  rtp_session->send_msg.header.p = 0;
3798  rtp_session->send_msg.header.x = 0;
3799  rtp_session->send_msg.header.cc = 0;
3800 
3801  rtp_session->recv_msg.header.ssrc = 0;
3802  rtp_session->recv_msg.header.ts = 0;
3803  rtp_session->recv_msg.header.seq = 0;
3804  rtp_session->recv_msg.header.m = 0;
3805  rtp_session->recv_msg.header.pt = (switch_payload_t) htonl(payload);
3806  rtp_session->recv_msg.header.version = 2;
3807  rtp_session->recv_msg.header.p = 0;
3808  rtp_session->recv_msg.header.x = 0;
3809  rtp_session->recv_msg.header.cc = 0;
3810 
3811  rtp_session->payload = payload;
3812  rtp_session->rtcp_last_sent = switch_micro_time_now();
3813 
3814  switch_rtp_set_interval(rtp_session, ms_per_packet, samples_per_interval);
3815  rtp_session->conf_samples_per_interval = samples_per_interval;
3816 
3817  if (rtp_session->flags[SWITCH_RTP_FLAG_USE_TIMER] && zstr(timer_name)) {
3818  timer_name = "soft";
3819  }
3820 
3821  if (!zstr(timer_name) && !strcasecmp(timer_name, "none")) {
3822  timer_name = NULL;
3823  }
3824 
3825  if (!zstr(timer_name)) {
3826  rtp_session->timer_name = switch_core_strdup(pool, timer_name);
3829 
3830  if (switch_core_timer_init(&rtp_session->timer, timer_name, ms_per_packet / 1000, samples_per_interval, pool) == SWITCH_STATUS_SUCCESS) {
3832  "Starting timer [%s] %d bytes per %dms\n", timer_name, samples_per_interval, ms_per_packet / 1000);
3833  } else {
3834  memset(&rtp_session->timer, 0, sizeof(rtp_session->timer));
3836  "Error Starting timer [%s] %d bytes per %dms, async RTP disabled\n", timer_name, samples_per_interval, ms_per_packet / 1000);
3838  }
3839  } else {
3840  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
3841  if (switch_core_timer_init(&rtp_session->timer, "soft", 1, 90, pool) == SWITCH_STATUS_SUCCESS) {
3842  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG, "Starting video timer.\n");
3843  }
3844 
3845  //switch_jb_create(&rtp_session->vb, 3, 10, rtp_session->pool);
3846  //switch_jb_debug_level(rtp_session->vb, 10);
3847 
3848  } else {
3849  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG, "Not using a timer\n");
3850  }
3851 
3854  }
3855 
3856 
3857  if (channel) {
3858  switch_channel_set_private(channel, "__rtcp_audio_rtp_session", rtp_session);
3859  }
3860 
3861 #ifdef ENABLE_ZRTP
3862  if (zrtp_on && session && channel && !rtp_session->flags[SWITCH_RTP_FLAG_PROXY_MEDIA]) {
3863  switch_rtp_t *master_rtp_session = NULL;
3864 
3865  int initiator = 0;
3866  const char *zrtp_enabled = switch_channel_get_variable(channel, "zrtp_secure_media");
3867  int srtp_enabled = switch_channel_test_flag(channel, CF_SECURE);
3868 
3869  if (srtp_enabled && switch_true(zrtp_enabled)) {
3871  "You can not have ZRTP and SRTP enabled simultaneously, ZRTP will be disabled for this call!\n");
3872  switch_channel_set_variable(channel, "zrtp_secure_media", NULL);
3873  zrtp_enabled = NULL;
3874  }
3875 
3876 
3877  if (switch_true(zrtp_enabled)) {
3878  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
3879  switch_channel_set_private(channel, "__zrtp_video_rtp_session", rtp_session);
3880  master_rtp_session = switch_channel_get_private(channel, "__zrtp_audio_rtp_session");
3881  } else {
3882  switch_channel_set_private(channel, "__zrtp_audio_rtp_session", rtp_session);
3883  master_rtp_session = rtp_session;
3884  }
3885 
3886 
3888  initiator = 1;
3889  }
3890 
3891  if (rtp_session == master_rtp_session) {
3892  rtp_session->zrtp_profile = switch_core_alloc(rtp_session->pool, sizeof(*rtp_session->zrtp_profile));
3893  zrtp_profile_defaults(rtp_session->zrtp_profile, zrtp_global);
3894 
3895  rtp_session->zrtp_profile->allowclear = 0;
3896  rtp_session->zrtp_profile->disclose_bit = 0;
3897  rtp_session->zrtp_profile->cache_ttl = (uint32_t) -1;
3898 
3899  if (zrtp_status_ok != zrtp_session_init(zrtp_global, rtp_session->zrtp_profile, zid, initiator, &rtp_session->zrtp_session)) {
3900  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "Error! zRTP INIT Failed\n");
3901  zrtp_session_down(rtp_session->zrtp_session);
3902  rtp_session->zrtp_session = NULL;
3903  goto end;
3904  }
3905 
3906  zrtp_session_set_userdata(rtp_session->zrtp_session, session);
3907 
3908 
3909  if (zrtp_status_ok != zrtp_stream_attach(master_rtp_session->zrtp_session, &rtp_session->zrtp_stream)) {
3910  abort();
3911  }
3912 
3913  zrtp_stream_set_userdata(rtp_session->zrtp_stream, rtp_session);
3914 
3915  if (switch_true(switch_channel_get_variable(channel, "zrtp_enrollment"))) {
3916  zrtp_stream_registration_start(rtp_session->zrtp_stream, rtp_session->ssrc);
3917  } else {
3918  zrtp_stream_start(rtp_session->zrtp_stream, rtp_session->ssrc);
3919  }
3920  }
3921 
3922  }
3923  }
3924 
3925  end:
3926 
3927 #endif
3928 
3929  /* Jitter */
3930  rtp_session->stats.inbound.last_proc_time = switch_time_now() / 1000;
3931  rtp_session->stats.inbound.jitter_n = 0;
3932  rtp_session->stats.inbound.jitter_add = 0;
3933  rtp_session->stats.inbound.jitter_addsq = 0;
3934  rtp_session->stats.inbound.min_variance = 0;
3935  rtp_session->stats.inbound.max_variance = 0;
3936 
3937  /* Burst and Packet Loss */
3938  rtp_session->stats.inbound.lossrate = 0;
3939  rtp_session->stats.inbound.burstrate = 0;
3940  memset(rtp_session->stats.inbound.loss, 0, sizeof(rtp_session->stats.inbound.loss));
3941  rtp_session->stats.inbound.last_loss = 0;
3942  rtp_session->stats.inbound.last_processed_seq = -1;
3943 
3944  rtp_session->ready = 1;
3945  *new_rtp_session = rtp_session;
3946 
3947  return SWITCH_STATUS_SUCCESS;
3948 }
3949 
3950 SWITCH_DECLARE(switch_rtp_t *) switch_rtp_new(const char *rx_host,
3951  switch_port_t rx_port,
3952  const char *tx_host,
3953  switch_port_t tx_port,
3954  switch_payload_t payload,
3955  uint32_t samples_per_interval,
3956  uint32_t ms_per_packet,
3957  switch_rtp_flag_t flags[SWITCH_RTP_FLAG_INVALID], char *timer_name, const char **err, switch_memory_pool_t *pool)
3958 {
3959  switch_rtp_t *rtp_session = NULL;
3960 
3961  if (zstr(rx_host)) {
3962  *err = "Missing local host";
3963  goto end;
3964  }
3965 
3966  if (!rx_port) {
3967  *err = "Missing local port";
3968  goto end;
3969  }
3970 
3971  if (zstr(tx_host)) {
3972  *err = "Missing remote host";
3973  goto end;
3974  }
3975 
3976  if (!tx_port) {
3977  *err = "Missing remote port";
3978  goto end;
3979  }
3980 
3981  if (switch_rtp_create(&rtp_session, payload, samples_per_interval, ms_per_packet, flags, timer_name, err, pool) != SWITCH_STATUS_SUCCESS) {
3982  goto end;
3983  }
3984 
3985  switch_mutex_lock(rtp_session->flag_mutex);
3986 
3987  if (switch_rtp_set_local_address(rtp_session, rx_host, rx_port, err) != SWITCH_STATUS_SUCCESS) {
3988  switch_mutex_unlock(rtp_session->flag_mutex);
3989  rtp_session = NULL;
3990  goto end;
3991  }
3992 
3993  if (switch_rtp_set_remote_address(rtp_session, tx_host, tx_port, 0, SWITCH_TRUE, err) != SWITCH_STATUS_SUCCESS) {
3994  switch_mutex_unlock(rtp_session->flag_mutex);
3995  rtp_session = NULL;
3996  goto end;
3997  }
3998 
3999  end:
4000 
4001  if (rtp_session) {
4002  switch_mutex_unlock(rtp_session->flag_mutex);
4003  rtp_session->ready = 2;
4004  rtp_session->rx_host = switch_core_strdup(rtp_session->pool, rx_host);
4005  rtp_session->rx_port = rx_port;
4007  } else {
4008  switch_rtp_release_port(rx_host, rx_port);
4009  }
4010 
4011  return rtp_session;
4012 }
4013 
4015 {
4016  if (te > 95) {
4017  rtp_session->te = te;
4018  }
4019 }
4020 
4021 
4023 {
4024  if (te > 95) {
4025  rtp_session->recv_te = te;
4026  }
4027 }
4028 
4029 
4030 SWITCH_DECLARE(void) switch_rtp_set_cng_pt(switch_rtp_t *rtp_session, switch_payload_t pt)
4031 {
4032  rtp_session->cng_pt = pt;
4033  rtp_session->flags[SWITCH_RTP_FLAG_AUTO_CNG] = 1;
4034 }
4035 
4037 {
4038 
4039  if (rtp_session && rtp_session->timer.timer_interface) {
4040  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
4041  switch_core_timer_sync(&rtp_session->timer);
4042  }
4043  return &rtp_session->timer;
4044  }
4045 
4046  return NULL;
4047 }
4048 
4049 
4051 {
4052  if (!switch_rtp_ready(rtp_session) || !rtp_session->jb) {
4053  return NULL;
4054  }
4055 
4056  return rtp_session->jb;
4057 }
4058 
4060 {
4061 
4062  if (!switch_rtp_ready(rtp_session) || !rtp_session->jb) {
4063  return SWITCH_STATUS_FALSE;
4064  }
4065 
4066  if (!!pause == !!rtp_session->pause_jb) {
4067  return SWITCH_STATUS_FALSE;
4068  }
4069 
4070  if (rtp_session->pause_jb && !pause) {
4071  switch_jb_reset(rtp_session->jb);
4072  }
4073 
4074  rtp_session->pause_jb = pause ? 1 : 0;
4075 
4076  return SWITCH_STATUS_SUCCESS;
4077 }
4078 
4080 {
4081 
4082  if (!switch_rtp_ready(rtp_session) || !rtp_session->jb) {
4083  return SWITCH_STATUS_FALSE;
4084  }
4085 
4086  rtp_session->flags[SWITCH_RTP_FLAG_KILL_JB]++;
4087 
4088  return SWITCH_STATUS_SUCCESS;
4089 }
4090 
4091 SWITCH_DECLARE(switch_status_t) switch_rtp_get_video_buffer_size(switch_rtp_t *rtp_session, uint32_t *min_frame_len, uint32_t *max_frame_len, uint32_t *cur_frame_len, uint32_t *highest_frame_len)
4092 {
4093 
4094  if (rtp_session->vb) {
4095  return switch_jb_get_frames(rtp_session->vb, min_frame_len, max_frame_len, cur_frame_len, highest_frame_len);
4096  }
4097 
4098  return SWITCH_STATUS_FALSE;
4099 }
4100 
4101 SWITCH_DECLARE(switch_status_t) switch_rtp_set_video_buffer_size(switch_rtp_t *rtp_session, uint32_t frames, uint32_t max_frames)
4102 {
4103  if (!switch_rtp_ready(rtp_session)) {
4104  return SWITCH_STATUS_FALSE;
4105  }
4106 
4107  if (!max_frames) {
4108  max_frames = 50;
4109  }
4110 
4111  if (!rtp_session->vb) {
4112  switch_jb_create(&rtp_session->vb, SJB_VIDEO, frames, max_frames, rtp_session->pool);
4113  switch_jb_set_session(rtp_session->vb, rtp_session->session);
4114  } else {
4115  switch_jb_set_frames(rtp_session->vb, frames, max_frames);
4116  }
4117 
4118  //switch_rtp_flush(rtp_session);
4119  switch_core_session_request_video_refresh(rtp_session->session);
4120 
4121  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG1, "Setting video buffer %u Frames.\n", frames);
4122 
4123  return SWITCH_STATUS_SUCCESS;
4124 }
4125 
4126 SWITCH_DECLARE(switch_status_t) switch_rtp_debug_jitter_buffer(switch_rtp_t *rtp_session, const char *name)
4127 {
4128  int x = 0;
4129 
4130  if (!switch_rtp_ready(rtp_session)) {
4131  return SWITCH_STATUS_FALSE;
4132  }
4133 
4134  if (name) x = atoi(name);
4135  if (x < 0) x = 0;
4136 
4137  if (rtp_session->jb) {
4138  switch_jb_debug_level(rtp_session->jb, x);
4139  } else if (rtp_session->vb) {
4140  switch_jb_debug_level(rtp_session->vb, x);
4141  }
4142 
4143  return SWITCH_STATUS_SUCCESS;
4144 }
4145 
4147  uint32_t queue_frames,
4148  uint32_t max_queue_frames,
4149  uint32_t samples_per_packet,
4150  uint32_t samples_per_second)
4151 {
4153 
4154  if (!switch_rtp_ready(rtp_session)) {
4155  return SWITCH_STATUS_FALSE;
4156  }
4157 
4158  if (queue_frames < 1) {
4159  queue_frames = 3;
4160  }
4161 
4162  if (max_queue_frames < queue_frames) {
4163  max_queue_frames = queue_frames * 3;
4164  }
4165 
4166 
4167 
4168  if (rtp_session->jb) {
4169  status = switch_jb_set_frames(rtp_session->jb, queue_frames, max_queue_frames);
4170  } else {
4171  READ_INC(rtp_session);
4172  status = switch_jb_create(&rtp_session->jb, SJB_AUDIO, queue_frames, max_queue_frames, rtp_session->pool);
4173  switch_jb_set_session(rtp_session->jb, rtp_session->session);
4174  if (switch_true(switch_channel_get_variable_dup(switch_core_session_get_channel(rtp_session->session), "jb_use_timestamps", SWITCH_FALSE, -1))) {
4175  switch_jb_ts_mode(rtp_session->jb, samples_per_packet, samples_per_second);
4176  }
4177  //switch_jb_debug_level(rtp_session->jb, 10);
4178  READ_DEC(rtp_session);
4179  }
4180 
4181 
4182 
4183  return status;
4184 }
4185 
4186 SWITCH_DECLARE(switch_status_t) switch_rtp_activate_rtcp(switch_rtp_t *rtp_session, int send_rate, switch_port_t remote_port, switch_bool_t mux)
4187 {
4188  const char *err = NULL;
4189 
4190  if (!rtp_session->ms_per_packet) {
4191  return SWITCH_STATUS_FALSE;
4192  }
4193 
4194  rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP] = 1;
4195 
4196  if (!(rtp_session->remote_rtcp_port = remote_port)) {
4197  rtp_session->remote_rtcp_port = rtp_session->remote_port + 1;
4198  }
4199 
4200  if (mux) {
4201  rtp_session->flags[SWITCH_RTP_FLAG_RTCP_MUX]++;
4202  }
4203 
4204 
4205  if (send_rate == -1) {
4206 
4207  rtp_session->flags[SWITCH_RTP_FLAG_RTCP_PASSTHRU] = 1;
4208  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG, "RTCP passthru enabled. Remote Port: %d\n", rtp_session->remote_rtcp_port);
4209  } else {
4210  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_DEBUG, "RTCP send rate is: %d and packet rate is: %d Remote Port: %d\n", send_rate, rtp_session->ms_per_packet, rtp_session->remote_rtcp_port);
4211 
4212  rtp_session->rtcp_interval = send_rate;
4213  }
4214 
4215  if (rtp_session->flags[SWITCH_RTP_FLAG_RTCP_MUX]) {
4216 
4217  if (switch_sockaddr_info_get(&rtp_session->rtcp_remote_addr, rtp_session->eff_remote_host_str, SWITCH_UNSPEC,
4218  rtp_session->remote_rtcp_port, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS || !rtp_session->rtcp_remote_addr) {
4219  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "RTCP MUX Remote Address Error!");
4220  return SWITCH_STATUS_FALSE;
4221  }
4222 
4223  rtp_session->rtcp_local_addr = rtp_session->local_addr;
4224  rtp_session->rtcp_from_addr = rtp_session->from_addr;
4225  rtp_session->rtcp_sock_input = rtp_session->sock_input;
4226  rtp_session->rtcp_sock_output = rtp_session->sock_output;
4227 
4228  rtp_session->rtcp_recv_msg_p = (rtcp_msg_t *) &rtp_session->recv_msg;
4229 
4230  return SWITCH_STATUS_SUCCESS;
4231 
4232  //return enable_remote_rtcp_socket(rtp_session, &err);
4233  } else {
4234  rtp_session->rtcp_recv_msg_p = (rtcp_msg_t *) &rtp_session->rtcp_recv_msg;
4235  }
4236 
4237  return enable_local_rtcp_socket(rtp_session, &err) || enable_remote_rtcp_socket(rtp_session, &err);
4238 
4239 }
4240 
4241 SWITCH_DECLARE(switch_status_t) switch_rtp_activate_ice(switch_rtp_t *rtp_session, char *login, char *rlogin,
4242  const char *password, const char *rpassword, ice_proto_t proto,
4243  switch_core_media_ice_type_t type, ice_t *ice_params)
4244 {
4245  char ice_user[80];
4246  char user_ice[80];
4247  char luser_ice[80];
4248  switch_rtp_ice_t *ice;
4249  char *host = NULL;
4250  switch_port_t port = 0;
4251  char bufc[50];
4252 
4253 
4254  switch_mutex_lock(rtp_session->ice_mutex);
4255 
4256  if (proto == IPR_RTP) {
4257  ice = &rtp_session->ice;
4258  rtp_session->flags[SWITCH_RTP_FLAG_PAUSE] = 0;
4259  rtp_session->flags[SWITCH_RTP_FLAG_MUTE] = 0;
4260  } else {
4261  ice = &rtp_session->rtcp_ice;
4262  }
4263 
4264  ice->proto = proto;
4265 
4266  if ((type & ICE_VANILLA)) {
4267  switch_snprintf(ice_user, sizeof(ice_user), "%s:%s", login, rlogin);
4268  switch_snprintf(user_ice, sizeof(user_ice), "%s:%s", rlogin, login);
4269  switch_snprintf(luser_ice, sizeof(user_ice), "%s%s", rlogin, login);
4270  ice->ready = ice->rready = 0;
4271  } else {
4272  switch_snprintf(ice_user, sizeof(ice_user), "%s%s", login, rlogin);
4273  switch_snprintf(user_ice, sizeof(user_ice), "%s%s", rlogin, login);
4274  ice->ready = ice->rready = 1;
4275  }
4276 
4277  ice->ice_user = switch_core_strdup(rtp_session->pool, ice_user);
4278  ice->user_ice = switch_core_strdup(rtp_session->pool, user_ice);
4279  ice->luser_ice = switch_core_strdup(rtp_session->pool, luser_ice);
4280  ice->type = type;
4281  ice->ice_params = ice_params;
4282  ice->pass = "";
4283  ice->rpass = "";
4285 
4286  if (password) {
4287  ice->pass = switch_core_strdup(rtp_session->pool, password);
4288  }
4289 
4290  if (rpassword) {
4291  ice->rpass = switch_core_strdup(rtp_session->pool, rpassword);
4292  }
4293 
4294  if ((ice->type & ICE_VANILLA) && ice->ice_params) {
4295  host = ice->ice_params->cands[ice->ice_params->chosen[ice->proto]][ice->proto].con_addr;
4296  port = ice->ice_params->cands[ice->ice_params->chosen[ice->proto]][ice->proto].con_port;
4297 
4298  if (!host || !port || switch_sockaddr_info_get(&ice->addr, host, SWITCH_UNSPEC, port, 0, rtp_session->pool) != SWITCH_STATUS_SUCCESS || !ice->addr) {
4299  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_ERROR, "Error setting remote host!\n");
4300  return SWITCH_STATUS_FALSE;
4301  }
4302  } else {
4303  if (proto == IPR_RTP) {
4304  ice->addr = rtp_session->remote_addr;
4305  } else {
4306  ice->addr = rtp_session->rtcp_remote_addr;
4307  }
4308 
4309  host = (char *)switch_get_addr(bufc, sizeof(bufc), ice->addr);
4310  port = switch_sockaddr_get_port(ice->addr);
4311  }
4312 
4313  switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(rtp_session->session), SWITCH_LOG_NOTICE, "Activating %s %s ICE: %s %s:%d\n",
4314  proto == IPR_RTP ? "RTP" : "RTCP", rtp_type(rtp_session), ice_user, host, port);
4315 
4316 
4317  rtp_session->rtp_bugs |= RTP_BUG_ACCEPT_ANY_PACKETS;
4318 
4319 
4320  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
4321  rtp_session->flags[SWITCH_RTP_FLAG_VIDEO_BREAK] = 1;
4322  switch_rtp_break(rtp_session);
4323  }
4324 
4325  switch_mutex_unlock(rtp_session->ice_mutex);
4326 
4327  return SWITCH_STATUS_SUCCESS;
4328 }
4329 
4330 
4331 SWITCH_DECLARE(void) switch_rtp_flush(switch_rtp_t *rtp_session)
4332 {
4333  if (!switch_rtp_ready(rtp_session)) {
4334  return;
4335  }
4336 
4338 }
4339 
4340 SWITCH_DECLARE(switch_status_t) switch_rtp_req_bitrate(switch_rtp_t *rtp_session, uint32_t bps)
4341 {
4342  if (!rtp_write_ready(rtp_session, 0, __LINE__) || rtp_session->tmmbr) {
4343  return SWITCH_STATUS_FALSE;
4344  }
4345 
4346  rtp_session->tmmbr = bps;
4347 
4348  return SWITCH_STATUS_SUCCESS;
4349 }
4350 
4351 SWITCH_DECLARE(switch_status_t) switch_rtp_ack_bitrate(switch_rtp_t *rtp_session, uint32_t bps)
4352 {
4353  if (!rtp_write_ready(rtp_session, 0, __LINE__) || rtp_session->tmmbn) {
4354  return SWITCH_STATUS_FALSE;
4355  }
4356 
4357  rtp_session->tmmbn = bps;
4358 
4359  return SWITCH_STATUS_SUCCESS;
4360 }
4361 
4362 SWITCH_DECLARE(void) switch_rtp_video_refresh(switch_rtp_t *rtp_session)
4363 {
4364 
4365  if (!rtp_write_ready(rtp_session, 0, __LINE__)) {
4366  return;
4367  }
4368 
4369  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO] && (rtp_session->ice.ice_user || rtp_session->flags[SWITCH_RTP_FLAG_FIR])) {
4370  rtp_session->fir_count = 1;
4371  }
4372 }
4373 
4374 SWITCH_DECLARE(void) switch_rtp_video_loss(switch_rtp_t *rtp_session)
4375 {
4376  if (!rtp_write_ready(rtp_session, 0, __LINE__)) {
4377  return;
4378  }
4379 
4380  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO] && (rtp_session->ice.ice_user || rtp_session->flags[SWITCH_RTP_FLAG_PLI])) {
4381  rtp_session->pli_count = 1;
4382  }
4383 }
4384 
4385 SWITCH_DECLARE(void) switch_rtp_break(switch_rtp_t *rtp_session)
4386 {
4387  if (!switch_rtp_ready(rtp_session)) {
4388  return;
4389  }
4390 
4391  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO]) {
4392  int ret = 1;
4393 
4394  if (rtp_session->flags[SWITCH_RTP_FLAG_VIDEO_BREAK]) {
4395  rtp_session->flags[SWITCH_RTP_FLAG_VIDEO_BREAK] = 0;
4396  ret = 0;
4397  } else if (rtp_session->session) {
4398  switch_channel_t *channel = switch_core_session_get_channel(rtp_session->session);
4399  if (switch_channel_test_flag(channel, CF_VIDEO_BREAK)) {
4401  ret = 0;
4402  }
4403  }
4404 
4405  if (ret) return;
4406 
4407  switch_rtp_video_refresh(rtp_session);
4408  }
4409 
4410  switch_mutex_lock(rtp_session->flag_mutex);
4411  rtp_session->flags[SWITCH_RTP_FLAG_BREAK] = 1;
4412 
4413  if (rtp_session->flags[SWITCH_RTP_FLAG_NOBLOCK]) {
4414  switch_mutex_unlock(rtp_session->flag_mutex);
4415  return;
4416  }
4417 
4418  if (rtp_session->sock_input) {
4419  ping_socket(rtp_session);
4420  }
4421 
4422  switch_mutex_unlock(rtp_session->flag_mutex);
4423 }
4424 
4425 SWITCH_DECLARE(void) switch_rtp_kill_socket(switch_rtp_t *rtp_session)
4426 {
4427  switch_assert(rtp_session != NULL);
4428  switch_mutex_lock(rtp_session->flag_mutex);
4429  if (rtp_session->flags[SWITCH_RTP_FLAG_IO]) {
4430  rtp_session->flags[SWITCH_RTP_FLAG_IO] = 0;
4431  if (rtp_session->sock_input) {
4432  ping_socket(rtp_session);
4433  switch_socket_shutdown(rtp_session->sock_input, SWITCH_SHUTDOWN_READWRITE);
4434  }
4435  if (rtp_session->sock_output && rtp_session->sock_output != rtp_session->sock_input) {
4436  switch_socket_shutdown(rtp_session->sock_output, SWITCH_SHUTDOWN_READWRITE);
4437  }
4438 
4439  if (rtp_session->flags[SWITCH_RTP_FLAG_ENABLE_RTCP]) {
4440  if (rtp_session->rtcp_sock_input) {
4441  ping_socket(rtp_session);
4442  switch_socket_shutdown(rtp_session->rtcp_sock_input, SWITCH_SHUTDOWN_READWRITE);
4443  }
4444  if (rtp_session->rtcp_sock_output && rtp_session->rtcp_sock_output != rtp_session->rtcp_sock_input) {
4445  switch_socket_shutdown(rtp_session->rtcp_sock_output, SWITCH_SHUTDOWN_READWRITE);
4446  }
4447  }
4448  }
4449  switch_mutex_unlock(rtp_session->flag_mutex);
4450 }
4451 
4452 SWITCH_DECLARE(uint8_t) switch_rtp_ready(switch_rtp_t *rtp_session)
4453 {
4454  uint8_t ret;
4455 
4456  if (!rtp_session || !rtp_session->flag_mutex || rtp_session->flags[SWITCH_RTP_FLAG_SHUTDOWN]) {
4457  return 0;
4458  }
4459 
4460  switch_mutex_lock(rtp_session->flag_mutex);
4461  ret = (rtp_session->flags[SWITCH_RTP_FLAG_IO] && rtp_session->sock_input && rtp_session->sock_output && rtp_session->remote_addr
4462  && rtp_session->ready == 2) ? 1 : 0;
4463  switch_mutex_unlock(rtp_session->flag_mutex);
4464 
4465  return ret;
4466 }
4467 
4469 {
4470  if (!rtp_session) {
4471  return SWITCH_STATUS_FALSE;
4472  }
4473 
4474  if (rtp_session->flags[SWITCH_RTP_FLAG_VAD]) {
4475  switch_channel_t *channel = switch_core_session_get_channel(rtp_session->vad_data.session);
4476 
4477  switch_channel_set_variable_printf(channel, "vad_total_talk_time_ms", "%u", (uint32_t)rtp_session->vad_data.total_talk_time / 1000);
4478  switch_channel_set_variable_printf(channel, "vad_total_talk_time_sec", "%u", (uint32_t)rtp_session->vad_data.total_talk_time / 1000000);
4479  }
4480 
4481  do_mos(rtp_session, SWITCH_TRUE);
4482 
4483  if (rtp_session->stats.inbound.error_log && !rtp_session->stats.inbound.error_log->stop) {
4484  rtp_session->stats.inbound.error_log->stop = switch_micro_time_now();
4485  }
4486 
4487  return SWITCH_STATUS_SUCCESS;
4488 }
4489 
4490 
4491 SWITCH_DECLARE(void) switch_rtp_destroy(switch_rtp_t **rtp_session)
4492 {
4493  void *pop;
4494  switch_socket_t *sock;
4495 #ifdef ENABLE_SRTP
4496  int x;
4497 #endif
4498 
4499  if (!rtp_session || !*rtp_session || !(*rtp_session)->ready) {
4500  return;
4501  }
4502 
4503  (*rtp_session)->flags[SWITCH_RTP_FLAG_SHUTDOWN] = 1;
4504 
4505  READ_INC((*rtp_session));
4506  WRITE_INC((*rtp_session));
4507 
4508  (*rtp_session)->ready = 0;
4509 
4510  READ_DEC((*rtp_session));
4511  WRITE_DEC((*rtp_session));
4512 
4513  if ((*rtp_session)->flags[SWITCH_RTP_FLAG_VAD]) {
4514  switch_rtp_disable_vad(*rtp_session);
4515  }
4516 
4517  switch_mutex_lock((*rtp_session)->flag_mutex);
4518 
4519  switch_rtp_kill_socket(*rtp_session);
4520 
4521  while (switch_queue_trypop((*rtp_session)->dtmf_data.dtmf_inqueue, &pop) == SWITCH_STATUS_SUCCESS) {
4522  switch_safe_free(pop);
4523  }
4524 
4525  while (switch_queue_trypop((*rtp_session)->dtmf_data.dtmf_queue, &pop) == SWITCH_STATUS_SUCCESS) {
4526  switch_safe_free(pop);
4527  }
4528 
4529  if ((*rtp_session)->jb) {
4530  switch_jb_destroy(&(*rtp_session)->jb);
4531  }
4532 
4533  if ((*rtp_session)->vb) {
4534  switch_jb_destroy(&(*rtp_session)->vb);
4535  }
4536 
4537  if ((*rtp_session)->vbw) {
4538  switch_jb_destroy(&(*rtp_session)->vbw);
4539  }
4540 
4541  if ((*rtp_session)->dtls && (*rtp_session)->dtls == (*rtp_session)->rtcp_dtls) {
4542  (*rtp_session)->rtcp_dtls = NULL;
4543  }
4544 
4545  if ((*rtp_session)->dtls) {
4546  free_dtls(&(*rtp_session)->dtls);
4547  }
4548 
4549  if ((*rtp_session)->rtcp_dtls) {
4550  free_dtls(&(*rtp_session)->rtcp_dtls);
4551  }
4552 
4553 
4554  sock = (*rtp_session)->sock_input;
4555  (*rtp_session)->sock_input = NULL;
4556  switch_socket_close(sock);
4557 
4558  if ((*rtp_session)->sock_output != sock) {
4559  sock = (*rtp_session)->sock_output;
4560  (*rtp_session)->sock_output = NULL;
4561  switch_socket_close(sock);
4562  }
4563 
4564  if ((sock = (*rtp_session)->rtcp_sock_input)) {
4565  (*rtp_session)->rtcp_sock_input = NULL;
4566  switch_socket_close(sock);
4567 
4568  if ((*rtp_session)->rtcp_sock_output && (*rtp_session)->rtcp_sock_output != sock) {
4569  if ((sock = (*rtp_session)->rtcp_sock_output)) {
4570  (*rtp_session)->rtcp_sock_output = NULL;
4571  switch_socket_close(sock);
4572  }
4573  }
4574  }
4575 
4576 #ifdef ENABLE_SRTP
4577  if ((*rtp_session)->flags[SWITCH_RTP_FLAG_SECURE_SEND]) {
4578  for(x = 0; x < 2; x++) {
4579  if ((*rtp_session)->send_ctx[x]) {
4580  srtp_dealloc((*rtp_session)->send_ctx[x]);
4581  (*rtp_session)->send_ctx[x] = NULL;
4582  }
4583  }
4584  (*rtp_session)->flags[SWITCH_RTP_FLAG_SECURE_SEND] = 0;
4585  }
4586 
4587  if ((*rtp_session)->flags[SWITCH_RTP_FLAG_SECURE_RECV]) {
4588  for (x = 0; x < 2; x++) {
4589  if ((*rtp_session)->recv_ctx[x]) {
4590  srtp_dealloc((*rtp_session)->recv_ctx[x]);
4591  (*rtp_session)->recv_ctx[x] = NULL;
4592  }
4593  }
4594  (*rtp_session)->flags[SWITCH_RTP_FLAG_SECURE_RECV] = 0;
4595  }
4596 #endif
4597 
4598 #ifdef ENABLE_ZRTP
4599  /* ZRTP */
4600  if (zrtp_on && !(*rtp_session)->flags[SWITCH_RTP_FLAG_PROXY_MEDIA]) {
4601 
4602  if ((*rtp_session)->zrtp_stream != NULL) {
4603  zrtp_stream_stop((*rtp_session)->zrtp_stream);
4604  }
4605 
4606  if ((*rtp_session)->flags[SWITCH_ZRTP_FLAG_SECURE_SEND]) {
4607  (*rtp_session)->flags[SWITCH_ZRTP_FLAG_SECURE_SEND] = 0;
4608  }
4609 
4610  if ((*rtp_session)->flags[SWITCH_ZRTP_FLAG_SECURE_RECV]) {
4611  (*rtp_session)->flags[SWITCH_ZRTP_FLAG_SECURE_RECV] = 0;
4612  }
4613 
4614  if ((*rtp_session)->zrtp_session) {
4615  zrtp_session_down((*rtp_session)->zrtp_session);
4616  (*rtp_session)->zrtp_session = NULL;
4617  }
4618  }
4619 #endif
4620  if ((*rtp_session)->timer.timer_interface) {
4621  switch_core_timer_destroy(&(*rtp_session)->timer);
4622  }
4623 
4624  switch_rtp_release_port((*rtp_session)->rx_host, (*rtp_session)->rx_port);
4625  switch_mutex_unlock((*rtp_session)->flag_mutex);
4626 
4627  return;
4628 }
4629 
4630 SWITCH_DECLARE(void) switch_rtp_set_interdigit_delay(switch_rtp_t *rtp_session, uint32_t delay)
4631 {
4632  rtp_session->interdigit_delay = delay;
4633 }
4634 
4636 {
4637  return rtp_session->sock_input;
4638 }
4639 
4641 {
4642  return rtp_session->samples_per_interval;
4643 }
4644 
4645 SWITCH_DECLARE(void) switch_rtp_set_default_payload(switch_rtp_t *rtp_session, switch_payload_t payload)
4646 {
4647  rtp_session->payload = payload;
4648 }
4649 
4650 SWITCH_DECLARE(uint32_t) switch_rtp_get_default_payload(switch_rtp_t *rtp_session)
4651 {
4652  return rtp_session->payload;
4653 }
4654 
4656 {
4657  rtp_session->invalid_handler = on_invalid;
4658 }
4659 
4661 {
4662  int i;
4663 
4664  for(i = 0; i < SWITCH_RTP_FLAG_INVALID; i++) {
4665  if (flags[i]) {
4666  rtp_session->flags[i] = flags[i];
4667 
4668  if (i == SWITCH_RTP_FLAG_AUTOADJ) {
4669  rtp_session->autoadj_window = 20;
4670  rtp_session->autoadj_threshold = 10;
4671  rtp_session->autoadj_tally = 0;
4672  if (rtp_session->session) {
4673  switch_channel_t *channel = switch_core_session_get_channel(rtp_session->session);
4674  const char *x = switch_channel_get_variable(channel, "rtp_auto_adjust_threshold");
4675  if (x && *x) {
4676  int xn = atoi(x);
4677  if (xn > 0 && xn <= 65535) {
4678  rtp_session->autoadj_window = xn*2;
4679  rtp_session->autoadj_threshold = xn;
4680  }
4681  }
4682  }
4684  } else if (i == SWITCH_RTP_FLAG_NOBLOCK && rtp_session->sock_input) {
4685  switch_socket_opt_set(rtp_session->sock_input, SWITCH_SO_NONBLOCK, TRUE);
4686  }
4687  }
4688  }
4689 }
4690 
4692 {
4693  int i;
4694 
4695  for(i = 0; i < SWITCH_RTP_FLAG_INVALID; i++) {
4696  if (flags[i]) {
4697  rtp_session->flags[i] = 0;
4698  }
4699  }
4700 }
4701 
4702 SWITCH_DECLARE(void) switch_rtp_set_flag(switch_rtp_t *rtp_session, switch_rtp_flag_t flag)
4703 {
4704 
4705  switch_mutex_lock(rtp_session->flag_mutex);
4706  rtp_session->flags[flag] = 1;
4707  switch_mutex_unlock(rtp_session->flag_mutex);
4708 
4709  if (flag == SWITCH_RTP_FLAG_DTMF_ON) {
4710  rtp_session->stats.inbound.last_processed_seq = 0;
4711  } else if (flag == SWITCH_RTP_FLAG_FLUSH) {
4712  reset_jitter_seq(rtp_session);
4713  } else if (flag == SWITCH_RTP_FLAG_AUTOADJ) {
4714  rtp_session->autoadj_window = 20;
4715  rtp_session->autoadj_threshold = 10;
4716  rtp_session->autoadj_tally = 0;
4717  if (rtp_session->session) {
4718  switch_channel_t *channel = switch_core_session_get_channel(rtp_session->session);
4719  const char *x = switch_channel_get_variable(channel, "rtp_auto_adjust_threshold");
4720  if (x && *x) {
4721  int xn = atoi(x);
4722  if (xn > 0 && xn <= 65535) {
4723  rtp_session->autoadj_window = xn*2;
4724  rtp_session->autoadj_threshold = xn;
4725  }
4726  }
4727  }
4728 
4729 
4731 
4732 
4733  if (rtp_session->jb) {
4734  switch_jb_reset(rtp_session->jb);
4735  }
4736  } else if (flag == SWITCH_RTP_FLAG_NOBLOCK && rtp_session->sock_input) {
4737  switch_socket_opt_set(rtp_session->sock_input, SWITCH_SO_NONBLOCK, TRUE);
4738  }
4739 
4740 }
4741 
4742 SWITCH_DECLARE(uint32_t) switch_rtp_test_flag(switch_rtp_t *rtp_session, switch_rtp_flag_t flags)
4743 {
4744  return (uint32_t) rtp_session->flags[flags];
4745 }
4746 
4747 SWITCH_DECLARE(void) switch_rtp_clear_flag(switch_rtp_t *rtp_session, switch_rtp_flag_t flag)
4748 {
4749 
4750  switch_mutex_lock(rtp_session->flag_mutex);
4751  rtp_session->flags[flag] = 0;
4752  switch_mutex_unlock(rtp_session->flag_mutex);
4753 
4754  if (flag == SWITCH_RTP_FLAG_DTMF_ON) {
4755  rtp_session->stats.inbound.last_processed_seq = 0;
4756  } else if (flag == SWITCH_RTP_FLAG_PAUSE) {
4757  reset_jitter_seq(rtp_session);
4758  } else if (flag == SWITCH_RTP_FLAG_NOBLOCK && rtp_session->sock_input) {
4759