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;
500 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
502 unsigned int *rtpheader;
510 if ((digit <= '9') && (digit >= '0'))
512 else if (digit == '*')
514 else if (digit == '#')
516 else if ((digit >= 'A') && (digit <= 'D'))
517 digit = digit - 'A' + 12;
518 else if ((digit >= 'a') && (digit <= 'd'))
519 digit = digit - 'a' + 12;
521 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
526 /* If we have no peer, return immediately */
527 if (!rtp->them.sin_addr.s_addr)
530 ms = calc_txstamp(rtp);
531 /* Default prediction */
534 /* Get a pointer to the header */
535 rtpheader = (unsigned int *)data;
536 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (101 << 16) | (rtp->seqno++));
537 rtpheader[1] = htonl(rtp->lastts);
538 rtpheader[2] = htonl(rtp->ssrc);
539 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
541 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
542 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 4, 0, &rtp->them, sizeof(rtp->them));
544 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));
546 printf("Sent %d bytes of RTP data to %s:%d\n", res, inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
550 /* Clear marker bit and increment seqno */
551 rtpheader[0] = htonl((2 << 30) | (101 << 16) | (rtp->seqno++));
552 /* Make duration 240 */
553 rtpheader[3] |= htonl((240));
554 /* Set the End bit for the last 3 */
555 rtpheader[3] |= htonl((1 << 23));
561 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
563 unsigned int *rtpheader;
569 ms = calc_txstamp(rtp);
570 /* Default prediction */
573 switch(f->subclass) {
574 case AST_FORMAT_ULAW:
575 case AST_FORMAT_ALAW:
576 /* If we're within +/- 20ms from when where we
577 predict we should be, use that */
578 pred = rtp->lastts + f->datalen;
580 case AST_FORMAT_G729A:
581 pred = rtp->lastts + f->datalen * 8;
584 pred = rtp->lastts + (f->datalen * 160 / 33);
586 case AST_FORMAT_G723_1:
587 pred = rtp->lastts + g723_samples(f->data, f->datalen);
590 ast_log(LOG_WARNING, "Not sure about timestamp format for codec format %d\n", f->subclass);
593 /* Re-calculate last TS */
594 rtp->lastts = ms * 8;
595 #if 0 /* XXX Experiment -- Make timestamp always relative XXX */
596 /* If it's close to ou prediction, go for it */
597 if (abs(rtp->lastts - pred) < 640)
602 printf("Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
604 /* Get a pointer to the header */
605 rtpheader = (unsigned int *)(f->data - hdrlen);
606 rtpheader[0] = htonl((2 << 30) | (codec << 16) | (rtp->seqno++));
607 rtpheader[1] = htonl(rtp->lastts);
608 rtpheader[2] = htonl(rtp->ssrc);
609 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
610 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, &rtp->them, sizeof(rtp->them));
612 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));
614 printf("Sent %d bytes of RTP data to %s:%d\n", res, inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
620 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
627 /* If we have no peer, return immediately */
628 if (!rtp->them.sin_addr.s_addr)
631 /* Make sure we have enough space for RTP header */
632 if (_f->frametype != AST_FRAME_VOICE) {
633 ast_log(LOG_WARNING, "RTP can only send voice\n");
637 codec = ast2rtp(_f->subclass);
639 ast_log(LOG_WARNING, "Don't know how to send format %d packets with RTP\n", _f->subclass);
643 if (rtp->lasttxformat != _f->subclass) {
644 /* New format, reset the smoother */
645 ast_log(LOG_DEBUG, "Ooh, format changed from %d to %d\n", rtp->lasttxformat, _f->subclass);
646 rtp->lasttxformat = _f->subclass;
648 ast_smoother_free(rtp->smoother);
649 rtp->smoother = NULL;
653 switch(_f->subclass) {
654 case AST_FORMAT_ULAW:
655 case AST_FORMAT_ALAW:
656 if (!rtp->smoother) {
657 rtp->smoother = ast_smoother_new(160);
659 if (!rtp->smoother) {
660 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
663 ast_smoother_feed(rtp->smoother, _f);
665 while((f = ast_smoother_read(rtp->smoother)))
666 ast_rtp_raw_write(rtp, f, codec);
668 case AST_FORMAT_G729A:
669 if (!rtp->smoother) {
670 rtp->smoother = ast_smoother_new(20);
672 if (!rtp->smoother) {
673 ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
676 ast_smoother_feed(rtp->smoother, _f);
678 while((f = ast_smoother_read(rtp->smoother)))
679 ast_rtp_raw_write(rtp, f, codec);
682 if (!rtp->smoother) {
683 rtp->smoother = ast_smoother_new(33);
685 if (!rtp->smoother) {
686 ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
689 ast_smoother_feed(rtp->smoother, _f);
690 while((f = ast_smoother_read(rtp->smoother)))
691 ast_rtp_raw_write(rtp, f, codec);
694 ast_log(LOG_WARNING, "Not sure about sending format %d packets\n", _f->subclass);
695 if (_f->offset < hdrlen) {
700 ast_rtp_raw_write(rtp, f, codec);
706 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
708 struct ast_rtp_protocol *cur, *prev;
714 prev->next = proto->next;
716 protos = proto->next;
724 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
726 struct ast_rtp_protocol *cur;
729 if (cur->type == proto->type) {
730 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
735 proto->next = protos;
740 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
742 struct ast_rtp_protocol *cur;
745 if (cur->type == chan->type) {
753 int ast_rtp_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
756 struct ast_channel *who, *cs[3];
757 struct ast_rtp *p0, *p1;
758 struct ast_rtp_protocol *pr0, *pr1;
762 /* XXX Wait a half a second for things to settle up
763 this really should be fixed XXX */
764 ast_autoservice_start(c0);
765 ast_autoservice_start(c1);
767 ast_autoservice_stop(c0);
768 ast_autoservice_stop(c1);
770 /* if need DTMF, cant native bridge */
771 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
773 ast_pthread_mutex_lock(&c0->lock);
774 ast_pthread_mutex_lock(&c1->lock);
778 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
779 ast_pthread_mutex_unlock(&c0->lock);
780 ast_pthread_mutex_unlock(&c1->lock);
784 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
785 ast_pthread_mutex_unlock(&c0->lock);
786 ast_pthread_mutex_unlock(&c1->lock);
791 p0 = pr0->get_rtp_info(c0);
792 p1 = pr1->get_rtp_info(c1);
794 /* Somebody doesn't want to play... */
795 ast_pthread_mutex_unlock(&c0->lock);
796 ast_pthread_mutex_unlock(&c1->lock);
799 if (pr0->set_rtp_peer(c0, p1))
800 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
801 if (pr1->set_rtp_peer(c1, p0))
802 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
803 ast_pthread_mutex_unlock(&c0->lock);
804 ast_pthread_mutex_unlock(&c1->lock);
809 if ((c0->pvt->pvt != pvt0) ||
810 (c1->pvt->pvt != pvt1) ||
811 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
812 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
813 if (c0->pvt->pvt == pvt0) {
814 if (pr0->set_rtp_peer(c0, NULL))
815 ast_log(LOG_WARNING, "Channel '%s' failed to revert\n", c0->name);
817 if (c1->pvt->pvt == pvt1) {
818 if (pr1->set_rtp_peer(c1, NULL))
819 ast_log(LOG_WARNING, "Channel '%s' failed to revert back\n", c1->name);
821 /* Tell it to try again later */
825 who = ast_waitfor_n(cs, 2, &to);
827 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
831 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
832 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
833 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
836 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
837 if ((c0->pvt->pvt == pvt0) && (!c0->_softhangup)) {
838 if (pr0->set_rtp_peer(c0, NULL))
839 ast_log(LOG_WARNING, "Channel '%s' failed to revert\n", c0->name);
841 if ((c1->pvt->pvt == pvt1) && (!c1->_softhangup)) {
842 if (pr1->set_rtp_peer(c1, NULL))
843 ast_log(LOG_WARNING, "Channel '%s' failed to revert back\n", c1->name);
845 /* That's all we needed */
849 /* Swap priority not that it's a big deal at this point */