2 * Asterisk -- A telephony toolkit for Linux.
4 * Real-time Protocol Support
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
22 #include <netinet/in.h>
24 #include <sys/socket.h>
25 #include <arpa/inet.h>
28 #include <asterisk/rtp.h>
29 #include <asterisk/frame.h>
30 #include <asterisk/logger.h>
31 #include <asterisk/options.h>
32 #include <asterisk/channel.h>
33 #include <asterisk/acl.h>
34 #include <asterisk/channel.h>
35 #include <asterisk/channel_pvt.h>
36 #include <asterisk/config.h>
42 #define TYPE_SILENCE 0x2
43 #define TYPE_DONTSEND 0x3
46 static int dtmftimeout = 300; /* 300 samples */
48 static int rtpstart = 0;
49 static int rtpend = 0;
51 // The value of each payload format mapping:
52 struct rtpPayloadType {
53 int isAstFormat; // whether the following code is an AST_FORMAT
57 #define MAX_RTP_PT 256
63 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
66 unsigned int lastrxts;
67 unsigned int lastividtimestamp;
68 unsigned int lastovidtimestamp;
72 unsigned int dtmfduration;
74 struct sockaddr_in us;
75 struct sockaddr_in them;
76 struct timeval rxcore;
77 struct timeval txcore;
78 struct ast_smoother *smoother;
81 struct sched_context *sched;
82 struct io_context *io;
84 ast_rtp_callback callback;
85 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
86 // a cache for the result of rtp_lookup_code():
87 int rtp_lookup_code_cache_isAstFormat;
88 int rtp_lookup_code_cache_code;
89 int rtp_lookup_code_cache_result;
90 struct ast_rtcp *rtcp;
95 struct sockaddr_in us;
96 struct sockaddr_in them;
99 static struct ast_rtp_protocol *protos = NULL;
101 int ast_rtp_fd(struct ast_rtp *rtp)
106 int ast_rtcp_fd(struct ast_rtp *rtp)
113 static int g723_len(unsigned char buf)
115 switch(buf & TYPE_MASK) {
129 ast_log(LOG_WARNING, "Badly encoded frame (%d)\n", buf & TYPE_MASK);
134 static int g723_samples(unsigned char *buf, int maxlen)
139 while(pos < maxlen) {
140 res = g723_len(buf[pos]);
149 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
154 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
156 rtp->callback = callback;
159 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
164 static struct ast_frame *send_dtmf(struct ast_rtp *rtp)
166 ast_log(LOG_DEBUG, "Sending dtmf: %d (%c)\n", rtp->resp, rtp->resp);
167 rtp->f.frametype = AST_FRAME_DTMF;
168 rtp->f.subclass = rtp->resp;
174 rtp->dtmfduration = 0;
179 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
183 struct ast_frame *f = NULL;
184 event = ntohl(*((unsigned int *)(data)));
187 printf("Cisco Digit: %08x (len = %d)\n", event, len);
191 } else if (event < 11) {
193 } else if (event < 12) {
195 } else if (event < 16) {
196 resp = 'A' + (event - 12);
198 if (rtp->resp && (rtp->resp != resp)) {
202 rtp->dtmfcount = dtmftimeout;
206 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len)
209 unsigned int event_end;
210 unsigned int duration;
212 struct ast_frame *f = NULL;
213 event = ntohl(*((unsigned int *)(data)));
215 event_end = ntohl(*((unsigned int *)(data)));
218 duration = ntohl(*((unsigned int *)(data)));
221 printf("Event: %08x (len = %d)\n", event, len);
225 } else if (event < 11) {
227 } else if (event < 12) {
229 } else if (event < 16) {
230 resp = 'A' + (event - 12);
232 if (rtp->resp && (rtp->resp != resp)) {
235 else if(event_end & 0x80)
244 else if(rtp->dtmfduration && (duration < rtp->dtmfduration))
248 if (!(event_end & 0x80))
250 rtp->dtmfcount = dtmftimeout;
251 rtp->dtmfduration = duration;
255 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
257 struct ast_frame *f = NULL;
258 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
259 totally help us out becuase we don't have an engine to keep it going and we are not
260 guaranteed to have it every 20ms or anything */
262 printf("RFC3389: %d bytes, format is %d\n", len, rtp->lastrxformat);
264 ast_log(LOG_NOTICE, "RFC3389 support incomplete. Turn off on client if possible\n");
265 if (!rtp->lastrxformat)
267 switch(rtp->lastrxformat) {
268 case AST_FORMAT_ULAW:
269 rtp->f.frametype = AST_FRAME_VOICE;
270 rtp->f.subclass = AST_FORMAT_ULAW;
271 rtp->f.datalen = 160;
272 rtp->f.samples = 160;
273 memset(rtp->f.data, 0x7f, rtp->f.datalen);
276 case AST_FORMAT_ALAW:
277 rtp->f.frametype = AST_FRAME_VOICE;
278 rtp->f.subclass = AST_FORMAT_ALAW;
279 rtp->f.datalen = 160;
280 rtp->f.samples = 160;
281 memset(rtp->f.data, 0x7e, rtp->f.datalen); /* XXX Is this right? XXX */
284 case AST_FORMAT_SLINEAR:
285 rtp->f.frametype = AST_FRAME_VOICE;
286 rtp->f.subclass = AST_FORMAT_SLINEAR;
287 rtp->f.datalen = 320;
288 rtp->f.samples = 160;
289 memset(rtp->f.data, 0x00, rtp->f.datalen);
293 ast_log(LOG_NOTICE, "Don't know how to handle RFC3389 for receive codec %d\n", rtp->lastrxformat);
298 static int rtpread(int *id, int fd, short events, void *cbdata)
300 struct ast_rtp *rtp = cbdata;
302 f = ast_rtp_read(rtp);
305 rtp->callback(rtp, f, rtp->data);
310 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
312 static struct ast_frame null_frame = { AST_FRAME_NULL, };
316 struct sockaddr_in sin;
317 unsigned int rtcpdata[1024];
324 res = recvfrom(rtp->rtcp->s, rtcpdata, sizeof(rtcpdata),
325 0, (struct sockaddr *)&sin, &len);
328 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
335 ast_log(LOG_WARNING, "RTP Read too short\n");
340 /* Send to whoever sent to us */
341 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
342 (rtp->rtcp->them.sin_port != sin.sin_port)) {
343 memcpy(&rtp->them, &sin, sizeof(rtp->them));
344 ast_log(LOG_DEBUG, "RTP NAT: Using address %s:%d\n", inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
348 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
352 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp)
354 if (!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) {
355 gettimeofday(&rtp->rxcore, NULL);
356 rtp->rxcore.tv_usec -= timestamp / 8000;
357 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
358 if (rtp->rxcore.tv_usec < 0) {
359 /* Adjust appropriately if necessary */
360 rtp->rxcore.tv_usec += 1000000;
361 rtp->rxcore.tv_sec -= 1;
364 tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
365 tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
366 if (tv->tv_usec >= 1000000) {
367 tv->tv_usec -= 1000000;
372 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
375 struct sockaddr_in sin;
381 unsigned int timestamp;
382 unsigned int *rtpheader;
383 static struct ast_frame *f, null_frame = { AST_FRAME_NULL, };
384 struct rtpPayloadType rtpPT;
388 /* Cache where the header will go */
389 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
390 0, (struct sockaddr *)&sin, &len);
393 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
395 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
401 ast_log(LOG_WARNING, "RTP Read too short\n");
405 /* Send to whoever sent to us */
406 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
407 (rtp->them.sin_port != sin.sin_port)) {
408 memcpy(&rtp->them, &sin, sizeof(rtp->them));
409 ast_log(LOG_DEBUG, "RTP NAT: Using address %s:%d\n", inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
413 seqno = ntohl(rtpheader[0]);
414 payloadtype = (seqno & 0x7f0000) >> 16;
415 mark = seqno & (1 << 23);
417 timestamp = ntohl(rtpheader[1]);
420 printf("Got RTP packet from %s:%d (type %d, seq %d, ts %d, len = %d)\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
422 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
423 if (!rtpPT.isAstFormat) {
424 // This is special in-band data that's not one of our codecs
425 if (rtpPT.code == AST_RTP_DTMF) {
426 /* It's special -- rfc2833 process it */
427 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
428 if (f) return f; else return &null_frame;
429 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
430 /* It's really special -- process it the Cisco way */
431 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
432 if (f) return f; else return &null_frame;
433 } else if (rtpPT.code == AST_RTP_CN) {
435 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
436 if (f) return f; else return &null_frame;
438 ast_log(LOG_NOTICE, "Unknown RTP codec %d received\n", payloadtype);
442 rtp->f.subclass = rtpPT.code;
443 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO)
444 rtp->f.frametype = AST_FRAME_VOICE;
446 rtp->f.frametype = AST_FRAME_VIDEO;
447 rtp->lastrxformat = rtp->f.subclass;
450 rtp->lastrxts = timestamp;
452 if (rtp->dtmfcount) {
454 printf("dtmfcount was %d\n", rtp->dtmfcount);
456 rtp->dtmfcount -= (timestamp - rtp->lastrxts);
457 if (rtp->dtmfcount < 0)
460 if (dtmftimeout != rtp->dtmfcount)
461 printf("dtmfcount is %d\n", rtp->dtmfcount);
464 rtp->lastrxts = timestamp;
466 /* Send any pending DTMF */
467 if (rtp->resp && !rtp->dtmfcount) {
468 ast_log(LOG_DEBUG, "Sending pending DTMF\n");
469 return send_dtmf(rtp);
472 rtp->f.datalen = res - hdrlen;
473 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
474 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
475 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
476 switch(rtp->f.subclass) {
477 case AST_FORMAT_ULAW:
478 case AST_FORMAT_ALAW:
479 rtp->f.samples = rtp->f.datalen;
481 case AST_FORMAT_SLINEAR:
482 rtp->f.samples = rtp->f.datalen / 2;
485 rtp->f.samples = 160 * (rtp->f.datalen / 33);
487 case AST_FORMAT_ILBC:
488 rtp->f.samples = 240 * (rtp->f.datalen / 50);
490 case AST_FORMAT_ADPCM:
491 case AST_FORMAT_G726:
492 rtp->f.samples = rtp->f.datalen * 2;
494 case AST_FORMAT_G729A:
495 rtp->f.samples = rtp->f.datalen * 8;
497 case AST_FORMAT_G723_1:
498 rtp->f.samples = g723_samples(rtp->f.data, rtp->f.datalen);
500 case AST_FORMAT_SPEEX:
501 rtp->f.samples = 160;
502 // assumes that the RTP packet contained one Speex frame
505 ast_log(LOG_NOTICE, "Unable to calculate samples for format %s\n", ast_getformatname(rtp->f.subclass));
508 calc_rxstamp(&rtp->f.delivery, rtp, timestamp);
510 /* Video -- samples is # of samples vs. 90000 */
511 if (!rtp->lastividtimestamp)
512 rtp->lastividtimestamp = timestamp;
513 rtp->f.samples = timestamp - rtp->lastividtimestamp;
514 rtp->lastividtimestamp = timestamp;
516 rtp->f.subclass |= 0x1;
523 // The following array defines the MIME type (and subtype) for each
524 // of our codecs, or RTP-specific data type.
526 struct rtpPayloadType payloadType;
530 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
531 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
532 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
533 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
534 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
535 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
536 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
537 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
538 {{1, AST_FORMAT_G729A}, "audio", "G729"},
539 {{1, AST_FORMAT_SPEEX}, "audio", "SPEEX"},
540 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
541 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
542 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
543 {{0, AST_RTP_CN}, "audio", "CN"},
544 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
545 {{1, AST_FORMAT_PNG}, "video", "PNG"},
546 {{1, AST_FORMAT_H261}, "video", "H261"},
547 {{1, AST_FORMAT_H263}, "video", "H263"},
550 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
551 also, our own choices for dynamic payload types. This is our master
552 table for transmission */
553 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
554 [0] = {1, AST_FORMAT_ULAW},
555 [2] = {1, AST_FORMAT_G726}, // Technically this is G.721, but if Cisco can do it, so can we...
556 [3] = {1, AST_FORMAT_GSM},
557 [4] = {1, AST_FORMAT_G723_1},
558 [5] = {1, AST_FORMAT_ADPCM}, // 8 kHz
559 [6] = {1, AST_FORMAT_ADPCM}, // 16 kHz
560 [7] = {1, AST_FORMAT_LPC10},
561 [8] = {1, AST_FORMAT_ALAW},
562 [10] = {1, AST_FORMAT_SLINEAR}, // 2 channels
563 [11] = {1, AST_FORMAT_SLINEAR}, // 1 channel
564 [13] = {0, AST_RTP_CN},
565 [16] = {1, AST_FORMAT_ADPCM}, // 11.025 kHz
566 [17] = {1, AST_FORMAT_ADPCM}, // 22.050 kHz
567 [18] = {1, AST_FORMAT_G729A},
568 [26] = {1, AST_FORMAT_JPEG},
569 [31] = {1, AST_FORMAT_H261},
570 [34] = {1, AST_FORMAT_H263},
571 [97] = {1, AST_FORMAT_ILBC},
572 [101] = {0, AST_RTP_DTMF},
573 [110] = {1, AST_FORMAT_SPEEX},
574 [121] = {0, AST_RTP_CISCO_DTMF}, // Must be type 121
577 void ast_rtp_pt_clear(struct ast_rtp* rtp)
581 for (i = 0; i < MAX_RTP_PT; ++i) {
582 rtp->current_RTP_PT[i].isAstFormat = 0;
583 rtp->current_RTP_PT[i].code = 0;
586 rtp->rtp_lookup_code_cache_isAstFormat = 0;
587 rtp->rtp_lookup_code_cache_code = 0;
588 rtp->rtp_lookup_code_cache_result = 0;
591 void ast_rtp_pt_default(struct ast_rtp* rtp)
594 /* Initialize to default payload types */
595 for (i = 0; i < MAX_RTP_PT; ++i) {
596 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
597 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
600 rtp->rtp_lookup_code_cache_isAstFormat = 0;
601 rtp->rtp_lookup_code_cache_code = 0;
602 rtp->rtp_lookup_code_cache_result = 0;
605 // Make a note of a RTP payload type that was seen in a SDP "m=" line.
606 // By default, use the well-known value for this type (although it may
607 // still be set to a different value by a subsequent "a=rtpmap:" line):
608 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt) {
609 if (pt < 0 || pt > MAX_RTP_PT) return; // bogus payload type
611 if (static_RTP_PT[pt].code != 0) {
612 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
616 // Make a note of a RTP payload type (with MIME type) that was seen in
617 // a SDP "a=rtpmap:" line.
618 void ast_rtp_set_rtpmap_type(struct ast_rtp* rtp, int pt,
619 char* mimeType, char* mimeSubtype) {
622 if (pt < 0 || pt > MAX_RTP_PT) return; // bogus payload type
624 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
625 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
626 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
627 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
633 // Return the union of all of the codecs that were set by rtp_set...() calls
634 // They're returned as two distinct sets: AST_FORMATs, and AST_RTPs
635 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
636 int* astFormats, int* nonAstFormats) {
639 *astFormats = *nonAstFormats = 0;
640 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
641 if (rtp->current_RTP_PT[pt].isAstFormat) {
642 *astFormats |= rtp->current_RTP_PT[pt].code;
644 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
649 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt) {
650 if (pt < 0 || pt > MAX_RTP_PT) {
651 struct rtpPayloadType result;
652 result.isAstFormat = result.code = 0;
653 return result; // bogus payload type
655 /* Gotta use our static one, since that's what we sent against */
656 return static_RTP_PT[pt];
659 int ast_rtp_lookup_code(struct ast_rtp* rtp, int isAstFormat, int code) {
662 /* Looks up an RTP code out of our *static* outbound list */
664 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
665 code == rtp->rtp_lookup_code_cache_code) {
666 // Use our cached mapping, to avoid the overhead of the loop below
667 return rtp->rtp_lookup_code_cache_result;
670 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
671 if (static_RTP_PT[pt].code == code &&
672 static_RTP_PT[pt].isAstFormat == isAstFormat) {
673 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
674 rtp->rtp_lookup_code_cache_code = code;
675 rtp->rtp_lookup_code_cache_result = pt;
682 char* ast_rtp_lookup_mime_subtype(int isAstFormat, int code) {
685 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
686 if (mimeTypes[i].payloadType.code == code &&
687 mimeTypes[i].payloadType.isAstFormat == isAstFormat) {
688 return mimeTypes[i].subtype;
694 static struct ast_rtcp *ast_rtcp_new(void)
696 struct ast_rtcp *rtcp;
698 rtcp = malloc(sizeof(struct ast_rtcp));
701 memset(rtcp, 0, sizeof(struct ast_rtcp));
702 rtcp->s = socket(AF_INET, SOCK_DGRAM, 0);
703 rtcp->us.sin_family = AF_INET;
706 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
709 flags = fcntl(rtcp->s, F_GETFL);
710 fcntl(rtcp->s, F_SETFL, flags | O_NONBLOCK);
714 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
720 rtp = malloc(sizeof(struct ast_rtp));
723 memset(rtp, 0, sizeof(struct ast_rtp));
724 rtp->them.sin_family = AF_INET;
725 rtp->us.sin_family = AF_INET;
726 rtp->s = socket(AF_INET, SOCK_DGRAM, 0);
728 rtp->seqno = rand() & 0xffff;
731 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
734 if (sched && rtcpenable) {
736 rtp->rtcp = ast_rtcp_new();
738 flags = fcntl(rtp->s, F_GETFL);
739 fcntl(rtp->s, F_SETFL, flags | O_NONBLOCK);
740 /* Find us a place */
741 x = (rand() % (rtpend-rtpstart)) + rtpstart;
745 /* Must be an even port number by RTP spec */
746 rtp->us.sin_port = htons(x);
748 rtp->rtcp->us.sin_port = htons(x + 1);
749 if (!bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us)) &&
750 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
752 if (errno != EADDRINUSE) {
753 ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
764 x = (rtpstart + 1) & ~1;
765 if (x == startplace) {
766 ast_log(LOG_WARNING, "No RTP ports remaining\n");
776 if (io && sched && callbackmode) {
777 /* Operate this one in a callback mode */
780 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
782 ast_rtp_pt_default(rtp);
786 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
789 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
790 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
794 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
796 rtp->them.sin_port = them->sin_port;
797 rtp->them.sin_addr = them->sin_addr;
799 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
800 rtp->rtcp->them.sin_addr = them->sin_addr;
804 void ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
806 them->sin_family = AF_INET;
807 them->sin_port = rtp->them.sin_port;
808 them->sin_addr = rtp->them.sin_addr;
811 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
813 memcpy(us, &rtp->us, sizeof(rtp->us));
816 void ast_rtp_stop(struct ast_rtp *rtp)
818 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
819 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
821 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
822 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->them.sin_port));
826 void ast_rtp_destroy(struct ast_rtp *rtp)
829 ast_smoother_free(rtp->smoother);
831 ast_io_remove(rtp->io, rtp->ioid);
841 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
845 if (!rtp->txcore.tv_sec && !rtp->txcore.tv_usec) {
846 gettimeofday(&rtp->txcore, NULL);
848 if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
849 /* Use previous txcore */
850 ms = (delivery->tv_sec - rtp->txcore.tv_usec) * 1000;
851 ms += (delivery->tv_usec - rtp->txcore.tv_usec) / 1000;
852 rtp->txcore.tv_sec = delivery->tv_sec;
853 rtp->txcore.tv_usec = delivery->tv_usec;
855 gettimeofday(&now, NULL);
856 ms = (now.tv_sec - rtp->txcore.tv_sec) * 1000;
857 ms += (now.tv_usec - rtp->txcore.tv_usec) / 1000;
858 /* Use what we just got for next time */
859 rtp->txcore.tv_sec = now.tv_sec;
860 rtp->txcore.tv_usec = now.tv_usec;
865 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
867 unsigned int *rtpheader;
875 if ((digit <= '9') && (digit >= '0'))
877 else if (digit == '*')
879 else if (digit == '#')
881 else if ((digit >= 'A') && (digit <= 'D'))
882 digit = digit - 'A' + 12;
883 else if ((digit >= 'a') && (digit <= 'd'))
884 digit = digit - 'a' + 12;
886 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
891 /* If we have no peer, return immediately */
892 if (!rtp->them.sin_addr.s_addr)
895 ms = calc_txstamp(rtp, NULL);
896 /* Default prediction */
897 pred = rtp->lastts + ms * 8;
899 /* Get a pointer to the header */
900 rtpheader = (unsigned int *)data;
901 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (101 << 16) | (rtp->seqno++));
902 rtpheader[1] = htonl(rtp->lastts);
903 rtpheader[2] = htonl(rtp->ssrc);
904 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
906 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
907 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 4, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
909 ast_log(LOG_NOTICE, "RTP Transmission error to %s:%d: %s\n", inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
911 printf("Sent %d bytes of RTP data to %s:%d\n", res, inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
915 /* Clear marker bit and increment seqno */
916 rtpheader[0] = htonl((2 << 30) | (101 << 16) | (rtp->seqno++));
917 /* Make duration 240 */
918 rtpheader[3] |= htonl((240));
919 /* Set the End bit for the last 3 */
920 rtpheader[3] |= htonl((1 << 23));
926 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
928 unsigned int *rtpheader;
935 ms = calc_txstamp(rtp, &f->delivery);
936 /* Default prediction */
937 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
938 pred = rtp->lastts + ms * 8;
940 switch(f->subclass) {
941 case AST_FORMAT_ULAW:
942 case AST_FORMAT_ALAW:
943 /* If we're within +/- 20ms from when where we
944 predict we should be, use that */
945 pred = rtp->lastts + f->datalen;
947 case AST_FORMAT_ADPCM:
948 case AST_FORMAT_G726:
949 /* If we're within +/- 20ms from when where we
950 predict we should be, use that */
951 pred = rtp->lastts + f->datalen * 2;
953 case AST_FORMAT_G729A:
954 pred = rtp->lastts + f->datalen * 8;
957 pred = rtp->lastts + (f->datalen * 160 / 33);
959 case AST_FORMAT_ILBC:
960 pred = rtp->lastts + (f->datalen * 240 / 50);
962 case AST_FORMAT_G723_1:
963 pred = rtp->lastts + g723_samples(f->data, f->datalen);
965 case AST_FORMAT_SPEEX:
966 pred = rtp->lastts + 160;
967 // assumes that the RTP packet contains one Speex frame
970 ast_log(LOG_WARNING, "Not sure about timestamp format for codec format %s\n", ast_getformatname(f->subclass));
973 /* Re-calculate last TS */
974 rtp->lastts = rtp->lastts + ms * 8;
975 /* If it's close to our prediction, go for it */
976 if (abs(rtp->lastts - pred) < 640)
979 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
981 mark = f->subclass & 0x1;
982 pred = rtp->lastovidtimestamp + f->samples;
983 /* Re-calculate last TS */
984 rtp->lastts = rtp->lastts + ms * 90;
985 /* If it's close to our prediction, go for it */
986 if (abs(rtp->lastts - pred) < 7200) {
988 rtp->lastovidtimestamp += f->samples;
990 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
991 rtp->lastovidtimestamp = rtp->lastts;
994 /* Get a pointer to the header */
995 rtpheader = (unsigned int *)(f->data - hdrlen);
996 rtpheader[0] = htonl((2 << 30) | (codec << 16) | (rtp->seqno++) | (mark << 23));
997 rtpheader[1] = htonl(rtp->lastts);
998 rtpheader[2] = htonl(rtp->ssrc);
999 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1000 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1002 ast_log(LOG_NOTICE, "RTP Transmission error to %s:%d: %s\n", inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
1004 printf("Sent %d bytes of RTP data to %s:%d\n", res, inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
1010 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
1012 struct ast_frame *f;
1018 /* If we have no peer, return immediately */
1019 if (!rtp->them.sin_addr.s_addr)
1022 /* If there is no data length, return immediately */
1026 /* Make sure we have enough space for RTP header */
1027 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
1028 ast_log(LOG_WARNING, "RTP can only send voice\n");
1032 subclass = _f->subclass;
1033 if (_f->frametype == AST_FRAME_VIDEO)
1036 codec = ast_rtp_lookup_code(rtp, 1, subclass);
1038 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
1042 if (rtp->lasttxformat != subclass) {
1043 /* New format, reset the smoother */
1044 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
1045 rtp->lasttxformat = subclass;
1047 ast_smoother_free(rtp->smoother);
1048 rtp->smoother = NULL;
1053 case AST_FORMAT_ULAW:
1054 case AST_FORMAT_ALAW:
1055 if (!rtp->smoother) {
1056 rtp->smoother = ast_smoother_new(160);
1058 if (!rtp->smoother) {
1059 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1062 ast_smoother_feed(rtp->smoother, _f);
1064 while((f = ast_smoother_read(rtp->smoother)))
1065 ast_rtp_raw_write(rtp, f, codec);
1067 case AST_FORMAT_ADPCM:
1068 case AST_FORMAT_G726:
1069 if (!rtp->smoother) {
1070 rtp->smoother = ast_smoother_new(80);
1072 if (!rtp->smoother) {
1073 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1076 ast_smoother_feed(rtp->smoother, _f);
1078 while((f = ast_smoother_read(rtp->smoother)))
1079 ast_rtp_raw_write(rtp, f, codec);
1081 case AST_FORMAT_G729A:
1082 if (!rtp->smoother) {
1083 rtp->smoother = ast_smoother_new(20);
1085 if (!rtp->smoother) {
1086 ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
1089 ast_smoother_feed(rtp->smoother, _f);
1091 while((f = ast_smoother_read(rtp->smoother)))
1092 ast_rtp_raw_write(rtp, f, codec);
1094 case AST_FORMAT_GSM:
1095 if (!rtp->smoother) {
1096 rtp->smoother = ast_smoother_new(33);
1098 if (!rtp->smoother) {
1099 ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
1102 ast_smoother_feed(rtp->smoother, _f);
1103 while((f = ast_smoother_read(rtp->smoother)))
1104 ast_rtp_raw_write(rtp, f, codec);
1106 case AST_FORMAT_ILBC:
1107 if (!rtp->smoother) {
1108 rtp->smoother = ast_smoother_new(50);
1110 if (!rtp->smoother) {
1111 ast_log(LOG_WARNING, "Unable to create ILBC smoother :(\n");
1114 ast_smoother_feed(rtp->smoother, _f);
1115 while((f = ast_smoother_read(rtp->smoother)))
1116 ast_rtp_raw_write(rtp, f, codec);
1119 ast_log(LOG_WARNING, "Not sure about sending format %s packets\n", ast_getformatname(subclass));
1120 // fall through to...
1121 case AST_FORMAT_H261:
1122 case AST_FORMAT_H263:
1123 case AST_FORMAT_G723_1:
1124 case AST_FORMAT_SPEEX:
1125 // Don't buffer outgoing frames; send them one-per-packet:
1126 if (_f->offset < hdrlen) {
1131 ast_rtp_raw_write(rtp, f, codec);
1137 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
1139 struct ast_rtp_protocol *cur, *prev;
1145 prev->next = proto->next;
1147 protos = proto->next;
1155 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
1157 struct ast_rtp_protocol *cur;
1160 if (cur->type == proto->type) {
1161 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
1166 proto->next = protos;
1171 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1173 struct ast_rtp_protocol *cur;
1176 if (cur->type == chan->type) {
1184 int ast_rtp_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1186 struct ast_frame *f;
1187 struct ast_channel *who, *cs[3];
1188 struct ast_rtp *p0, *p1;
1189 struct ast_rtp *vp0, *vp1;
1190 struct ast_rtp_protocol *pr0, *pr1;
1191 struct sockaddr_in ac0, ac1;
1192 struct sockaddr_in vac0, vac1;
1193 struct sockaddr_in t0, t1;
1194 struct sockaddr_in vt0, vt1;
1198 memset(&vt0, 0, sizeof(vt0));
1199 memset(&vt1, 0, sizeof(vt1));
1200 memset(&vac0, 0, sizeof(vac0));
1201 memset(&vac1, 0, sizeof(vac1));
1203 /* XXX Wait a half a second for things to settle up
1204 this really should be fixed XXX */
1205 ast_autoservice_start(c0);
1206 ast_autoservice_start(c1);
1208 ast_autoservice_stop(c0);
1209 ast_autoservice_stop(c1);
1211 /* if need DTMF, cant native bridge */
1212 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
1214 ast_mutex_lock(&c0->lock);
1215 ast_mutex_lock(&c1->lock);
1216 pr0 = get_proto(c0);
1217 pr1 = get_proto(c1);
1219 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
1220 ast_mutex_unlock(&c0->lock);
1221 ast_mutex_unlock(&c1->lock);
1225 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1226 ast_mutex_unlock(&c0->lock);
1227 ast_mutex_unlock(&c1->lock);
1230 pvt0 = c0->pvt->pvt;
1231 pvt1 = c1->pvt->pvt;
1232 p0 = pr0->get_rtp_info(c0);
1233 if (pr0->get_vrtp_info)
1234 vp0 = pr0->get_vrtp_info(c0);
1237 p1 = pr1->get_rtp_info(c1);
1238 if (pr1->get_vrtp_info)
1239 vp1 = pr1->get_vrtp_info(c1);
1243 /* Somebody doesn't want to play... */
1244 ast_mutex_unlock(&c0->lock);
1245 ast_mutex_unlock(&c1->lock);
1248 if (pr0->get_codec && pr1->get_codec) {
1250 codec0 = pr0->get_codec(c0);
1251 codec1 = pr1->get_codec(c1);
1252 /* Hey, we can't do reinvite if both parties speak diffrent codecs */
1253 if (!(codec0 & codec1)) {
1254 ast_log(LOG_WARNING, "codec0 = %d is not codec1 = %d, cannot native bridge.\n",codec0,codec1);
1255 ast_mutex_unlock(&c0->lock);
1256 ast_mutex_unlock(&c1->lock);
1260 if (pr0->set_rtp_peer(c0, p1, vp1))
1261 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1263 /* Store RTP peer */
1264 ast_rtp_get_peer(p1, &ac1);
1266 ast_rtp_get_peer(p1, &vac1);
1268 if (pr1->set_rtp_peer(c1, p0, vp0))
1269 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1271 /* Store RTP peer */
1272 ast_rtp_get_peer(p0, &ac0);
1274 ast_rtp_get_peer(p0, &vac0);
1276 ast_mutex_unlock(&c0->lock);
1277 ast_mutex_unlock(&c1->lock);
1282 if ((c0->pvt->pvt != pvt0) ||
1283 (c1->pvt->pvt != pvt1) ||
1284 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1285 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
1286 if (c0->pvt->pvt == pvt0) {
1287 if (pr0->set_rtp_peer(c0, NULL, NULL))
1288 ast_log(LOG_WARNING, "Channel '%s' failed to revert\n", c0->name);
1290 if (c1->pvt->pvt == pvt1) {
1291 if (pr1->set_rtp_peer(c1, NULL, NULL))
1292 ast_log(LOG_WARNING, "Channel '%s' failed to revert back\n", c1->name);
1294 /* Tell it to try again later */
1298 ast_rtp_get_peer(p1, &t1);
1299 ast_rtp_get_peer(p0, &t0);
1301 ast_rtp_get_peer(vp1, &vt1);
1303 ast_rtp_get_peer(vp0, &vt0);
1304 if (inaddrcmp(&t1, &ac1) || (vp1 && inaddrcmp(&vt1, &vac1))) {
1305 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address\n", c1->name);
1306 if (pr0->set_rtp_peer(c0, t1.sin_addr.s_addr ? p1 : NULL, vt1.sin_addr.s_addr ? vp1 : NULL))
1307 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
1308 memcpy(&ac1, &t1, sizeof(ac1));
1309 memcpy(&vac1, &vt1, sizeof(vac1));
1311 if (inaddrcmp(&t0, &ac0) || (vp0 && inaddrcmp(&vt0, &vac0))) {
1312 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address\n", c0->name);
1313 if (pr1->set_rtp_peer(c1, t0.sin_addr.s_addr ? p0 : NULL, vt0.sin_addr.s_addr ? vp0 : NULL))
1314 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
1315 memcpy(&ac0, &t0, sizeof(ac0));
1316 memcpy(&vac0, &vt0, sizeof(vac0));
1318 who = ast_waitfor_n(cs, 2, &to);
1320 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
1321 /* check for hagnup / whentohangup */
1322 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1327 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
1328 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
1329 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
1332 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
1333 if ((c0->pvt->pvt == pvt0) && (!c0->_softhangup)) {
1334 if (pr0->set_rtp_peer(c0, NULL, NULL))
1335 ast_log(LOG_WARNING, "Channel '%s' failed to revert\n", c0->name);
1337 if ((c1->pvt->pvt == pvt1) && (!c1->_softhangup)) {
1338 if (pr1->set_rtp_peer(c1, NULL, NULL))
1339 ast_log(LOG_WARNING, "Channel '%s' failed to revert back\n", c1->name);
1341 /* That's all we needed */
1344 if ((f->frametype == AST_FRAME_DTMF) ||
1345 (f->frametype == AST_FRAME_VOICE) ||
1346 (f->frametype == AST_FRAME_VIDEO)) {
1347 /* Forward voice or DTMF frames if they happen upon us */
1350 } else if (who == c1) {
1356 /* Swap priority not that it's a big deal at this point */
1365 void ast_rtp_reload(void)
1367 struct ast_config *cfg;
1371 cfg = ast_load("rtp.conf");
1373 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
1375 if (rtpstart < 1024)
1377 if (rtpstart > 65535)
1380 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
1389 if (rtpstart >= rtpend) {
1390 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end\n");
1394 if (option_verbose > 1)
1395 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
1398 void ast_rtp_init(void)