feat: AudioSocket channel, application, and ARI support.
authorSeán C McCord <ulexus@gmail.com>
Thu, 18 Jul 2019 00:47:50 +0000 (20:47 -0400)
committerBen Ford <bford@digium.com>
Tue, 14 Jan 2020 15:36:44 +0000 (09:36 -0600)
This commit adds support for
[AudioSocket](
https://wiki.asterisk.org/wiki/display/AST/AudioSocket),
a very simple bidirectional audio streaming protocol. There are both
channel and application interfaces.

A description of the protocol can be found on the above referenced
GitHub page.  A short talk about the reasons and implementation can be
found on [YouTube](https://www.youtube.com/watch?v=tjduXbZZEgI), from
CommCon 2019.

ARI support has also been added via the existing "externalMedia" ARI
functionality. The UUID is specified using the arbitrary "data" field.

ASTERISK-28484 #close

Change-Id: Ie866e6c4fa13178ec76f2a6971ad3590a3a588b5

apps/app_audiosocket.c [new file with mode: 0644]
channels/chan_audiosocket.c [new file with mode: 0644]
doc/CHANGES-staging/feat_audiosocket.txt [new file with mode: 0644]
include/asterisk/res_audiosocket.h [new file with mode: 0644]
res/ari/resource_channels.c
res/ari/resource_channels.h
res/res_ari_channels.c
res/res_audiosocket.c [new file with mode: 0644]
res/res_audiosocket.exports.in [new file with mode: 0644]
rest-api/api-docs/channels.json

diff --git a/apps/app_audiosocket.c b/apps/app_audiosocket.c
new file mode 100644 (file)
index 0000000..45d3396
--- /dev/null
@@ -0,0 +1,240 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2019, CyCore Systems, Inc
+ *
+ * Seán C McCord <scm@cycoresys.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ *
+ * \brief AudioSocket application -- transmit and receive audio through a TCP socket
+ *
+ * \author Seán C McCord <scm@cycoresys.com>
+ *
+ * \ingroup applications
+ */
+
+/*** MODULEINFO
+       <depend>res_audiosocket</depend>
+       <support_level>extended</support_level>
+ ***/
+
+#include "asterisk.h"
+#include "errno.h"
+#include <uuid/uuid.h>
+
+#include "asterisk/file.h"
+#include "asterisk/module.h"
+#include "asterisk/channel.h"
+#include "asterisk/app.h"
+#include "asterisk/res_audiosocket.h"
+#include "asterisk/utils.h"
+#include "asterisk/format_cache.h"
+
+#define AST_MODULE "app_audiosocket"
+#define AUDIOSOCKET_CONFIG "audiosocket.conf"
+#define MAX_CONNECT_TIMEOUT_MSEC 2000
+
+/*** DOCUMENTATION
+       <application name="AudioSocket" language="en_US">
+               <synopsis>
+                       Transmit and receive audio between channel and TCP socket
+               </synopsis>
+               <syntax>
+                       <parameter name="uuid" required="true">
+                               <para>UUID is the universally-unique identifier of the call for the audio socket service.  This ID must conform to the string form of a standard UUID.</para>
+                       </parameter>
+                       <parameter name="service" required="true">
+                               <para>Service is the name or IP address and port number of the audio socket service to which this call should be connected.  This should be in the form host:port, such as myserver:9019 </para>
+                       </parameter>
+               </syntax>
+               <description>
+                       <para>Connects to the given TCP service, then transmits channel audio over that socket.  In turn, audio is received from the socket and sent to the channel.  Only audio frames will be transmitted.</para>
+                       <para>Protocol is specified at https://wiki.asterisk.org/wiki/display/AST/AudioSocket</para>
+                       <para>This application does not automatically answer and should generally be preceeded by an application such as Answer() or Progress().</para>
+               </description>
+       </application>
+ ***/
+
+static const char app[] = "AudioSocket";
+
+static int audiosocket_run(struct ast_channel *chan, const char *id, const int svc);
+
+static int audiosocket_exec(struct ast_channel *chan, const char *data)
+{
+       char *parse;
+       struct ast_format *readFormat, *writeFormat;
+       const char *chanName;
+       int res;
+
+       AST_DECLARE_APP_ARGS(args,
+               AST_APP_ARG(idStr);
+               AST_APP_ARG(server);
+       );
+
+       int s = 0;
+       uuid_t uu;
+
+
+       chanName = ast_channel_name(chan);
+
+       /* Parse and validate arguments */
+       parse = ast_strdupa(data);
+       AST_STANDARD_APP_ARGS(args, parse);
+       if (ast_strlen_zero(args.idStr)) {
+               ast_log(LOG_ERROR, "UUID is required\n");
+               return -1;
+       }
+       if (uuid_parse(args.idStr, uu)) {
+               ast_log(LOG_ERROR, "Failed to parse UUID '%s'\n", args.idStr);
+               return -1;
+       }
+       if ((s = ast_audiosocket_connect(args.server, chan)) < 0) {
+               /* The res module will already output a log message, so another is not needed */
+               return -1;
+       }
+
+       writeFormat = ao2_bump(ast_channel_writeformat(chan));
+       readFormat = ao2_bump(ast_channel_readformat(chan));
+
+       if (ast_set_write_format(chan, ast_format_slin)) {
+               ast_log(LOG_ERROR, "Failed to set write format to SLINEAR for channel %s\n", chanName);
+               ao2_ref(writeFormat, -1);
+               ao2_ref(readFormat, -1);
+               close(s);
+               return -1;
+       }
+       if (ast_set_read_format(chan, ast_format_slin)) {
+               ast_log(LOG_ERROR, "Failed to set read format to SLINEAR for channel %s\n", chanName);
+
+               /* Attempt to restore previous write format even though it is likely to
+                * fail, since setting the read format did.
+                */
+               if (ast_set_write_format(chan, writeFormat)) {
+                       ast_log(LOG_ERROR, "Failed to restore write format for channel %s\n", chanName);
+               }
+               ao2_ref(writeFormat, -1);
+               ao2_ref(readFormat, -1);
+               close(s);
+               return -1;
+       }
+
+       res = audiosocket_run(chan, args.idStr, s);
+       /* On non-zero return, report failure */
+       if (res) {
+               /* Restore previous formats and close the connection */
+               if (ast_set_write_format(chan, writeFormat)) {
+                       ast_log(LOG_ERROR, "Failed to restore write format for channel %s\n", chanName);
+               }
+               if (ast_set_read_format(chan, readFormat)) {
+                       ast_log(LOG_ERROR, "Failed to restore read format for channel %s\n", chanName);
+               }
+               ao2_ref(writeFormat, -1);
+               ao2_ref(readFormat, -1);
+               close(s);
+               return res;
+       }
+       close(s);
+
+       if (ast_set_write_format(chan, writeFormat)) {
+               ast_log(LOG_ERROR, "Failed to restore write format for channel %s\n", chanName);
+       }
+       if (ast_set_read_format(chan, readFormat)) {
+               ast_log(LOG_ERROR, "Failed to restore read format for channel %s\n", chanName);
+       }
+       ao2_ref(writeFormat, -1);
+       ao2_ref(readFormat, -1);
+
+       return 0;
+}
+
+static int audiosocket_run(struct ast_channel *chan, const char *id, int svc)
+{
+       const char *chanName;
+       struct ast_channel *targetChan;
+       int ms = 0;
+       int outfd = -1;
+       struct ast_frame *f;
+
+       if (!chan || ast_channel_state(chan) != AST_STATE_UP) {
+               ast_log(LOG_ERROR, "Channel is %s\n", chan ? "not answered" : "missing");
+               return -1;
+       }
+
+       if (ast_audiosocket_init(svc, id)) {
+               ast_log(LOG_ERROR, "Failed to intialize AudioSocket\n");
+               return -1;
+       }
+
+       chanName = ast_channel_name(chan);
+
+       while (1) {
+
+               targetChan = ast_waitfor_nandfds(&chan, 1, &svc, 1, NULL, &outfd, &ms);
+               if (targetChan) {
+                       f = ast_read(chan);
+                       if (!f) {
+                               return -1;
+                       }
+
+                       if (f->frametype == AST_FRAME_VOICE) {
+                               /* Send audio frame to audiosocket */
+                               if (ast_audiosocket_send_frame(svc, f)) {
+                                       ast_log(LOG_ERROR, "Failed to forward channel frame from %s to AudioSocket\n",
+                                               chanName);
+                                       ast_frfree(f);
+                                       return -1;
+                               }
+                       }
+                       ast_frfree(f);
+               }
+
+               if (outfd >= 0) {
+                       f = ast_audiosocket_receive_frame(svc);
+                       if (!f) {
+                               ast_log(LOG_ERROR, "Failed to receive frame from AudioSocket message for"
+                                       "channel %s\n", chanName);
+                               return -1;
+                       }
+                       if (ast_write(chan, f)) {
+                               ast_log(LOG_WARNING, "Failed to forward frame to channel %s\n", chanName);
+                               ast_frfree(f);
+                               return -1;
+                       }
+                       ast_frfree(f);
+               }
+       }
+       return 0;
+}
+
+static int unload_module(void)
+{
+       return ast_unregister_application(app);
+}
+
+static int load_module(void)
+{
+       return ast_register_application_xml(app, audiosocket_exec);
+}
+
+AST_MODULE_INFO(
+       ASTERISK_GPL_KEY,
+       AST_MODFLAG_LOAD_ORDER,
+       "AudioSocket Application",
+       .support_level = AST_MODULE_SUPPORT_EXTENDED,
+       .load = load_module,
+       .unload = unload_module,
+       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
+       .requires = "res_audiosocket",
+);
diff --git a/channels/chan_audiosocket.c b/channels/chan_audiosocket.c
new file mode 100644 (file)
index 0000000..823a978
--- /dev/null
@@ -0,0 +1,302 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2019, CyCore Systems, Inc
+ *
+ * Seán C McCord <scm@cycoresys.com>
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ *
+ * \author Seán C McCord <scm@cycoresys.com>
+ *
+ * \brief AudioSocket Channel
+ *
+ * \ingroup channel_drivers
+ */
+
+/*** MODULEINFO
+       <depend>res_audiosocket</depend>
+       <support_level>extended</support_level>
+ ***/
+
+#include "asterisk.h"
+#include <uuid/uuid.h>
+
+#include "asterisk/channel.h"
+#include "asterisk/module.h"
+#include "asterisk/res_audiosocket.h"
+#include "asterisk/pbx.h"
+#include "asterisk/acl.h"
+#include "asterisk/app.h"
+#include "asterisk/causes.h"
+#include "asterisk/format_cache.h"
+
+#define FD_OUTPUT 1    /* A fd of -1 means an error, 0 is stdin */
+
+struct audiosocket_instance {
+       int svc;        /* The file descriptor for the AudioSocket instance */
+       char id[38];    /* The UUID identifying this AudioSocket instance */
+} audiosocket_instance;
+
+/* Forward declarations */
+static struct ast_channel *audiosocket_request(const char *type,
+       struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids,
+       const struct ast_channel *requestor, const char *data, int *cause);
+static int audiosocket_call(struct ast_channel *ast, const char *dest, int timeout);
+static int audiosocket_hangup(struct ast_channel *ast);
+static struct ast_frame *audiosocket_read(struct ast_channel *ast);
+static int audiosocket_write(struct ast_channel *ast, struct ast_frame *f);
+
+/* AudioSocket channel driver declaration */
+static struct ast_channel_tech audiosocket_channel_tech = {
+       .type = "AudioSocket",
+       .description = "AudioSocket Channel Driver",
+       .requester = audiosocket_request,
+       .call = audiosocket_call,
+       .hangup = audiosocket_hangup,
+       .read = audiosocket_read,
+       .write = audiosocket_write,
+};
+
+/*! \brief Function called when we should read a frame from the channel */
+static struct ast_frame *audiosocket_read(struct ast_channel *ast)
+{
+       struct audiosocket_instance *instance;
+
+       /* The channel should always be present from the API */
+       instance = ast_channel_tech_pvt(ast);
+       if (instance == NULL || instance->svc < FD_OUTPUT) {
+               return NULL;
+       }
+       return ast_audiosocket_receive_frame(instance->svc);
+}
+
+/*! \brief Function called when we should write a frame to the channel */
+static int audiosocket_write(struct ast_channel *ast, struct ast_frame *f)
+{
+       struct audiosocket_instance *instance;
+
+       /* The channel should always be present from the API */
+       instance = ast_channel_tech_pvt(ast);
+       if (instance == NULL || instance->svc < 1) {
+               return -1;
+       }
+       return ast_audiosocket_send_frame(instance->svc, f);
+}
+
+/*! \brief Function called when we should actually call the destination */
+static int audiosocket_call(struct ast_channel *ast, const char *dest, int timeout)
+{
+       struct audiosocket_instance *instance = ast_channel_tech_pvt(ast);
+
+       ast_queue_control(ast, AST_CONTROL_ANSWER);
+
+       return ast_audiosocket_init(instance->svc, instance->id);
+}
+
+/*! \brief Function called when we should hang the channel up */
+static int audiosocket_hangup(struct ast_channel *ast)
+{
+       struct audiosocket_instance *instance;
+
+       /* The channel should always be present from the API */
+       instance = ast_channel_tech_pvt(ast);
+       if (instance != NULL && instance->svc > 0) {
+               close(instance->svc);
+       }
+
+       ast_channel_tech_pvt_set(ast, NULL);
+       ast_free(instance);
+
+       return 0;
+}
+
+enum {
+       OPT_AUDIOSOCKET_CODEC = (1 << 0),
+};
+
+enum {
+       OPT_ARG_AUDIOSOCKET_CODEC = (1 << 0),
+       OPT_ARG_ARRAY_SIZE
+};
+
+AST_APP_OPTIONS(audiosocket_options, BEGIN_OPTIONS
+       AST_APP_OPTION_ARG('c', OPT_AUDIOSOCKET_CODEC, OPT_ARG_AUDIOSOCKET_CODEC),
+END_OPTIONS );
+
+/*! \brief Function called when we should prepare to call the unicast destination */
+static struct ast_channel *audiosocket_request(const char *type,
+       struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids,
+       const struct ast_channel *requestor, const char *data, int *cause)
+{
+       char *parse;
+       struct audiosocket_instance *instance = NULL;
+       struct ast_sockaddr address;
+       struct ast_channel *chan;
+       struct ast_format_cap *caps = NULL;
+       struct ast_format *fmt = NULL;
+       uuid_t uu;
+       int fd;
+       AST_DECLARE_APP_ARGS(args,
+               AST_APP_ARG(destination);
+               AST_APP_ARG(idStr);
+               AST_APP_ARG(options);
+       );
+       struct ast_flags opts = { 0, };
+       char *opt_args[OPT_ARG_ARRAY_SIZE];
+
+       if (ast_strlen_zero(data)) {
+               ast_log(LOG_ERROR, "Destination is required for the 'AudioSocket' channel\n");
+               goto failure;
+       }
+       parse = ast_strdupa(data);
+       AST_NONSTANDARD_APP_ARGS(args, parse, '/');
+
+       if (ast_strlen_zero(args.destination)) {
+               ast_log(LOG_ERROR, "Destination is required for the 'AudioSocket' channel\n");
+               goto failure;
+       }
+       if (ast_sockaddr_resolve_first_af
+               (&address, args.destination, PARSE_PORT_REQUIRE, AST_AF_UNSPEC)) {
+               ast_log(LOG_ERROR, "Destination '%s' could not be parsed\n", args.destination);
+               goto failure;
+       }
+
+       if (ast_strlen_zero(args.idStr)) {
+               ast_log(LOG_ERROR, "UUID is required for the 'AudioSocket' channel\n");
+               goto failure;
+       }
+       if (uuid_parse(args.idStr, uu)) {
+               ast_log(LOG_ERROR, "Failed to parse UUID '%s'\n", args.idStr);
+               goto failure;
+       }
+
+       if (!ast_strlen_zero(args.options)
+               && ast_app_parse_options(audiosocket_options, &opts, opt_args,
+                       ast_strdupa(args.options))) {
+               ast_log(LOG_ERROR, "'AudioSocket' channel options '%s' parse error\n",
+                       args.options);
+               goto failure;
+       }
+
+       if (ast_test_flag(&opts, OPT_AUDIOSOCKET_CODEC)
+               && !ast_strlen_zero(opt_args[OPT_ARG_AUDIOSOCKET_CODEC])) {
+               fmt = ast_format_cache_get(opt_args[OPT_ARG_AUDIOSOCKET_CODEC]);
+               if (!fmt) {
+                       ast_log(LOG_ERROR, "Codec '%s' not found for AudioSocket connection to '%s'\n",
+                               opt_args[OPT_ARG_AUDIOSOCKET_CODEC], args.destination);
+                       goto failure;
+               }
+       } else {
+               fmt = ast_format_cap_get_format(cap, 0);
+               if (!fmt) {
+                       ast_log(LOG_ERROR, "No codec available for AudioSocket connection to '%s'\n",
+                               args.destination);
+                       goto failure;
+               }
+       }
+
+       caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
+       if (!caps) {
+               goto failure;
+       }
+
+       instance = ast_calloc(1, sizeof(*instance));
+       if (!instance) {
+               ast_log(LOG_ERROR, "Failed to allocate AudioSocket channel pvt\n");
+               goto failure;
+       }
+       ast_copy_string(instance->id, args.idStr, sizeof(instance->id));
+
+       if ((fd = ast_audiosocket_connect(args.destination, NULL)) < 0) {
+               goto failure;
+       }
+       instance->svc = fd;
+
+       chan = ast_channel_alloc(1, AST_STATE_DOWN, "", "", "", "", "", assignedids,
+               requestor, 0, "AudioSocket/%s-%s", args.destination, args.idStr);
+       if (!chan) {
+               goto failure;
+       }
+       ast_channel_set_fd(chan, 0, fd);
+
+       ast_channel_tech_set(chan, &audiosocket_channel_tech);
+
+       ast_format_cap_append(caps, fmt, 0);
+       ast_channel_nativeformats_set(chan, caps);
+       ast_channel_set_writeformat(chan, fmt);
+       ast_channel_set_rawwriteformat(chan, fmt);
+       ast_channel_set_readformat(chan, fmt);
+       ast_channel_set_rawreadformat(chan, fmt);
+
+       ast_channel_tech_pvt_set(chan, instance);
+
+       pbx_builtin_setvar_helper(chan, "AUDIOSOCKET_UUID", args.idStr);
+       pbx_builtin_setvar_helper(chan, "AUDIOSOCKET_SERVICE", args.destination);
+
+       ast_channel_unlock(chan);
+
+       ao2_ref(fmt, -1);
+       ao2_ref(caps, -1);
+       return chan;
+
+failure:
+       *cause = AST_CAUSE_FAILURE;
+       ao2_cleanup(fmt);
+       ao2_cleanup(caps);
+       if (instance != NULL) {
+               ast_free(instance);
+               if (fd >= 0) {
+                       close(fd);
+               }
+       }
+
+       return NULL;
+}
+
+/*! \brief Function called when our module is unloaded */
+static int unload_module(void)
+{
+       ast_channel_unregister(&audiosocket_channel_tech);
+       ao2_cleanup(audiosocket_channel_tech.capabilities);
+       audiosocket_channel_tech.capabilities = NULL;
+
+       return 0;
+}
+
+/*! \brief Function called when our module is loaded */
+static int load_module(void)
+{
+       if (!(audiosocket_channel_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
+               return AST_MODULE_LOAD_DECLINE;
+       }
+       ast_format_cap_append_by_type(audiosocket_channel_tech.capabilities, AST_MEDIA_TYPE_UNKNOWN);
+       if (ast_channel_register(&audiosocket_channel_tech)) {
+               ast_log(LOG_ERROR, "Unable to register channel class AudioSocket");
+               ao2_ref(audiosocket_channel_tech.capabilities, -1);
+               audiosocket_channel_tech.capabilities = NULL;
+               return AST_MODULE_LOAD_DECLINE;
+       }
+
+       return AST_MODULE_LOAD_SUCCESS;
+}
+
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER,
+       "AudioSocket Channel",
+       .support_level = AST_MODULE_SUPPORT_EXTENDED,
+       .load = load_module,
+       .unload = unload_module,
+       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
+       .requires = "res_audiosocket",
+);
diff --git a/doc/CHANGES-staging/feat_audiosocket.txt b/doc/CHANGES-staging/feat_audiosocket.txt
new file mode 100644 (file)
index 0000000..cc7b352
--- /dev/null
@@ -0,0 +1,14 @@
+Subject: Features
+
+Adds support for AudioSocket, a very simple bidirectional audio streaming
+protocol. There are both channel and application interfaces.
+
+A description of the protocol can be found on the referenced wiki page. A
+short talk about the reasons and implementation can be found on YouTube at
+the link provided.
+
+ARI support has also been added via the existing "externalMedia" ARI
+functionality. The UUID is specified using the arbitrary "data" field.
+
+Wiki: https://wiki.asterisk.org/wiki/display/AST/AudioSocket
+YouTube: https://www.youtube.com/watch?v=tjduXbZZEgI
diff --git a/include/asterisk/res_audiosocket.h b/include/asterisk/res_audiosocket.h
new file mode 100644 (file)
index 0000000..0357bcd
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2019, CyCore Systems, Inc
+ *
+ * Seán C McCord <scm@cycoresys.com
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*!
+ * \file
+ * \brief AudioSocket support functions
+ *
+ * \author Seán C McCord <scm@cycoresys.com>
+ *
+ */
+
+#ifndef _ASTERISK_RES_AUDIOSOCKET_H
+#define _ASTERISK_RES_AUDIOSOCKET_H
+
+#if defined(__cplusplus) || defined(c_plusplus)
+extern "C" {
+#endif
+
+#include <uuid/uuid.h>
+
+#include "asterisk/frame.h"
+#include "asterisk/uuid.h"
+
+/*!
+ * \brief Send the initial message to an AudioSocket server
+ *
+ * \param server The server address, including port.
+ * \param chan An optional channel which will be put into autoservice during
+ * the connection period.  If there is no channel to be autoserviced, pass NULL
+ * instead.
+ *
+ * \retval socket file descriptor for AudioSocket on success
+ * \retval -1 on error
+ */
+const int ast_audiosocket_connect(const char *server, struct ast_channel *chan);
+
+/*!
+ * \brief Send the initial message to an AudioSocket server
+ *
+ * \param svc The file descriptor of the network socket to the AudioSocket server.
+ * \param id The UUID to send to the AudioSocket server to uniquely identify this connection.
+ *
+ * \retval 0 on success
+ * \retval -1 on error
+ */
+const int ast_audiosocket_init(const int svc, const char *id);
+
+/*!
+ * \brief Send an Asterisk audio frame to an AudioSocket server
+ *
+ * \param svc The file descriptor of the network socket to the AudioSocket server.
+ * \param f The Asterisk audio frame to send.
+ *
+ * \retval 0 on success
+ * \retval -1 on error
+ */
+const int ast_audiosocket_send_frame(const int svc, const struct ast_frame *f);
+
+/*!
+ * \brief Receive an Asterisk frame from an AudioSocket server
+ *
+ * This returned object is a pointer to an Asterisk frame which must be
+ * manually freed by the caller.
+ *
+ * \param svc The file descriptor of the network socket to the AudioSocket server.
+ *
+ * \retval A \ref ast_frame on success
+ * \retval NULL on error
+ */
+struct ast_frame *ast_audiosocket_receive_frame(const int svc);
+
+#endif /* _ASTERISK_RES_AUDIOSOCKET_H */
index 81a902c..549883d 100644 (file)
@@ -2101,6 +2101,51 @@ static void external_media_rtp_udp(struct ast_ari_channels_external_media_args *
        ast_channel_unref(chan);
 }
 
+static void external_media_audiosocket_tcp(struct ast_ari_channels_external_media_args *args,
+       struct ast_variable *variables,
+       struct ast_ari_response *response)
+{
+       size_t endpoint_len;
+       char *endpoint;
+       struct ast_channel *chan;
+       struct varshead *vars;
+
+       endpoint_len = strlen("AudioSocket/") + strlen(args->external_host) + 1 + strlen(args->data) + 1;
+       endpoint = ast_alloca(endpoint_len);
+       /* The UUID is stored in the arbitrary data field */
+       snprintf(endpoint, endpoint_len, "AudioSocket/%s/%s", args->external_host, args->data);
+
+       chan = ari_channels_handle_originate_with_id(
+               endpoint,
+               NULL,
+               NULL,
+               0,
+               NULL,
+               args->app,
+               NULL,
+               NULL,
+               0,
+               variables,
+               args->channel_id,
+               NULL,
+               NULL,
+               args->format,
+               response);
+       ast_variables_destroy(variables);
+
+       if (!chan) {
+               return;
+       }
+
+       ast_channel_lock(chan);
+       vars = ast_channel_varshead(chan);
+       if (vars && !AST_LIST_EMPTY(vars)) {
+               ast_json_object_set(response->message, "channelvars", ast_json_channel_vars(vars));
+       }
+       ast_channel_unlock(chan);
+       ast_channel_unref(chan);
+}
+
 #include "asterisk/config.h"
 #include "asterisk/netsock2.h"
 
@@ -2161,6 +2206,8 @@ void ast_ari_channels_external_media(struct ast_variable *headers,
 
        if (strcasecmp(args->encapsulation, "rtp") == 0 && strcasecmp(args->transport, "udp") == 0) {
                external_media_rtp_udp(args, variables, response);
+       } else if (strcasecmp(args->encapsulation, "audiosocket") == 0 && strcasecmp(args->transport, "tcp") == 0) {
+               external_media_audiosocket_tcp(args, variables, response);
        } else {
                ast_ari_response_error(
                        response, 501, "Not Implemented",
index 49a3882..d06e30b 100644 (file)
@@ -844,6 +844,8 @@ struct ast_ari_channels_external_media_args {
        const char *format;
        /*! External media direction */
        const char *direction;
+       /*! An arbitrary data field */
+       const char *data;
 };
 /*!
  * \brief Body parsing function for /channels/externalMedia.
index f938e14..72e47f1 100644 (file)
@@ -2852,6 +2852,10 @@ int ast_ari_channels_external_media_parse_body(
        if (field) {
                args->direction = ast_json_string_get(field);
        }
+       field = ast_json_object_get(body, "data");
+       if (field) {
+               args->data = ast_json_string_get(field);
+       }
        return 0;
 }
 
@@ -2899,6 +2903,9 @@ static void ast_ari_channels_external_media_cb(
                if (strcmp(i->name, "direction") == 0) {
                        args.direction = (i->value);
                } else
+               if (strcmp(i->name, "data") == 0) {
+                       args.data = (i->value);
+               } else
                {}
        }
        args.variables = body;
diff --git a/res/res_audiosocket.c b/res/res_audiosocket.c
new file mode 100644 (file)
index 0000000..6dc64e7
--- /dev/null
@@ -0,0 +1,345 @@
+/*
+ * Asterisk -- An open source telephony toolkit.
+ *
+ * Copyright (C) 2019, CyCore Systems, Inc
+ *
+ * Seán C McCord <scm@cycoresys.com
+ *
+ * See http://www.asterisk.org for more information about
+ * the Asterisk project. Please do not directly contact
+ * any of the maintainers of this project for assistance;
+ * the project provides a web site, mailing lists and IRC
+ * channels for your use.
+ *
+ * This program is free software, distributed under the terms of
+ * the GNU General Public License Version 2. See the LICENSE file
+ * at the top of the source tree.
+ */
+
+/*! \file
+ *
+ * \brief AudioSocket support for Asterisk
+ *
+ * \author Seán C McCord <scm@cycoresys.com>
+ *
+ */
+
+/*** MODULEINFO
+       <support_level>extended</support_level>
+ ***/
+
+#include "asterisk.h"
+#include "errno.h"
+#include <uuid/uuid.h>
+
+#include "asterisk/file.h"
+#include "asterisk/res_audiosocket.h"
+#include "asterisk/channel.h"
+#include "asterisk/module.h"
+#include "asterisk/uuid.h"
+#include "asterisk/format_cache.h"
+
+#define        MODULE_DESCRIPTION      "AudioSocket support functions for Asterisk"
+
+#define MAX_CONNECT_TIMEOUT_MSEC 2000
+
+/*!
+ * \internal
+ * \brief Attempt to complete the audiosocket connection.
+ *
+ * \param server Url that we are trying to connect to.
+ * \param addr Address that host was resolved to.
+ * \param netsockfd File descriptor of socket.
+ *
+ * \retval 0 when connection is succesful.
+ * \retval 1 when there is an error.
+ */
+static int handle_audiosocket_connection(const char *server,
+       const struct ast_sockaddr addr, const int netsockfd)
+{
+       struct pollfd pfds[1];
+       int res, conresult;
+       socklen_t reslen;
+
+       reslen = sizeof(conresult);
+
+       pfds[0].fd = netsockfd;
+       pfds[0].events = POLLOUT;
+
+       while ((res = ast_poll(pfds, 1, MAX_CONNECT_TIMEOUT_MSEC)) != 1) {
+               if (errno != EINTR) {
+                       if (!res) {
+                               ast_log(LOG_WARNING, "AudioSocket connection to '%s' timed"
+                                       "out after MAX_CONNECT_TIMEOUT_MSEC (%d) milliseconds.\n",
+                                       server, MAX_CONNECT_TIMEOUT_MSEC);
+                       } else {
+                               ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", server,
+                                       strerror(errno));
+                       }
+
+                       return -1;
+               }
+       }
+
+       if (getsockopt(pfds[0].fd, SOL_SOCKET, SO_ERROR, &conresult, &reslen) < 0) {
+               ast_log(LOG_WARNING, "Connection to %s failed with error: %s\n",
+                       ast_sockaddr_stringify(&addr), strerror(errno));
+               return -1;
+       }
+
+       if (conresult) {
+               ast_log(LOG_WARNING, "Connecting to '%s' failed for url '%s': %s\n",
+                       ast_sockaddr_stringify(&addr), server, strerror(conresult));
+               return -1;
+       }
+
+       return 0;
+}
+
+const int ast_audiosocket_connect(const char *server, struct ast_channel *chan)
+{
+       int s = -1;
+       struct ast_sockaddr *addrs;
+       int num_addrs = 0, i = 0;
+
+       if (chan && ast_autoservice_start(chan) < 0) {
+               ast_log(LOG_WARNING, "Failed to start autoservice for channel "
+                       "%s\n", ast_channel_name(chan));
+               goto end;
+       }
+
+       if (ast_strlen_zero(server)) {
+               ast_log(LOG_ERROR, "No AudioSocket server provided\n");
+               goto end;
+       }
+
+       if (!(num_addrs = ast_sockaddr_resolve(&addrs, server, PARSE_PORT_REQUIRE,
+               AST_AF_UNSPEC))) {
+               ast_log(LOG_ERROR, "Failed to resolve AudioSocket service using %s - "
+                       "requires a valid hostname and port\n", server);
+               goto end;
+       }
+
+       /* Connect to AudioSocket service */
+       for (i = 0; i < num_addrs; i++) {
+
+               if (!ast_sockaddr_port(&addrs[i])) {
+                       /* If there's no port, other addresses should have the
+                        * same problem. Stop here.
+                        */
+                       ast_log(LOG_ERROR, "No port provided for %s\n",
+                               ast_sockaddr_stringify(&addrs[i]));
+                       s = -1;
+                       goto end;
+               }
+
+               if ((s = ast_socket_nonblock(addrs[i].ss.ss_family, SOCK_STREAM,
+                       IPPROTO_TCP)) < 0) {
+                       ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
+                       continue;
+               }
+
+               if (ast_connect(s, &addrs[i]) && errno == EINPROGRESS) {
+
+                       if (handle_audiosocket_connection(server, addrs[i], s)) {
+                               close(s);
+                               continue;
+                       }
+
+               } else {
+                       ast_log(LOG_ERROR, "Connection to %s failed with unexpected error: %s\n",
+                               ast_sockaddr_stringify(&addrs[i]), strerror(errno));
+                       close(s);
+                       s = -1;
+               }
+
+               break;
+       }
+
+end:
+       if (addrs) {
+               ast_free(addrs);
+       }
+
+       if (chan && ast_autoservice_stop(chan) < 0) {
+               ast_log(LOG_WARNING, "Failed to stop autoservice for channel %s\n",
+               ast_channel_name(chan));
+               close(s);
+               return -1;
+       }
+
+       if (i == num_addrs) {
+               ast_log(LOG_ERROR, "Failed to connect to AudioSocket service\n");
+               close(s);
+               return -1;
+       }
+
+       return s;
+}
+
+const int ast_audiosocket_init(const int svc, const char *id)
+{
+       uuid_t uu;
+       int ret = 0;
+       uint8_t buf[3 + 16];
+
+       if (ast_strlen_zero(id)) {
+               ast_log(LOG_ERROR, "No UUID for AudioSocket\n");
+               return -1;
+       }
+
+       if (uuid_parse(id, uu)) {
+               ast_log(LOG_ERROR, "Failed to parse UUID '%s'\n", id);
+               return -1;
+       }
+
+       buf[0] = 0x01;
+       buf[1] = 0x00;
+       buf[2] = 0x10;
+       memcpy(buf + 3, uu, 16);
+
+       if (write(svc, buf, 3 + 16) != 3 + 16) {
+               ast_log(LOG_WARNING, "Failed to write data to AudioSocket\n");
+               ret = -1;
+       }
+
+       return ret;
+}
+
+const int ast_audiosocket_send_frame(const int svc, const struct ast_frame *f)
+{
+       int ret = 0;
+       uint8_t kind = 0x10;    /* always 16-bit, 8kHz signed linear mono, for now */
+       uint8_t *p;
+       uint8_t buf[3 + f->datalen];
+
+       p = buf;
+
+       *(p++) = kind;
+       *(p++) = f->datalen >> 8;
+       *(p++) = f->datalen & 0xff;
+       memcpy(p, f->data.ptr, f->datalen);
+
+       if (write(svc, buf, 3 + f->datalen) != 3 + f->datalen) {
+               ast_log(LOG_WARNING, "Failed to write data to AudioSocket\n");
+               ret = -1;
+       }
+
+       return ret;
+}
+
+struct ast_frame *ast_audiosocket_receive_frame(const int svc)
+{
+
+       int i = 0, n = 0, ret = 0, not_audio = 0;
+       struct ast_frame f = {
+               .frametype = AST_FRAME_VOICE,
+               .subclass.format = ast_format_slin,
+               .src = "AudioSocket",
+               .mallocd = AST_MALLOCD_DATA,
+       };
+       uint8_t kind;
+       uint8_t len_high;
+       uint8_t len_low;
+       uint16_t len = 0;
+       uint8_t *data;
+
+       n = read(svc, &kind, 1);
+       if (n < 0 && errno == EAGAIN) {
+               return &ast_null_frame;
+       }
+       if (n == 0) {
+               return &ast_null_frame;
+       }
+       if (n != 1) {
+               ast_log(LOG_WARNING, "Failed to read type header from AudioSocket\n");
+               return NULL;
+       }
+       if (kind == 0x00) {
+               /* AudioSocket ended by remote */
+               return NULL;
+       }
+       if (kind != 0x10) {
+               /* read but ignore non-audio message */
+               ast_log(LOG_WARNING, "Received non-audio AudioSocket message\n");
+               not_audio = 1;
+       }
+
+       n = read(svc, &len_high, 1);
+       if (n != 1) {
+               ast_log(LOG_WARNING, "Failed to read data length from AudioSocket\n");
+               return NULL;
+       }
+       len += len_high * 256;
+       n = read(svc, &len_low, 1);
+       if (n != 1) {
+               ast_log(LOG_WARNING, "Failed to read data length from AudioSocket\n");
+               return NULL;
+       }
+       len += len_low;
+
+       if (len < 1) {
+               return &ast_null_frame;
+       }
+
+       data = ast_malloc(len);
+       if (!data) {
+               ast_log(LOG_ERROR, "Failed to allocate for data from AudioSocket\n");
+               return NULL;
+       }
+
+       ret = 0;
+       n = 0;
+       i = 0;
+       while (i < len) {
+               n = read(svc, data + i, len - i);
+               if (n < 0) {
+                       ast_log(LOG_ERROR, "Failed to read data from AudioSocket\n");
+                       ret = n;
+                       break;
+               }
+               if (n == 0) {
+                       ast_log(LOG_ERROR, "Insufficient data read from AudioSocket\n");
+                       ret = -1;
+                       break;
+               }
+               i += n;
+       }
+
+       if (ret != 0) {
+               ast_free(data);
+               return NULL;
+       }
+
+       if (not_audio) {
+               ast_free(data);
+               return &ast_null_frame;
+       }
+
+       f.data.ptr = data;
+       f.datalen = len;
+       f.samples = len / 2;
+
+       /* The frame steals data, so it doesn't need to be freed here */
+       return ast_frisolate(&f);
+}
+
+static int load_module(void)
+{
+       ast_verb(1, "Loading AudioSocket Support module\n");
+       return AST_MODULE_LOAD_SUCCESS;
+}
+
+static int unload_module(void)
+{
+       ast_verb(1, "Unloading AudioSocket Support module\n");
+       return AST_MODULE_LOAD_SUCCESS;
+}
+
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER,
+       "AudioSocket support",
+       .support_level = AST_MODULE_SUPPORT_EXTENDED,
+       .load = load_module,
+       .unload = unload_module,
+       .load_pri = AST_MODPRI_CHANNEL_DEPEND,
+);
diff --git a/res/res_audiosocket.exports.in b/res/res_audiosocket.exports.in
new file mode 100644 (file)
index 0000000..c89c9a9
--- /dev/null
@@ -0,0 +1,4 @@
+{
+       global:
+               LINKER_SYMBOL_PREFIX*;
+};
index 94afb27..a20e9f2 100644 (file)
                                                        "allowableValues": {
                                                                "valueType": "LIST",
                                                                "values": [
-                                                                       "rtp"
+                                                                       "rtp",
+                                                                       "audiosocket"
                                                                ]
                                                        }
                                                },
                                                        "allowableValues": {
                                                                "valueType": "LIST",
                                                                "values": [
-                                                                       "udp"
+                                                                       "udp",
+                                                                       "tcp"
                                                                ]
                                                        }
                                                },
                                                                        "both"
                                                                ]
                                                        }
+                                               },
+                                               {
+                                                       "name": "data",
+                                                       "description": "An arbitrary data field",
+                                                       "paramType": "query",
+                                                       "required": false,
+                                                       "allowMultiple": false,
+                                                       "dataType": "string"
                                                }
                                        ],
                                        "errorResponses": [