Merge "Core: Add support for systemd socket activation."
authorJenkins2 <jenkins2@gerrit.asterisk.org>
Wed, 26 Jul 2017 14:17:40 +0000 (09:17 -0500)
committerGerrit Code Review <gerrit2@gerrit.digium.api>
Wed, 26 Jul 2017 14:17:40 +0000 (09:17 -0500)
114 files changed:
CHANGES
UPGRADE-15.txt [new file with mode: 0644]
UPGRADE.txt
apps/app_confbridge.c
apps/app_meetme.c
apps/app_playback.c
apps/app_queue.c
apps/app_stream_echo.c
apps/app_voicemail.c
apps/confbridge/conf_config_parser.c
apps/confbridge/include/confbridge.h
bridges/bridge_native_rtp.c
bridges/bridge_softmix.c
bridges/bridge_softmix/include/bridge_softmix_internal.h
channels/chan_dahdi.c
channels/chan_iax2.c
channels/chan_pjsip.c
channels/chan_sip.c
channels/pjsip/cli_commands.c
channels/pjsip/dialplan_functions.c
channels/pjsip/include/chan_pjsip.h
configs/basic-pbx/modules.conf
configs/samples/cdr.conf.sample
configs/samples/confbridge.conf.sample
configs/samples/config_test.conf.sample
configs/samples/musiconhold.conf.sample
configs/samples/pjsip.conf.sample
configs/samples/voicemail.conf.sample
configure
configure.ac
contrib/ast-db-manage/config/versions/164abbd708c_add_auto_info_to_endpoint_dtmf_mode.py [new file with mode: 0644]
contrib/ast-db-manage/config/versions/39959b9c2566_pjsip_stream_maximum.py [new file with mode: 0644]
contrib/ast-db-manage/config/versions/d7983954dd96_add_ps_endpoints_notify_early_inuse_.py [new file with mode: 0644]
contrib/scripts/install_prereq
include/asterisk/_private.h
include/asterisk/bridge.h
include/asterisk/channel.h
include/asterisk/config.h
include/asterisk/config_options.h
include/asterisk/core_local.h
include/asterisk/data.h [deleted file]
include/asterisk/format.h
include/asterisk/format_cache.h
include/asterisk/frame.h
include/asterisk/indications.h
include/asterisk/manager.h
include/asterisk/res_pjsip.h
include/asterisk/res_pjsip_presence_xml.h
include/asterisk/res_pjsip_session.h
include/asterisk/rtp_engine.h
include/asterisk/sdp.h
include/asterisk/sdp_options.h
include/asterisk/sdp_state.h
include/asterisk/stream.h
main/app.c
main/asterisk.c
main/bridge.c
main/bridge_channel.c
main/cdr.c
main/channel.c
main/channel_internal_api.c
main/codec_builtin.c
main/config.c
main/config_options.c
main/core_local.c
main/core_unreal.c
main/data.c [deleted file]
main/format_cache.c
main/http.c
main/indications.c
main/json.c
main/pbx.c
main/pbx_builtins.c
main/rtp_engine.c
main/say.c
main/sdp.c
main/sdp_options.c
main/sdp_private.h
main/sdp_state.c
main/stream.c
res/res_agi.c
res/res_corosync.c
res/res_musiconhold.c
res/res_odbc.c
res/res_pjsip.c
res/res_pjsip.exports.in
res/res_pjsip/pjsip_configuration.c
res/res_pjsip/pjsip_distributor.c
res/res_pjsip/presence_xml.c
res/res_pjsip_dialog_info_body_generator.c
res/res_pjsip_mwi.c
res/res_pjsip_pidf_body_generator.c
res/res_pjsip_pidf_eyebeam_body_supplement.c
res/res_pjsip_sdp_rtp.c
res/res_pjsip_session.c
res/res_pjsip_session.exports.in
res/res_pjsip_t38.c
res/res_pjsip_xpidf_body_generator.c
res/res_rtp_asterisk.c
res/res_sdp_translator_pjmedia.c
res/res_stasis.c
res/res_stasis_device_state.c
res/res_stasis_snoop.c
rest-api-templates/make_ari_stubs.py
rest-api/resources.json
sounds/Makefile
sounds/sounds.xml
tests/test_config.c
tests/test_sdp.c
third-party/configure.m4
third-party/pjproject/Makefile.rules
third-party/pjproject/configure.m4
third-party/pjproject/patches/0070-Set-PJSIP_INV_SUPPORT_UPDATE-correctly-in-pjsip_inv_.patch [new file with mode: 0644]
third-party/pjproject/patches/config_site.h

diff --git a/CHANGES b/CHANGES
index 9bfa506..5daa816 100644 (file)
--- a/CHANGES
+++ b/CHANGES
@@ -18,9 +18,35 @@ app_queue
    been defined.
 
 ------------------------------------------------------------------------------
+--- Functionality changes from Asterisk 14.6.0 to Asterisk 14.7.0 ------------
+------------------------------------------------------------------------------
+
+res_musiconhold
+------------------
+ * By default, when res_musiconhold reloads or unloads, it sends a HUP signal
+   to custom applications (and all descendants), waits 100ms, then sends a
+   TERM signal, waits 100ms, then finally sends a KILL signal.  An application
+   which is interacting with an external device and/or spawns children of its
+   own may not be able to exit cleanly in the default times, expecially if sent
+   a KILL signal, or if it's children are getting signals directly from
+   res_musiconhoild.  To allow extra time, the 'kill_escalation_delay'
+   class option can be used to set the number of milliseconds res_musiconhold
+   waits before escalating kill signals, with the default being the current
+   100ms.  To control to whom the signals are sent, the "kill_method"
+   class option can be set to "process_group" (the default, existing behavior),
+   which sends signals to the application and its descendants directly, or
+   "process" which sends signals only to the application itself.
+
+------------------------------------------------------------------------------
 --- Functionality changes from Asterisk 14.5.0 to Asterisk 14.6.0 ------------
 ------------------------------------------------------------------------------
 
+app_voicemail
+------------------
+ * A new global option "imap_poll_logout" was added to specify whether need to
+   disconnect from the IMAP server after polling of mailboxes.
+   Default: no
+
 res_pjsip
 ------------------
  * A new endpoint option "refer_blind_progress" was added to turn off notifying
@@ -30,6 +56,14 @@ res_pjsip
    Some SIP phones like Mitel/Aastra or Snom keep the line busy until
    receive "200 OK".
 
+ * A new endpoint option "notify_early_inuse_ringing" was added to control
+   whether to notify dialog-info state 'early' or 'confirmed' on Ringing
+   when already INUSE.
+
+ * The endpoint option 'dtmf_mode' has a new option 'auto_dtmf' added. This
+   mode works similar to 'auto' except uses DTMF INFO as fallback instead of
+   INBAND.
+
 res_agi
 ------------------
  * The EAGI() application will now look for a dialplan variable named
@@ -49,6 +83,14 @@ chan_pjsip
    from the SDP, unless the remote side sends a different codec and we will
    switch to match.
 
+Build System
+------------------
+ * Added a new PJPROJECT_CONFIGURE_OPTS environment variable which can be used
+   to pass arbitrary options to the bundled pjproject configure.
+
+ * Automatically set the bundled pjproject configure --host and --build
+   options to match those supplied for the asterisk configure.
+
 ------------------------------------------------------------------------------
 --- Functionality changes from Asterisk 14.4.0 to Asterisk 14.5.0 ------------
 ------------------------------------------------------------------------------
diff --git a/UPGRADE-15.txt b/UPGRADE-15.txt
new file mode 100644 (file)
index 0000000..4ebe400
--- /dev/null
@@ -0,0 +1,85 @@
+===========================================================
+===
+=== Information for upgrading between Asterisk versions
+===
+=== These files document all the changes that MUST be taken
+=== into account when upgrading between the Asterisk
+=== versions listed below. These changes may require that
+=== you modify your configuration files, dialplan or (in
+=== some cases) source code if you have your own Asterisk
+=== modules or patches. These files also include advance
+=== notice of any functionality that has been marked as
+=== 'deprecated' and may be removed in a future release,
+=== along with the suggested replacement functionality.
+===
+=== UPGRADE-1.2.txt -- Upgrade info for 1.0 to 1.2
+=== UPGRADE-1.4.txt -- Upgrade info for 1.2 to 1.4
+=== UPGRADE-1.6.txt -- Upgrade info for 1.4 to 1.6
+=== UPGRADE-1.8.txt -- Upgrade info for 1.6 to 1.8
+=== UPGRADE-10.txt  -- Upgrade info for 1.8 to 10
+=== UPGRADE-11.txt  -- Upgrade info for 10 to 11
+=== UPGRADE-12.txt  -- Upgrade info for 11 to 12
+=== UPGRADE-13.txt  -- Upgrade info for 12 to 13
+=== UPGRADE-14.txt  -- Upgrade info for 13 to 14
+=== UPGRADE-15.txt  -- Upgrade info for 14 to 15
+===========================================================
+
+New in 15.0.0:
+
+Core:
+ - The 'Data Retrieval API' has been removed. This API was not actively
+   maintained, was not added to new modules (such as res_pjsip), and there
+   exist better alternatives to acquire the same information, such as the
+   ARI. As a result, the 'DataGet' AMI action as well as the 'data get'
+   CLI command have been removed.
+
+From 14.6.0 to 14.7.0:
+
+Core:
+ - ast_app_parse_timelen now returns an error if it encounters extra characters
+   at the end of the string to be parsed.
+
+From 14.4.0 to 14.5.0:
+
+Core:
+ - Support for embedded modules has been removed.  This has not worked in
+   many years.  LOADABLE_MODULES menuselect option is also removed as
+   loadable module support is now always enabled.
+
+From 14.3.0 to 14.4.0:
+
+res_rtp_asterisk:
+ - The RTP layer of Asterisk now has support for RFC 5761: "Multiplexing RTP
+   Data and Control Packets on a Single Port." For the PJSIP channel driver,
+   chan_pjsip, you can set "rtcp_mux = yes" on a PJSIP endpoint in pjsip.conf
+   to enable the feature. For chan_sip you can set "rtcp_mux = yes" either
+   globally or on a per-peer basis in sip.conf.
+
+New in 14.0.0
+
+ARI:
+ - The policy for when to send "Dial" events has changed. Previously, "Dial"
+   events were sent on the calling channel's topic. However, starting in Asterisk
+   14, if there is no calling channel on which to send the event, the event is
+   instead sent on the called channel's topic. Note that for the ARI channels
+   resource's dial operation, this means that the "Dial" events will always be
+   sent on the called channel's topic.
+
+Queue:
+ - When reloading the members of a queue, the members added dynamically (i.e.
+   added via the CLI command "queue add" or the AMI action "QueueAdd") now have
+   their ringinuse value updated to the value of the queue. Previously, the
+   ringinuse value for dynamic members was not updated on reload.
+
+Queue log:
+ - New RINGCANCELED event is logged when the caller hangs up while ringing.
+   The data1 field contains number of miliseconds since start of ringing.
+
+Channel Drivers:
+
+chan_dahdi:
+ - Support for specifying a DAHDI channel using a path under /dev/dahdi
+   ("by name") has been removed. It was never used. Instead you should
+   use kernel-level channel number allocation using span assignments.
+   See the documentation of dahdi-linux and dahdi-tools.
+
index 62bb801..87eabde 100644 (file)
 === UPGRADE-12.txt  -- Upgrade info for 11 to 12
 === UPGRADE-13.txt  -- Upgrade info for 12 to 13
 === UPGRADE-14.txt  -- Upgrade info for 13 to 14
+=== UPGRADE-15.txt  -- Upgrade info for 14 to 15
 ===========================================================
-
-From 14.4.0 to 14.5.0:
-
-Core:
- - Support for embedded modules has been removed.  This has not worked in
-   many years.  LOADABLE_MODULES menuselect option is also removed as
-   loadable module support is now always enabled.
-
-From 14.3.0 to 14.4.0:
-
-res_rtp_asterisk:
- - The RTP layer of Asterisk now has support for RFC 5761: "Multiplexing RTP
-   Data and Control Packets on a Single Port." For the PJSIP channel driver,
-   chan_pjsip, you can set "rtcp_mux = yes" on a PJSIP endpoint in pjsip.conf
-   to enable the feature. For chan_sip you can set "rtcp_mux = yes" either
-   globally or on a per-peer basis in sip.conf.
-
-New in 14.0.0
-
-ARI:
- - The policy for when to send "Dial" events has changed. Previously, "Dial"
-   events were sent on the calling channel's topic. However, starting in Asterisk
-   14, if there is no calling channel on which to send the event, the event is
-   instead sent on the called channel's topic. Note that for the ARI channels
-   resource's dial operation, this means that the "Dial" events will always be
-   sent on the called channel's topic.
-
-Queue:
- - When reloading the members of a queue, the members added dynamically (i.e.
-   added via the CLI command "queue add" or the AMI action "QueueAdd") now have
-   their ringinuse value updated to the value of the queue. Previously, the
-   ringinuse value for dynamic members was not updated on reload.
-
-Queue log:
- - New RINGCANCELED event is logged when the caller hangs up while ringing.
-   The data1 field contains number of miliseconds since start of ringing.
-
-Channel Drivers:
-
-chan_dahdi:
- - Support for specifying a DAHDI channel using a path under /dev/dahdi
-   ("by name") has been removed. It was never used. Instead you should
-   use kernel-level channel number allocation using span assignments.
-   See the documentation of dahdi-linux and dahdi-tools.
-
index 0f846b6..b2d612d 100644 (file)
@@ -1485,6 +1485,7 @@ static struct confbridge_conference *join_conference_bridge(const char *conferen
                        ast_bridge_set_talker_src_video_mode(conference->bridge);
                } else if (ast_test_flag(&conference->b_profile, BRIDGE_OPT_VIDEO_SRC_SFU)) {
                        ast_bridge_set_sfu_video_mode(conference->bridge);
+                       ast_bridge_set_video_update_discard(conference->bridge, conference->b_profile.video_update_discard);
                }
 
                /* Link it into the conference bridges container */
@@ -2145,6 +2146,7 @@ static int conf_rec_name(struct confbridge_user *user, const char *conf_name)
        }
 
        if (res == -1) {
+               ast_filedelete(user->name_rec_location, NULL);
                user->name_rec_location[0] = '\0';
                return -1;
        }
@@ -2236,6 +2238,7 @@ static int confbridge_exec(struct ast_channel *chan, const char *data)
 {
        int res = 0, volume_adjustments[2];
        int quiet = 0;
+       int async_delete_task_pushed = 0;
        char *parse;
        const char *b_profile_name = NULL;
        const char *u_profile_name = NULL;
@@ -2481,6 +2484,7 @@ static int confbridge_exec(struct ast_channel *chan, const char *data)
                async_play_sound_file(conference,
                        conf_get_sound(CONF_SOUND_HAS_LEFT, conference->b_profile.sounds), NULL);
                async_delete_name_rec(conference, user.name_rec_location);
+               async_delete_task_pushed = 1;
        }
 
        /* play the leave sound */
@@ -2509,6 +2513,9 @@ static int confbridge_exec(struct ast_channel *chan, const char *data)
        }
 
 confbridge_cleanup:
+       if (!async_delete_task_pushed && !ast_strlen_zero(user.name_rec_location)) {
+               ast_filedelete(user.name_rec_location, NULL);
+       }
        ast_bridge_features_cleanup(&user.features);
        conf_bridge_profile_destroy(&user.b_profile);
        return res;
index 71ca9dc..d98c418 100644 (file)
@@ -69,7 +69,6 @@
 #include "asterisk/dial.h"
 #include "asterisk/causes.h"
 #include "asterisk/paths.h"
-#include "asterisk/data.h"
 #include "asterisk/test.h"
 #include "asterisk/stasis.h"
 #include "asterisk/stasis_channels.h"
@@ -8005,186 +8004,6 @@ static int load_config(int reload)
        return sla_load_config(reload);
 }
 
