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/channel_pvt.h>
35 #define TYPE_SILENCE 0x2
40 static int dtmftimeout = 300; /* 300 samples */
46 unsigned char rawdata[1024 + AST_FRIENDLY_OFFSET];
49 unsigned int lastrxts;
53 struct sockaddr_in us;
54 struct sockaddr_in them;
55 struct timeval rxcore;
56 struct timeval txcore;
57 struct ast_smoother *smoother;
60 struct sched_context *sched;
61 struct io_context *io;
63 ast_rtp_callback callback;
66 static struct ast_rtp_protocol *protos = NULL;
68 int ast_rtp_fd(struct ast_rtp *rtp)
73 static int g723_len(unsigned char buf)
75 switch(buf & TYPE_MASK) {
87 ast_log(LOG_WARNING, "Badly encoded frame (%d)\n", buf & TYPE_MASK);
92 static int g723_samples(unsigned char *buf, int maxlen)
98 res = g723_len(buf[pos]);
107 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
112 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
114 rtp->callback = callback;
117 static struct ast_frame *send_dtmf(struct ast_rtp *rtp)
119 ast_log(LOG_DEBUG, "Sending dtmf: %d (%c)\n", rtp->resp, rtp->resp);
120 rtp->f.frametype = AST_FRAME_DTMF;
121 rtp->f.subclass = rtp->resp;
131 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len)
135 struct ast_frame *f = NULL;
136 event = ntohl(*((unsigned int *)(data)));
139 printf("Event: %08x (len = %d)\n", event, len);
143 } else if (event < 11) {
145 } else if (event < 12) {
147 } else if (event < 16) {
148 resp = 'A' + (event - 12);
150 if (rtp->resp && (rtp->resp != resp)) {
154 rtp->dtmfcount = dtmftimeout;
158 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
160 struct ast_frame *f = NULL;
161 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
162 totally help us out becuase we don't have an engine to keep it going and we are not
163 guaranteed to have it every 20ms or anything */
165 printf("RFC3389: %d bytes, format is %d\n", len, rtp->lastrxformat);
167 ast_log(LOG_NOTICE, "RFC3389 support incomplete. Turn off on client if possible\n");
168 if (!rtp->lastrxformat)
170 switch(rtp->lastrxformat) {
171 case AST_FORMAT_ULAW:
172 rtp->f.frametype = AST_FRAME_VOICE;
173 rtp->f.subclass = AST_FORMAT_ULAW;
174 rtp->f.datalen = 160;
175 rtp->f.samples = 160;
176 memset(rtp->f.data, 0x7f, rtp->f.datalen);
179 case AST_FORMAT_ALAW:
180 rtp->f.frametype = AST_FRAME_VOICE;
181 rtp->f.subclass = AST_FORMAT_ALAW;
182 rtp->f.datalen = 160;
183 rtp->f.samples = 160;
184 memset(rtp->f.data, 0x7e, rtp->f.datalen); /* XXX Is this right? XXX */
187 case AST_FORMAT_SLINEAR:
188 rtp->f.frametype = AST_FRAME_VOICE;
189 rtp->f.subclass = AST_FORMAT_SLINEAR;
190 rtp->f.datalen = 320;
191 rtp->f.samples = 160;
192 memset(rtp->f.data, 0x00, rtp->f.datalen);
196 ast_log(LOG_NOTICE, "Don't know how to handle RFC3389 for receive codec %d\n", rtp->lastrxformat);
201 static struct ast_frame *process_type121(struct ast_rtp *rtp, unsigned char *data, int len)
204 struct ast_frame *f = NULL;
205 unsigned char b0,b1,b2,b3,b4,b5,b6,b7;
207 b0=*(data+0);b1=*(data+1);b2=*(data+2);b3=*(data+3);
208 b4=*(data+4);b5=*(data+5);b6=*(data+6);b7=*(data+7);
209 // printf("%u %u %u %u %u %u %u %u\n",b0,b1,b2,b3,b4,b5,b6,b7);
211 // printf("Start %d\n",b3);
213 // printf("Detection point for DTMF %d\n",b3);
228 // printf("Stop(3) %d\n",b3);
231 // printf("Stop(0) %d\n",b3);
236 static int rtpread(int *id, int fd, short events, void *cbdata)
238 struct ast_rtp *rtp = cbdata;
240 f = ast_rtp_read(rtp);
243 rtp->callback(rtp, f, rtp->data);
248 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
251 struct sockaddr_in sin;
256 unsigned int timestamp;
257 unsigned int *rtpheader;
258 static struct ast_frame *f, null_frame = { AST_FRAME_NULL, };
262 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
263 0, (struct sockaddr *)&sin, &len);
265 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
267 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
273 ast_log(LOG_WARNING, "RTP Read too short\n");
277 seqno = ntohl(rtpheader[0]);
278 payloadtype = (seqno & 0x7f0000) >> 16;
280 timestamp = ntohl(rtpheader[1]);
282 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);
284 rtp->f.frametype = AST_FRAME_VOICE;
285 rtp->f.subclass = rtp2ast(payloadtype);
286 if (rtp->f.subclass < 0) {
288 if (payloadtype == 101) {
289 /* It's special -- rfc2833 process it */
290 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
291 } else if (payloadtype == 121) {
292 /* CISCO proprietary DTMF bridge */
293 f = process_type121(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
294 } else if (payloadtype == 100) {
295 /* CISCO's notso proprietary DTMF bridge */
296 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
297 } else if (payloadtype == 13) {
298 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
300 ast_log(LOG_NOTICE, "Unknown RTP codec %d received\n", payloadtype);
307 rtp->lastrxformat = rtp->f.subclass;
310 rtp->lastrxts = timestamp;
312 if (rtp->dtmfcount) {
314 printf("dtmfcount was %d\n", rtp->dtmfcount);
316 rtp->dtmfcount -= (timestamp - rtp->lastrxts);
317 if (rtp->dtmfcount < 0)
320 if (dtmftimeout != rtp->dtmfcount)
321 printf("dtmfcount is %d\n", rtp->dtmfcount);
324 rtp->lastrxts = timestamp;
326 /* Send any pending DTMF */
327 if (rtp->resp && !rtp->dtmfcount) {
328 ast_log(LOG_DEBUG, "Sending pending DTMF\n");
329 return send_dtmf(rtp);
332 rtp->f.datalen = res - hdrlen;
333 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
334 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
335 switch(rtp->f.subclass) {
336 case AST_FORMAT_ULAW:
337 case AST_FORMAT_ALAW:
338 rtp->f.samples = rtp->f.datalen;
340 case AST_FORMAT_SLINEAR:
341 rtp->f.samples = rtp->f.datalen / 2;
344 rtp->f.samples = 160 * (rtp->f.datalen / 33);
346 case AST_FORMAT_ADPCM:
347 rtp->f.samples = rtp->f.datalen * 2;
349 case AST_FORMAT_G729A:
350 rtp->f.samples = rtp->f.datalen * 8;
352 case AST_FORMAT_G723_1:
353 rtp->f.samples = g723_samples(rtp->f.data, rtp->f.datalen);
356 ast_log(LOG_NOTICE, "Unable to calculate samples for format %d\n", rtp->f.subclass);
368 { 0, AST_FORMAT_ULAW, "PCMU" },
369 { 3, AST_FORMAT_GSM, "GSM" },
370 { 4, AST_FORMAT_G723_1, "G723" },
371 { 5, AST_FORMAT_ADPCM, "ADPCM" },
372 { 8, AST_FORMAT_ALAW, "PCMA" },
373 { 18, AST_FORMAT_G729A, "G729" },
379 for (x=0;x<sizeof(cmap) / sizeof(cmap[0]); x++) {
380 if (cmap[x].rtp == id)
389 for (x=0;x<sizeof(cmap) / sizeof(cmap[0]); x++) {
390 if (cmap[x].ast == id)
396 char *ast2rtpn(int id)
399 for (x=0;x<sizeof(cmap) / sizeof(cmap[0]); x++) {
400 if (cmap[x].ast == id)
401 return cmap[x].label;
405 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io)
410 rtp = malloc(sizeof(struct ast_rtp));
413 memset(rtp, 0, sizeof(struct ast_rtp));
414 rtp->them.sin_family = AF_INET;
415 rtp->us.sin_family = AF_INET;
416 rtp->s = socket(AF_INET, SOCK_DGRAM, 0);
418 rtp->seqno = rand() & 0xffff;
421 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
424 flags = fcntl(rtp->s, F_GETFL);
425 fcntl(rtp->s, F_SETFL, flags | O_NONBLOCK);
427 /* Find us a place */
428 x = (rand() % (65000-1025)) + 1025;
429 /* Must be an even port number by RTP spec */
431 rtp->us.sin_port = htons(x);
432 if (!bind(rtp->s, &rtp->us, sizeof(rtp->us)))
434 if (errno != EADDRINUSE) {
435 ast_log(LOG_WARNING, "Unexpected bind error: %s\n", strerror(errno));
442 /* Operate this one in a callback mode */
445 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
450 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
453 if ((res = setsockopt(rtp->s, SOL_IP, IP_TOS, &tos, sizeof(tos))))
454 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
458 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
460 rtp->them.sin_port = them->sin_port;
461 rtp->them.sin_addr = them->sin_addr;
464 void ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
466 them->sin_family = AF_INET;
467 them->sin_port = rtp->them.sin_port;
468 them->sin_addr = rtp->them.sin_addr;
471 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
473 memcpy(us, &rtp->us, sizeof(rtp->us));
476 void ast_rtp_destroy(struct ast_rtp *rtp)
479 ast_smoother_free(rtp->smoother);
481 ast_io_remove(rtp->io, rtp->ioid);
487 static unsigned int calc_txstamp(struct ast_rtp *rtp)
491 if (!rtp->txcore.tv_sec && !rtp->txcore.tv_usec) {
492 gettimeofday(&rtp->txcore, NULL);
494 gettimeofday(&now, NULL);
495 ms = (now.tv_sec - rtp->txcore.tv_sec) * 1000;
496 ms += (now.tv_usec - rtp->txcore.tv_usec) / 1000;
497 /* Use what we just got for next time */
498 rtp->txcore.tv_sec = now.tv_sec;
499 rtp->txcore.tv_usec = now.tv_usec;
503 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
505 unsigned int *rtpheader;
513 if ((digit <= '9') && (digit >= '0'))
515 else if (digit == '*')
517 else if (digit == '#')
519 else if ((digit >= 'A') && (digit <= 'D'))
520 digit = digit - 'A' + 12;
521 else if ((digit >= 'a') && (digit <= 'd'))
522 digit = digit - 'a' + 12;
524 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
529 /* If we have no peer, return immediately */
530 if (!rtp->them.sin_addr.s_addr)
533 ms = calc_txstamp(rtp);
534 /* Default prediction */
535 pred = rtp->lastts + ms * 8;
537 /* Get a pointer to the header */
538 rtpheader = (unsigned int *)data;
539 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (101 << 16) | (rtp->seqno++));
540 rtpheader[1] = htonl(rtp->lastts);
541 rtpheader[2] = htonl(rtp->ssrc);
542 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
544 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
545 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 4, 0, &rtp->them, sizeof(rtp->them));
547 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));
549 printf("Sent %d bytes of RTP data to %s:%d\n", res, inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
553 /* Clear marker bit and increment seqno */
554 rtpheader[0] = htonl((2 << 30) | (101 << 16) | (rtp->seqno++));
555 /* Make duration 240 */
556 rtpheader[3] |= htonl((240));
557 /* Set the End bit for the last 3 */
558 rtpheader[3] |= htonl((1 << 23));
564 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
566 unsigned int *rtpheader;
572 ms = calc_txstamp(rtp);
573 /* Default prediction */
574 pred = rtp->lastts + ms * 8;
576 switch(f->subclass) {
577 case AST_FORMAT_ULAW:
578 case AST_FORMAT_ALAW:
579 /* If we're within +/- 20ms from when where we
580 predict we should be, use that */
581 pred = rtp->lastts + f->datalen;
583 case AST_FORMAT_G729A:
584 pred = rtp->lastts + f->datalen * 8;
587 pred = rtp->lastts + (f->datalen * 160 / 33);
589 case AST_FORMAT_G723_1:
590 pred = rtp->lastts + g723_samples(f->data, f->datalen);
593 ast_log(LOG_WARNING, "Not sure about timestamp format for codec format %d\n", f->subclass);
596 /* Re-calculate last TS */
597 rtp->lastts = rtp->lastts + ms * 8;
598 /* If it's close to ou prediction, go for it */
599 if (abs(rtp->lastts - pred) < 640)
602 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
603 /* Get a pointer to the header */
604 rtpheader = (unsigned int *)(f->data - hdrlen);
605 rtpheader[0] = htonl((2 << 30) | (codec << 16) | (rtp->seqno++));
606 rtpheader[1] = htonl(rtp->lastts);
607 rtpheader[2] = htonl(rtp->ssrc);
608 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
609 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, &rtp->them, sizeof(rtp->them));
611 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));
613 printf("Sent %d bytes of RTP data to %s:%d\n", res, inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
619 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
626 /* If we have no peer, return immediately */
627 if (!rtp->them.sin_addr.s_addr)
630 /* Make sure we have enough space for RTP header */
631 if (_f->frametype != AST_FRAME_VOICE) {
632 ast_log(LOG_WARNING, "RTP can only send voice\n");
636 codec = ast2rtp(_f->subclass);
638 ast_log(LOG_WARNING, "Don't know how to send format %d packets with RTP\n", _f->subclass);
642 if (rtp->lasttxformat != _f->subclass) {
643 /* New format, reset the smoother */
644 ast_log(LOG_DEBUG, "Ooh, format changed from %d to %d\n", rtp->lasttxformat, _f->subclass);
645 rtp->lasttxformat = _f->subclass;
647 ast_smoother_free(rtp->smoother);
648 rtp->smoother = NULL;
652 switch(_f->subclass) {
653 case AST_FORMAT_ULAW:
654 case AST_FORMAT_ALAW:
655 if (!rtp->smoother) {
656 rtp->smoother = ast_smoother_new(160);
658 if (!rtp->smoother) {
659 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
662 ast_smoother_feed(rtp->smoother, _f);
664 while((f = ast_smoother_read(rtp->smoother)))
665 ast_rtp_raw_write(rtp, f, codec);
667 case AST_FORMAT_G729A:
668 if (!rtp->smoother) {
669 rtp->smoother = ast_smoother_new(20);
671 if (!rtp->smoother) {
672 ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
675 ast_smoother_feed(rtp->smoother, _f);
677 while((f = ast_smoother_read(rtp->smoother)))
678 ast_rtp_raw_write(rtp, f, codec);
681 if (!rtp->smoother) {
682 rtp->smoother = ast_smoother_new(33);
684 if (!rtp->smoother) {
685 ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
688 ast_smoother_feed(rtp->smoother, _f);
689 while((f = ast_smoother_read(rtp->smoother)))
690 ast_rtp_raw_write(rtp, f, codec);
693 ast_log(LOG_WARNING, "Not sure about sending format %d packets\n", _f->subclass);
694 if (_f->offset < hdrlen) {
699 ast_rtp_raw_write(rtp, f, codec);
705 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
707 struct ast_rtp_protocol *cur, *prev;
713 prev->next = proto->next;
715 protos = proto->next;
723 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
725 struct ast_rtp_protocol *cur;
728 if (cur->type == proto->type) {
729 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
734 proto->next = protos;
739 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
741 struct ast_rtp_protocol *cur;
744 if (cur->type == chan->type) {
752 int ast_rtp_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
755 struct ast_channel *who, *cs[3];
756 struct ast_rtp *p0, *p1;
757 struct ast_rtp_protocol *pr0, *pr1;
761 /* XXX Wait a half a second for things to settle up
762 this really should be fixed XXX */
763 ast_autoservice_start(c0);
764 ast_autoservice_start(c1);
766 ast_autoservice_stop(c0);
767 ast_autoservice_stop(c1);
769 /* if need DTMF, cant native bridge */
770 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
772 ast_pthread_mutex_lock(&c0->lock);
773 ast_pthread_mutex_lock(&c1->lock);
777 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
778 ast_pthread_mutex_unlock(&c0->lock);
779 ast_pthread_mutex_unlock(&c1->lock);
783 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
784 ast_pthread_mutex_unlock(&c0->lock);
785 ast_pthread_mutex_unlock(&c1->lock);
790 p0 = pr0->get_rtp_info(c0);
791 p1 = pr1->get_rtp_info(c1);
793 /* Somebody doesn't want to play... */
794 ast_pthread_mutex_unlock(&c0->lock);
795 ast_pthread_mutex_unlock(&c1->lock);
798 if (pr0->set_rtp_peer(c0, p1))
799 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
800 if (pr1->set_rtp_peer(c1, p0))
801 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
802 ast_pthread_mutex_unlock(&c0->lock);
803 ast_pthread_mutex_unlock(&c1->lock);
808 if ((c0->pvt->pvt != pvt0) ||
809 (c1->pvt->pvt != pvt1) ||
810 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
811 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
812 if (c0->pvt->pvt == pvt0) {
813 if (pr0->set_rtp_peer(c0, NULL))
814 ast_log(LOG_WARNING, "Channel '%s' failed to revert\n", c0->name);
816 if (c1->pvt->pvt == pvt1) {
817 if (pr1->set_rtp_peer(c1, NULL))
818 ast_log(LOG_WARNING, "Channel '%s' failed to revert back\n", c1->name);
820 /* Tell it to try again later */
824 who = ast_waitfor_n(cs, 2, &to);
826 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
830 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
831 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
832 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
835 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
836 if ((c0->pvt->pvt == pvt0) && (!c0->_softhangup)) {
837 if (pr0->set_rtp_peer(c0, NULL))
838 ast_log(LOG_WARNING, "Channel '%s' failed to revert\n", c0->name);
840 if ((c1->pvt->pvt == pvt1) && (!c1->_softhangup)) {
841 if (pr1->set_rtp_peer(c1, NULL))
842 ast_log(LOG_WARNING, "Channel '%s' failed to revert back\n", c1->name);
844 /* That's all we needed */
848 /* Swap priority not that it's a big deal at this point */