res_rtp_multicast.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2009, Digium, Inc.
  5. *
  6. * Joshua Colp <jcolp@digium.com>
  7. * Andreas 'MacBrody' Brodmann <andreas.brodmann@gmail.com>
  8. *
  9. * See http://www.asterisk.org for more information about
  10. * the Asterisk project. Please do not directly contact
  11. * any of the maintainers of this project for assistance;
  12. * the project provides a web site, mailing lists and IRC
  13. * channels for your use.
  14. *
  15. * This program is free software, distributed under the terms of
  16. * the GNU General Public License Version 2. See the LICENSE file
  17. * at the top of the source tree.
  18. */
  19. /*!
  20. * \file
  21. *
  22. * \brief Multicast RTP Engine
  23. *
  24. * \author Joshua Colp <jcolp@digium.com>
  25. * \author Andreas 'MacBrody' Brodmann <andreas.brodmann@gmail.com>
  26. *
  27. * \ingroup rtp_engines
  28. */
  29. /*** MODULEINFO
  30. <support_level>core</support_level>
  31. ***/
  32. #include "asterisk.h"
  33. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  34. #include <sys/time.h>
  35. #include <signal.h>
  36. #include <fcntl.h>
  37. #include <math.h>
  38. #include "asterisk/pbx.h"
  39. #include "asterisk/frame.h"
  40. #include "asterisk/channel.h"
  41. #include "asterisk/acl.h"
  42. #include "asterisk/config.h"
  43. #include "asterisk/lock.h"
  44. #include "asterisk/utils.h"
  45. #include "asterisk/cli.h"
  46. #include "asterisk/manager.h"
  47. #include "asterisk/unaligned.h"
  48. #include "asterisk/module.h"
  49. #include "asterisk/rtp_engine.h"
  50. #include "asterisk/format_cache.h"
  51. #include "asterisk/multicast_rtp.h"
  52. #include "asterisk/app.h"
  53. #include "asterisk/smoother.h"
  54. /*! Command value used for Linksys paging to indicate we are starting */
  55. #define LINKSYS_MCAST_STARTCMD 6
  56. /*! Command value used for Linksys paging to indicate we are stopping */
  57. #define LINKSYS_MCAST_STOPCMD 7
  58. /*! \brief Type of paging to do */
  59. enum multicast_type {
  60. /*! Type has not been set yet */
  61. MULTICAST_TYPE_UNSPECIFIED = 0,
  62. /*! Simple multicast enabled client/receiver paging like Snom and Barix uses */
  63. MULTICAST_TYPE_BASIC,
  64. /*! More advanced Linksys type paging which requires a start and stop packet */
  65. MULTICAST_TYPE_LINKSYS,
  66. };
  67. /*! \brief Structure for a Linksys control packet */
  68. struct multicast_control_packet {
  69. /*! Unique identifier for the control packet */
  70. uint32_t unique_id;
  71. /*! Actual command in the control packet */
  72. uint32_t command;
  73. /*! IP address for the RTP */
  74. uint32_t ip;
  75. /*! Port for the RTP */
  76. uint32_t port;
  77. };
  78. /*! \brief Structure for a multicast paging instance */
  79. struct multicast_rtp {
  80. /*! TYpe of multicast paging this instance is doing */
  81. enum multicast_type type;
  82. /*! Socket used for sending the audio on */
  83. int socket;
  84. /*! Synchronization source value, used when creating/sending the RTP packet */
  85. unsigned int ssrc;
  86. /*! Sequence number, used when creating/sending the RTP packet */
  87. uint16_t seqno;
  88. unsigned int lastts;
  89. struct timeval txcore;
  90. struct ast_smoother *smoother;
  91. };
  92. #define MAX_TIMESTAMP_SKEW 640
  93. enum {
  94. OPT_CODEC = (1 << 0),
  95. OPT_LOOP = (1 << 1),
  96. OPT_TTL = (1 << 2),
  97. OPT_IF = (1 << 3),
  98. };
  99. enum {
  100. OPT_ARG_CODEC = 0,
  101. OPT_ARG_LOOP,
  102. OPT_ARG_TTL,
  103. OPT_ARG_IF,
  104. OPT_ARG_ARRAY_SIZE,
  105. };
  106. AST_APP_OPTIONS(multicast_rtp_options, BEGIN_OPTIONS
  107. /*! Set the codec to be used for multicast RTP */
  108. AST_APP_OPTION_ARG('c', OPT_CODEC, OPT_ARG_CODEC),
  109. /*! Set whether multicast RTP is looped back to the sender */
  110. AST_APP_OPTION_ARG('l', OPT_LOOP, OPT_ARG_LOOP),
  111. /*! Set the hop count for multicast RTP */
  112. AST_APP_OPTION_ARG('t', OPT_TTL, OPT_ARG_TTL),
  113. /*! Set the interface from which multicast RTP is sent */
  114. AST_APP_OPTION_ARG('i', OPT_IF, OPT_ARG_IF),
  115. END_OPTIONS );
  116. struct ast_multicast_rtp_options {
  117. char *type;
  118. char *options;
  119. struct ast_format *fmt;
  120. struct ast_flags opts;
  121. char *opt_args[OPT_ARG_ARRAY_SIZE];
  122. /*! The type and options are stored in this buffer */
  123. char buf[0];
  124. };
  125. struct ast_multicast_rtp_options *ast_multicast_rtp_create_options(const char *type,
  126. const char *options)
  127. {
  128. struct ast_multicast_rtp_options *mcast_options;
  129. char *pos;
  130. mcast_options = ast_calloc(1, sizeof(*mcast_options)
  131. + strlen(type)
  132. + strlen(S_OR(options, "")) + 2);
  133. if (!mcast_options) {
  134. return NULL;
  135. }
  136. pos = mcast_options->buf;
  137. /* Safe */
  138. strcpy(pos, type);
  139. mcast_options->type = pos;
  140. pos += strlen(type) + 1;
  141. if (!ast_strlen_zero(options)) {
  142. strcpy(pos, options); /* Safe */
  143. }
  144. mcast_options->options = pos;
  145. if (ast_app_parse_options(multicast_rtp_options, &mcast_options->opts,
  146. mcast_options->opt_args, mcast_options->options)) {
  147. ast_log(LOG_WARNING, "Error parsing multicast RTP options\n");
  148. ast_multicast_rtp_free_options(mcast_options);
  149. return NULL;
  150. }
  151. return mcast_options;
  152. }
  153. void ast_multicast_rtp_free_options(struct ast_multicast_rtp_options *mcast_options)
  154. {
  155. ast_free(mcast_options);
  156. }
  157. struct ast_format *ast_multicast_rtp_options_get_format(struct ast_multicast_rtp_options *mcast_options)
  158. {
  159. if (ast_test_flag(&mcast_options->opts, OPT_CODEC)
  160. && !ast_strlen_zero(mcast_options->opt_args[OPT_ARG_CODEC])) {
  161. return ast_format_cache_get(mcast_options->opt_args[OPT_ARG_CODEC]);
  162. }
  163. return NULL;
  164. }
  165. /* Forward Declarations */
  166. static int multicast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
  167. static int multicast_rtp_activate(struct ast_rtp_instance *instance);
  168. static int multicast_rtp_destroy(struct ast_rtp_instance *instance);
  169. static int multicast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
  170. static struct ast_frame *multicast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
  171. /* RTP Engine Declaration */
  172. static struct ast_rtp_engine multicast_rtp_engine = {
  173. .name = "multicast",
  174. .new = multicast_rtp_new,
  175. .activate = multicast_rtp_activate,
  176. .destroy = multicast_rtp_destroy,
  177. .write = multicast_rtp_write,
  178. .read = multicast_rtp_read,
  179. };
  180. static int set_type(struct multicast_rtp *multicast, const char *type)
  181. {
  182. if (!strcasecmp(type, "basic")) {
  183. multicast->type = MULTICAST_TYPE_BASIC;
  184. } else if (!strcasecmp(type, "linksys")) {
  185. multicast->type = MULTICAST_TYPE_LINKSYS;
  186. } else {
  187. ast_log(LOG_WARNING, "Unrecognized multicast type '%s' specified.\n", type);
  188. return -1;
  189. }
  190. return 0;
  191. }
  192. static void set_ttl(int sock, const char *ttl_str)
  193. {
  194. int ttl;
  195. if (ast_strlen_zero(ttl_str)) {
  196. return;
  197. }
  198. ast_debug(3, "Setting multicast TTL to %s\n", ttl_str);
  199. if (sscanf(ttl_str, "%30d", &ttl) < 1) {
  200. ast_log(LOG_WARNING, "Invalid multicast ttl option '%s'\n", ttl_str);
  201. return;
  202. }
  203. if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) < 0) {
  204. ast_log(LOG_WARNING, "Could not set multicast ttl to '%s': %s\n",
  205. ttl_str, strerror(errno));
  206. }
  207. }
  208. static void set_loop(int sock, const char *loop_str)
  209. {
  210. unsigned char loop;
  211. if (ast_strlen_zero(loop_str)) {
  212. return;
  213. }
  214. ast_debug(3, "Setting multicast loop to %s\n", loop_str);
  215. if (sscanf(loop_str, "%30hhu", &loop) < 1) {
  216. ast_log(LOG_WARNING, "Invalid multicast loop option '%s'\n", loop_str);
  217. return;
  218. }
  219. if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)) < 0) {
  220. ast_log(LOG_WARNING, "Could not set multicast loop to '%s': %s\n",
  221. loop_str, strerror(errno));
  222. }
  223. }
  224. static void set_if(int sock, const char *if_str)
  225. {
  226. struct in_addr iface;
  227. if (ast_strlen_zero(if_str)) {
  228. return;
  229. }
  230. ast_debug(3, "Setting multicast if to %s\n", if_str);
  231. if (!inet_aton(if_str, &iface)) {
  232. ast_log(LOG_WARNING, "Cannot parse if option '%s'\n", if_str);
  233. }
  234. if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, &iface, sizeof(iface)) < 0) {
  235. ast_log(LOG_WARNING, "Could not set multicast if to '%s': %s\n",
  236. if_str, strerror(errno));
  237. }
  238. }
  239. /*! \brief Function called to create a new multicast instance */
  240. static int multicast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data)
  241. {
  242. struct multicast_rtp *multicast;
  243. struct ast_multicast_rtp_options *mcast_options = data;
  244. if (!(multicast = ast_calloc(1, sizeof(*multicast)))) {
  245. return -1;
  246. }
  247. if (set_type(multicast, mcast_options->type)) {
  248. ast_free(multicast);
  249. return -1;
  250. }
  251. if ((multicast->socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
  252. ast_free(multicast);
  253. return -1;
  254. }
  255. if (ast_test_flag(&mcast_options->opts, OPT_LOOP)) {
  256. set_loop(multicast->socket, mcast_options->opt_args[OPT_ARG_LOOP]);
  257. }
  258. if (ast_test_flag(&mcast_options->opts, OPT_TTL)) {
  259. set_ttl(multicast->socket, mcast_options->opt_args[OPT_ARG_TTL]);
  260. }
  261. if (ast_test_flag(&mcast_options->opts, OPT_IF)) {
  262. set_if(multicast->socket, mcast_options->opt_args[OPT_ARG_IF]);
  263. }
  264. multicast->ssrc = ast_random();
  265. ast_rtp_instance_set_data(instance, multicast);
  266. return 0;
  267. }
  268. static int rtp_get_rate(struct ast_format *format)
  269. {
  270. return ast_format_cmp(format, ast_format_g722) == AST_FORMAT_CMP_EQUAL ?
  271. 8000 : ast_format_get_sample_rate(format);
  272. }
  273. static unsigned int calc_txstamp(struct multicast_rtp *rtp, struct timeval *delivery)
  274. {
  275. struct timeval t;
  276. long ms;
  277. if (ast_tvzero(rtp->txcore)) {
  278. rtp->txcore = ast_tvnow();
  279. rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
  280. }
  281. t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
  282. if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
  283. ms = 0;
  284. }
  285. rtp->txcore = t;
  286. return (unsigned int) ms;
  287. }
  288. /*! \brief Helper function which populates a control packet with useful information and sends it */
  289. static int multicast_send_control_packet(struct ast_rtp_instance *instance, struct multicast_rtp *multicast, int command)
  290. {
  291. struct multicast_control_packet control_packet = { .unique_id = htonl((u_long)time(NULL)),
  292. .command = htonl(command),
  293. };
  294. struct ast_sockaddr control_address, remote_address;
  295. ast_rtp_instance_get_local_address(instance, &control_address);
  296. ast_rtp_instance_get_remote_address(instance, &remote_address);
  297. /* Ensure the user of us have given us both the control address and destination address */
  298. if (ast_sockaddr_isnull(&control_address) ||
  299. ast_sockaddr_isnull(&remote_address)) {
  300. return -1;
  301. }
  302. /* The protocol only supports IPv4. */
  303. if (ast_sockaddr_is_ipv6(&remote_address)) {
  304. ast_log(LOG_WARNING, "Cannot send control packet for IPv6 "
  305. "remote address.\n");
  306. return -1;
  307. }
  308. control_packet.ip = htonl(ast_sockaddr_ipv4(&remote_address));
  309. control_packet.port = htonl(ast_sockaddr_port(&remote_address));
  310. /* Based on a recommendation by Brian West who did the FreeSWITCH implementation we send control packets twice */
  311. ast_sendto(multicast->socket, &control_packet, sizeof(control_packet), 0, &control_address);
  312. ast_sendto(multicast->socket, &control_packet, sizeof(control_packet), 0, &control_address);
  313. return 0;
  314. }
  315. /*! \brief Function called to indicate that audio is now going to flow */
  316. static int multicast_rtp_activate(struct ast_rtp_instance *instance)
  317. {
  318. struct multicast_rtp *multicast = ast_rtp_instance_get_data(instance);
  319. if (multicast->type != MULTICAST_TYPE_LINKSYS) {
  320. return 0;
  321. }
  322. return multicast_send_control_packet(instance, multicast, LINKSYS_MCAST_STARTCMD);
  323. }
  324. /*! \brief Function called to destroy a multicast instance */
  325. static int multicast_rtp_destroy(struct ast_rtp_instance *instance)
  326. {
  327. struct multicast_rtp *multicast = ast_rtp_instance_get_data(instance);
  328. if (multicast->type == MULTICAST_TYPE_LINKSYS) {
  329. multicast_send_control_packet(instance, multicast, LINKSYS_MCAST_STOPCMD);
  330. }
  331. if (multicast->smoother) {
  332. ast_smoother_free(multicast->smoother);
  333. }
  334. close(multicast->socket);
  335. ast_free(multicast);
  336. return 0;
  337. }
  338. static int rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
  339. {
  340. struct multicast_rtp *multicast = ast_rtp_instance_get_data(instance);
  341. unsigned int ms = calc_txstamp(multicast, &frame->delivery);
  342. unsigned char *rtpheader;
  343. struct ast_sockaddr remote_address = { {0,} };
  344. int rate = rtp_get_rate(frame->subclass.format) / 1000;
  345. int hdrlen = 12, mark = 0;
  346. if (ast_format_cmp(frame->subclass.format, ast_format_g722) == AST_FORMAT_CMP_EQUAL) {
  347. frame->samples /= 2;
  348. }
  349. if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
  350. multicast->lastts = frame->ts * rate;
  351. } else {
  352. /* Try to predict what our timestamp should be */
  353. int pred = multicast->lastts + frame->samples;
  354. /* Calculate last TS */
  355. multicast->lastts = multicast->lastts + ms * rate;
  356. if (ast_tvzero(frame->delivery)) {
  357. int delta = abs((int) multicast->lastts - pred);
  358. if (delta < MAX_TIMESTAMP_SKEW) {
  359. multicast->lastts = pred;
  360. } else {
  361. ast_debug(3, "Difference is %d, ms is %u\n", delta, ms);
  362. mark = 1;
  363. }
  364. }
  365. }
  366. /* Construct an RTP header for our packet */
  367. rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
  368. put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (multicast->seqno) | (mark << 23)));
  369. put_unaligned_uint32(rtpheader + 4, htonl(multicast->lastts));
  370. put_unaligned_uint32(rtpheader + 8, htonl(multicast->ssrc));
  371. /* Increment sequence number and wrap to 0 if it overflows 16 bits. */
  372. multicast->seqno = 0xFFFF & (multicast->seqno + 1);
  373. /* Finally send it out to the eager phones listening for us */
  374. ast_rtp_instance_get_remote_address(instance, &remote_address);
  375. if (ast_sendto(multicast->socket, (void *) rtpheader, frame->datalen + hdrlen, 0, &remote_address) < 0) {
  376. ast_log(LOG_ERROR, "Multicast RTP Transmission error to %s: %s\n",
  377. ast_sockaddr_stringify(&remote_address),
  378. strerror(errno));
  379. return -1;
  380. }
  381. return 0;
  382. }
  383. /*! \brief Function called to broadcast some audio on a multicast instance */
  384. static int multicast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
  385. {
  386. struct multicast_rtp *multicast = ast_rtp_instance_get_data(instance);
  387. struct ast_format *format;
  388. struct ast_frame *f;
  389. int codec;
  390. /* We only accept audio, nothing else */
  391. if (frame->frametype != AST_FRAME_VOICE) {
  392. return 0;
  393. }
  394. /* Grab the actual payload number for when we create the RTP packet */
  395. if ((codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 1, frame->subclass.format, 0)) < 0) {
  396. return -1;
  397. }
  398. format = frame->subclass.format;
  399. if (!multicast->smoother && ast_format_can_be_smoothed(format)) {
  400. unsigned int smoother_flags = ast_format_get_smoother_flags(format);
  401. unsigned int framing_ms = ast_rtp_codecs_get_framing(ast_rtp_instance_get_codecs(instance));
  402. if (!framing_ms && (smoother_flags & AST_SMOOTHER_FLAG_FORCED)) {
  403. framing_ms = ast_format_get_default_ms(format);
  404. }
  405. if (framing_ms) {
  406. multicast->smoother = ast_smoother_new((framing_ms * ast_format_get_minimum_bytes(format)) / ast_format_get_minimum_ms(format));
  407. if (!multicast->smoother) {
  408. ast_log(LOG_WARNING, "Unable to create smoother: format %s ms: %u len %u\n",
  409. ast_format_get_name(format), framing_ms, ast_format_get_minimum_bytes(format));
  410. return -1;
  411. }
  412. ast_smoother_set_flags(multicast->smoother, smoother_flags);
  413. }
  414. }
  415. if (multicast->smoother) {
  416. if (ast_smoother_test_flag(multicast->smoother, AST_SMOOTHER_FLAG_BE)) {
  417. ast_smoother_feed_be(multicast->smoother, frame);
  418. } else {
  419. ast_smoother_feed(multicast->smoother, frame);
  420. }
  421. while ((f = ast_smoother_read(multicast->smoother)) && f->data.ptr) {
  422. rtp_raw_write(instance, f, codec);
  423. }
  424. } else {
  425. int hdrlen = 12;
  426. /* If we do not have space to construct an RTP header duplicate the frame so we get some */
  427. if (frame->offset < hdrlen) {
  428. f = ast_frdup(frame);
  429. } else {
  430. f = frame;
  431. }
  432. if (f->data.ptr) {
  433. rtp_raw_write(instance, f, codec);
  434. }
  435. if (f != frame) {
  436. ast_frfree(f);
  437. }
  438. }
  439. return 0;
  440. }
  441. /*! \brief Function called to read from a multicast instance */
  442. static struct ast_frame *multicast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
  443. {
  444. return &ast_null_frame;
  445. }
  446. static int load_module(void)
  447. {
  448. if (ast_rtp_engine_register(&multicast_rtp_engine)) {
  449. return AST_MODULE_LOAD_DECLINE;
  450. }
  451. return AST_MODULE_LOAD_SUCCESS;
  452. }
  453. static int unload_module(void)
  454. {
  455. ast_rtp_engine_unregister(&multicast_rtp_engine);
  456. return 0;
  457. }
  458. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Multicast RTP Engine",
  459. .support_level = AST_MODULE_SUPPORT_CORE,
  460. .load = load_module,
  461. .unload = unload_module,
  462. .load_pri = AST_MODPRI_CHANNEL_DEPEND,
  463. );