-#define MEETME_DATA_EXPORT(MEMBER)                                     \
-       MEMBER(ast_conference, confno, AST_DATA_STRING)                 \
-       MEMBER(ast_conference, dahdiconf, AST_DATA_INTEGER)             \
-       MEMBER(ast_conference, users, AST_DATA_INTEGER)                 \
-       MEMBER(ast_conference, markedusers, AST_DATA_INTEGER)           \
-       MEMBER(ast_conference, maxusers, AST_DATA_INTEGER)              \
-       MEMBER(ast_conference, isdynamic, AST_DATA_BOOLEAN)             \
-       MEMBER(ast_conference, locked, AST_DATA_BOOLEAN)                \
-       MEMBER(ast_conference, recordingfilename, AST_DATA_STRING)      \
-       MEMBER(ast_conference, recordingformat, AST_DATA_STRING)        \
-       MEMBER(ast_conference, pin, AST_DATA_PASSWORD)                  \
-       MEMBER(ast_conference, pinadmin, AST_DATA_PASSWORD)             \
-       MEMBER(ast_conference, start, AST_DATA_TIMESTAMP)               \
-       MEMBER(ast_conference, endtime, AST_DATA_TIMESTAMP)
-
-AST_DATA_STRUCTURE(ast_conference, MEETME_DATA_EXPORT);
-
-#define MEETME_USER_DATA_EXPORT(MEMBER)                                        \
-       MEMBER(ast_conf_user, user_no, AST_DATA_INTEGER)                \
-       MEMBER(ast_conf_user, talking, AST_DATA_BOOLEAN)                \
-       MEMBER(ast_conf_user, dahdichannel, AST_DATA_BOOLEAN)           \
-       MEMBER(ast_conf_user, jointime, AST_DATA_TIMESTAMP)             \
-       MEMBER(ast_conf_user, kicktime, AST_DATA_TIMESTAMP)             \
-       MEMBER(ast_conf_user, timelimit, AST_DATA_MILLISECONDS)         \
-       MEMBER(ast_conf_user, play_warning, AST_DATA_MILLISECONDS)      \
-       MEMBER(ast_conf_user, warning_freq, AST_DATA_MILLISECONDS)
-
-AST_DATA_STRUCTURE(ast_conf_user, MEETME_USER_DATA_EXPORT);
-
-static int user_add_provider_cb(void *obj, void *arg, int flags)
-{
-       struct ast_data *data_meetme_user;
-       struct ast_data *data_meetme_user_channel;
-       struct ast_data *data_meetme_user_volume;
-
-       struct ast_conf_user *user = obj;
-       struct ast_data *data_meetme_users = arg;
-
-       data_meetme_user = ast_data_add_node(data_meetme_users, "user");
-       if (!data_meetme_user) {
-               return 0;
-       }
-       /* user structure */
-       ast_data_add_structure(ast_conf_user, data_meetme_user, user);
-
-       /* user's channel */
-       data_meetme_user_channel = ast_data_add_node(data_meetme_user, "channel");
-       if (!data_meetme_user_channel) {
-               return 0;
-       }
-
-       ast_channel_data_add_structure(data_meetme_user_channel, user->chan, 1);
-
-       /* volume structure */
-       data_meetme_user_volume = ast_data_add_node(data_meetme_user, "listen-volume");
-       if (!data_meetme_user_volume) {
-               return 0;
-       }
-       ast_data_add_int(data_meetme_user_volume, "desired", user->listen.desired);
-       ast_data_add_int(data_meetme_user_volume, "actual", user->listen.actual);
-
-       data_meetme_user_volume = ast_data_add_node(data_meetme_user, "talk-volume");
-       if (!data_meetme_user_volume) {
-               return 0;
-       }
-       ast_data_add_int(data_meetme_user_volume, "desired", user->talk.desired);
-       ast_data_add_int(data_meetme_user_volume, "actual", user->talk.actual);
-
-       return 0;
-}
-
-/*!
- * \internal
- * \brief Implements the meetme data provider.
- */
-static int meetme_data_provider_get(const struct ast_data_search *search,
-       struct ast_data *data_root)
-{
-       struct ast_conference *cnf;
-       struct ast_data *data_meetme, *data_meetme_users;
-
-       AST_LIST_LOCK(&confs);
-       AST_LIST_TRAVERSE(&confs, cnf, list) {
-               data_meetme = ast_data_add_node(data_root, "meetme");
-               if (!data_meetme) {
-                       continue;
-               }
-
-               ast_data_add_structure(ast_conference, data_meetme, cnf);
-
-               if (ao2_container_count(cnf->usercontainer)) {
-                       data_meetme_users = ast_data_add_node(data_meetme, "users");
-                       if (!data_meetme_users) {
-                               ast_data_remove_node(data_root, data_meetme);
-                               continue;
-                       }
-
-                       ao2_callback(cnf->usercontainer, OBJ_NODATA, user_add_provider_cb, data_meetme_users); 
-               }
-
-               if (!ast_data_search_match(search, data_meetme)) {
-                       ast_data_remove_node(data_root, data_meetme);
-               }
-       }
-       AST_LIST_UNLOCK(&confs);
-
-       return 0;
-}
-
-static const struct ast_data_handler meetme_data_provider = {
-       .version = AST_DATA_HANDLER_VERSION,
-       .get = meetme_data_provider_get
-};
-
-static const struct ast_data_entry meetme_data_providers[] = {
-       AST_DATA_ENTRY("asterisk/application/meetme/list", &meetme_data_provider),
-};
-
-#ifdef TEST_FRAMEWORK
-AST_TEST_DEFINE(test_meetme_data_provider)
-{
-       struct ast_channel *chan;
-       struct ast_conference *cnf;
-       struct ast_data *node;
-       struct ast_data_query query = {
-               .path = "/asterisk/application/meetme/list",
-               .search = "list/meetme/confno=9898"
-       };
-
-       switch (cmd) {
-       case TEST_INIT:
-               info->name = "meetme_get_data_test";
-               info->category = "/main/data/app_meetme/list/";
-               info->summary = "Meetme data provider unit test";
-               info->description =
-                       "Tests whether the Meetme data provider implementation works as expected.";
-               return AST_TEST_NOT_RUN;
-       case TEST_EXECUTE:
-               break;
-       }
-
-       chan = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, "MeetMeTest");
-       if (!chan) {
-               ast_test_status_update(test, "Channel allocation failed\n");
-               return AST_TEST_FAIL;
-       }
-
-       ast_channel_unlock(chan);
-
-       cnf = build_conf("9898", "", "1234", 1, 1, 1, chan, test);
-       if (!cnf) {
-               ast_test_status_update(test, "Build of test conference 9898 failed\n");
-               ast_hangup(chan);
-               return AST_TEST_FAIL;
-       }
-
-       node = ast_data_get(&query);
-       if (!node) {
-               ast_test_status_update(test, "Data query for test conference 9898 failed\n");
-               dispose_conf(cnf);
-               ast_hangup(chan);
-               return AST_TEST_FAIL;
-       }
-
-       if (strcmp(ast_data_retrieve_string(node, "meetme/confno"), "9898")) {
-               ast_test_status_update(test, "Query returned the wrong conference\n");
-               dispose_conf(cnf);
-               ast_hangup(chan);
-               ast_data_free(node);
-               return AST_TEST_FAIL;
-       }
-
-       ast_data_free(node);
-       dispose_conf(cnf);
-       ast_hangup(chan);
-
-       return AST_TEST_PASS;
-}
-#endif
-
 static int unload_module(void)
 {
        int res = 0;
@@ -8201,11 +8020,6 @@ static int unload_module(void)
        res |= ast_unregister_application(slastation_app);
        res |= ast_unregister_application(slatrunk_app);
 
-#ifdef TEST_FRAMEWORK
-       AST_TEST_UNREGISTER(test_meetme_data_provider);
-#endif
-       ast_data_unregister(NULL);
-
        ast_devstate_prov_del("Meetme");
        ast_devstate_prov_del("SLA");
        
@@ -8249,11 +8063,6 @@ static int load_module(void)
        res |= ast_register_application_xml(slastation_app, sla_station_exec);
        res |= ast_register_application_xml(slatrunk_app, sla_trunk_exec);
 
-#ifdef TEST_FRAMEWORK
-       AST_TEST_REGISTER(test_meetme_data_provider);
-#endif
-       ast_data_register_multiple(meetme_data_providers, ARRAY_LEN(meetme_data_providers));
-
        res |= ast_devstate_prov_add("Meetme", meetmestate);
        res |= ast_devstate_prov_add("SLA", sla_state);
 
index 35900e8..7c895e3 100644 (file)
@@ -322,7 +322,7 @@ static int say_date_generic(struct ast_channel *chan, time_t t,
        if (format == NULL)
                format = "";
 
-       ast_localtime(&when, &tm, NULL);
+       ast_localtime(&when, &tm, timezonename);
        snprintf(buf, sizeof(buf), "%s:%s:%04d%02d%02d%02d%02d.%02d-%d-%3d",
                prefix,
                format,
index f158a4c..762119e 100644 (file)
@@ -99,7 +99,6 @@
 #include "asterisk/taskprocessor.h"
 #include "asterisk/aoc.h"
 #include "asterisk/callerid.h"
-#include "asterisk/data.h"
 #include "asterisk/term.h"
 #include "asterisk/dial.h"
 #include "asterisk/stasis_channels.h"
                        <ref type="function">QUEUE_MEMBER_PENALTY</ref>
                </see-also>
        </function>
-       <manager name="Queues" language="en_US">
-               <synopsis>
-                       Queues.
-               </synopsis>
-               <syntax>
-               </syntax>
-               <description>
-                       <para>Show queues information.</para>
-               </description>
-       </manager>
        <manager name="QueueStatus" language="en_US">
                <synopsis>
                        Show queue status.
                        <para>Reset the statistics for a queue.</para>
                </description>
        </manager>
+       <manager name="QueueChangePriorityCaller" language="en_US">
+               <synopsis>
+                       Change priority of a caller on queue.
+               </synopsis>
+               <syntax>
+                       <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
+                       <parameter name="Queue" required="true">
+                               <para>The name of the queue to take action on.</para>
+                       </parameter>
+                       <parameter name="Caller" required="true">
+                               <para>The caller (channel) to change priority on queue.</para>
+                       </parameter>
+
+                       <parameter name="Priority" required="true">
+                               <para>Priority value for change for caller on queue.</para>
+                       </parameter>
+               </syntax>
+               <description>
+               </description>
+       </manager>
 
        <managerEvent language="en_US" name="QueueMemberStatus">
                <managerEventInstance class="EVENT_FLAG_AGENT">
@@ -1408,6 +1417,7 @@ static const struct autopause {
 #define        RES_OUTOFMEMORY (-2)            /*!< Out of memory */
 #define        RES_NOSUCHQUEUE (-3)            /*!< No such queue */
 #define RES_NOT_DYNAMIC (-4)           /*!< Member is not dynamic */
+#define RES_NOT_CALLER  (-5)           /*!< Caller not found */
 
 static char *app = "Queue";
 
@@ -7286,6 +7296,39 @@ static int add_to_queue(const char *queuename, const char *interface, const char
        return res;
 }
 
+
+/*! \brief Change priority caller into a queue
+ * \retval RES_NOSUCHQUEUE queue does not exist
+ * \retval RES_OKAY change priority
+ * \retval RES_NOT_CALLER queue exists but no caller
+*/
+static int change_priority_caller_on_queue(const char *queuename, const char *caller, int priority)
+{
+       struct call_queue *q;
+       struct queue_ent *qe;
+       int res = RES_NOSUCHQUEUE;
+
+       /*! \note Ensure the appropriate realtime queue is loaded.  Note that this
+        * short-circuits if the queue is already in memory. */
+       if (!(q = find_load_queue_rt_friendly(queuename))) {
+               return res;
+       }
+
+       ao2_lock(q);
+       res = RES_NOT_CALLER;
+       for (qe = q->head; qe; qe = qe->next) {
+               if (strcmp(ast_channel_name(qe->chan), caller) == 0) {
+                       ast_debug(1, "%s Caller new prioriry %d in queue %s\n",
+                                    caller, priority, queuename);
+                       qe->prio = priority;
+                       res = RES_OKAY;
+               }
+       }
+       ao2_unlock(q);
+       return res;
+}
+
+
 static int publish_queue_member_pause(struct call_queue *q, struct member *member, const char *reason)
 {
        struct ast_json *json_blob = queue_member_blob_create(q, member);
@@ -8301,6 +8344,9 @@ stop:
                        } else if (qcontinue) {
                                reason = QUEUE_CONTINUE;
                                res = 0;
+                       } else if (reason == QUEUE_LEAVEEMPTY) {
+                               /* Return back to dialplan, don't hang up */
+                               res = 0;
                        }
                } else if (qe.valid_digits) {
                        ast_queue_log(args.queuename, ast_channel_uniqueid(chan), "NONE", "EXITWITHKEY",
@@ -9728,19 +9774,6 @@ static char *queue_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a
        return __queues_show(NULL, a->fd, a->argc, a->argv);
 }
 
-/*!\brief callback to display queues status in manager
-   \addtogroup Group_AMI
- */
-static int manager_queues_show(struct mansession *s, const struct message *m)
-{
-       static const char * const a[] = { "queue", "show" };
-
-       __queues_show(s, -1, 2, a);
-       astman_append(s, "\r\n\r\n");   /* Properly terminate Manager output */
-
-       return RESULT_SUCCESS;
-}
-
 static int manager_queue_rule_show(struct mansession *s, const struct message *m)
 {
        const char *rule = astman_get_header(m, "Rule");
@@ -9949,6 +9982,7 @@ static int manager_queues_status(struct mansession *s, const struct message *m)
                                        "ConnectedLineNum: %s\r\n"
                                        "ConnectedLineName: %s\r\n"
                                        "Wait: %ld\r\n"
+                                       "Priority: %d\r\n"
                                        "%s"
                                        "\r\n",
                                        q->name, pos++, ast_channel_name(qe->chan), ast_channel_uniqueid(qe->chan),
@@ -9956,7 +9990,7 @@ static int manager_queues_status(struct mansession *s, const struct message *m)
                                        S_COR(ast_channel_caller(qe->chan)->id.name.valid, ast_channel_caller(qe->chan)->id.name.str, "unknown"),
                                        S_COR(ast_channel_connected(qe->chan)->id.number.valid, ast_channel_connected(qe->chan)->id.number.str, "unknown"),
                                        S_COR(ast_channel_connected(qe->chan)->id.name.valid, ast_channel_connected(qe->chan)->id.name.str, "unknown"),
-                                       (long) (now - qe->start), idText);
+                                       (long) (now - qe->start), qe->prio, idText);
                                ++q_items;
                        }
                }
@@ -10259,6 +10293,50 @@ static int manager_queue_member_penalty(struct mansession *s, const struct messa
        return 0;
 }
 
+static int manager_change_priority_caller_on_queue(struct mansession *s, const struct message *m)
+{
+       const char *queuename, *caller, *priority_s;
+       int priority = 0;
+
+       queuename = astman_get_header(m, "Queue");
+       caller = astman_get_header(m, "Caller");
+       priority_s = astman_get_header(m, "Priority");
+
+       if (ast_strlen_zero(queuename)) {
+               astman_send_error(s, m, "'Queue' not specified.");
+               return 0;
+       }
+
+       if (ast_strlen_zero(caller)) {
+               astman_send_error(s, m, "'Caller' not specified.");
+               return 0;
+       }
+
+       if (ast_strlen_zero(priority_s)) {
+               astman_send_error(s, m, "'Priority' not specified.");
+               return 0;
+       } else if (sscanf(priority_s, "%30d", &priority) != 1) {
+               astman_send_error(s, m, "'Priority' need integer.");
+               return 0;
+       }
+
+       switch (change_priority_caller_on_queue(queuename, caller, priority)) {
+       case RES_OKAY:
+               astman_send_ack(s, m, "Priority change for caller on queue");
+               break;
+       case RES_NOSUCHQUEUE:
+               astman_send_error(s, m, "Unable to change priority caller on queue: No such queue");
+               break;
+       case RES_NOT_CALLER:
+               astman_send_error(s, m, "Unable to change priority caller on queue: No such caller");
+               break;
+       }
+
+       return 0;
+}
+
+
+
 static char *handle_queue_add_member(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
        const char *queuename, *interface, *membername = NULL, *state_interface = NULL;
@@ -10446,6 +10524,57 @@ static char *handle_queue_remove_member(struct ast_cli_entry *e, int cmd, struct
        return res;
 }
 
+
+
+static char *handle_queue_change_priority_caller(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       const char *queuename, *caller;
+       int priority;
+       char *res = CLI_FAILURE;
+
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "queue priority caller";
+               e->usage =
+                       "Usage: queue priority caller <channel> on <queue> to <priority>\n"
+                       "       Change the priority of a channel on a queue.\n";
+               return NULL;
+       case CLI_GENERATE:
+               return NULL;
+       }
+
+       if (a->argc != 8) {
+               return CLI_SHOWUSAGE;
+       } else if (strcmp(a->argv[4], "on")) {
+               return CLI_SHOWUSAGE;
+       } else if (strcmp(a->argv[6], "to")) {
+               return CLI_SHOWUSAGE;
+       } else if (sscanf(a->argv[7], "%30d", &priority) != 1) {
+               ast_log (LOG_ERROR, "<priority> parameter must be an integer.\n");
+               return CLI_SHOWUSAGE;
+       }
+
+       caller = a->argv[3];
+       queuename = a->argv[5];
+
+       switch (change_priority_caller_on_queue(queuename, caller, priority)) {
+       case RES_OKAY:
+               res = CLI_SUCCESS;
+               break;
+       case RES_NOSUCHQUEUE:
+               ast_cli(a->fd, "Unable change priority caller %s on queue '%s': No such queue\n", caller, queuename);
+               break;
+       case RES_NOT_CALLER:
+               ast_cli(a->fd, "Unable to change priority caller '%s' on queue '%s': Not there\n", caller, queuename);
+
+               break;
+       }
+
+       return res;
+}
+
+
+
 static char *complete_queue_pause_member(const char *line, const char *word, int pos, int state)
 {
        /* 0 - queue; 1 - pause; 2 - member; 3 - <interface>; 4 - queue; 5 - <queue>; 6 - reason; 7 - <reason> */
@@ -10891,275 +11020,7 @@ static struct ast_cli_entry cli_queue[] = {
        AST_CLI_DEFINE(handle_queue_set_member_ringinuse, "Set ringinuse for a channel of a specified queue"),
        AST_CLI_DEFINE(handle_queue_reload, "Reload queues, members, queue rules, or parameters"),
        AST_CLI_DEFINE(handle_queue_reset, "Reset statistics for a queue"),
-};
-
-/* struct call_queue astdata mapping. */
-#define DATA_EXPORT_CALL_QUEUE(MEMBER)                                 \
-       MEMBER(call_queue, name, AST_DATA_STRING)                       \
-       MEMBER(call_queue, moh, AST_DATA_STRING)                        \
-       MEMBER(call_queue, announce, AST_DATA_STRING)                   \
-       MEMBER(call_queue, context, AST_DATA_STRING)                    \
-       MEMBER(call_queue, membermacro, AST_DATA_STRING)                \
-       MEMBER(call_queue, membergosub, AST_DATA_STRING)                \
-       MEMBER(call_queue, defaultrule, AST_DATA_STRING)                \
-       MEMBER(call_queue, sound_next, AST_DATA_STRING)                 \
-       MEMBER(call_queue, sound_thereare, AST_DATA_STRING)             \
-       MEMBER(call_queue, sound_calls, AST_DATA_STRING)                \
-       MEMBER(call_queue, queue_quantity1, AST_DATA_STRING)            \
-       MEMBER(call_queue, queue_quantity2, AST_DATA_STRING)            \
-       MEMBER(call_queue, sound_holdtime, AST_DATA_STRING)             \
-       MEMBER(call_queue, sound_minutes, AST_DATA_STRING)              \
-       MEMBER(call_queue, sound_minute, AST_DATA_STRING)               \
-       MEMBER(call_queue, sound_seconds, AST_DATA_STRING)              \
-       MEMBER(call_queue, sound_thanks, AST_DATA_STRING)               \
-       MEMBER(call_queue, sound_callerannounce, AST_DATA_STRING)       \
-       MEMBER(call_queue, sound_reporthold, AST_DATA_STRING)           \
-       MEMBER(call_queue, dead, AST_DATA_BOOLEAN)                      \
-       MEMBER(call_queue, ringinuse, AST_DATA_BOOLEAN)                 \
-       MEMBER(call_queue, announce_to_first_user, AST_DATA_BOOLEAN)    \
-       MEMBER(call_queue, setinterfacevar, AST_DATA_BOOLEAN)           \
-       MEMBER(call_queue, setqueuevar, AST_DATA_BOOLEAN)               \
-       MEMBER(call_queue, setqueueentryvar, AST_DATA_BOOLEAN)          \
-       MEMBER(call_queue, reportholdtime, AST_DATA_BOOLEAN)            \
-       MEMBER(call_queue, wrapped, AST_DATA_BOOLEAN)                   \
-       MEMBER(call_queue, timeoutrestart, AST_DATA_BOOLEAN)            \
-       MEMBER(call_queue, announceholdtime, AST_DATA_INTEGER)          \
-       MEMBER(call_queue, realtime, AST_DATA_BOOLEAN)                  \
-       MEMBER(call_queue, found, AST_DATA_BOOLEAN)                     \
-       MEMBER(call_queue, announcepositionlimit, AST_DATA_INTEGER)     \
-       MEMBER(call_queue, announcefrequency, AST_DATA_SECONDS)         \
-       MEMBER(call_queue, minannouncefrequency, AST_DATA_SECONDS)      \
-       MEMBER(call_queue, periodicannouncefrequency, AST_DATA_SECONDS) \
-       MEMBER(call_queue, numperiodicannounce, AST_DATA_INTEGER)       \
-       MEMBER(call_queue, randomperiodicannounce, AST_DATA_INTEGER)    \
-       MEMBER(call_queue, roundingseconds, AST_DATA_SECONDS)           \
-       MEMBER(call_queue, holdtime, AST_DATA_SECONDS)                  \
-       MEMBER(call_queue, talktime, AST_DATA_SECONDS)                  \
-       MEMBER(call_queue, callscompleted, AST_DATA_INTEGER)            \
-       MEMBER(call_queue, callsabandoned, AST_DATA_INTEGER)            \
-       MEMBER(call_queue, servicelevel, AST_DATA_INTEGER)              \
-       MEMBER(call_queue, callscompletedinsl, AST_DATA_INTEGER)        \
-       MEMBER(call_queue, monfmt, AST_DATA_STRING)                     \
-       MEMBER(call_queue, montype, AST_DATA_INTEGER)                   \
-       MEMBER(call_queue, count, AST_DATA_INTEGER)                     \
-       MEMBER(call_queue, maxlen, AST_DATA_INTEGER)                    \
-       MEMBER(call_queue, wrapuptime, AST_DATA_SECONDS)                \
-       MEMBER(call_queue, retry, AST_DATA_SECONDS)                     \
-       MEMBER(call_queue, timeout, AST_DATA_SECONDS)                   \
-       MEMBER(call_queue, weight, AST_DATA_INTEGER)                    \
-       MEMBER(call_queue, autopause, AST_DATA_INTEGER)                 \
-       MEMBER(call_queue, timeoutpriority, AST_DATA_INTEGER)           \
-       MEMBER(call_queue, rrpos, AST_DATA_INTEGER)                     \
-       MEMBER(call_queue, memberdelay, AST_DATA_INTEGER)               \
-       MEMBER(call_queue, autofill, AST_DATA_INTEGER)                  \
-       MEMBER(call_queue, members, AST_DATA_CONTAINER)
-
-AST_DATA_STRUCTURE(call_queue, DATA_EXPORT_CALL_QUEUE);
-
-/* struct member astdata mapping. */
-#define DATA_EXPORT_MEMBER(MEMBER)                                     \
-       MEMBER(member, interface, AST_DATA_STRING)                      \
-       MEMBER(member, state_interface, AST_DATA_STRING)                \
-       MEMBER(member, membername, AST_DATA_STRING)                     \
-       MEMBER(member, penalty, AST_DATA_INTEGER)                       \
-       MEMBER(member, calls, AST_DATA_INTEGER)                         \
-       MEMBER(member, dynamic, AST_DATA_INTEGER)                       \
-       MEMBER(member, realtime, AST_DATA_INTEGER)                      \
-       MEMBER(member, status, AST_DATA_INTEGER)                        \
-       MEMBER(member, paused, AST_DATA_BOOLEAN)                        \
-       MEMBER(member, rt_uniqueid, AST_DATA_STRING)
-
-AST_DATA_STRUCTURE(member, DATA_EXPORT_MEMBER);
-
-#define DATA_EXPORT_QUEUE_ENT(MEMBER)                                          \
-       MEMBER(queue_ent, moh, AST_DATA_STRING)                                 \
-       MEMBER(queue_ent, announce, AST_DATA_STRING)                            \
-       MEMBER(queue_ent, context, AST_DATA_STRING)                             \
-       MEMBER(queue_ent, digits, AST_DATA_STRING)                              \
-       MEMBER(queue_ent, valid_digits, AST_DATA_INTEGER)                       \
-       MEMBER(queue_ent, pos, AST_DATA_INTEGER)                                \
-       MEMBER(queue_ent, prio, AST_DATA_INTEGER)                               \
-       MEMBER(queue_ent, last_pos_said, AST_DATA_INTEGER)                      \
-       MEMBER(queue_ent, last_periodic_announce_time, AST_DATA_INTEGER)        \
-       MEMBER(queue_ent, last_periodic_announce_sound, AST_DATA_INTEGER)       \
-       MEMBER(queue_ent, last_pos, AST_DATA_INTEGER)                           \
-       MEMBER(queue_ent, opos, AST_DATA_INTEGER)                               \
-       MEMBER(queue_ent, handled, AST_DATA_INTEGER)                            \
-       MEMBER(queue_ent, pending, AST_DATA_INTEGER)                            \
-       MEMBER(queue_ent, max_penalty, AST_DATA_INTEGER)                        \
-       MEMBER(queue_ent, min_penalty, AST_DATA_INTEGER)                        \
-       MEMBER(queue_ent, raise_penalty, AST_DATA_INTEGER)                      \
-       MEMBER(queue_ent, linpos, AST_DATA_INTEGER)                             \
-       MEMBER(queue_ent, linwrapped, AST_DATA_INTEGER)                         \
-       MEMBER(queue_ent, start, AST_DATA_INTEGER)                              \
-       MEMBER(queue_ent, expire, AST_DATA_INTEGER)                             \
-       MEMBER(queue_ent, cancel_answered_elsewhere, AST_DATA_INTEGER)
-
-AST_DATA_STRUCTURE(queue_ent, DATA_EXPORT_QUEUE_ENT);
-
-/*!
- * \internal
- * \brief Add a queue to the data_root node.
- * \param[in] search The search tree.
- * \param[in] data_root The main result node.
- * \param[in] queue The queue to add.
- */
-static void queues_data_provider_get_helper(const struct ast_data_search *search,
-       struct ast_data *data_root, struct call_queue *queue)
-{
-       struct ao2_iterator im;
-       struct member *member;
-       struct queue_ent *qe;
-       struct ast_data *data_queue, *data_members = NULL, *enum_node;
-       struct ast_data *data_member, *data_callers = NULL, *data_caller, *data_caller_channel;
-
-       data_queue = ast_data_add_node(data_root, "queue");
-       if (!data_queue) {
-               return;
-       }
-
-       ast_data_add_structure(call_queue, data_queue, queue);
-
-       ast_data_add_str(data_queue, "strategy", int2strat(queue->strategy));
-       ast_data_add_int(data_queue, "membercount", ao2_container_count(queue->members));
-
-       /* announce position */
-       enum_node = ast_data_add_node(data_queue, "announceposition");
-       if (!enum_node) {
-               return;
-       }
-       switch (queue->announceposition) {
-       case ANNOUNCEPOSITION_LIMIT:
-               ast_data_add_str(enum_node, "text", "limit");
-               break;
-       case ANNOUNCEPOSITION_MORE_THAN:
-               ast_data_add_str(enum_node, "text", "more");
-               break;
-       case ANNOUNCEPOSITION_YES:
-               ast_data_add_str(enum_node, "text", "yes");
-               break;
-       case ANNOUNCEPOSITION_NO:
-               ast_data_add_str(enum_node, "text", "no");
-               break;
-       default:
-               ast_data_add_str(enum_node, "text", "unknown");
-               break;
-       }
-       ast_data_add_int(enum_node, "value", queue->announceposition);
-
-       /* add queue members */
-       im = ao2_iterator_init(queue->members, 0);
-       while ((member = ao2_iterator_next(&im))) {
-               if (!data_members) {
-                       data_members = ast_data_add_node(data_queue, "members");
-                       if (!data_members) {
-                               ao2_ref(member, -1);
-                               continue;
-                       }
-               }
-
-               data_member = ast_data_add_node(data_members, "member");
-               if (!data_member) {
-                       ao2_ref(member, -1);
-                       continue;
-               }
-
-               ast_data_add_structure(member, data_member, member);
-
-               ao2_ref(member, -1);
-       }
-       ao2_iterator_destroy(&im);
-
-       /* include the callers inside the result. */
-       if (queue->head) {
-               for (qe = queue->head; qe; qe = qe->next) {
-                       if (!data_callers) {
-                               data_callers = ast_data_add_node(data_queue, "callers");
-                               if (!data_callers) {
-                                       continue;
-                               }
-                       }
-
-                       data_caller = ast_data_add_node(data_callers, "caller");
-                       if (!data_caller) {
-                               continue;
-                       }
-
-                       ast_data_add_structure(queue_ent, data_caller, qe);
-
-                       /* add the caller channel. */
-                       data_caller_channel = ast_data_add_node(data_caller, "channel");
-                       if (!data_caller_channel) {
-                               continue;
-                       }
-
-                       ast_channel_data_add_structure(data_caller_channel, qe->chan, 1);
-               }
-       }
-
-       /* if this queue doesn't match remove the added queue. */
-       if (!ast_data_search_match(search, data_queue)) {
-               ast_data_remove_node(data_root, data_queue);
-       }
-}
-
-/*!
- * \internal
- * \brief Callback used to generate the queues tree.
- * \param[in] search The search pattern tree.
- * \retval NULL on error.
- * \retval non-NULL The generated tree.
- */
-static int queues_data_provider_get(const struct ast_data_search *search,
-       struct ast_data *data_root)
-{
-       struct ao2_iterator i;
-       struct call_queue *queue, *queue_realtime = NULL;
-       struct ast_config *cfg;
-
-       /* load realtime queues. */
-       cfg = ast_load_realtime_multientry("queues", "name LIKE", "%", SENTINEL);
-       if (cfg) {
-               char *category = NULL;
-               while ((category = ast_category_browse(cfg, category))) {
-                       const char *queuename = ast_variable_retrieve(cfg, category, "name");
-                       if ((queue = find_load_queue_rt_friendly(queuename))) {
-                               queue_unref(queue);
-                       }
-               }
-               ast_config_destroy(cfg);
-       }
-
-       /* static queues. */
-       i = ao2_iterator_init(queues, 0);
-       while ((queue = ao2_iterator_next(&i))) {
-               ao2_lock(queue);
-               if (queue->realtime) {
-                       queue_realtime = find_load_queue_rt_friendly(queue->name);
-                       if (!queue_realtime) {
-                               ao2_unlock(queue);
-                               queue_unref(queue);
-                               continue;
-                       }
-                       queue_unref(queue_realtime);
-               }
-
-               queues_data_provider_get_helper(search, data_root, queue);
-               ao2_unlock(queue);
-               queue_unref(queue);
-       }
-       ao2_iterator_destroy(&i);
-
-       return 0;
-}
-
-static const struct ast_data_handler queues_data_provider = {
-       .version = AST_DATA_HANDLER_VERSION,
-       .get = queues_data_provider_get
-};
-
-static const struct ast_data_entry queue_data_providers[] = {
-       AST_DATA_ENTRY("asterisk/application/queue/list", &queues_data_provider),
+       AST_CLI_DEFINE(handle_queue_change_priority_caller, "Change priority caller on queue"),
 };
 
 static struct stasis_message_router *agent_router;
@@ -11191,7 +11052,6 @@ static int unload_module(void)
 
        ast_cli_unregister_multiple(cli_queue, ARRAY_LEN(cli_queue));
        ast_manager_unregister("QueueStatus");
-       ast_manager_unregister("Queues");
        ast_manager_unregister("QueueRule");
        ast_manager_unregister("QueueSummary");
        ast_manager_unregister("QueueAdd");
@@ -11203,6 +11063,7 @@ static int unload_module(void)
        ast_manager_unregister("QueueReload");
        ast_manager_unregister("QueueReset");
        ast_manager_unregister("QueueMemberRingInUse");
+       ast_manager_unregister("QueueChangePriorityCaller");
        ast_unregister_application(app_aqm);
        ast_unregister_application(app_rqm);
        ast_unregister_application(app_pqm);
@@ -11219,8 +11080,6 @@ static int unload_module(void)
        ast_custom_function_unregister(&queuewaitingcount_function);
        ast_custom_function_unregister(&queuememberpenalty_function);
 
-       ast_data_unregister(NULL);
-
        device_state_sub = stasis_unsubscribe_and_join(device_state_sub);
 
        ast_extension_state_del(0, extension_state_cb);
@@ -11299,8 +11158,6 @@ static int load_module(void)
                reload_queue_members();
        }
 
-       ast_data_register_multiple(queue_data_providers, ARRAY_LEN(queue_data_providers));
-
        err |= ast_cli_register_multiple(cli_queue, ARRAY_LEN(cli_queue));
        err |= ast_register_application_xml(app, queue_exec);
        err |= ast_register_application_xml(app_aqm, aqm_exec);
@@ -11309,7 +11166,6 @@ static int load_module(void)
        err |= ast_register_application_xml(app_upqm, upqm_exec);
        err |= ast_register_application_xml(app_ql, ql_exec);
        err |= ast_register_application_xml(app_qupd, qupd_exec);
-       err |= ast_manager_register_xml("Queues", 0, manager_queues_show);
        err |= ast_manager_register_xml("QueueStatus", 0, manager_queues_status);
        err |= ast_manager_register_xml("QueueSummary", 0, manager_queues_summary);
        err |= ast_manager_register_xml("QueueAdd", EVENT_FLAG_AGENT, manager_add_queue_member);
@@ -11321,6 +11177,7 @@ static int load_module(void)
        err |= ast_manager_register_xml("QueueRule", 0, manager_queue_rule_show);
        err |= ast_manager_register_xml("QueueReload", 0, manager_queue_reload);
        err |= ast_manager_register_xml("QueueReset", 0, manager_queue_reset);
+       err |= ast_manager_register_xml("QueueChangePriorityCaller", 0,  manager_change_priority_caller_on_queue);
        err |= ast_custom_function_register(&queuevar_function);
        err |= ast_custom_function_register(&queueexists_function);
        err |= ast_custom_function_register(&queuemembercount_function);
index 79d1591..9695dcc 100644 (file)
@@ -108,7 +108,6 @@ static int stream_echo_write(struct ast_channel *chan, struct ast_frame *frame,
         * we simply want to echo it back out onto the same stream number.
         */
        num = ast_channel_is_multistream(chan) ? frame->stream_num : -1;
-
        if (ast_write_stream(chan, num, frame)) {
                return stream_echo_write_error(chan, frame, num);
        }
@@ -120,7 +119,8 @@ static int stream_echo_write(struct ast_channel *chan, struct ast_frame *frame,
         * Note, if the channel is not multi-stream capable then one_to_one will
         * always be true, so it is safe to also not check for that here too.
         */
-       if (one_to_one || ast_format_get_type(frame->subclass.format) != type) {
+       if (one_to_one || !frame->subclass.format ||
+           ast_format_get_type(frame->subclass.format) != type) {
                return 0;
        }
 
@@ -141,7 +141,6 @@ static int stream_echo_write(struct ast_channel *chan, struct ast_frame *frame,
 
        for (i = 0; i < ast_stream_topology_get_count(topology); ++i) {
                struct ast_stream *stream = ast_stream_topology_get_stream(topology, i);
-
                if (num != i && ast_stream_get_type(stream) == type) {
                        if (ast_write_stream(chan, i, frame)) {
                                return stream_echo_write_error(chan, frame, i);
@@ -171,7 +170,7 @@ static int stream_echo_perform(struct ast_channel *chan,
                        request_change = 0;
                }
 
-               f = ast_read(chan);
+               f = ast_read_stream(chan);
                if (!f) {
                        return -1;
                }
@@ -186,11 +185,13 @@ static int stream_echo_perform(struct ast_channel *chan,
 
                if (f->frametype == AST_FRAME_CONTROL) {
                        if (f->subclass.integer == AST_CONTROL_VIDUPDATE && !update_sent) {
-                               if (stream_echo_write(chan, f, one_to_one, type)) {
+                               if (stream_echo_write(chan, f, type, one_to_one)) {
                                        ast_frfree(f);
                                        return -1;
                                }
                                update_sent = 1;
+                       } else if (f->subclass.integer == AST_CONTROL_SRCCHANGE) {
+                               update_sent = 0;
                        } else if (f->subclass.integer == AST_CONTROL_STREAM_TOPOLOGY_CHANGED) {
                                update_sent = 0;
                                one_to_one = 0; /* Switch writing to one to many */
@@ -200,14 +201,14 @@ static int stream_echo_perform(struct ast_channel *chan,
                                .frametype = AST_FRAME_CONTROL,
                                .subclass.integer = AST_CONTROL_VIDUPDATE,
                        };
-                       stream_echo_write(chan, &frame, one_to_one, type);
+                       stream_echo_write(chan, &frame, type, one_to_one);
                        update_sent = 1;
                }
 
                if (f->frametype != AST_FRAME_CONTROL &&
                    f->frametype != AST_FRAME_MODEM &&
                    f->frametype != AST_FRAME_NULL &&
-                   stream_echo_write(chan, f, one_to_one, type)) {
+                   stream_echo_write(chan, f, type, one_to_one)) {
                        ast_frfree(f);
                        return -1;
                }
index 8f50e11..0a07cc1 100644 (file)
@@ -505,6 +505,7 @@ static int imapversion = 1;
 
 static int expungeonhangup = 1;
 static int imapgreetings = 0;
+static int imap_poll_logout = 0;
 static char delimiter = '\0';
 
 /* mail_open cannot be protected on a stream basis */
@@ -542,6 +543,8 @@ static int imap_retrieve_file (const char *dir, const int msgnum, const char *ma
 static int imap_delete_old_greeting (char *dir, struct vm_state *vms);
 static void check_quota(struct vm_state *vms, char *mailbox);
 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box);
+static void imap_logout(const char *mailbox_id);
+
 struct vmstate {
        struct vm_state *vms;
        AST_LIST_ENTRY(vmstate) list;
@@ -3776,12 +3779,12 @@ static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
        SQLHSTMT stmt;
 
        res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
-       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
+       if (!SQL_SUCCEEDED(res)) {
                ast_log(AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
                return NULL;
        }
        res = SQLPrepare(stmt, (unsigned char *) gps->sql, SQL_NTS);
-       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
+       if (!SQL_SUCCEEDED(res)) {
                ast_log(AST_LOG_WARNING, "SQL Prepare failed![%s]\n", gps->sql);
                SQLFreeHandle(SQL_HANDLE_STMT, stmt);
                return NULL;
@@ -3823,14 +3826,14 @@ static void odbc_update_msg_id(char *dir, int msg_num, char *msg_id)
  * \brief Retrieves a file from an ODBC data store.
  * \param dir the path to the file to be retrieved.
  * \param msgnum the message number, such as within a mailbox folder.
- * 
+ *
  * This method is used by the RETRIEVE macro when mailboxes are stored in an ODBC back end.
  * The purpose is to get the message from the database store to the local file system, so that the message may be played, or the information file may be read.
  *
  * The file is looked up by invoking a SQL on the odbc_table (default 'voicemessages') using the dir and msgnum input parameters.
  * The output is the message information file with the name msgnum and the extension .txt
  * and the message file with the extension of its format, in the directory with base file name of the msgnum.
- * 
+ *
  * \return 0 on success, -1 on error.
  */
 static int retrieve_file(char *dir, int msgnum)
@@ -3843,7 +3846,7 @@ static int retrieve_file(char *dir, int msgnum)
        SQLSMALLINT colcount = 0;
        SQLHSTMT stmt;
        char sql[PATH_MAX];
-       char fmt[80]="";
+       char fmt[80] = "";
        char *c;
        char coltitle[256];
        SQLSMALLINT collen;
@@ -3859,144 +3862,139 @@ static int retrieve_file(char *dir, int msgnum)
        char msgnums[80];
        char *argv[] = { dir, msgnums };
        struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
-
        struct odbc_obj *obj;
+
        obj = ast_odbc_request_obj(odbc_database, 0);
-       if (obj) {
-               ast_copy_string(fmt, vmfmts, sizeof(fmt));
-               c = strchr(fmt, '|');
-               if (c)
-                       *c = '\0';
-               if (!strcasecmp(fmt, "wav49"))
-                       strcpy(fmt, "WAV");
-               snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
-               if (msgnum > -1)
-                       make_file(fn, sizeof(fn), dir, msgnum);
-               else
-                       ast_copy_string(fn, dir, sizeof(fn));
+       if (!obj) {
+               ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
+               return -1;
+       }
 
-               /* Create the information file */
-               snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
-               
-               if (!(f = fopen(full_fn, "w+"))) {
-                       ast_log(AST_LOG_WARNING, "Failed to open/create '%s'\n", full_fn);
-                       goto yuck;
-               }
-               
-               snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
-               snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE dir=? AND msgnum=?", odbc_table);
-               stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
-               if (!stmt) {
-                       ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               }
-               res = SQLFetch(stmt);
-               if (res == SQL_NO_DATA) {
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               } else if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
+       ast_copy_string(fmt, vmfmts, sizeof(fmt));
+       c = strchr(fmt, '|');
+       if (c)
+               *c = '\0';
+       if (!strcasecmp(fmt, "wav49"))
+               strcpy(fmt, "WAV");
+
+       snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
+       if (msgnum > -1)
+               make_file(fn, sizeof(fn), dir, msgnum);
+       else
+               ast_copy_string(fn, dir, sizeof(fn));
+
+       /* Create the information file */
+       snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
+
+       if (!(f = fopen(full_fn, "w+"))) {
+               ast_log(AST_LOG_WARNING, "Failed to open/create '%s'\n", full_fn);
+               goto bail;
+       }
+
+       snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
+       snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE dir=? AND msgnum=?", odbc_table);
+
+       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
+       if (!stmt) {
+               ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
+               goto bail;
+       }
+
+       res = SQLFetch(stmt);
+       if (!SQL_SUCCEEDED(res)) {
+               if (res != SQL_NO_DATA) {
                        ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
                }
-               fd = open(full_fn, O_RDWR | O_CREAT | O_TRUNC, VOICEMAIL_FILE_MODE);
-               if (fd < 0) {
-                       ast_log(AST_LOG_WARNING, "Failed to write '%s': %s\n", full_fn, strerror(errno));
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               }
-               res = SQLNumResultCols(stmt, &colcount);
-               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {   
-                       ast_log(AST_LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               }
-               if (f) 
-                       fprintf(f, "[message]\n");
-               for (x = 0; x < colcount; x++) {
-                       rowdata[0] = '\0';
-                       colsize = 0;
-                       collen = sizeof(coltitle);
-                       res = SQLDescribeCol(stmt, x + 1, (unsigned char *) coltitle, sizeof(coltitle), &collen, 
-                                               &datatype, &colsize, &decimaldigits, &nullable);
-                       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                               ast_log(AST_LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
-                               SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                               ast_odbc_release_obj(obj);
-                               goto yuck;
-                       }
-                       if (!strcasecmp(coltitle, "recording")) {
-                               off_t offset;
-                               res = SQLGetData(stmt, x + 1, SQL_BINARY, rowdata, 0, &colsize2);
-                               fdlen = colsize2;
-                               if (fd > -1) {
-                                       char tmp[1]="";
-                                       lseek(fd, fdlen - 1, SEEK_SET);
-                                       if (write(fd, tmp, 1) != 1) {
-                                               close(fd);
-                                               fd = -1;
-                                               continue;
-                                       }
-                                       /* Read out in small chunks */
-                                       for (offset = 0; offset < colsize2; offset += CHUNKSIZE) {
-                                               if ((fdm = mmap(NULL, CHUNKSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset)) == MAP_FAILED) {
-                                                       ast_log(AST_LOG_WARNING, "Could not mmap the output file: %s (%d)\n", strerror(errno), errno);
-                                                       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
-                                                       ast_odbc_release_obj(obj);
-                                                       goto yuck;
-                                               } else {
-                                                       res = SQLGetData(stmt, x + 1, SQL_BINARY, fdm, CHUNKSIZE, NULL);
-                                                       munmap(fdm, CHUNKSIZE);
-                                                       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                                                               ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
-                                                               unlink(full_fn);
-                                                               SQLFreeHandle(SQL_HANDLE_STMT, stmt);
-                                                               ast_odbc_release_obj(obj);
-                                                               goto yuck;
-                                                       }
-                                               }
+               goto bail_with_handle;
+       }
+
+       fd = open(full_fn, O_RDWR | O_CREAT | O_TRUNC, VOICEMAIL_FILE_MODE);
+       if (fd < 0) {
+               ast_log(AST_LOG_WARNING, "Failed to write '%s': %s\n", full_fn, strerror(errno));
+               goto bail_with_handle;
+       }
+
+       res = SQLNumResultCols(stmt, &colcount);
+       if (!SQL_SUCCEEDED(res)) {
+               ast_log(AST_LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
+               goto bail_with_handle;
+       }
+
+       fprintf(f, "[message]\n");
+       for (x = 0; x < colcount; x++) {
+               rowdata[0] = '\0';
+               colsize = 0;
+               collen = sizeof(coltitle);
+               res = SQLDescribeCol(stmt, x + 1, (unsigned char *) coltitle, sizeof(coltitle), &collen,
+                                                       &datatype, &colsize, &decimaldigits, &nullable);
+               if (!SQL_SUCCEEDED(res)) {
+                       ast_log(AST_LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
+                       goto bail_with_handle;
+               }
+               if (!strcasecmp(coltitle, "recording")) {
+                       off_t offset;
+                       res = SQLGetData(stmt, x + 1, SQL_BINARY, rowdata, 0, &colsize2);
+                       fdlen = colsize2;
+                       if (fd > -1) {
+                               char tmp[1] = "";
+                               lseek(fd, fdlen - 1, SEEK_SET);
+                               if (write(fd, tmp, 1) != 1) {
+                                       close(fd);
+                                       fd = -1;
+                                       continue;
+                               }
+                               /* Read out in small chunks */
+                               for (offset = 0; offset < colsize2; offset += CHUNKSIZE) {
+                                       if ((fdm = mmap(NULL, CHUNKSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset)) == MAP_FAILED) {
+                                               ast_log(AST_LOG_WARNING, "Could not mmap the output file: %s (%d)\n", strerror(errno), errno);
+                                               goto bail_with_handle;
                                        }
-                                       if (truncate(full_fn, fdlen) < 0) {
-                                               ast_log(LOG_WARNING, "Unable to truncate '%s': %s\n", full_fn, strerror(errno));
+                                       res = SQLGetData(stmt, x + 1, SQL_BINARY, fdm, CHUNKSIZE, NULL);
+                                       munmap(fdm, CHUNKSIZE);
+                                       if (!SQL_SUCCEEDED(res)) {
+                                               ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
+                                               unlink(full_fn);
+                                               goto bail_with_handle;
                                        }
                                }
-                       } else {
-                               res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
-                               if ((res == SQL_NULL_DATA) && (!strcasecmp(coltitle, "msg_id"))) {
-                                       char msg_id[MSG_ID_LEN];
-                                       generate_msg_id(msg_id);
-                                       snprintf(rowdata, sizeof(rowdata), "%s", msg_id);
-                                       odbc_update_msg_id(dir, msgnum, msg_id);
-                               } else if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                                       ast_log(AST_LOG_WARNING, "SQL Get Data error! coltitle=%s\n[%s]\n\n", coltitle, sql);
-                                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                                       ast_odbc_release_obj(obj);
-                                       goto yuck;
+                               if (truncate(full_fn, fdlen) < 0) {
+                                       ast_log(LOG_WARNING, "Unable to truncate '%s': %s\n", full_fn, strerror(errno));
                                }
-                               if (strcasecmp(coltitle, "msgnum") && strcasecmp(coltitle, "dir") && f)
-                                       fprintf(f, "%s=%s\n", coltitle, rowdata);
+                       }
+               } else {
+                       res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
+                       if (res == SQL_NULL_DATA && !strcasecmp(coltitle, "msg_id")) {
+                               char msg_id[MSG_ID_LEN];
+                               generate_msg_id(msg_id);
+                               snprintf(rowdata, sizeof(rowdata), "%s", msg_id);
+                               odbc_update_msg_id(dir, msgnum, msg_id);
+                       } else if (!SQL_SUCCEEDED(res)) {
+                               ast_log(AST_LOG_WARNING, "SQL Get Data error! coltitle=%s\n[%s]\n\n", coltitle, sql);
+                               goto bail_with_handle;
+                       }
+                       if (strcasecmp(coltitle, "msgnum") && strcasecmp(coltitle, "dir")) {
+                               fprintf(f, "%s=%s\n", coltitle, rowdata);
                        }
                }
-               SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-               ast_odbc_release_obj(obj);
-       } else
-               ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
-yuck:
+       }
+
+bail_with_handle:
+       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+
+bail:
        if (f)
                fclose(f);
        if (fd > -1)
                close(fd);
+
+       ast_odbc_release_obj(obj);
+
        return x - 1;
 }
 
 /*!
  * \brief Determines the highest message number in use for a given user and mailbox folder.
- * \param vmu 
+ * \param vmu
  * \param dir the folder the mailbox folder to look for messages. Used to construct the SQL where clause.
  *
  * This method is used when mailboxes are stored in an ODBC back end.
@@ -4007,58 +4005,61 @@ yuck:
  */
 static int last_message_index(struct ast_vm_user *vmu, char *dir)
 {
-       int x = 0;
+       int x = -1;
        int res;
        SQLHSTMT stmt;
        char sql[PATH_MAX];
        char rowdata[20];
        char *argv[] = { dir };
        struct generic_prepare_struct gps = { .sql = sql, .argc = 1, .argv = argv };
-
        struct odbc_obj *obj;
+
        obj = ast_odbc_request_obj(odbc_database, 0);
-       if (obj) {
-               snprintf(sql, sizeof(sql), "SELECT msgnum FROM %s WHERE dir=? order by msgnum desc", odbc_table);
+       if (!obj) {
+               ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
+               return -1;
+       }
 
-               stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
-               if (!stmt) {
-                       ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
+       snprintf(sql, sizeof(sql), "SELECT msgnum FROM %s WHERE dir=? order by msgnum desc", odbc_table);
+
+       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
+       if (!stmt) {
+               ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
+               goto bail;
+       }
+
+       res = SQLFetch(stmt);
+       if (!SQL_SUCCEEDED(res)) {
+               if (res == SQL_NO_DATA) {
+                       ast_log(AST_LOG_DEBUG, "Directory '%s' has no messages and therefore no index was retrieved.\n", dir);
+               } else {
+                       ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
                }
-               res = SQLFetch(stmt);
-               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                       if (res == SQL_NO_DATA) {
-                               ast_log(AST_LOG_DEBUG, "Directory '%s' has no messages and therefore no index was retrieved.\n", dir);
-                       } else {
-                               ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
-                       }
+               goto bail_with_handle;
+       }
 
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               }
-               res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
-               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                       ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               }
-               if (sscanf(rowdata, "%30d", &x) != 1)
-                       ast_log(AST_LOG_WARNING, "Failed to read message index!\n");
-               SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-               ast_odbc_release_obj(obj);
-               return x;
-       } else
-               ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
-yuck:
-       return x - 1;
+       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
+       if (!SQL_SUCCEEDED(res)) {
+               ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
+               goto bail_with_handle;
+       }
+
+       if (sscanf(rowdata, "%30d", &x) != 1) {
+               ast_log(AST_LOG_WARNING, "Failed to read message index!\n");
+       }
+
+bail_with_handle:
+       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+
+bail:
+       ast_odbc_release_obj(obj);
+
+       return x;
 }
 
 /*!
  * \brief Determines if the specified message exists.
- * \param dir the folder the mailbox folder to look for messages. 
+ * \param dir the folder the mailbox folder to look for messages.
  * \param msgnum the message index to query for.
  *
  * This method is used when mailboxes are stored in an ODBC back end.
@@ -4075,39 +4076,43 @@ static int message_exists(char *dir, int msgnum)
        char msgnums[20];
        char *argv[] = { dir, msgnums };
        struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
-
        struct odbc_obj *obj;
+
        obj = ast_odbc_request_obj(odbc_database, 0);
-       if (obj) {
-               snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
-               snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=? AND msgnum=?", odbc_table);
-               stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
-               if (!stmt) {
-                       ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               }
-               res = SQLFetch(stmt);
-               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                       ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               }
-               res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
-               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                       ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               }
-               if (sscanf(rowdata, "%30d", &x) != 1)
-                       ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
-               SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-               ast_odbc_release_obj(obj);
-       } else
+       if (!obj) {
                ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
-yuck:
+               return 0;
+       }
+
+       snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
+       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=? AND msgnum=?", odbc_table);
+       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
+       if (!stmt) {
+               ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
+               goto bail;
+       }
+
+       res = SQLFetch(stmt);
+       if (!SQL_SUCCEEDED(res)) {
+               ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
+               goto bail_with_handle;
+       }
+
+       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
+       if (!SQL_SUCCEEDED(res)) {
+               ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
+               goto bail_with_handle;
+       }
+
+       if (sscanf(rowdata, "%30d", &x) != 1) {
+               ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
+       }
+
+bail_with_handle:
+       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+
+bail:
+       ast_odbc_release_obj(obj);
        return x;
 }
 
@@ -4122,48 +4127,50 @@ yuck:
  */
 static int count_messages(struct ast_vm_user *vmu, char *dir)
 {
-       int x = 0;
+       int x = -1;
        int res;
        SQLHSTMT stmt;
        char sql[PATH_MAX];
        char rowdata[20];
        char *argv[] = { dir };
        struct generic_prepare_struct gps = { .sql = sql, .argc = 1, .argv = argv };
-
        struct odbc_obj *obj;
+
        obj = ast_odbc_request_obj(odbc_database, 0);
-       if (obj) {
-               snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=?", odbc_table);
-               stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
-               if (!stmt) {
-                       ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               }
-               res = SQLFetch(stmt);
-               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                       ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               }
-               res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
-               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                       ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       ast_odbc_release_obj(obj);
-                       goto yuck;
-               }
-               if (sscanf(rowdata, "%30d", &x) != 1)
-                       ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
-               SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-               ast_odbc_release_obj(obj);
-               return x;
-       } else
+       if (!obj) {
                ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
-yuck:
-       return x - 1;
+               return -1;
+       }
+
+       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=?", odbc_table);
+       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
+       if (!stmt) {
+               ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
+               goto bail;
+       }
+
+       res = SQLFetch(stmt);
+       if (!SQL_SUCCEEDED(res)) {
+               ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
+               goto bail_with_handle;
+       }
+
+       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
+       if (!SQL_SUCCEEDED(res)) {
+               ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
+               goto bail_with_handle;
+       }
+
+       if (sscanf(rowdata, "%30d", &x) != 1) {
+               ast_log(AST_LOG_WARNING, "Failed to read message count!\n");
+       }
 
+bail_with_handle:
+       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+
+bail:
+       ast_odbc_release_obj(obj);
+       return x;
 }
 
 /*!
@@ -4173,7 +4180,7 @@ yuck:
  *
  * This method is used when mailboxes are stored in an ODBC back end.
  * The specified message is directly deleted from the database 'voicemessages' table.
- * 
+ *
  * \return the value greater than zero on success to indicate the number of messages, less than zero on error.
  */
 static void delete_file(const char *sdir, int smsg)
@@ -4185,21 +4192,25 @@ static void delete_file(const char *sdir, int smsg)
        struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
        struct odbc_obj *obj;
 
-       argv[0] = ast_strdupa(sdir);
-
        obj = ast_odbc_request_obj(odbc_database, 0);
-       if (obj) {
-               snprintf(msgnums, sizeof(msgnums), "%d", smsg);
-               snprintf(sql, sizeof(sql), "DELETE FROM %s WHERE dir=? AND msgnum=?", odbc_table);
-               stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
-               if (!stmt)
-                       ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
-               else
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-               ast_odbc_release_obj(obj);
-       } else
+       if (!obj) {
                ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
-       return; 
+               return;
+       }
+
+       argv[0] = ast_strdupa(sdir);
+
+       snprintf(msgnums, sizeof(msgnums), "%d", smsg);
+       snprintf(sql, sizeof(sql), "DELETE FROM %s WHERE dir=? AND msgnum=?", odbc_table);
+       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
+       if (!stmt) {
+               ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
+       } else {
+               SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+       }
+       ast_odbc_release_obj(obj);
+
+       return;
 }
 
 /*!
@@ -4227,19 +4238,22 @@ static void copy_file(char *sdir, int smsg, char *ddir, int dmsg, char *dmailbox
        generate_msg_id(msg_id);
        delete_file(ddir, dmsg);
        obj = ast_odbc_request_obj(odbc_database, 0);
-       if (obj) {
-               snprintf(msgnums, sizeof(msgnums), "%d", smsg);
-               snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
-               snprintf(sql, sizeof(sql), "INSERT INTO %s (dir, msgnum, msg_id, context, macrocontext, callerid, origtime, duration, recording, flag, mailboxuser, mailboxcontext) SELECT ?,?,?,context,macrocontext,callerid,origtime,duration,recording,flag,?,? FROM %s WHERE dir=? AND msgnum=?", odbc_table, odbc_table);
-               stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
-               if (!stmt)
-                       ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s] (You probably don't have MySQL 4.1 or later installed)\n\n", sql);
-               else
-                       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
-               ast_odbc_release_obj(obj);
-       } else
+       if (!obj) {
                ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
-       return; 
+               return;
+       }
+
+       snprintf(msgnums, sizeof(msgnums), "%d", smsg);
+       snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
+       snprintf(sql, sizeof(sql), "INSERT INTO %s (dir, msgnum, msg_id, context, macrocontext, callerid, origtime, duration, recording, flag, mailboxuser, mailboxcontext) SELECT ?,?,?,context,macrocontext,callerid,origtime,duration,recording,flag,?,? FROM %s WHERE dir=? AND msgnum=?", odbc_table, odbc_table);
+       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
+       if (!stmt)
+               ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s] (You probably don't have MySQL 4.1 or later installed)\n\n", sql);
+       else
+               SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+       ast_odbc_release_obj(obj);
+
+       return;
 }
 
 struct insert_data {
@@ -4268,9 +4282,8 @@ static SQLHSTMT insert_data_cb(struct odbc_obj *obj, void *vdata)
        SQLHSTMT stmt;
 
        res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
-       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
+       if (!SQL_SUCCEEDED(res)) {
                ast_log(AST_LOG_WARNING, "SQL Alloc Handle failed!\n");
-               SQLFreeHandle(SQL_HANDLE_STMT, stmt);
                return NULL;
        }
 
@@ -4290,7 +4303,7 @@ static SQLHSTMT insert_data_cb(struct odbc_obj *obj, void *vdata)
                SQLBindParameter(stmt, 13, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(data->category), 0, (void *) data->category, 0, NULL);
        }
        res = SQLExecDirect(stmt, (unsigned char *) data->sql, SQL_NTS);
-       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
+       if (!SQL_SUCCEEDED(res)) {
                ast_log(AST_LOG_WARNING, "SQL Direct Execute failed!\n");
                SQLFreeHandle(SQL_HANDLE_STMT, stmt);
                return NULL;
@@ -4307,7 +4320,7 @@ static SQLHSTMT insert_data_cb(struct odbc_obj *obj, void *vdata)
  * \param msgnum the message index for the message to be stored.
  *
  * This method is used when mailboxes are stored in an ODBC back end.
- * The message sound file and information file is looked up on the file system. 
+ * The message sound file and information file is looked up on the file system.
  * A SQL query is invoked to store the message into the (MySQL) database.
  *
  * \return the zero on success -1 on error.
@@ -4332,7 +4345,9 @@ static int store_file(const char *dir, const char *mailboxuser, const char *mail
        struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE };
 
        delete_file(dir, msgnum);
-       if (!(obj = ast_odbc_request_obj(odbc_database, 0))) {
+
+       obj = ast_odbc_request_obj(odbc_database, 0);
+       if (!obj) {
                ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
                return -1;
        }
@@ -4395,25 +4410,25 @@ static int store_file(const char *dir, const char *mailboxuser, const char *mail
                        ast_log(AST_LOG_WARNING, "Memory map failed for sound file '%s'!\n", full_fn);
                        res = -1;
                        break;
-               } 
+               }
                idata.data = fdm;
                idata.datalen = idata.indlen = fdlen;
 
-               if (!ast_strlen_zero(idata.category)) 
-                       snprintf(sql, sizeof(sql), "INSERT INTO %s (dir,msgnum,recording,context,macrocontext,callerid,origtime,duration,mailboxuser,mailboxcontext,flag,msg_id,category) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", odbc_table); 
+               if (!ast_strlen_zero(idata.category))
+                       snprintf(sql, sizeof(sql), "INSERT INTO %s (dir,msgnum,recording,context,macrocontext,callerid,origtime,duration,mailboxuser,mailboxcontext,flag,msg_id,category) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", odbc_table);
                else
                        snprintf(sql, sizeof(sql), "INSERT INTO %s (dir,msgnum,recording,context,macrocontext,callerid,origtime,duration,mailboxuser,mailboxcontext,flag,msg_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", odbc_table);
 
                if ((stmt = ast_odbc_direct_execute(obj, insert_data_cb, &idata))) {
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
+                       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
                } else {
                        ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
                        res = -1;
                }
        } while (0);
-       if (obj) {
-               ast_odbc_release_obj(obj);
-       }
+
+       ast_odbc_release_obj(obj);
+
        if (valid_config(cfg))
                ast_config_destroy(cfg);
        if (fdm != MAP_FAILED)
@@ -4447,20 +4462,23 @@ static void rename_file(char *sdir, int smsg, char *mailboxuser, char *mailboxco
        struct generic_prepare_struct gps = { .sql = sql, .argc = 6, .argv = argv };
 
        delete_file(ddir, dmsg);
+
        obj = ast_odbc_request_obj(odbc_database, 0);
-       if (obj) {
-               snprintf(msgnums, sizeof(msgnums), "%d", smsg);
-               snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
-               snprintf(sql, sizeof(sql), "UPDATE %s SET dir=?, msgnum=?, mailboxuser=?, mailboxcontext=? WHERE dir=? AND msgnum=?", odbc_table);
-               stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
-               if (!stmt)
-                       ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
-               else
-                       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
-               ast_odbc_release_obj(obj);
-       } else
+       if (!obj) {
                ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
-       return; 
+               return;
+       }
+
+       snprintf(msgnums, sizeof(msgnums), "%d", smsg);
+       snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
+       snprintf(sql, sizeof(sql), "UPDATE %s SET dir=?, msgnum=?, mailboxuser=?, mailboxcontext=? WHERE dir=? AND msgnum=?", odbc_table);
+       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
+       if (!stmt)
+               ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
+       else
+               SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+       ast_odbc_release_obj(obj);
+       return;
 }
 
 /*!
@@ -5660,17 +5678,48 @@ static void free_zone(struct vm_zone *z)
 }
 
 #ifdef ODBC_STORAGE
-static int inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
+
+static int count_messages_in_folder(struct odbc_obj *odbc, const char *context, const char *mailbox, const char *folder, int *messages)
 {
-       int x = -1;
        int res;
-       SQLHSTMT stmt = NULL;
        char sql[PATH_MAX];
        char rowdata[20];
+       SQLHSTMT stmt = NULL;
+       struct generic_prepare_struct gps = { .sql = sql, .argc = 0 };
+
+       if (!messages) {
+               return 0;
+       }
+
+       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, mailbox, folder);
+       if (!(stmt = ast_odbc_prepare_and_execute(odbc, generic_prepare, &gps))) {
+               ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
+               return 1;
+       }
+       res = SQLFetch(stmt);
+       if (!SQL_SUCCEEDED(res)) {
+               ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
+               SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+               return 1;
+       }
+       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
+       if (!SQL_SUCCEEDED(res)) {
+               ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
+               SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+               return 1;
+       }
+
+       *messages = atoi(rowdata);
+       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+
+       return 0;
+}
+
+static int inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
+{
        char tmp[PATH_MAX] = "";
-       struct odbc_obj *obj = NULL;
+       struct odbc_obj *obj;
        char *context;
-       struct generic_prepare_struct gps = { .sql = sql, .argc = 0 };
 
        if (newmsgs)
                *newmsgs = 0;
@@ -5712,87 +5761,28 @@ static int inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *
        } else
                context = "default";
 
-       if ((obj = ast_odbc_request_obj(odbc_database, 0))) {
-               do {
-                       if (newmsgs) {
-                               snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, tmp, "INBOX");
-                               if (!(stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps))) {
-                                       ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
-                                       break;
-                               }
-                               res = SQLFetch(stmt);
-                               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                                       ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
-                                       break;
-                               }
-                               res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
-                               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                                       ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
-                                       break;
-                               }
-                               *newmsgs = atoi(rowdata);
-                               SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       }
-
-                       if (oldmsgs) {
-                               snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, tmp, "Old");
-                               if (!(stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps))) {
-                                       ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
-                                       break;
-                               }
-                               res = SQLFetch(stmt);
-                               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                                       ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
-                                       break;
-                               }
-                               res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
-                               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                                       ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
-                                       break;
-                               }
-                               SQLFreeHandle(SQL_HANDLE_STMT, stmt);
-                               *oldmsgs = atoi(rowdata);
-                       }
-
-                       if (urgentmsgs) {
-                               snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, tmp, "Urgent");
-                               if (!(stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps))) {
-                                       ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
-                                       break;
-                               }
-                               res = SQLFetch(stmt);
-                               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                                       ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
-                                       break;
-                               }
-                               res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
-                               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                                       ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
-                                       break;
-                               }
-                               *urgentmsgs = atoi(rowdata);
-                       }
-
-                       x = 0;
-               } while (0);
-       } else {
+       obj = ast_odbc_request_obj(odbc_database, 0);
+       if (!obj) {
                ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
+               return -1;
        }
 
-       if (stmt) {
-               SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-       }
-       if (obj) {
-               ast_odbc_release_obj(obj);
+       if (count_messages_in_folder(obj, context, tmp, "INBOX", newmsgs)
+          || count_messages_in_folder(obj, context, tmp, "Old", oldmsgs)
+          || count_messages_in_folder(obj, context, tmp, "Urgent", urgentmsgs)) {
+               ast_log(AST_LOG_WARNING, "Failed to obtain message count for mailbox %s@%s\n",
+                               tmp, context);
        }
-       return x;
+
+       ast_odbc_release_obj(obj);
+       return 0;
 }
 
 /*!
  * \brief Gets the number of messages that exist in a mailbox folder.
  * \param mailbox_id
  * \param folder
- * 
+ *
  * This method is used when ODBC backend is used.
  * \return The number of messages in this mailbox folder (zero or more).
  */
@@ -5819,37 +5809,39 @@ static int messagecount(const char *mailbox_id, const char *folder)
        }
 
        obj = ast_odbc_request_obj(odbc_database, 0);
-       if (obj) {
-               if (!strcmp(folder, "INBOX")) {
-                       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/INBOX' OR dir = '%s%s/%s/Urgent'", odbc_table, VM_SPOOL_DIR, context, mailbox, VM_SPOOL_DIR, context, mailbox);
-               } else {
-                       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, mailbox, folder);
-               }
-               stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
-               if (!stmt) {
-                       ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
-                       goto yuck;
-               }
-               res = SQLFetch(stmt);
-               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                       ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       goto yuck;
-               }
-               res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
-               if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
-                       ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
-                       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-                       goto yuck;
-               }
-               nummsgs = atoi(rowdata);
-               SQLFreeHandle (SQL_HANDLE_STMT, stmt);
-       } else
+       if (!obj) {
                ast_log(AST_LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
+               return 0;
+       }
+
+       if (!strcmp(folder, "INBOX")) {
+               snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/INBOX' OR dir = '%s%s/%s/Urgent'", odbc_table, VM_SPOOL_DIR, context, mailbox, VM_SPOOL_DIR, context, mailbox);
+       } else {
+               snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, mailbox, folder);
+       }
+
+       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
+       if (!stmt) {
+               ast_log(AST_LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
+               goto bail;
+       }
+       res = SQLFetch(stmt);
+       if (!SQL_SUCCEEDED(res)) {
+               ast_log(AST_LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
+               goto bail_with_handle;
+       }
+       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
+       if (!SQL_SUCCEEDED(res)) {
+               ast_log(AST_LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
+               goto bail_with_handle;
+       }
+       nummsgs = atoi(rowdata);
 
-yuck:
-       if (obj)
-               ast_odbc_release_obj(obj);
+bail_with_handle:
+       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
+
+bail:
+       ast_odbc_release_obj(obj);
        return nummsgs;
 }
 
@@ -11072,7 +11064,7 @@ static int vm_authenticate(struct ast_channel *chan, char *mailbox, int mailbox_
                        int skipuser, int max_logins, int silent)
 {
        int useadsi = 0, valid = 0, logretries = 0;
-       char password[AST_MAX_EXTENSION]="", *passptr;
+       char password[AST_MAX_EXTENSION], *passptr;
        struct ast_vm_user vmus, *vmu = NULL;
 
        /* If ADSI is supported, setup login screen */
@@ -11114,7 +11106,8 @@ static int vm_authenticate(struct ast_channel *chan, char *mailbox, int mailbox_
                        adsi_password(chan);
 
                if (!ast_strlen_zero(prefix)) {
-                       char fullusername[80] = "";
+                       char fullusername[80];
+
                        ast_copy_string(fullusername, prefix, sizeof(fullusername));
                        strncat(fullusername, mailbox, sizeof(fullusername) - 1 - strlen(fullusername));
                        ast_copy_string(mailbox, fullusername, mailbox_size);
@@ -11172,6 +11165,10 @@ static int vm_authenticate(struct ast_channel *chan, char *mailbox, int mailbox_
                                        free_user(vmu);
                                        return -1;
                                }
+                               if (ast_waitstream(chan, "")) { /* Channel is hung up */
+                                       free_user(vmu);
+                                       return -1;
+                               }
                        } else {
                                if (useadsi)
                                        adsi_login(chan);
@@ -11181,10 +11178,6 @@ static int vm_authenticate(struct ast_channel *chan, char *mailbox, int mailbox_
                                        return -1;
                                }
                        }
-                       if (ast_waitstream(chan, "")) { /* Channel is hung up */
-                               free_user(vmu);
-                               return -1;
-                       }
                }
        }
        if (!valid && (logretries >= max_logins)) {
@@ -12303,6 +12296,9 @@ static int append_mailbox(const char *context, const char *box, const char *data
        strcat(mailbox_full, context);
 
        inboxcount2(mailbox_full, &urgent, &new, &old);
+#ifdef IMAP_STORAGE
+       imap_logout(mailbox_full);
+#endif
        queue_mwi_event(NULL, mailbox_full, urgent, new, old);
 
        return 0;
@@ -12908,153 +12904,18 @@ static struct ast_cli_entry cli_voicemail[] = {
        AST_CLI_DEFINE(handle_voicemail_reload, "Reload voicemail configuration"),
 };
 
-#ifdef IMAP_STORAGE
-       #define DATA_EXPORT_VM_USERS(USER)                                      \
-               USER(ast_vm_user, context, AST_DATA_STRING)                     \
-               USER(ast_vm_user, mailbox, AST_DATA_STRING)                     \
-               USER(ast_vm_user, password, AST_DATA_PASSWORD)                  \
-               USER(ast_vm_user, fullname, AST_DATA_STRING)                    \
-               USER(ast_vm_user, email, AST_DATA_STRING)                       \
-               USER(ast_vm_user, emailsubject, AST_DATA_STRING)                \
-               USER(ast_vm_user, emailbody, AST_DATA_STRING)                   \
-               USER(ast_vm_user, pager, AST_DATA_STRING)                       \
-               USER(ast_vm_user, serveremail, AST_DATA_STRING)                 \
-               USER(ast_vm_user, fromstring, AST_DATA_STRING)                  \
-               USER(ast_vm_user, language, AST_DATA_STRING)                    \
-               USER(ast_vm_user, zonetag, AST_DATA_STRING)                     \
-               USER(ast_vm_user, callback, AST_DATA_STRING)                    \
-               USER(ast_vm_user, dialout, AST_DATA_STRING)                     \
-               USER(ast_vm_user, uniqueid, AST_DATA_STRING)                    \
-               USER(ast_vm_user, exit, AST_DATA_STRING)                        \
-               USER(ast_vm_user, attachfmt, AST_DATA_STRING)                   \
-               USER(ast_vm_user, flags, AST_DATA_UNSIGNED_INTEGER)             \
-               USER(ast_vm_user, saydurationm, AST_DATA_INTEGER)               \
-               USER(ast_vm_user, maxmsg, AST_DATA_INTEGER)                     \
-               USER(ast_vm_user, maxdeletedmsg, AST_DATA_INTEGER)              \
-               USER(ast_vm_user, maxsecs, AST_DATA_INTEGER)                    \
-               USER(ast_vm_user, imapuser, AST_DATA_STRING)                    \
-               USER(ast_vm_user, imappassword, AST_DATA_STRING)                \
-               USER(ast_vm_user, imapvmshareid, AST_DATA_STRING)               \
-               USER(ast_vm_user, volgain, AST_DATA_DOUBLE)
-#else
-       #define DATA_EXPORT_VM_USERS(USER)                                      \
-               USER(ast_vm_user, context, AST_DATA_STRING)                     \
-               USER(ast_vm_user, mailbox, AST_DATA_STRING)                     \
-               USER(ast_vm_user, password, AST_DATA_PASSWORD)                  \
-               USER(ast_vm_user, fullname, AST_DATA_STRING)                    \
-               USER(ast_vm_user, email, AST_DATA_STRING)                       \
-               USER(ast_vm_user, emailsubject, AST_DATA_STRING)                \
-               USER(ast_vm_user, emailbody, AST_DATA_STRING)                   \
-               USER(ast_vm_user, pager, AST_DATA_STRING)                       \
-               USER(ast_vm_user, serveremail, AST_DATA_STRING)                 \
-               USER(ast_vm_user, fromstring, AST_DATA_STRING)                  \
-               USER(ast_vm_user, language, AST_DATA_STRING)                    \
-               USER(ast_vm_user, zonetag, AST_DATA_STRING)                     \
-               USER(ast_vm_user, callback, AST_DATA_STRING)                    \
-               USER(ast_vm_user, dialout, AST_DATA_STRING)                     \
-               USER(ast_vm_user, uniqueid, AST_DATA_STRING)                    \
-               USER(ast_vm_user, exit, AST_DATA_STRING)                        \
-               USER(ast_vm_user, attachfmt, AST_DATA_STRING)                   \
-               USER(ast_vm_user, flags, AST_DATA_UNSIGNED_INTEGER)             \
-               USER(ast_vm_user, saydurationm, AST_DATA_INTEGER)               \
-               USER(ast_vm_user, maxmsg, AST_DATA_INTEGER)                     \
-               USER(ast_vm_user, maxdeletedmsg, AST_DATA_INTEGER)              \
-               USER(ast_vm_user, maxsecs, AST_DATA_INTEGER)                    \
-               USER(ast_vm_user, volgain, AST_DATA_DOUBLE)
-#endif
-
-AST_DATA_STRUCTURE(ast_vm_user, DATA_EXPORT_VM_USERS);
-
-#define DATA_EXPORT_VM_ZONES(ZONE)                     \
-       ZONE(vm_zone, name, AST_DATA_STRING)            \
-       ZONE(vm_zone, timezone, AST_DATA_STRING)        \
-       ZONE(vm_zone, msg_format, AST_DATA_STRING)
-
-AST_DATA_STRUCTURE(vm_zone, DATA_EXPORT_VM_ZONES);
-
-/*!
- * \internal
- * \brief Add voicemail user to the data_root.
- * \param[in] search The search tree.
- * \param[in] data_root The main result node.
- * \param[in] user The voicemail user.
- */
-static int vm_users_data_provider_get_helper(const struct ast_data_search *search,
-    struct ast_data *data_root, struct ast_vm_user *user)
-{
-       struct ast_data *data_user, *data_zone;
-       struct ast_data *data_state;
-       struct vm_zone *zone = NULL;
-       int urgentmsg = 0, newmsg = 0, oldmsg = 0;
-       char ext_context[256] = "";
-
-       data_user = ast_data_add_node(data_root, "user");
-       if (!data_user) {
-               return -1;
-       }
-
-       ast_data_add_structure(ast_vm_user, data_user, user);
-
-       AST_LIST_LOCK(&zones);
-       AST_LIST_TRAVERSE(&zones, zone, list) {
-               if (!strcmp(zone->name, user->zonetag)) {
-                       break;
-               }
-       }
-       AST_LIST_UNLOCK(&zones);
-
-       /* state */
-       data_state = ast_data_add_node(data_user, "state");
-       if (!data_state) {
-               return -1;
-       }
-       snprintf(ext_context, sizeof(ext_context), "%s@%s", user->mailbox, user->context);
-       inboxcount2(ext_context, &urgentmsg, &newmsg, &oldmsg);
-       ast_data_add_int(data_state, "urgentmsg", urgentmsg);
-       ast_data_add_int(data_state, "newmsg", newmsg);
-       ast_data_add_int(data_state, "oldmsg", oldmsg);
-
-       if (zone) {
-               data_zone = ast_data_add_node(data_user, "zone");
-               ast_data_add_structure(vm_zone, data_zone, zone);
-       }
-
-       if (!ast_data_search_match(search, data_user)) {
-               ast_data_remove_node(data_root, data_user);
-       }
-
-       return 0;
-}
-
-static int vm_users_data_provider_get(const struct ast_data_search *search,
-       struct ast_data *data_root)
-{
-       struct ast_vm_user *user;
-
-       AST_LIST_LOCK(&users);
-       AST_LIST_TRAVERSE(&users, user, list) {
-               vm_users_data_provider_get_helper(search, data_root, user);
-       }
-       AST_LIST_UNLOCK(&users);
-
-       return 0;
-}
-
-static const struct ast_data_handler vm_users_data_provider = {
-       .version = AST_DATA_HANDLER_VERSION,
-       .get = vm_users_data_provider_get
-};
-
-static const struct ast_data_entry vm_data_providers[] = {
-       AST_DATA_ENTRY("asterisk/application/voicemail/list", &vm_users_data_provider)
-};
-
 static void poll_subscribed_mailbox(struct mwi_sub *mwi_sub)
 {
        int new = 0, old = 0, urgent = 0;
 
        inboxcount2(mwi_sub->mailbox, &urgent, &new, &old);
 
+#ifdef IMAP_STORAGE
+       if (imap_poll_logout) {
+               imap_logout(mwi_sub->mailbox);
+       }
+#endif
+
        if (urgent != mwi_sub->old_urgent || new != mwi_sub->old_new || old != mwi_sub->old_old) {
                mwi_sub->old_urgent = urgent;
                mwi_sub->old_new = new;
@@ -13134,10 +12995,25 @@ static void imap_logout(const char *mailbox_id)
                return;
        }
 
+       ast_mutex_lock(&vms->lock);
        vms->mailstream = mail_close(vms->mailstream);
+       ast_mutex_unlock(&vms->lock);
+
        vmstate_delete(vms);
 }
 
+static void imap_close_subscribed_mailboxes(void)
+{
+       struct mwi_sub *mwi_sub;
+
+       AST_RWLIST_RDLOCK(&mwi_subs);
+       AST_RWLIST_TRAVERSE(&mwi_subs, mwi_sub, entry) {
+               if (!ast_strlen_zero(mwi_sub->mailbox)) {
+                       imap_logout(mwi_sub->mailbox);
+               }
+       }
+       AST_RWLIST_UNLOCK(&mwi_subs);
+}
 #endif
 
 static int handle_unsubscribe(void *datap)
@@ -13591,7 +13467,11 @@ static int actual_load_config(int reload, struct ast_config *cfg, struct ast_con
        strcpy(listen_control_restart_key, DEFAULT_LISTEN_CONTROL_RESTART_KEY);
        strcpy(listen_control_stop_key, DEFAULT_LISTEN_CONTROL_STOP_KEY);
 
-       /* Free all the users structure */      
+#ifdef IMAP_STORAGE
+       imap_close_subscribed_mailboxes();
+#endif
+
+       /* Free all the users structure */
        free_vm_users();
 
        /* Free all the zones structure */
@@ -13756,6 +13636,11 @@ static int actual_load_config(int reload, struct ast_config *cfg, struct ast_con
                } else {
                        ast_copy_string(greetingfolder, imapfolder, sizeof(greetingfolder));
                }
+               if ((val = ast_variable_retrieve(cfg, "general", "imap_poll_logout"))) {
+                       imap_poll_logout = ast_true(val);
+               } else {
+                       imap_poll_logout = 0;
+               }
 
                /* There is some very unorthodox casting done here. This is due
                 * to the way c-client handles the argument passed in. It expects a 
@@ -14961,7 +14846,6 @@ static int unload_module(void)
        res |= ast_custom_function_unregister(&vm_info_acf);
        res |= ast_manager_unregister("VoicemailUsersList");
        res |= ast_manager_unregister("VoicemailRefresh");
-       res |= ast_data_unregister(NULL);
 #ifdef TEST_FRAMEWORK
        res |= AST_TEST_UNREGISTER(test_voicemail_vmsayname);
        res |= AST_TEST_UNREGISTER(test_voicemail_msgcount);
@@ -14985,6 +14869,9 @@ static int unload_module(void)
        ast_unload_realtime("voicemail");
        ast_unload_realtime("voicemail_data");
 
+#ifdef IMAP_STORAGE
+       imap_close_subscribed_mailboxes();
+#endif
        free_vm_users();
        free_vm_zones();
        return res;
@@ -15068,7 +14955,6 @@ static int load_module(void)
        }
 
        ast_cli_register_multiple(cli_voicemail, ARRAY_LEN(cli_voicemail));
-       ast_data_register_multiple(vm_data_providers, ARRAY_LEN(vm_data_providers));
 
 #ifdef TEST_FRAMEWORK
        ast_install_vm_test_functions(vm_test_create_user, vm_test_destroy_user);
index cc8fcfe..bfd9f4f 100644 (file)
                                                </enumlist>
                                        </description>
                                </configOption>
+                               <configOption name="video_update_discard" default="2000">
+                                       <synopsis>Sets the amount of time in milliseconds after sending a video update to discard subsequent video updates</synopsis>
+                                       <description><para>
+                                               Sets the amount of time in milliseconds after sending a video update request
+                                               that subsequent video updates should be discarded. This means that if we
+                                               send a video update we will discard any other video update requests until
+                                               after the configured amount of time has elapsed. This prevents flooding of
+                                               video update requests from clients.
+                                       </para></description>
+                               </configOption>
                                <configOption name="template">
                                        <synopsis>When using the CONFBRIDGE dialplan function, use a bridge profile as a template for creating a new temporary profile</synopsis>
                                </configOption>
@@ -1652,6 +1662,8 @@ static char *handle_cli_confbridge_show_bridge_profile(struct ast_cli_entry *e,
                break;
        }
 
+       ast_cli(a->fd,"Video Update Discard: %u\n", b_profile.video_update_discard);
+
        ast_cli(a->fd,"sound_only_person:    %s\n", conf_get_sound(CONF_SOUND_ONLY_PERSON, b_profile.sounds));
        ast_cli(a->fd,"sound_only_one:       %s\n", conf_get_sound(CONF_SOUND_ONLY_ONE, b_profile.sounds));
        ast_cli(a->fd,"sound_has_joined:     %s\n", conf_get_sound(CONF_SOUND_HAS_JOINED, b_profile.sounds));
@@ -2220,6 +2232,7 @@ int conf_load_config(void)
        aco_option_register(&cfg_info, "regcontext", ACO_EXACT, bridge_types, NULL, OPT_CHAR_ARRAY_T, 0, CHARFLDSET(struct bridge_profile, regcontext));
        aco_option_register(&cfg_info, "language", ACO_EXACT, bridge_types, "en", OPT_CHAR_ARRAY_T, 0, CHARFLDSET(struct bridge_profile, language));
        aco_option_register_custom(&cfg_info, "^sound_", ACO_REGEX, bridge_types, NULL, sound_option_handler, 0);
+       aco_option_register(&cfg_info, "video_update_discard", ACO_EXACT, bridge_types, "2000", OPT_UINT_T, 0, FLDSET(struct bridge_profile, video_update_discard));
        /* This option should only be used with the CONFBRIDGE dialplan function */
        aco_option_register_custom(&cfg_info, "template", ACO_EXACT, bridge_types, NULL, bridge_template_handler, 0);
 
index cf30d5c..adf9b86 100644 (file)
@@ -218,6 +218,7 @@ struct bridge_profile {
        unsigned int mix_interval;  /*!< The internal mixing interval used by the bridge. When set to 0 the bridgewill use a default interval. */
        struct bridge_profile_sounds *sounds;
        char regcontext[AST_MAX_CONTEXT];
+       unsigned int video_update_discard; /*!< Amount of time after sending a video update request that subsequent requests should be discarded */
 };
 
 /*! \brief The structure that represents a conference bridge */
index 4af93bf..02b27e1 100644 (file)
 #include "asterisk/frame.h"
 #include "asterisk/rtp_engine.h"
 
-/*! \brief Internal structure which contains information about bridged RTP channels */
-struct native_rtp_bridge_data {
+/*! \brief Internal structure which contains bridged RTP channel hook data */
+struct native_rtp_framehook_data {
        /*! \brief Framehook used to intercept certain control frames */
        int id;
        /*! \brief Set when this framehook has been detached */
        unsigned int detached;
 };
 
-/*! \brief Internal helper function which gets all RTP information (glue and instances) relating to the given channels */
-static enum ast_rtp_glue_result native_rtp_bridge_get(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp_glue **glue0,
-       struct ast_rtp_glue **glue1, struct ast_rtp_instance **instance0, struct ast_rtp_instance **instance1,
-       struct ast_rtp_instance **vinstance0, struct ast_rtp_instance **vinstance1)
+struct rtp_glue_stream {
+       /*! \brief RTP instance */
+       struct ast_rtp_instance *instance;
+       /*! \brief glue result */
+       enum ast_rtp_glue_result result;
+};
+
+struct rtp_glue_data {
+       /*!
+        * \brief glue callbacks
+        *
+        * \note The glue data is considered valid if cb is not NULL.
+        */
+       struct ast_rtp_glue *cb;
+       struct rtp_glue_stream audio;
+       struct rtp_glue_stream video;
+       /*! Combined glue result of both bridge channels. */
+       enum ast_rtp_glue_result result;
+};
+
+/*! \brief Internal structure which contains instance information about bridged RTP channels */
+struct native_rtp_bridge_channel_data {
+       /*! \brief Channel's hook data */
+       struct native_rtp_framehook_data *hook_data;
+       /*!
+        * \brief Glue callbacks to bring remote channel streams back to Asterisk.
+        * \note NULL if channel streams are local.
+        */
+       struct ast_rtp_glue *remote_cb;
+       /*! \brief Channel's cached RTP glue information */
+       struct rtp_glue_data glue;
+};
+
+static void rtp_glue_data_init(struct rtp_glue_data *glue)
 {
-       enum ast_rtp_glue_result audio_glue0_res;
-       enum ast_rtp_glue_result video_glue0_res;
-       enum ast_rtp_glue_result audio_glue1_res;
-       enum ast_rtp_glue_result video_glue1_res;
+       glue->cb = NULL;
+       glue->audio.instance = NULL;
+       glue->audio.result = AST_RTP_GLUE_RESULT_FORBID;
+       glue->video.instance = NULL;
+       glue->video.result = AST_RTP_GLUE_RESULT_FORBID;
+       glue->result = AST_RTP_GLUE_RESULT_FORBID;
+}
 
-       if (!(*glue0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type)) ||
-               !(*glue1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type))) {
-               return AST_RTP_GLUE_RESULT_FORBID;
+static void rtp_glue_data_destroy(struct rtp_glue_data *glue)
+{
+       if (!glue) {
+               return;
        }
+       ao2_cleanup(glue->audio.instance);
+       ao2_cleanup(glue->video.instance);
+}
+
+static void rtp_glue_data_reset(struct rtp_glue_data *glue)
+{
+       rtp_glue_data_destroy(glue);
+       rtp_glue_data_init(glue);
+}
+
+static void native_rtp_bridge_channel_data_free(struct native_rtp_bridge_channel_data *data)
+{
+       ast_debug(2, "Destroying channel tech_pvt data %p\n", data);
 
-       audio_glue0_res = (*glue0)->get_rtp_info(c0, instance0);
-       video_glue0_res = (*glue0)->get_vrtp_info ? (*glue0)->get_vrtp_info(c0, vinstance0) : AST_RTP_GLUE_RESULT_FORBID;
+       /*
+        * hook_data will probably already have been unreferenced by the framehook detach
+        * and the pointer set to null.
+        */
+       ao2_cleanup(data->hook_data);
 
-       audio_glue1_res = (*glue1)->get_rtp_info(c1, instance1);
-       video_glue1_res = (*glue1)->get_vrtp_info ? (*glue1)->get_vrtp_info(c1, vinstance1) : AST_RTP_GLUE_RESULT_FORBID;
+       rtp_glue_data_reset(&data->glue);
+       ast_free(data);
+}
+
+static struct native_rtp_bridge_channel_data *native_rtp_bridge_channel_data_alloc(void)
+{
+       struct native_rtp_bridge_channel_data *data;
+
+       data = ast_calloc(1, sizeof(*data));
+       if (data) {
+               rtp_glue_data_init(&data->glue);
+       }
+       return data;
+}
+
+/*!
+ * \internal
+ * \brief Helper function which gets all RTP information (glue and instances) relating to the given channels
+ *
+ * \retval 0 on success.
+ * \retval -1 on error.
+ */
+static int rtp_glue_data_get(struct ast_channel *c0, struct rtp_glue_data *glue0,
+       struct ast_channel *c1, struct rtp_glue_data *glue1)
+{
+       struct ast_rtp_glue *cb0;
+       struct ast_rtp_glue *cb1;
+       enum ast_rtp_glue_result combined_result;
+
+       cb0 = ast_rtp_instance_get_glue(ast_channel_tech(c0)->type);
+       cb1 = ast_rtp_instance_get_glue(ast_channel_tech(c1)->type);
+       if (!cb0 || !cb1) {
+               /* One or both channels doesn't have any RTP glue registered. */
+               return -1;
+       }
+
+       /* The glue callbacks bump the RTP instance refcounts for us. */
+
+       glue0->cb = cb0;
+       glue0->audio.result = cb0->get_rtp_info(c0, &glue0->audio.instance);
+       glue0->video.result = cb0->get_vrtp_info
+               ? cb0->get_vrtp_info(c0, &glue0->video.instance) : AST_RTP_GLUE_RESULT_FORBID;
+
+       glue1->cb = cb1;
+       glue1->audio.result = cb1->get_rtp_info(c1, &glue1->audio.instance);
+       glue1->video.result = cb1->get_vrtp_info
+               ? cb1->get_vrtp_info(c1, &glue1->video.instance) : AST_RTP_GLUE_RESULT_FORBID;
+
+       /*
+        * Now determine the combined glue result.
+        */
 
        /* Apply any limitations on direct media bridging that may be present */
-       if (audio_glue0_res == audio_glue1_res && audio_glue1_res == AST_RTP_GLUE_RESULT_REMOTE) {
-               if ((*glue0)->allow_rtp_remote && !((*glue0)->allow_rtp_remote(c0, *instance1))) {
+       if (glue0->audio.result == glue1->audio.result && glue1->audio.result == AST_RTP_GLUE_RESULT_REMOTE) {
+               if (glue0->cb->allow_rtp_remote && !glue0->cb->allow_rtp_remote(c0, glue1->audio.instance)) {
                        /* If the allow_rtp_remote indicates that remote isn't allowed, revert to local bridge */
-                       audio_glue0_res = audio_glue1_res = AST_RTP_GLUE_RESULT_LOCAL;
-               } else if ((*glue1)->allow_rtp_remote && !((*glue1)->allow_rtp_remote(c1, *instance0))) {
-                       audio_glue0_res = audio_glue1_res = AST_RTP_GLUE_RESULT_LOCAL;
+                       glue0->audio.result = glue1->audio.result = AST_RTP_GLUE_RESULT_LOCAL;
+               } else if (glue1->cb->allow_rtp_remote && !glue1->cb->allow_rtp_remote(c1, glue0->audio.instance)) {
+                       glue0->audio.result = glue1->audio.result = AST_RTP_GLUE_RESULT_LOCAL;
                }
        }
-       if (video_glue0_res == video_glue1_res && video_glue1_res == AST_RTP_GLUE_RESULT_REMOTE) {
-               if ((*glue0)->allow_vrtp_remote && !((*glue0)->allow_vrtp_remote(c0, *instance1))) {
-                       /* if the allow_vrtp_remote indicates that remote isn't allowed, revert to local bridge */
-                       video_glue0_res = video_glue1_res = AST_RTP_GLUE_RESULT_LOCAL;
-               } else if ((*glue1)->allow_vrtp_remote && !((*glue1)->allow_vrtp_remote(c1, *instance0))) {
-                       video_glue0_res = video_glue1_res = AST_RTP_GLUE_RESULT_LOCAL;
+       if (glue0->video.result == glue1->video.result && glue1->video.result == AST_RTP_GLUE_RESULT_REMOTE) {
+               if (glue0->cb->allow_vrtp_remote && !glue0->cb->allow_vrtp_remote(c0, glue1->video.instance)) {
+                       /* If the allow_vrtp_remote indicates that remote isn't allowed, revert to local bridge */
+                       glue0->video.result = glue1->video.result = AST_RTP_GLUE_RESULT_LOCAL;
+               } else if (glue1->cb->allow_vrtp_remote && !glue1->cb->allow_vrtp_remote(c1, glue0->video.instance)) {
+                       glue0->video.result = glue1->video.result = AST_RTP_GLUE_RESULT_LOCAL;
                }
        }
 
        /* If we are carrying video, and both sides are not going to remotely bridge... fail the native bridge */
-       if (video_glue0_res != AST_RTP_GLUE_RESULT_FORBID
-               && (audio_glue0_res != AST_RTP_GLUE_RESULT_REMOTE
-                       || video_glue0_res != AST_RTP_GLUE_RESULT_REMOTE)) {
-               audio_glue0_res = AST_RTP_GLUE_RESULT_FORBID;
+       if (glue0->video.result != AST_RTP_GLUE_RESULT_FORBID
+               && (glue0->audio.result != AST_RTP_GLUE_RESULT_REMOTE
+                       || glue0->video.result != AST_RTP_GLUE_RESULT_REMOTE)) {
+               glue0->audio.result = AST_RTP_GLUE_RESULT_FORBID;
        }
-       if (video_glue1_res != AST_RTP_GLUE_RESULT_FORBID
-               && (audio_glue1_res != AST_RTP_GLUE_RESULT_REMOTE
-                       || video_glue1_res != AST_RTP_GLUE_RESULT_REMOTE)) {
-               audio_glue1_res = AST_RTP_GLUE_RESULT_FORBID;
+       if (glue1->video.result != AST_RTP_GLUE_RESULT_FORBID
+               && (glue1->audio.result != AST_RTP_GLUE_RESULT_REMOTE
+                       || glue1->video.result != AST_RTP_GLUE_RESULT_REMOTE)) {
+               glue1->audio.result = AST_RTP_GLUE_RESULT_FORBID;
        }
 
        /* The order of preference is: forbid, local, and remote. */
-       if (audio_glue0_res == AST_RTP_GLUE_RESULT_FORBID ||
-               audio_glue1_res == AST_RTP_GLUE_RESULT_FORBID) {
+       if (glue0->audio.result == AST_RTP_GLUE_RESULT_FORBID
+               || glue1->audio.result == AST_RTP_GLUE_RESULT_FORBID) {
                /* If any sort of bridge is forbidden just completely bail out and go back to generic bridging */
-               return AST_RTP_GLUE_RESULT_FORBID;
-       } else if (audio_glue0_res == AST_RTP_GLUE_RESULT_LOCAL ||
-               audio_glue1_res == AST_RTP_GLUE_RESULT_LOCAL) {
-               return AST_RTP_GLUE_RESULT_LOCAL;
+               combined_result = AST_RTP_GLUE_RESULT_FORBID;
+       } else if (glue0->audio.result == AST_RTP_GLUE_RESULT_LOCAL
+               || glue1->audio.result == AST_RTP_GLUE_RESULT_LOCAL) {
+               combined_result = AST_RTP_GLUE_RESULT_LOCAL;
        } else {
-               return AST_RTP_GLUE_RESULT_REMOTE;
+               combined_result = AST_RTP_GLUE_RESULT_REMOTE;
+       }
+       glue0->result = combined_result;
+       glue1->result = combined_result;
+
+       return 0;
+}
+
+/*!
+ * \internal
+ * \brief Get the current RTP native bridge combined glue result.
+ * \since 15.0.0
+ *
+ * \param c0 First bridge channel
+ * \param c1 Second bridge channel
+ *
+ * \note Both channels must be locked when calling this function.
+ *
+ * \return Current combined glue result.
+ */
+static enum ast_rtp_glue_result rtp_glue_get_current_combined_result(struct ast_channel *c0,
+       struct ast_channel *c1)
+{
+       struct rtp_glue_data glue_a;
+       struct rtp_glue_data glue_b;
+       struct rtp_glue_data *glue0;
+       struct rtp_glue_data *glue1;
+       enum ast_rtp_glue_result combined_result;
+
+       rtp_glue_data_init(&glue_a);
+       glue0 = &glue_a;
+       rtp_glue_data_init(&glue_b);
+       glue1 = &glue_b;
+       if (rtp_glue_data_get(c0, glue0, c1, glue1)) {
+               return AST_RTP_GLUE_RESULT_FORBID;
        }
+
+       combined_result = glue0->result;
+       rtp_glue_data_destroy(glue0);
+       rtp_glue_data_destroy(glue1);
+       return combined_result;
 }
 
 /*!
@@ -129,52 +267,91 @@ static void native_rtp_bridge_start(struct ast_bridge *bridge, struct ast_channe
 {
        struct ast_bridge_channel *bc0 = AST_LIST_FIRST(&bridge->channels);
        struct ast_bridge_channel *bc1 = AST_LIST_LAST(&bridge->channels);
-       enum ast_rtp_glue_result native_type = AST_RTP_GLUE_RESULT_FORBID;
-       struct ast_rtp_glue *glue0, *glue1;
-       RAII_VAR(struct ast_rtp_instance *, instance0, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_rtp_instance *, instance1, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_rtp_instance *, vinstance0, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_rtp_instance *, vinstance1, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_rtp_instance *, tinstance0, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_rtp_instance *, tinstance1, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_format_cap *, cap0, ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT), ao2_cleanup);
-       RAII_VAR(struct ast_format_cap *, cap1, ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT), ao2_cleanup);
+       struct native_rtp_bridge_channel_data *data0;
+       struct native_rtp_bridge_channel_data *data1;
+       struct rtp_glue_data *glue0;
+       struct rtp_glue_data *glue1;
+       struct ast_format_cap *cap0;
+       struct ast_format_cap *cap1;
+       enum ast_rtp_glue_result native_type;
 
        if (bc0 == bc1) {
                return;
        }
+       data0 = bc0->tech_pvt;
+       data1 = bc1->tech_pvt;
+       if (!data0 || !data1) {
+               /* Not all channels are joined with the bridge tech yet */
+               return;
+       }
+       glue0 = &data0->glue;
+       glue1 = &data1->glue;
 
        ast_channel_lock_both(bc0->chan, bc1->chan);
-       if (!bc0->suspended && !bc1->suspended) {
-               native_type = native_rtp_bridge_get(bc0->chan, bc1->chan, &glue0, &glue1, &instance0, &instance1, &vinstance0, &vinstance1);
+
+       if (!glue0->cb || !glue1->cb) {
+               /*
+                * Somebody doesn't have glue data so the bridge isn't running
+                *
+                * Actually neither side should have glue data.
+                */
+               ast_assert(!glue0->cb && !glue1->cb);
+
+               if (rtp_glue_data_get(bc0->chan, glue0, bc1->chan, glue1)) {
+                       /*
+                        * This might happen if one of the channels got masqueraded
+                        * at a critical time.  It's a bit of a stretch even then
+                        * since the channel is in a bridge.
+                        */
+                       goto done;
+               }
        }
 
+       ast_debug(2, "Bridge '%s'.  Tech starting '%s' and '%s' with target '%s'\n",
+               bridge->uniqueid, ast_channel_name(bc0->chan), ast_channel_name(bc1->chan),
+               target ? ast_channel_name(target) : "none");
+
+       native_type = glue0->result;
+
        switch (native_type) {
        case AST_RTP_GLUE_RESULT_LOCAL:
-               if (ast_rtp_instance_get_engine(instance0)->local_bridge) {
-                       ast_rtp_instance_get_engine(instance0)->local_bridge(instance0, instance1);
+               if (ast_rtp_instance_get_engine(glue0->audio.instance)->local_bridge) {
+                       ast_rtp_instance_get_engine(glue0->audio.instance)->local_bridge(glue0->audio.instance, glue1->audio.instance);
                }
-               if (ast_rtp_instance_get_engine(instance1)->local_bridge) {
-                       ast_rtp_instance_get_engine(instance1)->local_bridge(instance1, instance0);
+               if (ast_rtp_instance_get_engine(glue1->audio.instance)->local_bridge) {
+                       ast_rtp_instance_get_engine(glue1->audio.instance)->local_bridge(glue1->audio.instance, glue0->audio.instance);
                }
-               ast_rtp_instance_set_bridged(instance0, instance1);
-               ast_rtp_instance_set_bridged(instance1, instance0);
+               ast_rtp_instance_set_bridged(glue0->audio.instance, glue1->audio.instance);
+               ast_rtp_instance_set_bridged(glue1->audio.instance, glue0->audio.instance);
                ast_verb(4, "Locally RTP bridged '%s' and '%s' in stack\n",
                        ast_channel_name(bc0->chan), ast_channel_name(bc1->chan));
                break;
-
        case AST_RTP_GLUE_RESULT_REMOTE:
-               if (glue0->get_codec) {
-                       glue0->get_codec(bc0->chan, cap0);
+               cap0 = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
+               cap1 = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
+               if (!cap0 || !cap1) {
+                       ao2_cleanup(cap0);
+                       ao2_cleanup(cap1);
+                       break;
                }
-               if (glue1->get_codec) {
-                       glue1->get_codec(bc1->chan, cap1);
+
+               if (glue0->cb->get_codec) {
+                       glue0->cb->get_codec(bc0->chan, cap0);
+               }
+               if (glue1->cb->get_codec) {
+                       glue1->cb->get_codec(bc1->chan, cap1);
                }
 
-               /* If we have a target, it's the channel that received the UNHOLD or UPDATE_RTP_PEER frame and was told to resume */
+               /*
+                * If we have a target, it's the channel that received the UNHOLD or
+                * UPDATE_RTP_PEER frame and was told to resume
+                */
                if (!target) {
-                       glue0->update_peer(bc0->chan, instance1, vinstance1, tinstance1, cap1, 0);
-                       glue1->update_peer(bc1->chan, instance0, vinstance0, tinstance0, cap0, 0);
+                       /* Send both channels to remote */
+                       data0->remote_cb = glue0->cb;
+                       data1->remote_cb = glue1->cb;
+                       glue0->cb->update_peer(bc0->chan, glue1->audio.instance, glue1->video.instance, NULL, cap1, 0);
+                       glue1->cb->update_peer(bc1->chan, glue0->audio.instance, glue0->video.instance, NULL, cap0, 0);
                        ast_verb(4, "Remotely bridged '%s' and '%s' - media will flow directly between them\n",
                                ast_channel_name(bc0->chan), ast_channel_name(bc1->chan));
                } else {
@@ -184,51 +361,121 @@ static void native_rtp_bridge_start(struct ast_bridge *bridge, struct ast_channe
                         * already set up to handle the new media path or will have its own set of updates independent
                         * of this pass.
                         */
+                       ast_debug(2, "Bridge '%s'.  Sending '%s' back to remote\n",
+                               bridge->uniqueid, ast_channel_name(target));
                        if (bc0->chan == target) {
-                               glue0->update_peer(bc0->chan, instance1, vinstance1, tinstance1, cap1, 0);
+                               data0->remote_cb = glue0->cb;
+                               glue0->cb->update_peer(bc0->chan, glue1->audio.instance, glue1->video.instance, NULL, cap1, 0);
                        } else {
-                               glue1->update_peer(bc1->chan, instance0, vinstance0, tinstance0, cap0, 0);
+                               data1->remote_cb = glue1->cb;
+                               glue1->cb->update_peer(bc1->chan, glue0->audio.instance, glue0->video.instance, NULL, cap0, 0);
                        }
                }
+
+               ao2_cleanup(cap0);
+               ao2_cleanup(cap1);
                break;
        case AST_RTP_GLUE_RESULT_FORBID:
                break;
        }
 
+       if (native_type != AST_RTP_GLUE_RESULT_REMOTE) {
+               /* Bring any remaining channels back to us. */
+               if (data0->remote_cb) {
+                       ast_debug(2, "Bridge '%s'.  Bringing back '%s' to us\n",
+                               bridge->uniqueid, ast_channel_name(bc0->chan));
+                       data0->remote_cb->update_peer(bc0->chan, NULL, NULL, NULL, NULL, 0);
+                       data0->remote_cb = NULL;
+               }
+               if (data1->remote_cb) {
+                       ast_debug(2, "Bridge '%s'.  Bringing back '%s' to us\n",
+                               bridge->uniqueid, ast_channel_name(bc1->chan));
+                       data1->remote_cb->update_peer(bc1->chan, NULL, NULL, NULL, NULL, 0);
+                       data1->remote_cb = NULL;
+               }
+       }
+
+done:
        ast_channel_unlock(bc0->chan);
        ast_channel_unlock(bc1->chan);
 }
 
+/*!
+ * \internal
+ * \brief Stop native RTP bridging of two channels
+ *
+ * \param bridge The bridge that had native RTP bridging happening on it
+ * \param target If remote RTP bridging, the channel that is held.
+ *
+ * \note The first channel to leave the bridge triggers the cleanup for both channels
+ */
 static void native_rtp_bridge_stop(struct ast_bridge *bridge, struct ast_channel *target)
 {
        struct ast_bridge_channel *bc0 = AST_LIST_FIRST(&bridge->channels);
        struct ast_bridge_channel *bc1 = AST_LIST_LAST(&bridge->channels);
-       enum ast_rtp_glue_result native_type;
-       struct ast_rtp_glue *glue0, *glue1 = NULL;
-       RAII_VAR(struct ast_rtp_instance *, instance0, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_rtp_instance *, instance1, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_rtp_instance *, vinstance0, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_rtp_instance *, vinstance1, NULL, ao2_cleanup);
+       struct native_rtp_bridge_channel_data *data0;
+       struct native_rtp_bridge_channel_data *data1;
+       struct rtp_glue_data *glue0;
+       struct rtp_glue_data *glue1;
 
        if (bc0 == bc1) {
                return;
        }
+       data0 = bc0->tech_pvt;
+       data1 = bc1->tech_pvt;
+       if (!data0 || !data1) {
+               /* Not all channels are joined with the bridge tech */
+               return;
+       }
+       glue0 = &data0->glue;
+       glue1 = &data1->glue;
+
+       ast_debug(2, "Bridge '%s'.  Tech stopping '%s' and '%s' with target '%s'\n",
+               bridge->uniqueid, ast_channel_name(bc0->chan), ast_channel_name(bc1->chan),
+               target ? ast_channel_name(target) : "none");
+
+       if (!glue0->cb || !glue1->cb) {
+               /*
+                * Somebody doesn't have glue data so the bridge isn't running
+                *
+                * Actually neither side should have glue data.
+                */
+               ast_assert(!glue0->cb && !glue1->cb);
+               /* At most one channel can be left at the remote endpoint here. */
+               ast_assert(!data0->remote_cb || !data1->remote_cb);
+
+               /* Bring selected channel streams back to us */
+               if (data0->remote_cb && (!target || target == bc0->chan)) {
+                       ast_channel_lock(bc0->chan);
+                       ast_debug(2, "Bridge '%s'.  Bringing back '%s' to us\n",
+                               bridge->uniqueid, ast_channel_name(bc0->chan));
+                       data0->remote_cb->update_peer(bc0->chan, NULL, NULL, NULL, NULL, 0);
+                       data0->remote_cb = NULL;
+                       ast_channel_unlock(bc0->chan);
+               }
+               if (data1->remote_cb && (!target || target == bc1->chan)) {
+                       ast_channel_lock(bc1->chan);
+                       ast_debug(2, "Bridge '%s'.  Bringing back '%s' to us\n",
+                               bridge->uniqueid, ast_channel_name(bc1->chan));
+                       data1->remote_cb->update_peer(bc1->chan, NULL, NULL, NULL, NULL, 0);
+                       data1->remote_cb = NULL;
+                       ast_channel_unlock(bc1->chan);
+               }
+               return;
+       }
 
        ast_channel_lock_both(bc0->chan, bc1->chan);
-       native_type = native_rtp_bridge_get(bc0->chan, bc1->chan, &glue0, &glue1, &instance0, &instance1, &vinstance0, &vinstance1);
 
-       switch (native_type) {
+       switch (glue0->result) {
        case AST_RTP_GLUE_RESULT_LOCAL:
-               if (ast_rtp_instance_get_engine(instance0)->local_bridge) {
-                       ast_rtp_instance_get_engine(instance0)->local_bridge(instance0, NULL);
-               }
-               if (instance1 && ast_rtp_instance_get_engine(instance1)->local_bridge) {
-                       ast_rtp_instance_get_engine(instance1)->local_bridge(instance1, NULL);
+               if (ast_rtp_instance_get_engine(glue0->audio.instance)->local_bridge) {
+                       ast_rtp_instance_get_engine(glue0->audio.instance)->local_bridge(glue0->audio.instance, NULL);
                }
-               ast_rtp_instance_set_bridged(instance0, NULL);
-               if (instance1) {
-                       ast_rtp_instance_set_bridged(instance1, NULL);
+               if (ast_rtp_instance_get_engine(glue1->audio.instance)->local_bridge) {
+                       ast_rtp_instance_get_engine(glue1->audio.instance)->local_bridge(glue1->audio.instance, NULL);
                }
+               ast_rtp_instance_set_bridged(glue0->audio.instance, NULL);
+               ast_rtp_instance_set_bridged(glue1->audio.instance, NULL);
                break;
        case AST_RTP_GLUE_RESULT_REMOTE:
                if (target) {
@@ -236,10 +483,38 @@ static void native_rtp_bridge_stop(struct ast_bridge *bridge, struct ast_channel
                         * If a target was provided, it is being put on hold and should expect to
                         * receive media from Asterisk instead of what it was previously connected to.
                         */
+                       ast_debug(2, "Bridge '%s'.  Bringing back '%s' to us\n",
+                               bridge->uniqueid, ast_channel_name(target));
                        if (bc0->chan == target) {
-                               glue0->update_peer(bc0->chan, NULL, NULL, NULL, NULL, 0);
+                               data0->remote_cb = NULL;
+                               glue0->cb->update_peer(bc0->chan, NULL, NULL, NULL, NULL, 0);
+                       } else {
+                               data1->remote_cb = NULL;
+                               glue1->cb->update_peer(bc1->chan, NULL, NULL, NULL, NULL, 0);
+                       }
+               } else {
+                       data0->remote_cb = NULL;
+                       data1->remote_cb = NULL;
+                       /*
+                        * XXX We don't want to bring back the channels if we are
+                        * switching to T.38.  We have received a reinvite on one channel
+                        * and we will be sending a reinvite on the other to start T.38.
+                        * If we bring the streams back now we confuse the chan_pjsip
+                        * channel driver processing the incoming T.38 reinvite with
+                        * reinvite glare.  I think this is really a bug in chan_pjsip
+                        * that this exception case is working around.
+                        */
+                       if (rtp_glue_get_current_combined_result(bc0->chan, bc1->chan)
+                               != AST_RTP_GLUE_RESULT_FORBID) {
+                               ast_debug(2, "Bridge '%s'.  Bringing back '%s' and '%s' to us\n",
+                                       bridge->uniqueid, ast_channel_name(bc0->chan),
+                                       ast_channel_name(bc1->chan));
+                               glue0->cb->update_peer(bc0->chan, NULL, NULL, NULL, NULL, 0);
+                               glue1->cb->update_peer(bc1->chan, NULL, NULL, NULL, NULL, 0);
                        } else {
-                               glue1->update_peer(bc1->chan, NULL, NULL, NULL, NULL, 0);
+                               ast_debug(2, "Bridge '%s'.  Skip bringing back '%s' and '%s' to us\n",
+                                       bridge->uniqueid, ast_channel_name(bc0->chan),
+                                       ast_channel_name(bc1->chan));
                        }
                }
                break;
@@ -247,10 +522,8 @@ static void native_rtp_bridge_stop(struct ast_bridge *bridge, struct ast_channel
                break;
        }
 
-       if (!target && native_type != AST_RTP_GLUE_RESULT_FORBID) {
-               glue0->update_peer(bc0->chan, NULL, NULL, NULL, NULL, 0);
-               glue1->update_peer(bc1->chan, NULL, NULL, NULL, NULL, 0);
-       }
+       rtp_glue_data_reset(glue0);
+       rtp_glue_data_reset(glue1);
 
        ast_debug(2, "Discontinued RTP bridging of '%s' and '%s' - media will flow through Asterisk core\n",
                ast_channel_name(bc0->chan), ast_channel_name(bc1->chan));
@@ -259,11 +532,15 @@ static void native_rtp_bridge_stop(struct ast_bridge *bridge, struct ast_channel
        ast_channel_unlock(bc1->chan);
 }
 
-/*! \brief Frame hook that is called to intercept hold/unhold */
-static struct ast_frame *native_rtp_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data)
+/*!
+ * \internal
+ * \brief Frame hook that is called to intercept hold/unhold
+ */
+static struct ast_frame *native_rtp_framehook(struct ast_channel *chan,
+       struct ast_frame *f, enum ast_framehook_event event, void *data)
 {
        RAII_VAR(struct ast_bridge *, bridge, NULL, ao2_cleanup);
-       struct native_rtp_bridge_data *native_data = data;
+       struct native_rtp_framehook_data *native_data = data;
 
        if (!f || (event != AST_FRAMEHOOK_EVENT_WRITE)) {
                return f;
@@ -293,39 +570,49 @@ static struct ast_frame *native_rtp_framehook(struct ast_channel *chan, struct a
                }
                ast_bridge_unlock(bridge);
                ast_channel_lock(chan);
-
        }
 
        return f;
 }
 
-/*! \brief Callback function which informs upstream if we are consuming a frame of a specific type */
+/*!
+ * \internal
+ * \brief Callback function which informs upstream if we are consuming a frame of a specific type
+ */
 static int native_rtp_framehook_consume(void *data, enum ast_frame_type type)
 {
        return (type == AST_FRAME_CONTROL ? 1 : 0);
 }
 
-/*! \brief Internal helper function which checks whether the channels are compatible with our native bridging */
+/*!
+ * \internal
+ * \brief Internal helper function which checks whether a channel is compatible with our native bridging
+ */
 static int native_rtp_bridge_capable(struct ast_channel *chan)
 {
        return !ast_channel_has_hook_requiring_audio(chan);
 }
 
+/*!
+ * \internal
+ * \brief Internal helper function which checks whether both channels are compatible with our native bridging
+ */
 static int native_rtp_bridge_compatible_check(struct ast_bridge *bridge, struct ast_bridge_channel *bc0, struct ast_bridge_channel *bc1)
 {
        enum ast_rtp_glue_result native_type;
-       struct ast_rtp_glue *glue0;
-       struct ast_rtp_glue *glue1;
-       RAII_VAR(struct ast_rtp_instance *, instance0, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_rtp_instance *, instance1, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_rtp_instance *, vinstance0, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_rtp_instance *, vinstance1, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_format_cap *, cap0, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_format_cap *, cap1, NULL, ao2_cleanup);
        int read_ptime0;
        int read_ptime1;
        int write_ptime0;
        int write_ptime1;
+       struct rtp_glue_data glue_a;
+       struct rtp_glue_data glue_b;
+       RAII_VAR(struct ast_format_cap *, cap0, NULL, ao2_cleanup);
+       RAII_VAR(struct ast_format_cap *, cap1, NULL, ao2_cleanup);
+       RAII_VAR(struct rtp_glue_data *, glue0, NULL, rtp_glue_data_destroy);
+       RAII_VAR(struct rtp_glue_data *, glue1, NULL, rtp_glue_data_destroy);
+
+       ast_debug(1, "Bridge '%s'.  Checking compatability for channels '%s' and '%s'\n",
+               bridge->uniqueid, ast_channel_name(bc0->chan), ast_channel_name(bc1->chan));
 
        if (!native_rtp_bridge_capable(bc0->chan)) {
                ast_debug(1, "Bridge '%s' can not use native RTP bridge as channel '%s' has features which prevent it\n",
@@ -339,8 +626,17 @@ static int native_rtp_bridge_compatible_check(struct ast_bridge *bridge, struct
                return 0;
        }
 
-       native_type = native_rtp_bridge_get(bc0->chan, bc1->chan, &glue0, &glue1,
-               &instance0, &instance1, &vinstance0, &vinstance1);
+       rtp_glue_data_init(&glue_a);
+       glue0 = &glue_a;
+       rtp_glue_data_init(&glue_b);
+       glue1 = &glue_b;
+       if (rtp_glue_data_get(bc0->chan, glue0, bc1->chan, glue1)) {
+               ast_debug(1, "Bridge '%s' can not use native RTP bridge as could not get details\n",
+                       bridge->uniqueid);
+               return 0;
+       }
+       native_type = glue0->result;
+
        if (native_type == AST_RTP_GLUE_RESULT_FORBID) {
                ast_debug(1, "Bridge '%s' can not use native RTP bridge as it was forbidden while getting details\n",
                        bridge->uniqueid);
@@ -348,25 +644,25 @@ static int native_rtp_bridge_compatible_check(struct ast_bridge *bridge, struct
        }
 
        if (ao2_container_count(bc0->features->dtmf_hooks)
-               && ast_rtp_instance_dtmf_mode_get(instance0)) {
+               && ast_rtp_instance_dtmf_mode_get(glue0->audio.instance)) {
                ast_debug(1, "Bridge '%s' can not use native RTP bridge as channel '%s' has DTMF hooks\n",
                        bridge->uniqueid, ast_channel_name(bc0->chan));
                return 0;
        }
 
        if (ao2_container_count(bc1->features->dtmf_hooks)
-               && ast_rtp_instance_dtmf_mode_get(instance1)) {
+               && ast_rtp_instance_dtmf_mode_get(glue1->audio.instance)) {
                ast_debug(1, "Bridge '%s' can not use native RTP bridge as channel '%s' has DTMF hooks\n",
                        bridge->uniqueid, ast_channel_name(bc1->chan));
                return 0;
        }
 
        if (native_type == AST_RTP_GLUE_RESULT_LOCAL
-               && (ast_rtp_instance_get_engine(instance0)->local_bridge
-                       != ast_rtp_instance_get_engine(instance1)->local_bridge
-                       || (ast_rtp_instance_get_engine(instance0)->dtmf_compatible
-                               && !ast_rtp_instance_get_engine(instance0)->dtmf_compatible(bc0->chan,
-                                       instance0, bc1->chan, instance1)))) {
+               && (ast_rtp_instance_get_engine(glue0->audio.instance)->local_bridge
+                       != ast_rtp_instance_get_engine(glue1->audio.instance)->local_bridge
+                       || (ast_rtp_instance_get_engine(glue0->audio.instance)->dtmf_compatible
+                               && !ast_rtp_instance_get_engine(glue0->audio.instance)->dtmf_compatible(bc0->chan,
+                                       glue0->audio.instance, bc1->chan, glue1->audio.instance)))) {
                ast_debug(1, "Bridge '%s' can not use local native RTP bridge as local bridge or DTMF is not compatible\n",
                        bridge->uniqueid);
                return 0;
@@ -379,11 +675,11 @@ static int native_rtp_bridge_compatible_check(struct ast_bridge *bridge, struct
        }
 
        /* Make sure that codecs match */
-       if (glue0->get_codec) {
-               glue0->get_codec(bc0->chan, cap0);
+       if (glue0->cb->get_codec) {
+               glue0->cb->get_codec(bc0->chan, cap0);
        }
-       if (glue1->get_codec) {
-               glue1->get_codec(bc1->chan, cap1);
+       if (glue1->cb->get_codec) {
+               glue1->cb->get_codec(bc1->chan, cap1);
        }
        if (ast_format_cap_count(cap0) != 0
                && ast_format_cap_count(cap1) != 0
@@ -413,6 +709,10 @@ static int native_rtp_bridge_compatible_check(struct ast_bridge *bridge, struct
        return 1;
 }
 
+/*!
+ * \internal
+ * \brief Called by the bridge core "compatible' callback
+ */
 static int native_rtp_bridge_compatible(struct ast_bridge *bridge)
 {
        struct ast_bridge_channel *bc0;
@@ -437,10 +737,13 @@ static int native_rtp_bridge_compatible(struct ast_bridge *bridge)
        return is_compatible;
 }
 
-/*! \brief Helper function which adds frame hook to bridge channel */
+/*!
+ * \internal
+ * \brief Helper function which adds frame hook to bridge channel
+ */
 static int native_rtp_bridge_framehook_attach(struct ast_bridge_channel *bridge_channel)
 {
-       struct native_rtp_bridge_data *data = ao2_alloc(sizeof(*data), NULL);
+       struct native_rtp_bridge_channel_data *data = bridge_channel->tech_pvt;
        static struct ast_framehook_interface hook = {
                .version = AST_FRAMEHOOK_INTERFACE_VERSION,
                .event_cb = native_rtp_framehook,
@@ -449,45 +752,82 @@ static int native_rtp_bridge_framehook_attach(struct ast_bridge_channel *bridge_
                .disable_inheritance = 1,
        };
 
-       if (!data) {
+       ast_assert(data->hook_data == NULL);
+       data->hook_data = ao2_alloc_options(sizeof(*data->hook_data), NULL,
+               AO2_ALLOC_OPT_LOCK_NOLOCK);
+       if (!data->hook_data) {
                return -1;
        }
 
+       ast_debug(2, "Bridge '%s'.  Attaching hook data %p to '%s'\n",
+               bridge_channel->bridge->uniqueid, data, ast_channel_name(bridge_channel->chan));
+
        ast_channel_lock(bridge_channel->chan);
-       hook.data = ao2_bump(data);
-       data->id = ast_framehook_attach(bridge_channel->chan, &hook);
+       /* We're giving 1 ref to the framehook and keeping the one from the alloc for ourselves */
+       hook.data = ao2_bump(data->hook_data);
+       data->hook_data->id = ast_framehook_attach(bridge_channel->chan, &hook);
        ast_channel_unlock(bridge_channel->chan);
-       if (data->id < 0) {
-               /* We need to drop both the reference we hold, and the one the framehook would hold */
-               ao2_ref(data, -2);
+       if (data->hook_data->id < 0) {
+               /*
+                * We need to drop both the reference we hold in data,
+                * and the one the framehook would hold.
+                */
+               ao2_ref(data->hook_data, -2);
+               data->hook_data = NULL;
+
                return -1;
        }
 
-       bridge_channel->tech_pvt = data;
-
        return 0;
 }
 
-/*! \brief Helper function which removes frame hook from bridge channel */
+/*!
+ * \internal
+ * \brief Helper function which removes frame hook from bridge channel
+ */
 static void native_rtp_bridge_framehook_detach(struct ast_bridge_channel *bridge_channel)
 {
-       RAII_VAR(struct native_rtp_bridge_data *, data, bridge_channel->tech_pvt, ao2_cleanup);
+       struct native_rtp_bridge_channel_data *data = bridge_channel->tech_pvt;
 
-       if (!data) {
+       if (!data || !data->hook_data) {
                return;
        }
 
+       ast_debug(2, "Bridge '%s'.  Detaching hook data %p from '%s'\n",
+               bridge_channel->bridge->uniqueid, data->hook_data, ast_channel_name(bridge_channel->chan));
+
        ast_channel_lock(bridge_channel->chan);
-       ast_framehook_detach(bridge_channel->chan, data->id);
-       data->detached = 1;
+       ast_framehook_detach(bridge_channel->chan, data->hook_data->id);
+       data->hook_data->detached = 1;
        ast_channel_unlock(bridge_channel->chan);
-       bridge_channel->tech_pvt = NULL;
+       ao2_cleanup(data->hook_data);
+       data->hook_data = NULL;
 }
 
+/*!
+ * \internal
+ * \brief Called by the bridge core 'join' callback for each channel joining he bridge
+ */
 static int native_rtp_bridge_join(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
 {
-       native_rtp_bridge_framehook_detach(bridge_channel);
+       ast_debug(2, "Bridge '%s'.  Channel '%s' is joining bridge tech\n",
+               bridge->uniqueid, ast_channel_name(bridge_channel->chan));
+
+       ast_assert(bridge_channel->tech_pvt == NULL);
+
+       if (bridge_channel->suspended) {
+               /* The channel will rejoin when it is unsuspended */
+               return 0;
+       }
+
+       bridge_channel->tech_pvt = native_rtp_bridge_channel_data_alloc();
+       if (!bridge_channel->tech_pvt) {
+               return -1;
+       }
+
        if (native_rtp_bridge_framehook_attach(bridge_channel)) {
+               native_rtp_bridge_channel_data_free(bridge_channel->tech_pvt);
+               bridge_channel->tech_pvt = NULL;
                return -1;
        }
 
@@ -495,15 +835,46 @@ static int native_rtp_bridge_join(struct ast_bridge *bridge, struct ast_bridge_c
        return 0;
 }
 
+/*!
+ * \internal
+ * \brief Add the channel back into the bridge
+ */
 static void native_rtp_bridge_unsuspend(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
 {
+       ast_debug(2, "Bridge '%s'.  Channel '%s' is unsuspended back to bridge tech\n",
+               bridge->uniqueid, ast_channel_name(bridge_channel->chan));
        native_rtp_bridge_join(bridge, bridge_channel);
 }
 
+/*!
+ * \internal
+ * \brief Leave the bridge
+ */
 static void native_rtp_bridge_leave(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
 {
+       ast_debug(2, "Bridge '%s'.  Channel '%s' is leaving bridge tech\n",
+               bridge->uniqueid, ast_channel_name(bridge_channel->chan));
+
+       if (!bridge_channel->tech_pvt) {
+               return;
+       }
+
        native_rtp_bridge_framehook_detach(bridge_channel);
        native_rtp_bridge_stop(bridge, NULL);
+
+       native_rtp_bridge_channel_data_free(bridge_channel->tech_pvt);
+       bridge_channel->tech_pvt = NULL;
+}
+
+/*!
+ * \internal
+ * \brief Suspend the channel from the bridge
+ */
+static void native_rtp_bridge_suspend(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
+{
+       ast_debug(2, "Bridge '%s'.  Channel '%s' is suspending from bridge tech\n",
+               bridge->uniqueid, ast_channel_name(bridge_channel->chan));
+       native_rtp_bridge_leave(bridge, bridge_channel);
 }
 
 static int native_rtp_bridge_write(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
@@ -548,7 +919,7 @@ static struct ast_bridge_technology native_rtp_bridge = {
        .join = native_rtp_bridge_join,
        .unsuspend = native_rtp_bridge_unsuspend,
        .leave = native_rtp_bridge_leave,
-       .suspend = native_rtp_bridge_leave,
+       .suspend = native_rtp_bridge_suspend,
        .write = native_rtp_bridge_write,
        .compatible = native_rtp_bridge_compatible,
 };
index ae877eb..c5428a8 100644 (file)
@@ -524,15 +524,32 @@ static int append_all_streams(struct ast_stream_topology *dest,
        const struct ast_stream_topology *source)
 {
        int i;
+       int dest_index = 0;
 
        for (i = 0; i < ast_stream_topology_get_count(source); ++i) {
                struct ast_stream *clone;
+               int added = 0;
 
                clone = ast_stream_clone(ast_stream_topology_get_stream(source, i), NULL);
                if (!clone) {
                        return -1;
                }
-               if (ast_stream_topology_append_stream(dest, clone) < 0) {
+
+               /* If we can reuse an existing removed stream then do so */
+               while (dest_index < ast_stream_topology_get_count(dest)) {
+                       struct ast_stream *stream = ast_stream_topology_get_stream(dest, dest_index);
+
+                       dest_index++;
+
+                       if (ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED) {
+                               ast_stream_topology_set_stream(dest, dest_index - 1, clone);
+                               added = 1;
+                               break;
+                       }
+               }
+
+               /* If no removed stream exists that we took the place of append the stream */
+               if (!added && ast_stream_topology_append_stream(dest, clone) < 0) {
                        ast_stream_free(clone);
                        return -1;
                }
@@ -600,7 +617,7 @@ static void sfu_topologies_on_join(struct ast_bridge_channel *joiner, struct ast
                if (participant == joiner) {
                        continue;
                }
-               participant_topology = ast_stream_topology_clone(ast_channel_get_stream_topology(joiner->chan));
+               participant_topology = ast_stream_topology_clone(ast_channel_get_stream_topology(participant->chan));
                if (!participant_topology) {
                        goto cleanup;
                }
@@ -701,14 +718,15 @@ static int remove_destination_streams(struct ast_stream_topology *dest,
 
                stream = ast_stream_topology_get_stream(source, i);
 
-               if (is_video_dest(stream, channel_name, NULL)) {
-                       continue;
-               }
-
                stream_clone = ast_stream_clone(stream, NULL);
                if (!stream_clone) {
                        continue;
                }
+
+               if (is_video_dest(stream, channel_name, NULL)) {
+                       ast_stream_set_state(stream_clone, AST_STREAM_STATE_REMOVED);
+               }
+
                if (ast_stream_topology_append_stream(dest, stream_clone) < 0) {
                        ast_stream_free(stream_clone);
                }
@@ -967,6 +985,8 @@ static void softmix_bridge_write_voice(struct ast_bridge *bridge, struct ast_bri
  */
 static int softmix_bridge_write_control(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
 {
+       struct softmix_bridge_data *softmix_data = bridge->tech_pvt;
+
        /*
         * XXX Softmix needs to use channel roles to determine what to
         * do with control frames.
@@ -974,7 +994,11 @@ static int softmix_bridge_write_control(struct ast_bridge *bridge, struct ast_br
 
        switch (frame->subclass.integer) {
        case AST_CONTROL_VIDUPDATE:
-               ast_bridge_queue_everyone_else(bridge, NULL, frame);
+               if (!bridge->softmix.video_mode.video_update_discard ||
+                       ast_tvdiff_ms(ast_tvnow(), softmix_data->last_video_update) > bridge->softmix.video_mode.video_update_discard) {
+                       ast_bridge_queue_everyone_else(bridge, NULL, frame);
+                       softmix_data->last_video_update = ast_tvnow();
+               }
                break;
        default:
                break;
@@ -1964,9 +1988,9 @@ AST_TEST_DEFINE(sfu_remove_destination_streams)
                int num_streams;
                int params_index[4];
        } removal_results[] = {
-               { "PJSIP/Bob-00000001", 3, { 0, 1, 3, -1 }, },
+               { "PJSIP/Bob-00000001", 4, { 0, 1, 2, 3 }, },
                { "PJSIP/Edward-00000004", 4, { 0, 1, 2, 3 }, },
-               { "", 2, { 0, 1, -1, -1 }, },
+               { "", 4, { 0, 1, 2, 3 }, },
        };
        struct ast_stream_topology *orig = NULL;
        struct ast_stream_topology *result = NULL;
@@ -2033,6 +2057,12 @@ AST_TEST_DEFINE(sfu_remove_destination_streams)
                                        ast_format_cap_get_names(ast_stream_get_formats(actual), &actual_str));
                                goto end;
                        }
+
+                       if (is_video_dest(actual, removal_results[i].channel_name, NULL) &&
+                               ast_stream_get_state(actual) != AST_STREAM_STATE_REMOVED) {
+                               ast_test_status_update(test, "Removed stream %s does not have a state of removed\n", ast_stream_get_name(actual));
+                               goto end;
+                       }
                }
        }
 
index 9daae4c..f93e663 100644 (file)
@@ -198,6 +198,8 @@ struct softmix_bridge_data {
         * (does not guarantee success)
         */
        unsigned int binaural_init;
+       /*! The last time a video update was sent into the bridge */
+       struct timeval last_video_update;
 };
 
 struct softmix_mixing_array {
index 72fbe6e..4f717ff 100644 (file)
 #include "asterisk/devicestate.h"
 #include "asterisk/paths.h"
 #include "asterisk/ccss.h"
-#include "asterisk/data.h"
 #include "asterisk/features_config.h"
 #include "asterisk/bridge.h"
 #include "asterisk/stasis_channels.h"
@@ -791,78 +790,6 @@ const char * const subnames[] = {
        "Threeway"
 };
 
-#define DATA_EXPORT_DAHDI_PVT(MEMBER)                                  \
-       MEMBER(dahdi_pvt, cid_rxgain, AST_DATA_DOUBLE)                  \
-       MEMBER(dahdi_pvt, rxgain, AST_DATA_DOUBLE)                      \
-       MEMBER(dahdi_pvt, txgain, AST_DATA_DOUBLE)                      \
-       MEMBER(dahdi_pvt, txdrc, AST_DATA_DOUBLE)                       \
-       MEMBER(dahdi_pvt, rxdrc, AST_DATA_DOUBLE)                       \
-       MEMBER(dahdi_pvt, adsi, AST_DATA_BOOLEAN)                       \
-       MEMBER(dahdi_pvt, answeronpolarityswitch, AST_DATA_BOOLEAN)     \
-       MEMBER(dahdi_pvt, busydetect, AST_DATA_BOOLEAN)                 \
-       MEMBER(dahdi_pvt, callreturn, AST_DATA_BOOLEAN)                 \
-       MEMBER(dahdi_pvt, callwaiting, AST_DATA_BOOLEAN)                \
-       MEMBER(dahdi_pvt, callwaitingcallerid, AST_DATA_BOOLEAN)        \
-       MEMBER(dahdi_pvt, cancallforward, AST_DATA_BOOLEAN)             \
-       MEMBER(dahdi_pvt, canpark, AST_DATA_BOOLEAN)                    \
-       MEMBER(dahdi_pvt, confirmanswer, AST_DATA_BOOLEAN)              \
-       MEMBER(dahdi_pvt, destroy, AST_DATA_BOOLEAN)                    \
-       MEMBER(dahdi_pvt, didtdd, AST_DATA_BOOLEAN)                     \
-       MEMBER(dahdi_pvt, dialednone, AST_DATA_BOOLEAN)                 \
-       MEMBER(dahdi_pvt, dialing, AST_DATA_BOOLEAN)                    \
-       MEMBER(dahdi_pvt, digital, AST_DATA_BOOLEAN)                    \
-       MEMBER(dahdi_pvt, dnd, AST_DATA_BOOLEAN)                        \
-       MEMBER(dahdi_pvt, echobreak, AST_DATA_BOOLEAN)                  \
-       MEMBER(dahdi_pvt, echocanbridged, AST_DATA_BOOLEAN)             \
-       MEMBER(dahdi_pvt, echocanon, AST_DATA_BOOLEAN)                  \
-       MEMBER(dahdi_pvt, faxhandled, AST_DATA_BOOLEAN)                 \
-       MEMBER(dahdi_pvt, usefaxbuffers, AST_DATA_BOOLEAN)              \
-       MEMBER(dahdi_pvt, bufferoverrideinuse, AST_DATA_BOOLEAN)        \
-       MEMBER(dahdi_pvt, firstradio, AST_DATA_BOOLEAN)                 \
-       MEMBER(dahdi_pvt, hanguponpolarityswitch, AST_DATA_BOOLEAN)     \
-       MEMBER(dahdi_pvt, hardwaredtmf, AST_DATA_BOOLEAN)               \
-       MEMBER(dahdi_pvt, hidecallerid, AST_DATA_BOOLEAN)               \
-       MEMBER(dahdi_pvt, hidecalleridname, AST_DATA_BOOLEAN)           \
-       MEMBER(dahdi_pvt, ignoredtmf, AST_DATA_BOOLEAN)                 \
-       MEMBER(dahdi_pvt, immediate, AST_DATA_BOOLEAN)                  \
-       MEMBER(dahdi_pvt, inalarm, AST_DATA_BOOLEAN)                    \
-       MEMBER(dahdi_pvt, mate, AST_DATA_BOOLEAN)                       \
-       MEMBER(dahdi_pvt, outgoing, AST_DATA_BOOLEAN)                   \
-       MEMBER(dahdi_pvt, permcallwaiting, AST_DATA_BOOLEAN)            \
-       MEMBER(dahdi_pvt, priindication_oob, AST_DATA_BOOLEAN)          \
-       MEMBER(dahdi_pvt, priexclusive, AST_DATA_BOOLEAN)               \
-       MEMBER(dahdi_pvt, pulse, AST_DATA_BOOLEAN)                      \
-       MEMBER(dahdi_pvt, pulsedial, AST_DATA_BOOLEAN)                  \
-       MEMBER(dahdi_pvt, restartpending, AST_DATA_BOOLEAN)             \
-       MEMBER(dahdi_pvt, restrictcid, AST_DATA_BOOLEAN)                \
-       MEMBER(dahdi_pvt, threewaycalling, AST_DATA_BOOLEAN)            \
-       MEMBER(dahdi_pvt, transfer, AST_DATA_BOOLEAN)                   \
-       MEMBER(dahdi_pvt, use_callerid, AST_DATA_BOOLEAN)               \
-       MEMBER(dahdi_pvt, use_callingpres, AST_DATA_BOOLEAN)            \
-       MEMBER(dahdi_pvt, usedistinctiveringdetection, AST_DATA_BOOLEAN)        \
-       MEMBER(dahdi_pvt, dahditrcallerid, AST_DATA_BOOLEAN)                    \
-       MEMBER(dahdi_pvt, transfertobusy, AST_DATA_BOOLEAN)                     \
-       MEMBER(dahdi_pvt, mwimonitor_neon, AST_DATA_BOOLEAN)                    \
-       MEMBER(dahdi_pvt, mwimonitor_fsk, AST_DATA_BOOLEAN)                     \
-       MEMBER(dahdi_pvt, mwimonitor_rpas, AST_DATA_BOOLEAN)                    \
-       MEMBER(dahdi_pvt, mwimonitoractive, AST_DATA_BOOLEAN)                   \
-       MEMBER(dahdi_pvt, mwisendactive, AST_DATA_BOOLEAN)                      \
-       MEMBER(dahdi_pvt, inservice, AST_DATA_BOOLEAN)                          \
-       MEMBER(dahdi_pvt, locallyblocked, AST_DATA_UNSIGNED_INTEGER)            \
-       MEMBER(dahdi_pvt, remotelyblocked, AST_DATA_UNSIGNED_INTEGER)           \
-       MEMBER(dahdi_pvt, manages_span_alarms, AST_DATA_BOOLEAN)                \
-       MEMBER(dahdi_pvt, use_smdi, AST_DATA_BOOLEAN)                           \
-       MEMBER(dahdi_pvt, context, AST_DATA_STRING)                             \
-       MEMBER(dahdi_pvt, defcontext, AST_DATA_STRING)                          \
-       MEMBER(dahdi_pvt, description, AST_DATA_STRING)                         \
-       MEMBER(dahdi_pvt, exten, AST_DATA_STRING)                               \
-       MEMBER(dahdi_pvt, language, AST_DATA_STRING)                            \
-       MEMBER(dahdi_pvt, mohinterpret, AST_DATA_STRING)                        \
-       MEMBER(dahdi_pvt, mohsuggest, AST_DATA_STRING)                          \
-       MEMBER(dahdi_pvt, parkinglot, AST_DATA_STRING)
-
-AST_DATA_STRUCTURE(dahdi_pvt, DATA_EXPORT_DAHDI_PVT);
-
 static struct dahdi_pvt *iflist = NULL;        /*!< Main interface list start */
 static struct dahdi_pvt *ifend = NULL; /*!< Main interface list end */
 
@@ -17313,7 +17240,6 @@ static int __unload_module(void)
        ast_manager_unregister("PRIDebugFileSet");
        ast_manager_unregister("PRIDebugFileUnset");
 #endif /* defined(HAVE_PRI) */
-       ast_data_unregister(NULL);
        ast_channel_unregister(&dahdi_tech);
 
        /* Hangup all interfaces if they have an owner */
@@ -19356,163 +19282,6 @@ static int setup_dahdi(int reload)
 }
 
 /*!
- * \internal
- * \brief Callback used to generate the dahdi status tree.
- * \param[in] search The search pattern tree.
- * \retval NULL on error.
- * \retval non-NULL The generated tree.
- */
-static int dahdi_status_data_provider_get(const struct ast_data_search *search,
-               struct ast_data *data_root)
-{
-       int ctl, res, span;
-       struct ast_data *data_span, *data_alarms;
-       struct dahdi_spaninfo s;
-
-       ctl = open("/dev/dahdi/ctl", O_RDWR);
-       if (ctl < 0) {
-               ast_log(LOG_ERROR, "No DAHDI found. Unable to open /dev/dahdi/ctl: %s\n", strerror(errno));
-               return -1;
-       }
-       for (span = 1; span < DAHDI_MAX_SPANS; ++span) {
-               s.spanno = span;
-               res = ioctl(ctl, DAHDI_SPANSTAT, &s);
-               if (res) {
-                       continue;
-               }
-
-               data_span = ast_data_add_node(data_root, "span");
-               if (!data_span) {
-                       continue;
-               }
-               ast_data_add_str(data_span, "description", s.desc);
-
-               /* insert the alarms status */
-               data_alarms = ast_data_add_node(data_span, "alarms");
-               if (!data_alarms) {
-                       continue;
-               }
-
-               ast_data_add_bool(data_alarms, "BLUE", s.alarms & DAHDI_ALARM_BLUE);
-               ast_data_add_bool(data_alarms, "YELLOW", s.alarms & DAHDI_ALARM_YELLOW);
-               ast_data_add_bool(data_alarms, "RED", s.alarms & DAHDI_ALARM_RED);
-               ast_data_add_bool(data_alarms, "LOOPBACK", s.alarms & DAHDI_ALARM_LOOPBACK);
-               ast_data_add_bool(data_alarms, "RECOVER", s.alarms & DAHDI_ALARM_RECOVER);
-               ast_data_add_bool(data_alarms, "NOTOPEN", s.alarms & DAHDI_ALARM_NOTOPEN);
-
-               ast_data_add_int(data_span, "irqmisses", s.irqmisses);
-               ast_data_add_int(data_span, "bpviol", s.bpvcount);
-               ast_data_add_int(data_span, "crc4", s.crc4count);
-               ast_data_add_str(data_span, "framing",  s.lineconfig & DAHDI_CONFIG_D4 ? "D4" :
-                                                       s.lineconfig & DAHDI_CONFIG_ESF ? "ESF" :
-                                                       s.lineconfig & DAHDI_CONFIG_CCS ? "CCS" :
-                                                       "CAS");
-               ast_data_add_str(data_span, "coding",   s.lineconfig & DAHDI_CONFIG_B8ZS ? "B8ZS" :
-                                                       s.lineconfig & DAHDI_CONFIG_HDB3 ? "HDB3" :
-                                                       s.lineconfig & DAHDI_CONFIG_AMI ? "AMI" :
-                                                       "Unknown");
-               ast_data_add_str(data_span, "options",  s.lineconfig & DAHDI_CONFIG_CRC4 ?
-                                                       s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "CRC4/YEL" : "CRC4" :
-                                                       s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "YEL" : "");
-               ast_data_add_str(data_span, "lbo", lbostr[s.lbo]);
-
-               /* if this span doesn't match remove it. */
-               if (!ast_data_search_match(search, data_span)) {
-                       ast_data_remove_node(data_root, data_span);
-               }
-       }
-       close(ctl);
-
-       return 0;
-}
-
-/*!
- * \internal
- * \brief Callback used to generate the dahdi channels tree.
- * \param[in] search The search pattern tree.
- * \retval NULL on error.
- * \retval non-NULL The generated tree.
- */
-static int dahdi_channels_data_provider_get(const struct ast_data_search *search,
-               struct ast_data *data_root)
-{
-       struct dahdi_pvt *tmp;
-       struct ast_data *data_channel;
-
-       ast_mutex_lock(&iflock);
-       for (tmp = iflist; tmp; tmp = tmp->next) {
-               data_channel = ast_data_add_node(data_root, "channel");
-               if (!data_channel) {
-                       continue;
-               }
-
-               ast_data_add_structure(dahdi_pvt, data_channel, tmp);
-
-               /* if this channel doesn't match remove it. */
-               if (!ast_data_search_match(search, data_channel)) {
-                       ast_data_remove_node(data_root, data_channel);
-               }
-       }
-       ast_mutex_unlock(&iflock);
-
-       return 0;
-}
-
-/*!
- * \internal
- * \brief Callback used to generate the dahdi channels tree.
- * \param[in] search The search pattern tree.
- * \retval NULL on error.
- * \retval non-NULL The generated tree.
- */
-static int dahdi_version_data_provider_get(const struct ast_data_search *search,
-               struct ast_data *data_root)
-{
-       int pseudo_fd = -1;
-       struct dahdi_versioninfo vi = {
-               .version = "Unknown",
-               .echo_canceller = "Unknown"
-       };
-
-       if ((pseudo_fd = open("/dev/dahdi/ctl", O_RDONLY)) < 0) {
-               ast_log(LOG_ERROR, "Failed to open control file to get version.\n");
-               return -1;
-       }
-
-       if (ioctl(pseudo_fd, DAHDI_GETVERSION, &vi)) {
-               ast_log(LOG_ERROR, "Failed to get DAHDI version: %s\n", strerror(errno));
-       }
-
-       close(pseudo_fd);
-
-       ast_data_add_str(data_root, "value", vi.version);
-       ast_data_add_str(data_root, "echocanceller", vi.echo_canceller);
-
-       return 0;
-}
-
-static const struct ast_data_handler dahdi_status_data_provider = {
-       .version = AST_DATA_HANDLER_VERSION,
-       .get = dahdi_status_data_provider_get
-};
-
-static const struct ast_data_handler dahdi_channels_data_provider = {
-       .version = AST_DATA_HANDLER_VERSION,
-       .get = dahdi_channels_data_provider_get
-};
-
-static const struct ast_data_handler dahdi_version_data_provider = {
-       .version = AST_DATA_HANDLER_VERSION,
-       .get = dahdi_version_data_provider_get
-};
-
-static const struct ast_data_entry dahdi_data_providers[] = {
-       AST_DATA_ENTRY("asterisk/channel/dahdi/status", &dahdi_status_data_provider),
-       AST_DATA_ENTRY("asterisk/channel/dahdi/channels", &dahdi_channels_data_provider),
-       AST_DATA_ENTRY("asterisk/channel/dahdi/version", &dahdi_version_data_provider)
-};
-
-/*!
  * \brief Load the module
  *
  * Module loading including tests for configuration or dependencies.
@@ -19608,8 +19377,6 @@ static int load_module(void)
 #endif
 
        ast_cli_register_multiple(dahdi_cli, ARRAY_LEN(dahdi_cli));
-       /* register all the data providers */
-       ast_data_register_multiple(dahdi_data_providers, ARRAY_LEN(dahdi_data_providers));
        memset(round_robin, 0, sizeof(round_robin));
        ast_manager_register_xml("DAHDITransfer", 0, action_transfer);
        ast_manager_register_xml("DAHDIHangup", 0, action_transferhangup);
index d15b55d..5abb6c3 100644 (file)
 #include "asterisk/timing.h"
 #include "asterisk/taskprocessor.h"
 #include "asterisk/test.h"
-#include "asterisk/data.h"
 #include "asterisk/security_events.h"
 #include "asterisk/stasis_endpoints.h"
 #include "asterisk/bridge.h"
@@ -1950,19 +1949,6 @@ static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *
        return res;
 }
 
-static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
-{
-       int res;
-       struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
-       if (!cap) {
-               return -1;
-       }
-       iax2_format_compatibility_bitfield2cap(formats, cap);
-       res = ast_data_add_codecs(root, node_name, cap);
-       ao2_ref(cap, -1);
-       return res;
-}
-
 /*!
  * \note The only member of the peer passed here guaranteed to be set is the name field
  */
@@ -13069,7 +13055,7 @@ static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, st
                ast_free_acl_list(oldacl);
        }
 
-       if (!ast_strlen_zero(peer->mailbox)) {
+       if (!ast_strlen_zero(peer->mailbox) && !peer->mwi_event_sub) {
                struct stasis_topic *mailbox_specific_topic;
 
                mailbox_specific_topic = ast_mwi_topic(peer->mailbox);
@@ -14555,129 +14541,6 @@ static struct ast_cli_entry cli_iax2[] = {
 #endif /* IAXTESTS */
 };
 
-#ifdef TEST_FRAMEWORK
-AST_TEST_DEFINE(test_iax2_peers_get)
-{
-       struct ast_data_query query = {
-               .path = "/asterisk/channel/iax2/peers",
-               .search = "peers/peer/name=test_peer_data_provider"
-       };
-       struct ast_data *node;
-       struct iax2_peer *peer;
-
-       switch (cmd) {
-               case TEST_INIT:
-                       info->name = "iax2_peers_get_data_test";
-                       info->category = "/main/data/iax2/peers/";
-                       info->summary = "IAX2 peers data providers unit test";
-                       info->description =
-                               "Tests whether the IAX2 peers data provider implementation works as expected.";
-                       return AST_TEST_NOT_RUN;
-               case TEST_EXECUTE:
-                       break;
-       }
-
-       /* build a test peer */
-       peer = build_peer("test_peer_data_provider", NULL, NULL, 0);
-       if (!peer) {
-               return AST_TEST_FAIL;
-       }
-       peer->expiry= 1010;
-       ao2_link(peers, peer);
-
-       node = ast_data_get(&query);
-       if (!node) {
-               ao2_unlink(peers, peer);
-               peer_unref(peer);
-               return AST_TEST_FAIL;
-       }
-
-       /* check returned data node. */
-       if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
-               ao2_unlink(peers, peer);
-               peer_unref(peer);
-               ast_data_free(node);
-               return AST_TEST_FAIL;
-       }
-
-       if (ast_data_retrieve_int(node, "peer/expiry") != 1010) {
-               ao2_unlink(peers, peer);
-               peer_unref(peer);
-               ast_data_free(node);
-               return AST_TEST_FAIL;
-       }
-
-       /* release resources */
-       ast_data_free(node);
-
-       ao2_unlink(peers, peer);
-       peer_unref(peer);
-
-       return AST_TEST_PASS;
-}
-
-AST_TEST_DEFINE(test_iax2_users_get)
-{
-       struct ast_data_query query = {
-               .path = "/asterisk/channel/iax2/users",
-               .search = "users/user/name=test_user_data_provider"
-       };
-       struct ast_data *node;
-       struct iax2_user *user;
-
-       switch (cmd) {
-               case TEST_INIT:
-                       info->name = "iax2_users_get_data_test";
-                       info->category = "/main/data/iax2/users/";
-                       info->summary = "IAX2 users data providers unit test";
-                       info->description =
-                               "Tests whether the IAX2 users data provider implementation works as expected.";
-                       return AST_TEST_NOT_RUN;
-               case TEST_EXECUTE:
-                       break;
-       }
-
-       user = build_user("test_user_data_provider", NULL, NULL, 0);
-       if (!user) {
-               ast_test_status_update(test, "Failed to build a test user\n");
-               return AST_TEST_FAIL;
-       }
-       user->amaflags = 1010;
-       ao2_link(users, user);
-
-       node = ast_data_get(&query);
-       if (!node) {
-               ast_test_status_update(test, "The data query to find our test user failed\n");
-               ao2_unlink(users, user);
-               user_unref(user);
-               return AST_TEST_FAIL;
-       }
-
-       if (strcmp(ast_data_retrieve_string(node, "user/name"), "test_user_data_provider")) {
-               ast_test_status_update(test, "Our data results did not return the test user created in the previous step.\n");
-               ao2_unlink(users, user);
-               user_unref(user);
-               ast_data_free(node);
-               return AST_TEST_FAIL;
-       }
-
-       if (ast_data_retrieve_int(node, "user/amaflags/value") != 1010) {
-               ast_test_status_update(test, "The amaflags field in our test user was '%d' not the expected value '1010'\n", ast_data_retrieve_int(node, "user/amaflags/value"));
-               ao2_unlink(users, user);
-               user_unref(user);
-               ast_data_free(node);
-               return AST_TEST_FAIL;
-       }
-
-       ast_data_free(node);
-
-       ao2_unlink(users, user);
-       user_unref(user);
-
-       return AST_TEST_PASS;
-}
-#endif
-
 static void cleanup_thread_list(void *head)
 {
        AST_LIST_HEAD(iax2_thread_list, iax2_thread);
@@ -14743,11 +14606,6 @@ static int __unload_module(void)
        ast_manager_unregister( "IAXnetstats" );
        ast_manager_unregister( "IAXregistry" );
        ast_unregister_application(papp);
-#ifdef TEST_FRAMEWORK
-       AST_TEST_UNREGISTER(test_iax2_peers_get);
-       AST_TEST_UNREGISTER(test_iax2_users_get);
-#endif
-       ast_data_unregister(NULL);
        ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
        ast_unregister_switch(&iax2_switch);
        ast_channel_unregister(&iax2_tech);
@@ -14889,191 +14747,6 @@ container_fail:
        return -1;
 }
 
-
-#define DATA_EXPORT_IAX2_PEER(MEMBER)                          \
-       MEMBER(iax2_peer, name, AST_DATA_STRING)                \
-       MEMBER(iax2_peer, username, AST_DATA_STRING)            \
-       MEMBER(iax2_peer, secret, AST_DATA_PASSWORD)            \
-       MEMBER(iax2_peer, dbsecret, AST_DATA_PASSWORD)          \
-       MEMBER(iax2_peer, outkey, AST_DATA_STRING)              \
-       MEMBER(iax2_peer, regexten, AST_DATA_STRING)            \
-       MEMBER(iax2_peer, context, AST_DATA_STRING)             \
-       MEMBER(iax2_peer, peercontext, AST_DATA_STRING)         \
-       MEMBER(iax2_peer, mailbox, AST_DATA_STRING)             \
-       MEMBER(iax2_peer, mohinterpret, AST_DATA_STRING)        \
-       MEMBER(iax2_peer, mohsuggest, AST_DATA_STRING)          \
-       MEMBER(iax2_peer, inkeys, AST_DATA_STRING)              \
-       MEMBER(iax2_peer, cid_num, AST_DATA_STRING)             \
-       MEMBER(iax2_peer, cid_name, AST_DATA_STRING)            \
-       MEMBER(iax2_peer, zonetag, AST_DATA_STRING)             \
-       MEMBER(iax2_peer, parkinglot, AST_DATA_STRING)          \
-       MEMBER(iax2_peer, expiry, AST_DATA_SECONDS)             \
-       MEMBER(iax2_peer, callno, AST_DATA_INTEGER)             \
-       MEMBER(iax2_peer, lastms, AST_DATA_MILLISECONDS)        \
-       MEMBER(iax2_peer, maxms, AST_DATA_MILLISECONDS)         \
-       MEMBER(iax2_peer, pokefreqok, AST_DATA_MILLISECONDS)    \
-       MEMBER(iax2_peer, pokefreqnotok, AST_DATA_MILLISECONDS) \
-       MEMBER(iax2_peer, historicms, AST_DATA_INTEGER)         \
-       MEMBER(iax2_peer, smoothing, AST_DATA_BOOLEAN)          \
-        MEMBER(iax2_peer, maxcallno, AST_DATA_INTEGER)
-
-AST_DATA_STRUCTURE(iax2_peer, DATA_EXPORT_IAX2_PEER);
-
-static int peers_data_provider_get(const struct ast_data_search *search,
-       struct ast_data *data_root)
-{
-       struct ast_data *data_peer;
-       struct iax2_peer *peer;
-       struct ao2_iterator i;
-       char status[20];
-       struct ast_str *encmethods = ast_str_alloca(256);
-
-       i = ao2_iterator_init(peers, 0);
-       while ((peer = ao2_iterator_next(&i))) {
-               data_peer = ast_data_add_node(data_root, "peer");
-               if (!data_peer) {
-                       peer_unref(peer);
-                       continue;
-               }
-
-               ast_data_add_structure(iax2_peer, data_peer, peer);
-
-               iax2_data_add_codecs(data_peer, "codecs", peer->capability);
-
-               peer_status(peer, status, sizeof(status));
-               ast_data_add_str(data_peer, "status", status);
-
-               ast_data_add_str(data_peer, "host", ast_sockaddr_stringify_host(&peer->addr));
-
-               ast_data_add_str(data_peer, "mask", ast_sockaddr_stringify_addr(&peer->mask));
-
-               ast_data_add_int(data_peer, "port", ast_sockaddr_port(&peer->addr));
-
-               ast_data_add_bool(data_peer, "trunk", ast_test_flag64(peer, IAX_TRUNK));
-
-               ast_data_add_bool(data_peer, "dynamic", ast_test_flag64(peer, IAX_DYNAMIC));
-
-               encmethods_to_str(peer->encmethods, &encmethods);
-               ast_data_add_str(data_peer, "encryption", peer->encmethods ? ast_str_buffer(encmethods) : "no");
-
-               peer_unref(peer);
-
-               if (!ast_data_search_match(search, data_peer)) {
-                       ast_data_remove_node(data_root, data_peer);
-               }
-       }
-       ao2_iterator_destroy(&i);
-
-       return 0;
-}
-
-#define DATA_EXPORT_IAX2_USER(MEMBER)                                  \
-        MEMBER(iax2_user, name, AST_DATA_STRING)                       \
-        MEMBER(iax2_user, dbsecret, AST_DATA_PASSWORD)                 \
-        MEMBER(iax2_user, accountcode, AST_DATA_STRING)                        \
-        MEMBER(iax2_user, mohinterpret, AST_DATA_STRING)               \
-        MEMBER(iax2_user, mohsuggest, AST_DATA_STRING)                 \
-        MEMBER(iax2_user, inkeys, AST_DATA_STRING)                     \
-        MEMBER(iax2_user, language, AST_DATA_STRING)                   \
-        MEMBER(iax2_user, cid_num, AST_DATA_STRING)                    \
-        MEMBER(iax2_user, cid_name, AST_DATA_STRING)                   \
-        MEMBER(iax2_user, parkinglot, AST_DATA_STRING)                 \
-        MEMBER(iax2_user, maxauthreq, AST_DATA_INTEGER)                        \
-        MEMBER(iax2_user, curauthreq, AST_DATA_INTEGER)
-
-AST_DATA_STRUCTURE(iax2_user, DATA_EXPORT_IAX2_USER);
-
-static int users_data_provider_get(const struct ast_data_search *search,
-       struct ast_data *data_root)
-{
-       struct ast_data *data_user, *data_authmethods, *data_enum_node;
-       struct iax2_user *user;
-       struct ao2_iterator i;
-       struct ast_str *auth;
-       char *pstr = "";
-
-       if (!(auth = ast_str_create(90))) {
-               ast_log(LOG_ERROR, "Unable to create temporary string for storing 'secret'\n");
-               return 0;
-       }
-
-       i = ao2_iterator_init(users, 0);
-       for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
-               data_user = ast_data_add_node(data_root, "user");
-               if (!data_user) {
-                       continue;
-               }
-
-               ast_data_add_structure(iax2_user, data_user, user);
-
-               iax2_data_add_codecs(data_user, "codecs", user->capability);
-
-               if (!ast_strlen_zero(user->secret)) {
-                       ast_str_set(&auth, 0, "%s", user->secret);
-               } else if (!ast_strlen_zero(user->inkeys)) {
-                       ast_str_set(&auth, 0, "Key: %s", user->inkeys);
-               } else {
-                       ast_str_set(&auth, 0, "no secret");
-               }
-               ast_data_add_password(data_user, "secret", ast_str_buffer(auth));
-
-               ast_data_add_str(data_user, "context", user->contexts ? user->contexts->context : DEFAULT_CONTEXT);
-
-               /* authmethods */
-               data_authmethods = ast_data_add_node(data_user, "authmethods");
-               if (!data_authmethods) {
-                       ast_data_remove_node(data_root, data_user);
-                       continue;
-               }
-               ast_data_add_bool(data_authmethods, "rsa", user->authmethods & IAX_AUTH_RSA);
-               ast_data_add_bool(data_authmethods, "md5", user->authmethods & IAX_AUTH_MD5);
-               ast_data_add_bool(data_authmethods, "plaintext", user->authmethods & IAX_AUTH_PLAINTEXT);
-
-               /* amaflags */
-               data_enum_node = ast_data_add_node(data_user, "amaflags");
-               if (!data_enum_node) {
-                       ast_data_remove_node(data_root, data_user);
-                       continue;
-               }
-               ast_data_add_int(data_enum_node, "value", user->amaflags);
-               ast_data_add_str(data_enum_node, "text", ast_channel_amaflags2string(user->amaflags));
-
-               ast_data_add_bool(data_user, "access-control", ast_acl_list_is_empty(user->acl) ? 0 : 1);
-
-               if (ast_test_flag64(user, IAX_CODEC_NOCAP)) {
-                       pstr = "REQ only";
-               } else if (ast_test_flag64(user, IAX_CODEC_NOPREFS)) {
-                       pstr = "disabled";
-               } else {
-                       pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "caller" : "host";
-               }
-               ast_data_add_str(data_user, "codec-preferences", pstr);
-
-               if (!ast_data_search_match(search, data_user)) {
-                       ast_data_remove_node(data_root, data_user);
-               }
-       }
-       ao2_iterator_destroy(&i);
-
-       ast_free(auth);
-       return 0;
-}
-
-static const struct ast_data_handler peers_data_provider = {
-       .version = AST_DATA_HANDLER_VERSION,
-       .get = peers_data_provider_get
-};
-
-static const struct ast_data_handler users_data_provider = {
-       .version = AST_DATA_HANDLER_VERSION,
-       .get = users_data_provider_get
-};
-
-static const struct ast_data_entry iax2_data_providers[] = {
-       AST_DATA_ENTRY("asterisk/channel/iax2/peers", &peers_data_provider),
-       AST_DATA_ENTRY("asterisk/channel/iax2/users", &users_data_provider),
-};
-
 /*!
  * \brief Load the module
  *
@@ -15173,13 +14846,6 @@ static int load_module(void)
                return AST_MODULE_LOAD_DECLINE;
        }
 
-#ifdef TEST_FRAMEWORK
-       AST_TEST_REGISTER(test_iax2_peers_get);
-       AST_TEST_REGISTER(test_iax2_users_get);
-#endif
-
-       /* Register AstData providers */
-       ast_data_register_multiple(iax2_data_providers, ARRAY_LEN(iax2_data_providers));
        ast_cli_register_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
 
        ast_register_application_xml(papp, iax2_prov_app);
index 83dc77f..51b5dab 100644 (file)
@@ -64,6 +64,7 @@
 
 #include "asterisk/res_pjsip.h"
 #include "asterisk/res_pjsip_session.h"
+#include "asterisk/stream.h"
 
 #include "pjsip/include/chan_pjsip.h"
 #include "pjsip/include/dialplan_functions.h"
@@ -78,25 +79,22 @@ static unsigned int chan_idx;
 
 static void chan_pjsip_pvt_dtor(void *obj)
 {
-       struct chan_pjsip_pvt *pvt = obj;
-       int i;
-
-       for (i = 0; i < SIP_MEDIA_SIZE; ++i) {
-               ao2_cleanup(pvt->media[i]);
-               pvt->media[i] = NULL;
-       }
 }
 
 /* \brief Asterisk core interaction functions */
 static struct ast_channel *chan_pjsip_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 struct ast_channel *chan_pjsip_request_with_stream_topology(const char *type,
+       struct ast_stream_topology *topology, const struct ast_assigned_ids *assignedids,
+       const struct ast_channel *requestor, const char *data, int *cause);
 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text);
 static int chan_pjsip_digit_begin(struct ast_channel *ast, char digit);
 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout);
 static int chan_pjsip_hangup(struct ast_channel *ast);
 static int chan_pjsip_answer(struct ast_channel *ast);
-static struct ast_frame *chan_pjsip_read(struct ast_channel *ast);
+static struct ast_frame *chan_pjsip_read_stream(struct ast_channel *ast);
 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *f);
+static int chan_pjsip_write_stream(struct ast_channel *ast, int stream_num, struct ast_frame *f);
 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
 static int chan_pjsip_transfer(struct ast_channel *ast, const char *target);
 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
@@ -109,16 +107,17 @@ struct ast_channel_tech chan_pjsip_tech = {
        .type = channel_type,
        .description = "PJSIP Channel Driver",
        .requester = chan_pjsip_request,
+       .requester_with_stream_topology = chan_pjsip_request_with_stream_topology,
        .send_text = chan_pjsip_sendtext,
        .send_digit_begin = chan_pjsip_digit_begin,
        .send_digit_end = chan_pjsip_digit_end,
        .call = chan_pjsip_call,
        .hangup = chan_pjsip_hangup,
        .answer = chan_pjsip_answer,
-       .read = chan_pjsip_read,
+       .read_stream = chan_pjsip_read_stream,
        .write = chan_pjsip_write,
-       .write_video = chan_pjsip_write,
-       .exception = chan_pjsip_read,
+       .write_stream = chan_pjsip_write_stream,
+       .exception = chan_pjsip_read_stream,
        .indicate = chan_pjsip_indicate,
        .transfer = chan_pjsip_transfer,
        .fixup = chan_pjsip_fixup,
@@ -159,11 +158,20 @@ static struct ast_sip_session_supplement chan_pjsip_ack_supplement = {
 static enum ast_rtp_glue_result chan_pjsip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
 {
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
-       struct chan_pjsip_pvt *pvt;
        struct ast_sip_endpoint *endpoint;
        struct ast_datastore *datastore;
+       struct ast_sip_session_media *media;
+
+       if (!channel || !channel->session) {
+               return AST_RTP_GLUE_RESULT_FORBID;
+       }
 
-       if (!channel || !channel->session || !(pvt = channel->pvt) || !pvt->media[SIP_MEDIA_AUDIO]->rtp) {
+       /* XXX Getting the first RTP instance for direct media related stuff seems just
+        * absolutely wrong. But the native RTP bridge knows no other method than single-stream
+        * for direct media. So this is the best we can do.
+        */
+       media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
+       if (!media || !media->rtp) {
                return AST_RTP_GLUE_RESULT_FORBID;
        }
 
@@ -175,7 +183,7 @@ static enum ast_rtp_glue_result chan_pjsip_get_rtp_peer(struct ast_channel *chan
 
        endpoint = channel->session->endpoint;
 
-       *instance = pvt->media[SIP_MEDIA_AUDIO]->rtp;
+       *instance = media->rtp;
        ao2_ref(*instance, +1);
 
        ast_assert(endpoint != NULL);
@@ -194,16 +202,21 @@ static enum ast_rtp_glue_result chan_pjsip_get_rtp_peer(struct ast_channel *chan
 static enum ast_rtp_glue_result chan_pjsip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
 {
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
-       struct chan_pjsip_pvt *pvt = channel->pvt;
        struct ast_sip_endpoint *endpoint;
+       struct ast_sip_session_media *media;
 
-       if (!pvt || !channel->session || !pvt->media[SIP_MEDIA_VIDEO]->rtp) {
+       if (!channel || !channel->session) {
+               return AST_RTP_GLUE_RESULT_FORBID;
+       }
+
+       media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO];
+       if (!media || !media->rtp) {
                return AST_RTP_GLUE_RESULT_FORBID;
        }
 
        endpoint = channel->session->endpoint;
 
-       *instance = pvt->media[SIP_MEDIA_VIDEO]->rtp;
+       *instance = media->rtp;
        ao2_ref(*instance, +1);
 
        ast_assert(endpoint != NULL);
@@ -265,18 +278,43 @@ static int direct_media_mitigate_glare(struct ast_sip_session *session)
        return 0;
 }
 
+/*! \brief Helper function to find the position for RTCP */
+static int rtp_find_rtcp_fd_position(struct ast_sip_session *session, struct ast_rtp_instance *rtp)
+{
+       int index;
+
+       for (index = 0; index < AST_VECTOR_SIZE(&session->active_media_state->read_callbacks); ++index) {
+               struct ast_sip_session_media_read_callback_state *callback_state =
+                       AST_VECTOR_GET_ADDR(&session->active_media_state->read_callbacks, index);
+
+               if (callback_state->fd != ast_rtp_instance_fd(rtp, 1)) {
+                       continue;
+               }
+
+               return index;
+       }
+
+       return -1;
+}
+
 /*!
  * \pre chan is locked
  */
 static int check_for_rtp_changes(struct ast_channel *chan, struct ast_rtp_instance *rtp,
-               struct ast_sip_session_media *media, int rtcp_fd)
+               struct ast_sip_session_media *media, struct ast_sip_session *session)
 {
-       int changed = 0;
+       int changed = 0, position = -1;
+
+       if (media->rtp) {
+               position = rtp_find_rtcp_fd_position(session, media->rtp);
+       }
 
        if (rtp) {
                changed = ast_rtp_instance_get_and_cmp_remote_address(rtp, &media->direct_media_addr);
                if (media->rtp) {
-                       ast_channel_set_fd(chan, rtcp_fd, -1);
+                       if (position != -1) {
+                               ast_channel_set_fd(chan, position + AST_EXTENDED_FDS, -1);
+                       }
                        ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 0);
                }
        } else if (!ast_sockaddr_isnull(&media->direct_media_addr)){
@@ -284,7 +322,9 @@ static int check_for_rtp_changes(struct ast_channel *chan, struct ast_rtp_instan
                changed = 1;
                if (media->rtp) {
                        ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 1);
-                       ast_channel_set_fd(chan, rtcp_fd, ast_rtp_instance_fd(media->rtp, 1));
+                       if (position != -1) {
+                               ast_channel_set_fd(chan, position + AST_EXTENDED_FDS, ast_rtp_instance_fd(media->rtp, 1));
+                       }
                }
        }
 
@@ -333,22 +373,27 @@ static int send_direct_media_request(void *data)
 {
        struct rtp_direct_media_data *cdata = data;
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(cdata->chan);
-       struct chan_pjsip_pvt *pvt = channel->pvt;
+       struct ast_sip_session *session;
        int changed = 0;
        int res = 0;
 
+       /* XXX In an ideal world each media stream would be direct, but for now preserve behavior
+        * and connect only the default media sessions for audio and video.
+        */
+
        /* The channel needs to be locked when checking for RTP changes.
         * Otherwise, we could end up destroying an underlying RTCP structure
         * at the same time that the channel thread is attempting to read RTCP
         */
        ast_channel_lock(cdata->chan);
-       if (pvt->media[SIP_MEDIA_AUDIO]) {
+       session = channel->session;
+       if (session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO]) {
                changed |= check_for_rtp_changes(
-                       cdata->chan, cdata->rtp, pvt->media[SIP_MEDIA_AUDIO], 1);
+                       cdata->chan, cdata->rtp, session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO], session);
        }
-       if (pvt->media[SIP_MEDIA_VIDEO]) {
+       if (session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO]) {
                changed |= check_for_rtp_changes(
-                       cdata->chan, cdata->vrtp, pvt->media[SIP_MEDIA_VIDEO], 3);
+                       cdata->chan, cdata->vrtp, session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO], session);
        }
        ast_channel_unlock(cdata->chan);
 
@@ -368,7 +413,7 @@ static int send_direct_media_request(void *data)
        if (changed) {
                ast_debug(4, "RTP changed on %s; initiating direct media update\n", ast_channel_name(cdata->chan));
                res = ast_sip_session_refresh(cdata->session, NULL, NULL, NULL,
-                       cdata->session->endpoint->media.direct_media.method, 1);
+                       cdata->session->endpoint->media.direct_media.method, 1, NULL);
        }
 
        ao2_ref(cdata, -1);
@@ -420,14 +465,53 @@ static struct ast_rtp_glue chan_pjsip_rtp_glue = {
        .update_peer = chan_pjsip_set_rtp_peer,
 };
 
-static void set_channel_on_rtp_instance(struct chan_pjsip_pvt *pvt, const char *channel_id)
+static void set_channel_on_rtp_instance(const struct ast_sip_session *session,
+       const char *channel_id)
 {
-       if (pvt->media[SIP_MEDIA_AUDIO] && pvt->media[SIP_MEDIA_AUDIO]->rtp) {
-               ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_AUDIO]->rtp, channel_id);
+       int i;
+
+       for (i = 0; i < AST_VECTOR_SIZE(&session->active_media_state->sessions); ++i) {
+               struct ast_sip_session_media *session_media;
+
+               session_media = AST_VECTOR_GET(&session->active_media_state->sessions, i);
+               if (!session_media || !session_media->rtp) {
+                       continue;
+               }
+
+               ast_rtp_instance_set_channel_id(session_media->rtp, channel_id);
        }
-       if (pvt->media[SIP_MEDIA_VIDEO] && pvt->media[SIP_MEDIA_VIDEO]->rtp) {
-               ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_VIDEO]->rtp, channel_id);
+}
+
+/*!
+ * \brief Determine if a topology is compatible with format capabilities
+ *
+ * This will return true if ANY formats in the topology are compatible with the format
+ * capabilities.
+ *
+ * XXX When supporting true multistream, we will need to be sure to mark which streams from
+ * top1 are compatible with which streams from top2. Then the ones that are not compatible
+ * will need to be marked as "removed" so that they are negotiated as expected.
+ *
+ * \param top Topology
+ * \param cap Format capabilities
+ * \retval 1 The topology has at least one compatible format
+ * \retval 0 The topology has no compatible formats or an error occurred.
+ */
+static int compatible_formats_exist(struct ast_stream_topology *top, struct ast_format_cap *cap)
+{
+       struct ast_format_cap *cap_from_top;
+       int res;
+
+       cap_from_top = ast_format_cap_from_stream_topology(top);
+
+       if (!cap_from_top) {
+               return 0;
        }
+
+       res = ast_format_cap_iscompatible(cap_from_top, cap);
+       ao2_ref(cap_from_top, -1);
+
+       return res;
 }
 
 /*! \brief Function called to create a new PJSIP Asterisk channel */
@@ -438,12 +522,9 @@ static struct ast_channel *chan_pjsip_new(struct ast_sip_session *session, int s
        RAII_VAR(struct chan_pjsip_pvt *, pvt, NULL, ao2_cleanup);
        struct ast_sip_channel_pvt *channel;
        struct ast_variable *var;
+       struct ast_stream_topology *topology;
 
-       if (!(pvt = ao2_alloc(sizeof(*pvt), chan_pjsip_pvt_dtor))) {
-               return NULL;
-       }
-       caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
-       if (!caps) {
+       if (!(pvt = ao2_alloc_options(sizeof(*pvt), chan_pjsip_pvt_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK))) {
                return NULL;
        }
 
@@ -457,31 +538,46 @@ static struct ast_channel *chan_pjsip_new(struct ast_sip_session *session, int s
                ast_sorcery_object_get_id(session->endpoint),
                (unsigned) ast_atomic_fetchadd_int((int *) &chan_idx, +1));
        if (!chan) {
-               ao2_ref(caps, -1);
                return NULL;
        }
 
        ast_channel_tech_set(chan, &chan_pjsip_tech);
 
        if (!(channel = ast_sip_channel_pvt_alloc(pvt, session))) {
-               ao2_ref(caps, -1);
                ast_channel_unlock(chan);
                ast_hangup(chan);
                return NULL;
        }
 
-       ast_channel_stage_snapshot(chan);
-
        ast_channel_tech_pvt_set(chan, channel);
 
-       if (!ast_format_cap_count(session->req_caps) ||
-               !ast_format_cap_iscompatible(session->req_caps, session->endpoint->media.codecs)) {
+       if (!ast_stream_topology_get_count(session->pending_media_state->topology) ||
+               !compatible_formats_exist(session->pending_media_state->topology, session->endpoint->media.codecs)) {
+               caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
+               if (!caps) {
+                       ast_channel_unlock(chan);
+                       ast_hangup(chan);
+                       return NULL;
+               }
                ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
+               topology = ast_stream_topology_clone(session->endpoint->media.topology);
        } else {
-               ast_format_cap_append_from_cap(caps, session->req_caps, AST_MEDIA_TYPE_UNKNOWN);
+               caps = ast_format_cap_from_stream_topology(session->pending_media_state->topology);
+               topology = ast_stream_topology_clone(session->pending_media_state->topology);
        }
 
+       if (!topology || !caps) {
+               ao2_cleanup(caps);
+               ast_stream_topology_free(topology);
+               ast_channel_unlock(chan);
+               ast_hangup(chan);
+               return NULL;
+       }
+
+       ast_channel_stage_snapshot(chan);
+
        ast_channel_nativeformats_set(chan, caps);
+       ast_channel_set_stream_topology(chan, topology);
 
        if (!ast_format_cap_empty(caps)) {
                struct ast_format *fmt;
@@ -538,12 +634,7 @@ static struct ast_channel *chan_pjsip_new(struct ast_sip_session *session, int s
        ast_channel_stage_snapshot_done(chan);
        ast_channel_unlock(chan);
 
-       /* If res_pjsip_session is ever updated to create/destroy ast_sip_session_media
-        * during a call such as if multiple same-type stream support is introduced,
-        * these will need to be recaptured as well */
-       pvt->media[SIP_MEDIA_AUDIO] = ao2_find(session->media, "audio", OBJ_KEY);
-       pvt->media[SIP_MEDIA_VIDEO] = ao2_find(session->media, "video", OBJ_KEY);
-       set_channel_on_rtp_instance(pvt, ast_channel_uniqueid(chan));
+       set_channel_on_rtp_instance(session, ast_channel_uniqueid(chan));
 
        return chan;
 }
@@ -682,49 +773,30 @@ static struct ast_frame *chan_pjsip_cng_tone_detected(struct ast_sip_session *se
  *
  * \note The channel is already locked.
  */
-static struct ast_frame *chan_pjsip_read(struct ast_channel *ast)
+static struct ast_frame *chan_pjsip_read_stream(struct ast_channel *ast)
 {
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
-       struct ast_sip_session *session;
-       struct chan_pjsip_pvt *pvt = channel->pvt;
+       struct ast_sip_session *session = channel->session;
+       struct ast_sip_session_media_read_callback_state *callback_state;
        struct ast_frame *f;
-       struct ast_sip_session_media *media = NULL;
-       int rtcp = 0;
-       int fdno = ast_channel_fdno(ast);
+       int fdno = ast_channel_fdno(ast) - AST_EXTENDED_FDS;
 
-       switch (fdno) {
-       case 0:
-               media = pvt->media[SIP_MEDIA_AUDIO];
-               break;
-       case 1:
-               media = pvt->media[SIP_MEDIA_AUDIO];
-               rtcp = 1;
-               break;
-       case 2:
-               media = pvt->media[SIP_MEDIA_VIDEO];
-               break;
-       case 3:
-               media = pvt->media[SIP_MEDIA_VIDEO];
-               rtcp = 1;
-               break;
-       }
-
-       if (!media || !media->rtp) {
+       if (fdno >= AST_VECTOR_SIZE(&session->active_media_state->read_callbacks)) {
                return &ast_null_frame;
        }
 
-       if (!(f = ast_rtp_instance_read(media->rtp, rtcp))) {
+       callback_state = AST_VECTOR_GET_ADDR(&session->active_media_state->read_callbacks, fdno);
+       f = callback_state->read_callback(session, callback_state->session);
+
+       if (!f) {
                return f;
        }
 
-       ast_rtp_instance_set_last_rx(media->rtp, time(NULL));
-
-       if (f->frametype != AST_FRAME_VOICE) {
+       if (f->frametype != AST_FRAME_VOICE ||
+               callback_state->session != session->active_media_state->default_session[callback_state->session->type]) {
                return f;
        }
 
-       session = channel->session;
-
        if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
                ast_debug(1, "Oooh, got a frame with format of %s on channel '%s' when it has not been negotiated\n",
                        ast_format_get_name(f->subclass.format), ast_channel_name(ast));
@@ -794,22 +866,31 @@ static struct ast_frame *chan_pjsip_read(struct ast_channel *ast)
        return f;
 }
 
-/*! \brief Function called by core to write frames */
-static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
+static int chan_pjsip_write_stream(struct ast_channel *ast, int stream_num, struct ast_frame *frame)
 {
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
-       struct chan_pjsip_pvt *pvt = channel->pvt;
-       struct ast_sip_session_media *media;
+       struct ast_sip_session *session = channel->session;
+       struct ast_sip_session_media *media = NULL;
        int res = 0;
 
+       /* The core provides a guarantee that the stream will exist when we are called if stream_num is provided */
+       if (stream_num >= 0) {
+               /* What is not guaranteed is that a media session will exist */
+               if (stream_num < AST_VECTOR_SIZE(&channel->session->active_media_state->sessions)) {
+                       media = AST_VECTOR_GET(&channel->session->active_media_state->sessions, stream_num);
+               }
+       }
+
        switch (frame->frametype) {
        case AST_FRAME_VOICE:
-               media = pvt->media[SIP_MEDIA_AUDIO];
-
                if (!media) {
                        return 0;
-               }
-               if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
+               } else if (media->type != AST_MEDIA_TYPE_AUDIO) {
+                       ast_debug(3, "Channel %s stream %d is of type '%s', not audio!\n",
+                               ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
+                       return 0;
+               } else if (media == channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO] &&
+                       ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
                        struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
                        struct ast_str *write_transpath = ast_str_alloca(256);
                        struct ast_str *read_transpath = ast_str_alloca(256);
@@ -826,17 +907,32 @@ static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
                                ast_format_get_name(ast_channel_rawwriteformat(ast)),
                                ast_translate_path_to_str(ast_channel_writetrans(ast), &write_transpath));
                        return 0;
-               }
-               if (media->rtp) {
-                       res = ast_rtp_instance_write(media->rtp, frame);
+               } else if (media->write_callback) {
+                       res = media->write_callback(session, media, frame);
+
                }
                break;
        case AST_FRAME_VIDEO:
-               if ((media = pvt->media[SIP_MEDIA_VIDEO]) && media->rtp) {
-                       res = ast_rtp_instance_write(media->rtp, frame);
+               if (!media) {
+                       return 0;
+               } else if (media->type != AST_MEDIA_TYPE_VIDEO) {
+                       ast_debug(3, "Channel %s stream %d is of type '%s', not video!\n",
+                               ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
+                       return 0;
+               } else if (media->write_callback) {
+                       res = media->write_callback(session, media, frame);
                }
                break;
        case AST_FRAME_MODEM:
+               if (!media) {
+                       return 0;
+               } else if (media->type != AST_MEDIA_TYPE_IMAGE) {
+                       ast_debug(3, "Channel %s stream %d is of type '%s', not image!\n",
+                               ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
+                       return 0;
+               } else if (media->write_callback) {
+                       res = media->write_callback(session, media, frame);
+               }
                break;
        default:
                ast_log(LOG_WARNING, "Can't send %u type frames with PJSIP\n", frame->frametype);
@@ -846,11 +942,15 @@ static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
        return res;
 }
 
+static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
+{
+       return chan_pjsip_write_stream(ast, -1, frame);
+}
+
 /*! \brief Function called by core to change the underlying owner channel */
 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
 {
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(newchan);
-       struct chan_pjsip_pvt *pvt = channel->pvt;
 
        if (channel->session->channel != oldchan) {
                return -1;
@@ -863,7 +963,7 @@ static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *new
         */
        channel->session->channel = newchan;
 
-       set_channel_on_rtp_instance(pvt, ast_channel_uniqueid(newchan));
+       set_channel_on_rtp_instance(channel->session, ast_channel_uniqueid(newchan));
 
        return 0;
 }
@@ -1270,15 +1370,14 @@ static int update_connected_line_information(void *data)
                        int generate_new_sdp;
 
                        method = session->endpoint->id.refresh_method;
-                       if (session->inv_session->invite_tsx
-                               && (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE)) {
+                       if (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE) {
                                method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
                        }
 
                        /* Only the INVITE method actually needs SDP, UPDATE can do without */
                        generate_new_sdp = (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE);
 
-                       ast_sip_session_refresh(session, NULL, NULL, NULL, method, generate_new_sdp);
+                       ast_sip_session_refresh(session, NULL, NULL, NULL, method, generate_new_sdp, NULL);
                }
        } else if (session->endpoint->id.rpid_immediate
                && session->inv_session->state != PJSIP_INV_STATE_DISCONNECTED
@@ -1309,21 +1408,18 @@ static int update_connected_line_information(void *data)
 }
 
 /*! \brief Callback which changes the value of locally held on the media stream */
-static int local_hold_set_state(void *obj, void *arg, int flags)
+static void local_hold_set_state(struct ast_sip_session_media *session_media, unsigned int held)
 {
-       struct ast_sip_session_media *session_media = obj;
-       unsigned int *held = arg;
-
-       session_media->locally_held = *held;
-
-       return 0;
+       if (session_media) {
+               session_media->locally_held = held;
+       }
 }
 
 /*! \brief Update local hold state and send a re-INVITE with the new SDP */
 static int remote_send_hold_refresh(struct ast_sip_session *session, unsigned int held)
 {
-       ao2_callback(session->media, OBJ_NODATA, local_hold_set_state, &held);
-       ast_sip_session_refresh(session, NULL, NULL, NULL, AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1);
+       AST_VECTOR_CALLBACK_VOID(&session->active_media_state->sessions, local_hold_set_state, held);
+       ast_sip_session_refresh(session, NULL, NULL, NULL, AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, NULL);
        ao2_ref(session, -1);
 
        return 0;
@@ -1341,16 +1437,103 @@ static int remote_send_unhold(void *data)
        return remote_send_hold_refresh(data, 0);
 }
 
+struct topology_change_refresh_data {
+       struct ast_sip_session *session;
+       struct ast_sip_session_media_state *media_state;
+};
+
+static void topology_change_refresh_data_free(struct topology_change_refresh_data *refresh_data)
+{
+       ao2_cleanup(refresh_data->session);
+
+       ast_sip_session_media_state_free(refresh_data->media_state);
+       ast_free(refresh_data);
+}
+
+static struct topology_change_refresh_data *topology_change_refresh_data_alloc(
+       struct ast_sip_session *session, const struct ast_stream_topology *topology)
+{
+       struct topology_change_refresh_data *refresh_data;
+
+       refresh_data = ast_calloc(1, sizeof(*refresh_data));
+       if (!refresh_data) {
+               return NULL;
+       }
+
+       refresh_data->session = ao2_bump(session);
+       refresh_data->media_state = ast_sip_session_media_state_alloc();
+       if (!refresh_data->media_state) {
+               topology_change_refresh_data_free(refresh_data);
+               return NULL;
+       }
+       refresh_data->media_state->topology = ast_stream_topology_clone(topology);
+       if (!refresh_data->media_state->topology) {
+               topology_change_refresh_data_free(refresh_data);
+               return NULL;
+       }
+
+       return refresh_data;
+}
+
+static int on_topology_change_response(struct ast_sip_session *session, pjsip_rx_data *rdata)
+{
+       if (rdata->msg_info.msg->line.status.code == 200) {
+               /* The topology was changed to something new so give notice to what requested
+                * it so it queries the channel and updates accordingly.
+                */
+               if (session->channel) {
+                       ast_queue_control(session->channel, AST_CONTROL_STREAM_TOPOLOGY_CHANGED);
+               }
+       } else if (rdata->msg_info.msg->line.status.code != 100) {
+               /* The topology change failed, so drop the current pending media state */
+               ast_sip_session_media_state_reset(session->pending_media_state);
+       }
+
+       return 0;
+}
+
+static int send_topology_change_refresh(void *data)
+{
+       struct topology_change_refresh_data *refresh_data = data;
+       int ret;
+
+       ret = ast_sip_session_refresh(refresh_data->session, NULL, NULL, on_topology_change_response,
+               AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, refresh_data->media_state);
+       refresh_data->media_state = NULL;
+       topology_change_refresh_data_free(refresh_data);
+
+       return ret;
+}
+
+static int handle_topology_request_change(struct ast_sip_session *session,
+       const struct ast_stream_topology *proposed)
+{
+       struct topology_change_refresh_data *refresh_data;
+       int res;
+
+       refresh_data = topology_change_refresh_data_alloc(session, proposed);
+       if (!refresh_data) {
+               return -1;
+       }
+
+       res = ast_sip_push_task(session->serializer, send_topology_change_refresh, refresh_data);
+       if (res) {
+               topology_change_refresh_data_free(refresh_data);
+       }
+       return res;
+}
+
 /*! \brief Function called by core to ask the channel to indicate some sort of condition */
 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
 {
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
-       struct chan_pjsip_pvt *pvt = channel->pvt;
        struct ast_sip_session_media *media;
        int response_code = 0;
        int res = 0;
        char *device_buf;
        size_t device_buf_size;
+       int i;
+       const struct ast_stream_topology *topology;
 
        switch (condition) {
        case AST_CONTROL_RINGING:
@@ -1403,39 +1586,50 @@ static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const voi
                ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
                break;
        case AST_CONTROL_VIDUPDATE:
-               media = pvt->media[SIP_MEDIA_VIDEO];
-               if (media && media->rtp) {
-                       /* FIXME: Only use this for VP8. Additional work would have to be done to
-                        * fully support other video codecs */
-
-                       if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL) {
-                               /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
-                                * RTP engine would provide a way to externally write/schedule RTCP
-                                * packets */
-                               struct ast_frame fr;
-                               fr.frametype = AST_FRAME_CONTROL;
-                               fr.subclass.integer = AST_CONTROL_VIDUPDATE;
-                               res = ast_rtp_instance_write(media->rtp, &fr);
-                       } else {
-                               ao2_ref(channel->session, +1);
-#ifdef HAVE_PJSIP_INV_SESSION_REF
-                               if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
-                                       ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
-                                       ao2_cleanup(channel->session);
+               for (i = 0; i < AST_VECTOR_SIZE(&channel->session->active_media_state->sessions); ++i) {
+                       media = AST_VECTOR_GET(&channel->session->active_media_state->sessions, i);
+                       if (!media || media->type != AST_MEDIA_TYPE_VIDEO) {
+                               continue;
+                       }
+                       if (media->rtp) {
+                               /* FIXME: Only use this for VP8. Additional work would have to be done to
+                                * fully support other video codecs */
+
+                               if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL ||
+                                       ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp9) != AST_FORMAT_CMP_NOT_EQUAL ||
+                                       (channel->session->endpoint->media.webrtc &&
+                                        ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_h264) != AST_FORMAT_CMP_NOT_EQUAL)) {
+                                       /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
+                                        * RTP engine would provide a way to externally write/schedule RTCP
+                                        * packets */
+                                       struct ast_frame fr;
+                                       fr.frametype = AST_FRAME_CONTROL;
+                                       fr.subclass.integer = AST_CONTROL_VIDUPDATE;
+                                       res = ast_rtp_instance_write(media->rtp, &fr);
                                } else {
-#endif
-                                       if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
+                                       ao2_ref(channel->session, +1);
+#ifdef HAVE_PJSIP_INV_SESSION_REF
+                                       if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
+                                               ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
                                                ao2_cleanup(channel->session);
-                                       }
+                                       } else {
+#endif
+                                               if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
+                                                       ao2_cleanup(channel->session);
+                                               }
 #ifdef HAVE_PJSIP_INV_SESSION_REF
-                               }
+                                       }
 #endif
+                               }
+                               ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Success");
+                       } else {
+                               ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Failure");
+                               res = -1;
                        }
-                       ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Success");
-               } else {
-                       ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Failure");
-                       res = -1;
                }
+               /* XXX If there were no video streams, then this should set
+                * res to -1
+                */
                break;
        case AST_CONTROL_CONNECTED_LINE:
                ao2_ref(channel->session, +1);
@@ -1531,6 +1725,10 @@ static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const voi
                }
 
                break;
+       case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
+               topology = data;
+               res = handle_topology_request_change(channel->session, topology);
+               break;
        case -1:
                res = -1;
                break;
@@ -1744,10 +1942,11 @@ static int chan_pjsip_transfer(struct ast_channel *chan, const char *target)
 static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
 {
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
-       struct chan_pjsip_pvt *pvt = channel->pvt;
-       struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
+       struct ast_sip_session_media *media;
        int res = 0;
 
+       media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
+
        switch (channel->session->endpoint->dtmf) {
        case AST_SIP_DTMF_RFC_4733:
                if (!media || !media->rtp) {
@@ -1755,14 +1954,20 @@ static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
                }
 
                ast_rtp_instance_dtmf_begin(media->rtp, digit);
-                break;
+               break;
        case AST_SIP_DTMF_AUTO:
-                       if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
-                        return -1;
-                }
+               if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
+                       return -1;
+               }
 
-                ast_rtp_instance_dtmf_begin(media->rtp, digit);
-                break;
+               ast_rtp_instance_dtmf_begin(media->rtp, digit);
+               break;
+       case AST_SIP_DTMF_AUTO_INFO:
+               if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_NONE)) {
+                       return -1;
+               }
+               ast_rtp_instance_dtmf_begin(media->rtp, digit);
+               break;
        case AST_SIP_DTMF_NONE:
                break;
        case AST_SIP_DTMF_INBAND:
@@ -1858,11 +2063,26 @@ failure:
 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
 {
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
-       struct chan_pjsip_pvt *pvt = channel->pvt;
-       struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
+       struct ast_sip_session_media *media;
        int res = 0;
 
+       media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
+
        switch (channel->session->endpoint->dtmf) {
+       case AST_SIP_DTMF_AUTO_INFO:
+       {
+               if (!media || !media->rtp) {
+                       return -1;
+               }
+               if (ast_rtp_instance_dtmf_mode_get(media->rtp) != AST_RTP_DTMF_MODE_NONE) {
+                       ast_debug(3, "Told to send end of digit on Auto-Info channel %s RFC4733 negotiated so using it.\n", ast_channel_name(ast));
+                       ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
+                       break;
+               }
+               /* If RFC_4733 was not negotiated, fail through to the DTMF_INFO processing */
+               ast_debug(3, "Told to send end of digit on Auto-Info channel %s RFC4733 NOT negotiated using INFO instead.\n", ast_channel_name(ast));
+       }
+
        case AST_SIP_DTMF_INFO:
        {
                struct info_dtmf_data *dtmf_data = info_dtmf_data_alloc(channel->session, digit, duration);
@@ -1895,14 +2115,15 @@ static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned in
                }
 
                ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
-                break;
-        case AST_SIP_DTMF_AUTO:
-                if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
-                        return -1;
-                }
+               break;
+       case AST_SIP_DTMF_AUTO:
+               if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
+                        return -1;
+               }
+
+               ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
+               break;
 
-                ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
-                break;
 
        case AST_SIP_DTMF_NONE:
                break;
@@ -1943,7 +2164,6 @@ static int call(void *data)
 {
        struct ast_sip_channel_pvt *channel = data;
        struct ast_sip_session *session = channel->session;
-       struct chan_pjsip_pvt *pvt = channel->pvt;
        pjsip_tx_data *tdata;
 
        int res = ast_sip_session_create_invite(session, &tdata);
@@ -1952,7 +2172,7 @@ static int call(void *data)
                ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
                ast_queue_hangup(session->channel);
        } else {
-               set_channel_on_rtp_instance(pvt, ast_channel_uniqueid(session->channel));
+               set_channel_on_rtp_instance(session, ast_channel_uniqueid(session->channel));
                update_initial_connected_line(session);
                ast_sip_session_send_request(session, tdata);
        }
@@ -2050,10 +2270,10 @@ static struct hangup_data *hangup_data_alloc(int cause, struct ast_channel *chan
 }
 
 /*! \brief Clear a channel from a session along with its PVT */
-static void clear_session_and_channel(struct ast_sip_session *session, struct ast_channel *ast, struct chan_pjsip_pvt *pvt)
+static void clear_session_and_channel(struct ast_sip_session *session, struct ast_channel *ast)
 {
        session->channel = NULL;
-       set_channel_on_rtp_instance(pvt, "");
+       set_channel_on_rtp_instance(session, "");
        ast_channel_tech_pvt_set(ast, NULL);
 }
 
@@ -2062,7 +2282,6 @@ static int hangup(void *data)
        struct hangup_data *h_data = data;
        struct ast_channel *ast = h_data->chan;
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
-       struct chan_pjsip_pvt *pvt = channel->pvt;
        struct ast_sip_session *session = channel->session;
        int cause = h_data->cause;
 
@@ -2072,7 +2291,7 @@ static int hangup(void *data)
         * afterwards.
         */
        ast_sip_session_terminate(ao2_bump(session), cause);
-       clear_session_and_channel(session, ast, pvt);
+       clear_session_and_channel(session, ast);
        ao2_cleanup(session);
        ao2_cleanup(channel);
        ao2_cleanup(h_data);
@@ -2083,7 +2302,6 @@ static int hangup(void *data)
 static int chan_pjsip_hangup(struct ast_channel *ast)
 {
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
-       struct chan_pjsip_pvt *pvt;
        int cause;
        struct hangup_data *h_data;
 
@@ -2091,7 +2309,6 @@ static int chan_pjsip_hangup(struct ast_channel *ast)
                return -1;
        }
 
-       pvt = channel->pvt;
        cause = hangup_cause2sip(ast_channel_hangupcause(channel->session->channel));
        h_data = hangup_data_alloc(cause, ast);
 
@@ -2110,7 +2327,7 @@ failure:
        /* Go ahead and do our cleanup of the session and channel even if we're not going
         * to be able to send our SIP request/response
         */
-       clear_session_and_channel(channel->session, ast, pvt);
+       clear_session_and_channel(channel->session, ast);
        ao2_cleanup(channel);
        ao2_cleanup(h_data);
 
@@ -2119,7 +2336,7 @@ failure:
 
 struct request_data {
        struct ast_sip_session *session;
-       struct ast_format_cap *caps;
+       struct ast_stream_topology *topology;
        const char *dest;
        int cause;
 };
@@ -2193,7 +2410,7 @@ static int request(void *obj)
                }
        }
 
-       if (!(session = ast_sip_session_create_outgoing(endpoint, NULL, args.aor, request_user, req_data->caps))) {
+       if (!(session = ast_sip_session_create_outgoing(endpoint, NULL, args.aor, request_user, req_data->topology))) {
                ast_log(LOG_ERROR, "Failed to create outgoing session to endpoint '%s'\n", endpoint_name);
                req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
                return -1;
@@ -2205,12 +2422,12 @@ static int request(void *obj)
 }
 
 /*! \brief Function called by core to create a new outgoing PJSIP session */
-static struct ast_channel *chan_pjsip_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 struct ast_channel *chan_pjsip_request_with_stream_topology(const char *type, struct ast_stream_topology *topology, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
 {
        struct request_data req_data;
        RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
 
-       req_data.caps = cap;
+       req_data.topology = topology;
        req_data.dest = data;
 
        if (ast_sip_push_task_synchronous(NULL, request, &req_data)) {
@@ -2228,6 +2445,23 @@ static struct ast_channel *chan_pjsip_request(const char *type, struct ast_forma
        return session->channel;
 }
 
+static struct ast_channel *chan_pjsip_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)
+{
+       struct ast_stream_topology *topology;
+       struct ast_channel *chan;
+
+       topology = ast_stream_topology_create_from_format_cap(cap);
+       if (!topology) {
+               return NULL;
+       }
+
+       chan = chan_pjsip_request_with_stream_topology(type, topology, assignedids, requestor, data, cause);
+
+       ast_stream_topology_free(topology);
+
+       return chan;
+}
+
 struct sendtext_data {
        struct ast_sip_session *session;
        char text[0];
index aaeb01e..f2daf2b 100644 (file)
 #include "asterisk/threadstorage.h"
 #include "asterisk/translate.h"
 #include "asterisk/ast_version.h"
-#include "asterisk/data.h"
 #include "asterisk/aoc.h"
 #include "asterisk/message.h"
 #include "sip/include/sip.h"
@@ -33278,17 +33277,17 @@ static int reload_config(enum channelreloadreason reason)
 
                /* If TCP is running on a different IP than UDP, then add it too */
                if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
-                   !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
+                   ast_sockaddr_cmp_addr(&bindaddr, &sip_tcp_desc.local_address)) {
                        add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
                                       SIP_DOMAIN_AUTO, NULL);
                }
 
                /* If TLS is running on a different IP than UDP and TCP, then add that too */
                if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
-                   !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
-                   !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
+                   ast_sockaddr_cmp_addr(&bindaddr, &sip_tls_desc.local_address) &&
+                   ast_sockaddr_cmp_addr(&sip_tcp_desc.local_address,
                                      &sip_tls_desc.local_address)) {
-                       add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
+                       add_sip_domain(ast_sockaddr_stringify_addr(&sip_tls_desc.local_address),
                                       SIP_DOMAIN_AUTO, NULL);
                }
 
@@ -34530,75 +34529,6 @@ AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
        return res;
 }
 
-AST_TEST_DEFINE(test_sip_peers_get)
-{
-       struct sip_peer *peer;
-       struct ast_data *node;
-       struct ast_data_query query = {
-               .path = "/asterisk/channel/sip/peers",
-               .search = "peers/peer/name=test_peer_data_provider"
-       };
-
-       switch (cmd) {
-               case TEST_INIT:
-                       info->name = "sip_peers_get_data_test";
-                       info->category = "/main/data/sip/peers/";
-                       info->summary = "SIP peers data providers unit test";
-                       info->description =
-                               "Tests whether the SIP peers data provider implementation works as expected.";
-                       return AST_TEST_NOT_RUN;
-               case TEST_EXECUTE:
-                       break;
-       }
-
-       /* Create the peer that we will retrieve. */
-       peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
-       if (!peer) {
-               return AST_TEST_FAIL;
-       }
-       peer->type = SIP_TYPE_USER;
-       peer->call_limit = 10;
-       ao2_link(peers, peer);
-
-       /* retrieve the chan_sip/peers tree and check the created peer. */
-       node = ast_data_get(&query);
-       if (!node) {
-               ao2_unlink(peers, peer);
-               ao2_ref(peer, -1);
-               return AST_TEST_FAIL;
-       }
-
-       /* compare item. */
-       if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
-               ao2_unlink(peers, peer);
-               ao2_ref(peer, -1);
-               ast_data_free(node);
-               return AST_TEST_FAIL;
-       }
-
-       if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
-               ao2_unlink(peers, peer);
-               ao2_ref(peer, -1);
-               ast_data_free(node);
-               return AST_TEST_FAIL;
-       }
-
-       if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
-               ao2_unlink(peers, peer);
-               ao2_ref(peer, -1);
-               ast_data_free(node);
-               return AST_TEST_FAIL;
-       }
-
-       /* release resources */
-       ast_data_free(node);
-
-       ao2_unlink(peers, peer);
-       ao2_ref(peer, -1);
-
-       return AST_TEST_PASS;
-}
-
 /*!
  * \brief Imitation TCP reception loop
  *
@@ -35130,170 +35060,6 @@ AST_TEST_DEFINE(get_in_brackets_const_test)
 
 #endif
 
-#define DATA_EXPORT_SIP_PEER(MEMBER)                           \
-       MEMBER(sip_peer, name, AST_DATA_STRING)                 \
-       MEMBER(sip_peer, secret, AST_DATA_PASSWORD)             \
-       MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD)          \
-       MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD)       \
-       MEMBER(sip_peer, context, AST_DATA_STRING)              \
-       MEMBER(sip_peer, subscribecontext, AST_DATA_STRING)     \
-       MEMBER(sip_peer, username, AST_DATA_STRING)             \
-       MEMBER(sip_peer, accountcode, AST_DATA_STRING)          \
-       MEMBER(sip_peer, tohost, AST_DATA_STRING)               \
-       MEMBER(sip_peer, regexten, AST_DATA_STRING)             \
-       MEMBER(sip_peer, fromuser, AST_DATA_STRING)             \
-       MEMBER(sip_peer, fromdomain, AST_DATA_STRING)           \
-       MEMBER(sip_peer, fullcontact, AST_DATA_STRING)          \
-       MEMBER(sip_peer, cid_num, AST_DATA_STRING)              \
-       MEMBER(sip_peer, cid_name, AST_DATA_STRING)             \
-       MEMBER(sip_peer, vmexten, AST_DATA_STRING)              \
-       MEMBER(sip_peer, language, AST_DATA_STRING)             \
-       MEMBER(sip_peer, mohinterpret, AST_DATA_STRING)         \
-       MEMBER(sip_peer, mohsuggest, AST_DATA_STRING)           \
-       MEMBER(sip_peer, parkinglot, AST_DATA_STRING)           \
-       MEMBER(sip_peer, useragent, AST_DATA_STRING)            \
-       MEMBER(sip_peer, mwi_from, AST_DATA_STRING)             \
-       MEMBER(sip_peer, engine, AST_DATA_STRING)               \
-       MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING)  \
-       MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN)         \
-       MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN)        \
-       MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN)         \
-       MEMBER(sip_peer, inuse, AST_DATA_INTEGER)               \
-       MEMBER(sip_peer, ringing, AST_DATA_INTEGER)             \
-       MEMBER(sip_peer, onhold, AST_DATA_INTEGER)              \
-       MEMBER(sip_peer, call_limit, AST_DATA_INTEGER)          \
-       MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER)     \
-       MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER)      \
-       MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS)          \
-       MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS)      \
-       MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS)        \
-       MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS)         \
-       MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS)          \
-       MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS)    \
-       MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS)       \
-       MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)        \
-       MEMBER(sip_peer, description, AST_DATA_STRING)
-
-AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
-
-static int peers_data_provider_get(const struct ast_data_search *search,
-       struct ast_data *data_root)
-{
-       struct sip_peer *peer;
-       struct ao2_iterator i;
-       struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
-       struct ast_data *data_sip_options;
-       int total_mailboxes, x;
-       struct sip_mailbox *mailbox;
-
-       i = ao2_iterator_init(peers, 0);
-       while ((peer = ao2_iterator_next(&i))) {
-               ao2_lock(peer);
-
-               data_peer = ast_data_add_node(data_root, "peer");
-               if (!data_peer) {
-                       ao2_unlock(peer);
-                       ao2_ref(peer, -1);
-                       continue;
-               }
-
-               ast_data_add_structure(sip_peer, data_peer, peer);
-
-               /* transfer mode */
-               enum_node = ast_data_add_node(data_peer, "allowtransfer");
-               if (!enum_node) {
-                       ao2_unlock(peer);
-                       ao2_ref(peer, -1);
-                       continue;
-               }
-               ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
-               ast_data_add_int(enum_node, "value", peer->allowtransfer);
-
-               /* transports */
-               ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
-
-               /* peer type */
-               if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
-                       ast_data_add_str(data_peer, "type", "friend");
-               } else if (peer->type & SIP_TYPE_PEER) {
-                       ast_data_add_str(data_peer, "type", "peer");
-               } else if (peer->type & SIP_TYPE_USER) {
-                       ast_data_add_str(data_peer, "type", "user");
-               }
-
-               /* mailboxes */
-               total_mailboxes = 0;
-               AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
-                       if (!total_mailboxes) {
-                               data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
-                               if (!data_peer_mailboxes) {
-                                       break;
-                               }
-                               total_mailboxes++;
-                       }
-
-                       data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
-                       if (!data_peer_mailbox) {
-                               continue;
-                       }
-                       ast_data_add_str(data_peer_mailbox, "id", mailbox->id);
-               }
-
-               /* amaflags */
-               enum_node = ast_data_add_node(data_peer, "amaflags");
-               if (!enum_node) {
-                       ao2_unlock(peer);
-                       ao2_ref(peer, -1);
-                       continue;
-               }
-               ast_data_add_int(enum_node, "value", peer->amaflags);
-               ast_data_add_str(enum_node, "text", ast_channel_amaflags2string(peer->amaflags));
-
-               /* sip options */
-               data_sip_options = ast_data_add_node(data_peer, "sipoptions");
-               if (!data_sip_options) {
-                       ao2_unlock(peer);
-                       ao2_ref(peer, -1);
-                       continue;
-               }
-               for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
-                       ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
-               }
-
-               /* callingpres */
-               enum_node = ast_data_add_node(data_peer, "callingpres");
-               if (!enum_node) {
-                       ao2_unlock(peer);
-                       ao2_ref(peer, -1);
-                       continue;
-               }
-               ast_data_add_int(enum_node, "value", peer->callingpres);
-               ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
-
-               /* codecs */
-               ast_data_add_codecs(data_peer, "codecs", peer->caps);
-
-               if (!ast_data_search_match(search, data_peer)) {
-                       ast_data_remove_node(data_root, data_peer);
-               }
-
-               ao2_unlock(peer);
-               ao2_ref(peer, -1);
-       }
-       ao2_iterator_destroy(&i);
-
-       return 0;
-}
-
-static const struct ast_data_handler peers_data_provider = {
-       .version = AST_DATA_HANDLER_VERSION,
-       .get = peers_data_provider_get
-};
-
-static const struct ast_data_entry sip_data_providers[] = {
-       AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
-};
-
 static const struct ast_sip_api_tech chan_sip_api_provider = {
        .version = AST_SIP_API_VERSION,
        .name = "chan_sip",
@@ -35414,15 +35180,11 @@ static int load_module(void)
        }
 
 #ifdef TEST_FRAMEWORK
-       AST_TEST_REGISTER(test_sip_peers_get);
        AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
        AST_TEST_REGISTER(test_tcp_message_fragmentation);
        AST_TEST_REGISTER(get_in_brackets_const_test);
 #endif
 
-       /* Register AstData providers */
-       ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
-
        /* Register all CLI functions for SIP */
        ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
 
@@ -35549,14 +35311,10 @@ static int unload_module(void)
 #ifdef TEST_FRAMEWORK
        ast_unregister_application(app_sipsendcustominfo);
 
-       AST_TEST_UNREGISTER(test_sip_peers_get);
        AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
        AST_TEST_UNREGISTER(test_tcp_message_fragmentation);
        AST_TEST_UNREGISTER(get_in_brackets_const_test);
 #endif
-       /* Unregister all the AstData providers */
-       ast_data_unregister(NULL);
-
        /* Unregister CLI commands */
        ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
 
index fc14b25..33d0e02 100644 (file)
@@ -342,8 +342,9 @@ static int cli_channelstats_print_body(void *obj, void *arg, int flags)
        const struct ast_channel_snapshot *snapshot = obj;
        struct ast_channel *channel = ast_channel_get_by_name(snapshot->name);
        struct ast_sip_channel_pvt *cpvt = channel ? ast_channel_tech_pvt(channel) : NULL;
-       struct chan_pjsip_pvt *pvt = cpvt ? cpvt->pvt : NULL;
-       struct ast_sip_session_media *media = pvt ? pvt->media[SIP_MEDIA_AUDIO] : NULL;
+       struct ast_sip_session *session;
+       struct ast_sip_session_media *media;
+       struct ast_rtp_instance *rtp;
        struct ast_rtp_instance_stats stats;
        char *print_name = NULL;
        char *print_time = alloca(32);
@@ -351,29 +352,46 @@ static int cli_channelstats_print_body(void *obj, void *arg, int flags)
 
        ast_assert(context->output_buffer != NULL);
 
+       if (!channel) {
+               ast_str_append(&context->output_buffer, 0, " %s not valid\n", snapshot->name);
+               return -1;
+       }
+
+       ast_channel_lock(channel);
+
+       session = cpvt->session;
+       if (!session) {
+               ast_str_append(&context->output_buffer, 0, " %s not valid\n", snapshot->name);
+               ast_channel_unlock(channel);
+               ao2_cleanup(channel);
+               return -1;
+       }
+
+       media = session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
        if (!media || !media->rtp) {
                ast_str_append(&context->output_buffer, 0, " %s not valid\n", snapshot->name);
+               ast_channel_unlock(channel);
                ao2_cleanup(channel);
                return -1;
        }
 
+       rtp = ao2_bump(media->rtp);
+
        codec_in_use[0] = '\0';
 
-       if (channel) {
-               ast_channel_lock(channel);
-               if (ast_channel_rawreadformat(channel)) {
-                       ast_copy_string(codec_in_use, ast_format_get_name(ast_channel_rawreadformat(channel)), sizeof(codec_in_use));
-               }
-               ast_channel_unlock(channel);
+       if (ast_channel_rawreadformat(channel)) {
+               ast_copy_string(codec_in_use, ast_format_get_name(ast_channel_rawreadformat(channel)), sizeof(codec_in_use));
        }
 
+       ast_channel_unlock(channel);
+
        print_name = ast_strdupa(snapshot->name);
        /* Skip the PJSIP/.  We know what channel type it is and we need the space. */
        print_name += 6;
 
        ast_format_duration_hh_mm_ss(ast_tvnow().tv_sec - snapshot->creationtime.tv_sec, print_time, 32);
 
-       if (ast_rtp_instance_get_stats(media->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
+       if (ast_rtp_instance_get_stats(rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
                ast_str_append(&context->output_buffer, 0, "%s direct media\n", snapshot->name);
        } else {
                ast_str_append(&context->output_buffer, 0,
@@ -398,6 +416,7 @@ static int cli_channelstats_print_body(void *obj, void *arg, int flags)
                );
        }
 
+       ao2_cleanup(rtp);
        ao2_cleanup(channel);
 
        return 0;
index e2c78cd..59ca9d7 100644 (file)
 #include "asterisk/acl.h"
 #include "asterisk/app.h"
 #include "asterisk/channel.h"
+#include "asterisk/stream.h"
 #include "asterisk/format.h"
 #include "asterisk/pbx.h"
 #include "asterisk/res_pjsip.h"
@@ -461,8 +462,8 @@ static const char *t38state_to_string[T38_MAX_ENUM] = {
 static int channel_read_rtp(struct ast_channel *chan, const char *type, const char *field, char *buf, size_t buflen)
 {
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
-       struct chan_pjsip_pvt *pvt;
-       struct ast_sip_session_media *media = NULL;
+       struct ast_sip_session *session;
+       struct ast_sip_session_media *media;
        struct ast_sockaddr addr;
 
        if (!channel) {
@@ -470,9 +471,9 @@ static int channel_read_rtp(struct ast_channel *chan, const char *type, const ch
                return -1;
        }
 
-       pvt = channel->pvt;
-       if (!pvt) {
-               ast_log(AST_LOG_WARNING, "Channel %s has no chan_pjsip pvt!\n", ast_channel_name(chan));
+       session = channel->session;
+       if (!session) {
+               ast_log(AST_LOG_WARNING, "Channel %s has no session!\n", ast_channel_name(chan));
                return -1;
        }
 
@@ -482,9 +483,9 @@ static int channel_read_rtp(struct ast_channel *chan, const char *type, const ch
        }
 
        if (ast_strlen_zero(field) || !strcmp(field, "audio")) {
-               media = pvt->media[SIP_MEDIA_AUDIO];
+               media = session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
        } else if (!strcmp(field, "video")) {
-               media = pvt->media[SIP_MEDIA_VIDEO];
+               media = session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO];
        } else {
                ast_log(AST_LOG_WARNING, "Unknown media type field '%s' for 'rtp' information\n", field);
                return -1;
@@ -522,17 +523,17 @@ static int channel_read_rtp(struct ast_channel *chan, const char *type, const ch
 static int channel_read_rtcp(struct ast_channel *chan, const char *type, const char *field, char *buf, size_t buflen)
 {
        struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
-       struct chan_pjsip_pvt *pvt;
-       struct ast_sip_session_media *media = NULL;
+       struct ast_sip_session *session;
+       struct ast_sip_session_media *media;
 
        if (!channel) {
                ast_log(AST_LOG_WARNING, "Channel %s has no pvt!\n", ast_channel_name(chan));
                return -1;
        }
 
-       pvt = channel->pvt;
-       if (!pvt) {
-               ast_log(AST_LOG_WARNING, "Channel %s has no chan_pjsip pvt!\n", ast_channel_name(chan));
+       session = channel->session;
+       if (!session) {
+               ast_log(AST_LOG_WARNING, "Channel %s has no session!\n", ast_channel_name(chan));
                return -1;
        }
 
@@ -542,9 +543,9 @@ static int channel_read_rtcp(struct ast_channel *chan, const char *type, const c
        }
 
        if (ast_strlen_zero(field) || !strcmp(field, "audio")) {
-               media = pvt->media[SIP_MEDIA_AUDIO];
+               media = session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
        } else if (!strcmp(field, "video")) {
-               media = pvt->media[SIP_MEDIA_VIDEO];
+               media = session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO];
        } else {
                ast_log(AST_LOG_WARNING, "Unknown media type field '%s' for 'rtcp' information\n", field);
                return -1;
@@ -924,22 +925,117 @@ int pjsip_acf_dial_contacts_read(struct ast_channel *chan, const char *cmd, char
        return 0;
 }
 
+/*! \brief Session refresh state information */
+struct session_refresh_state {
+       /*! \brief Created proposed media state */
+       struct ast_sip_session_media_state *media_state;
+};
+
+/*! \brief Destructor for session refresh information */
+static void session_refresh_state_destroy(void *obj)
+{
+       struct session_refresh_state *state = obj;
+
+       ast_sip_session_media_state_free(state->media_state);
+       ast_free(obj);
+}
+
+/*! \brief Datastore for attaching session refresh state information */
+static const struct ast_datastore_info session_refresh_datastore = {
+       .type = "pjsip_session_refresh",
+       .destroy = session_refresh_state_destroy,
+};
+
+/*! \brief Helper function which retrieves or allocates a session refresh state information datastore */
+static struct session_refresh_state *session_refresh_state_get_or_alloc(struct ast_sip_session *session)
+{
+       RAII_VAR(struct ast_datastore *, datastore, ast_sip_session_get_datastore(session, "pjsip_session_refresh"), ao2_cleanup);
+       struct session_refresh_state *state;
+
+       /* While the datastore refcount is decremented this is operating in the serializer so it will remain valid regardless */
+       if (datastore) {
+               return datastore->data;
+       }
+
+       if (!(datastore = ast_sip_session_alloc_datastore(&session_refresh_datastore, "pjsip_session_refresh"))
+               || !(datastore->data = ast_calloc(1, sizeof(struct session_refresh_state)))
+               || ast_sip_session_add_datastore(session, datastore)) {
+               return NULL;
+       }
+
+       state = datastore->data;
+       state->media_state = ast_sip_session_media_state_alloc();
+       if (!state->media_state) {
+               ast_sip_session_remove_datastore(session, "pjsip_session_refresh");
+               return NULL;
+       }
+       state->media_state->topology = ast_stream_topology_clone(session->endpoint->media.topology);
+       if (!state->media_state->topology) {
+               ast_sip_session_remove_datastore(session, "pjsip_session_refresh");
+               return NULL;
+       }
+
+       datastore->data = state;
+
+       return state;
+}
+
 static int media_offer_read_av(struct ast_sip_session *session, char *buf,
                               size_t len, enum ast_media_type media_type)
 {
+       struct ast_stream_topology *topology;
        int idx;
+       struct ast_stream *stream = NULL;
+       struct ast_format_cap *caps;
        size_t accum = 0;
 
+       if (session->inv_session->dlg->state == PJSIP_DIALOG_STATE_ESTABLISHED) {
+               struct session_refresh_state *state;
+
+               /* As we've already answered we need to store our media state until we are ready to send it */
+               state = session_refresh_state_get_or_alloc(session);
+               if (!state) {
+                       return -1;
+               }
+               topology = state->media_state->topology;
+       } else {
+               /* The session is not yet up so we are initially answering or offering */
+               if (!session->pending_media_state->topology) {
+                       session->pending_media_state->topology = ast_stream_topology_clone(session->endpoint->media.topology);
+                       if (!session->pending_media_state->topology) {
+                               return -1;
+                       }
+               }
+               topology = session->pending_media_state->topology;
+       }
+
+       /* Find the first suitable stream */
+       for (idx = 0; idx < ast_stream_topology_get_count(topology); ++idx) {
+               stream = ast_stream_topology_get_stream(topology, idx);
+
+               if (ast_stream_get_type(stream) != media_type ||
+                       ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED) {
+                       stream = NULL;
+                       continue;
+               }
+
+               break;
+       }
+
+       /* If no suitable stream then exit early */
+       if (!stream) {
+               buf[0] = '\0';
+               return 0;
+       }
+
+       caps = ast_stream_get_formats(stream);
+
        /* Note: buf is not terminated while the string is being built. */
-       for (idx = 0; idx < ast_format_cap_count(session->req_caps); ++idx) {
+       for (idx = 0; idx < ast_format_cap_count(caps); ++idx) {
                struct ast_format *fmt;
                size_t size;
 
-               fmt = ast_format_cap_get_format(session->req_caps, idx);
-               if (ast_format_get_type(fmt) != media_type) {
-                       ao2_ref(fmt, -1);
-                       continue;
-               }
+               fmt = ast_format_cap_get_format(caps, idx);
 
                /* Add one for a comma or terminator */
                size = strlen(ast_format_get_name(fmt)) + 1;
@@ -973,9 +1069,43 @@ struct media_offer_data {
 static int media_offer_write_av(void *obj)
 {
        struct media_offer_data *data = obj;
+       struct ast_stream_topology *topology;
+       struct ast_stream *stream;
+       struct ast_format_cap *caps;
 
-       ast_format_cap_remove_by_type(data->session->req_caps, data->media_type);
-       ast_format_cap_update_by_allow_disallow(data->session->req_caps, data->value, 1);
+       if (data->session->inv_session->dlg->state == PJSIP_DIALOG_STATE_ESTABLISHED) {
+               struct session_refresh_state *state;
+
+               /* As we've already answered we need to store our media state until we are ready to send it */
+               state = session_refresh_state_get_or_alloc(data->session);
+               if (!state) {
+                       return -1;
+               }
+               topology = state->media_state->topology;
+       } else {
+               /* The session is not yet up so we are initially answering or offering */
+               if (!data->session->pending_media_state->topology) {
+                       data->session->pending_media_state->topology = ast_stream_topology_clone(data->session->endpoint->media.topology);
+                       if (!data->session->pending_media_state->topology) {
+                               return -1;
+                       }
+               }
+               topology = data->session->pending_media_state->topology;
+       }
+
+       /* XXX This method won't work when it comes time to do multistream support. The proper way to do this
+        * will either be to
+        * a) Alter all media streams of a particular type.
+        * b) Change the dialplan function to be able to specify which stream to alter and alter only that
+        * one stream
+        */
+       stream = ast_stream_topology_get_first_stream_by_type(topology, data->media_type);
+       if (!stream) {
+               return 0;
+       }
+       caps = ast_stream_get_formats(stream);
+       ast_format_cap_remove_by_type(caps, data->media_type);
+       ast_format_cap_update_by_allow_disallow(caps, data->value, 1);
 
        return 0;
 }
@@ -1068,9 +1198,18 @@ static int sip_session_response_cb(struct ast_sip_session *session, pjsip_rx_dat
 static int refresh_write_cb(void *obj)
 {
        struct refresh_data *data = obj;
+       struct session_refresh_state *state;
+
+       state = session_refresh_state_get_or_alloc(data->session);
+       if (!state) {
+               return -1;
+       }
 
        ast_sip_session_refresh(data->session, NULL, NULL,
-               sip_session_response_cb, data->method, 1);
+               sip_session_response_cb, data->method, 1, state->media_state);
+
+       state->media_state = NULL;
+       ast_sip_session_remove_datastore(data->session, "pjsip_session_refresh");
 
        return 0;
 }
index b229a04..1fee864 100644 (file)
@@ -34,25 +34,12 @@ struct transport_info_data {
        pj_sockaddr local_addr;
 };
 
-/*!
- * \brief Positions of various media
- */
-enum sip_session_media_position {
-       /*! \brief First is audio */
-       SIP_MEDIA_AUDIO = 0,
-       /*! \brief Second is video */
-       SIP_MEDIA_VIDEO,
-       /*! \brief Last is the size for media details */
-       SIP_MEDIA_SIZE,
-};
 
 /*!
  * \brief The PJSIP channel driver pvt, stored in the \ref ast_sip_channel_pvt
  * data structure
  */
 struct chan_pjsip_pvt {
-       /*! \brief The available media sessions */
-       struct ast_sip_session_media *media[SIP_MEDIA_SIZE];
 };
 
 #endif /* _CHAN_PJSIP_HEADER */
index 8de58bf..9711745 100644 (file)
@@ -77,7 +77,6 @@ load = res_pjsip_exten_state.so
 load = res_pjsip_header_funcs.so
 load = res_pjsip_logger.so
 load = res_pjsip_messaging.so
-load = res_pjsip_multihomed.so
 load = res_pjsip_mwi_body_generator.so
 load = res_pjsip_mwi.so
 load = res_pjsip_nat.so
index e175a2a..1d0af78 100644 (file)
@@ -17,7 +17,7 @@
 ; party. Setting this to "yes" will make calls to extensions that don't answer
 ; and don't set a B side channel (such as by using the Dial application)
 ; receive CDR log entries. If this option is set to "no", then those log
-; entries will not be created. Unasnwered Calls which get offered to an
+; entries will not be created. Unanswered Calls which get offered to an
 ; outgoing line will always receive log entries regardless of this option, and
 ; that is the intended behaviour.
 ;unanswered = no
index 0e07f6b..265b953 100644 (file)
@@ -218,6 +218,12 @@ type=bridge
                            ; Default is en (English).
 
 ;regcontext=conferences    ; The name of the context into which to register conference names as extensions.
+;video_update_discard=2000 ; Amount of time (in milliseconds) to discard video update requests after sending a video
+                           ; update request. Default is 2000. A video update request is a request for a full video
+                           ; intra-frame. Clients can request this if they require a full frame in order to decode
+                           ; the video stream. Since a full frame can be large limiting how often they occur can
+                           ; reduce bandwidth usage at the cost of increasing how long it may take a newly joined
+                           ; channel to receive the video stream.
 
 ; All sounds in the conference are customizable using the bridge profile options below.
 ; Simply state the option followed by the filename or full path of the filename after
index 2fff45e..b7cb212 100644 (file)
@@ -6,6 +6,10 @@
 [global]
 intopt=-1
 uintopt=1
+timelenopt1=1ms
+timelenopt2=1s
+timelenopt3=1m
+timelenopt4=1h
 doubleopt=0.1
 sockaddropt=1.2.3.4:1234
 boolopt=true
@@ -23,6 +27,10 @@ customopt=yes
 [item]
 intopt=-1
 uintopt=1
+timelenopt1=1
+timelenopt2=1
+timelenopt3=1
+timelenopt4=1
 doubleopt=0.1
 sockaddropt=1.2.3.4:1234
 boolopt=true
index b2980fc..741bde6 100644 (file)
@@ -97,3 +97,26 @@ directory=moh
 ;mode=custom
 ;directory=/var/lib/asterisk/mohmp3
 ;application=/site/sw/bin/madplay -Q -o raw:- --mono -R 8000 -a -12
+
+; By default, when res_musiconhold reloads or unloads, it sends a HUP signal
+; to custom applications (and all descendants), waits 100ms, then sends a
+; TERM signal, waits 100ms, then finally sends a KILL signal.  An application
+; which is interacting with an external device and/or spawns children of its
+; own may not be able to exit cleanly in the default times, expecially if sent
+; a KILL signal, or if it's children are getting signals directly from
+; res_musiconhoild.  To allow extra time, the 'kill_escalation_delay'
+; class option can be used to set the number of milliseconds res_musiconhold
+; waits before escalating kill signals, with the default being the current
+; 100ms.  To control to whom the signals are sent, the "kill_method"
+; class option can be set to "process_group" (the default, existing behavior),
+; which sends signals to the application and its descendants directly, or
+; "process" which sends signals only to the application itself.
+
+;[sox_from_device]
+;mode=custom
+;directory=/var/lib/asterisk/mohmp3
+;application=/usr/bin/sox -q -t alsa -c 2 -r 48000 hw:1 -c 1 -r 8000 -t raw -s -
+; Wait 500ms before escalating kill signals
+;kill_escalation_delay=500
+; Send signals to just the child process instead of all descendants
+;kill_method=process
index a992ff8..3c3e52a 100644 (file)
 ;direct_media_glare_mitigation=none     ; Mitigation of direct media re INVITE
                                         ; glare (default: "none")
 ;direct_media_method=invite     ; Direct Media method type (default: "invite")
-;connected_line_method=invite   ; Connected line method type (default:
-                                ; "invite")
+;connected_line_method=invite   ; Connected line method type.
+                                ; When set to "invite", check the remote's
+                                ; Allow header and if UPDATE is allowed, send
+                                ; UPDATE instead of INVITE to avoid SDP
+                                ; renegotiation.  If UPDATE is not Allowed,
+                                ; send INVITE.
+                                ; If set to "update", send UPDATE regardless
+                                ; of what the remote Allows.
+                                ; (default: "invite")
 ;direct_media=yes       ; Determines whether media may flow directly between
                         ; endpoints (default: "yes")
 ;disable_direct_media_on_nat=no ; Disable direct media session refreshes when
                        ; transfer (default: "yes"). The value "no" is useful
                        ; for some SIP phones (Mitel/Aastra, Snom) which expect
                        ; a sip/frag "200 OK" after REFER has been accepted.
+;notify_early_inuse_ringing = ; Whether to notifies dialog-info 'early'
+                              ; on INUSE && RINGING state (default: "no").
+                              ; The value "yes" is useful for some SIP phones
+                              ; (Cisco SPA) to be able to indicate and pick up
+                              ; ringing devices.
+;max_audio_streams= ; The maximum number of allowed negotiated audio streams
+                    ; (default: 1)
+;max_video_streams= ; The maximum number of allowed negotiated video streams
+                    ; (default: 1)
+;webrtc= ; When set to "yes" this also enables the following values that are needed
+         ; for webrtc: rtcp_mux, use_avpf, ice_support, and use_received_transport.
+         ; The following configuration settings also get defaulted as follows:
+         ;     media_encryption=dtls
+         ;     dtls_verify=fingerprint
+         ;     dtls_setup=actpass
+         ; A dtls_cert_file and a dtls_ca_file still need to be specified.
+         ; Default for this option is "no"
 
 ;==========================AUTH SECTION OPTIONS=========================
 ;[auth]
index f8221ee..84e83a3 100644 (file)
@@ -227,6 +227,9 @@ pagerdateformat=%A, %B %d, %Y at %r
 ;imapclosetimeout=60     ; The TCP close timeout (in seconds)
 ;imapreadtimeout=60      ; The TCP read timeout (in seconds)
 ;imapwritetimeout=60     ; The TCP write timeout (in seconds)
+;imap_poll_logout=no     ; If pollmailboxes=yes, then specify whether need to
+                         ; disconnect from the IMAP server after polling.
+                         ; Default: no
 
 ; -----------------------------------------------------------------------------
 ;
index 361af88..5bb7523 100755 (executable)
--- a/