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