res_pjsip res_pjsip_mwi: Misc fixes and cleanups.
[asterisk/asterisk.git] / res / res_musiconhold.c
index 086139a..3c7199e 100644 (file)
 
 #include "asterisk.h"
 
-ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+ASTERISK_REGISTER_FILE()
 
 #include <ctype.h>
 #include <signal.h>
 #include <sys/time.h>
-#include <sys/signal.h>
+#include <signal.h>
 #include <netinet/in.h>
 #include <sys/stat.h>
 #include <dirent.h>
@@ -98,36 +98,6 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
                        an application such as Answer() or Progress().</para>
                </description>
        </application>
-       <application name="WaitMusicOnHold" language="en_US">
-               <synopsis>
-                       Wait, playing Music On Hold.
-               </synopsis>
-               <syntax>
-                       <parameter name="delay" required="true" />
-               </syntax>
-               <description>
-                       <para> !!! DEPRECATED. Use MusicOnHold instead !!!</para>
-                       <para>Plays hold music specified number of seconds. Returns <literal>0</literal> when done,
-                       or <literal>-1</literal> on hangup. If no hold music is available, the delay will still occur
-                       with no sound.</para>
-                       <para> !!! DEPRECATED. Use MusicOnHold instead !!!</para>
-               </description>
-       </application>
-       <application name="SetMusicOnHold" language="en_US">
-               <synopsis>
-                       Set default Music On Hold class.
-               </synopsis>
-               <syntax>
-                       <parameter name="class" required="yes" />
-               </syntax>
-               <description>
-                       <para>!!! DEPRECATED. USe Set(CHANNEL(musicclass)=...) instead !!!</para>
-                       <para>Sets the default class for music on hold for a given channel.
-                       When music on hold is activated, this class will be used to select which
-                       music is played.</para>
-                       <para>!!! DEPRECATED. USe Set(CHANNEL(musicclass)=...) instead !!!</para>
-               </description>
-       </application>
        <application name="StartMusicOnHold" language="en_US">
                <synopsis>
                        Play Music On Hold.
@@ -153,8 +123,6 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  ***/
 
 static const char play_moh[] = "MusicOnHold";
-static const char wait_moh[] = "WaitMusicOnHold";
-static const char set_moh[] = "SetMusicOnHold";
 static const char start_moh[] = "StartMusicOnHold";
 static const char stop_moh[] = "StopMusicOnHold";
 
@@ -163,15 +131,15 @@ static int respawn_time = 20;
 struct moh_files_state {
        /*! Holds a reference to the MOH class. */
        struct mohclass *class;
-       char name[MAX_MUSICCLASS];
-       struct ast_format origwfmt;
-       struct ast_format mohwfmt;
+       struct ast_format *origwfmt;
+       struct ast_format *mohwfmt;
        int announcement;
        int samples;
        int sample_queue;
        int pos;
        int save_pos;
        int save_total;
+       char name[MAX_MUSICCLASS];
        char save_pos_filename[PATH_MAX];
 };
 
@@ -180,9 +148,12 @@ struct moh_files_state {
 #define MOH_CUSTOM             (1 << 2)
 #define MOH_RANDOMIZE          (1 << 3)
 #define MOH_SORTALPHA          (1 << 4)
+#define MOH_RANDSTART          (MOH_RANDOMIZE | MOH_SORTALPHA) /*!< Sorted but start at random position */
+#define MOH_SORTMODE           (3 << 3)
 
-#define MOH_CACHERTCLASSES      (1 << 5)        /*!< Should we use a separate instance of MOH for each user or not */
-#define MOH_ANNOUNCEMENT       (1 << 6)                        /*!< Do we play announcement files between songs on this channel? */
+#define MOH_CACHERTCLASSES     (1 << 5)        /*!< Should we use a separate instance of MOH for each user or not */
+#define MOH_ANNOUNCEMENT       (1 << 6)        /*!< Do we play announcement files between songs on this channel? */
+#define MOH_PREFERCHANNELCLASS (1 << 7)        /*!< Should queue moh override channel moh */
 
 /* Custom astobj2 flag */
 #define MOH_NOTDELETED          (1 << 30)       /*!< Find only records that aren't deleted? */
@@ -204,7 +175,7 @@ struct mohclass {
        int total_files;
        unsigned int flags;
        /*! The format from the MOH source, not applicable to "files" mode */
-       struct ast_format format;
+       struct ast_format *format;
        /*! The pid of the external application delivering MOH */
        int pid;
        time_t start;
@@ -222,7 +193,7 @@ struct mohclass {
 
 struct mohdata {
        int pipe[2];
-       struct ast_format origwfmt;
+       struct ast_format *origwfmt;
        struct mohclass *parent;
        struct ast_frame f;
        AST_LIST_ENTRY(mohdata) list;
@@ -234,36 +205,75 @@ static struct ao2_container *mohclasses;
 #define MPG_123 "/usr/bin/mpg123"
 #define MAX_MP3S 256
 
+static void moh_parse_options(struct ast_variable *var, struct mohclass *mohclass);
 static int reload(void);
 
 #define mohclass_ref(class,string)   (ao2_t_ref((class), +1, (string)), class)
 
-#ifndef REF_DEBUG
-#define mohclass_unref(class,string) (ao2_t_ref((class), -1, (string)), (struct mohclass *) NULL)
+#ifndef AST_DEVMODE
+#define mohclass_unref(class,string) ({ ao2_t_ref((class), -1, (string)); (struct mohclass *) NULL; })
 #else
 #define mohclass_unref(class,string) _mohclass_unref(class, string, __FILE__,__LINE__,__PRETTY_FUNCTION__)
 static struct mohclass *_mohclass_unref(struct mohclass *class, const char *tag, const char *file, int line, const char *funcname)
 {
-       struct mohclass *dup;
-       if ((dup = ao2_find(mohclasses, class, OBJ_POINTER))) {
-               if (__ao2_ref_debug(dup, -1, (char *) tag, (char *) file, line, funcname) == 2) {
-                       FILE *ref = fopen("/tmp/refs", "a");
-                       if (ref) {
-                               fprintf(ref, "%p =1   %s:%d:%s (%s) BAD ATTEMPT!\n", class, file, line, funcname, tag);
-                               fclose(ref);
-                       }
+       struct mohclass *dup = ao2_callback(mohclasses, OBJ_POINTER, ao2_match_by_addr, class);
+
+       if (dup) {
+               if (__ao2_ref(dup, -1, tag, file, line, funcname) == 2) {
                        ast_log(LOG_WARNING, "Attempt to unref mohclass %p (%s) when only 1 ref remained, and class is still in a container! (at %s:%d (%s))\n",
                                class, class->name, file, line, funcname);
                } else {
                        ao2_ref(class, -1);
                }
        } else {
-               ao2_t_ref(class, -1, (char *) tag);
+               __ao2_ref(class, -1, tag, file, line, funcname);
        }
        return NULL;
 }
 #endif
 
+static void moh_post_start(struct ast_channel *chan, const char *moh_class_name)
+{
+       struct stasis_message *message;
+       struct ast_json *json_object;
+
+       ast_verb(3, "Started music on hold, class '%s', on channel '%s'\n",
+               moh_class_name, ast_channel_name(chan));
+
+       json_object = ast_json_pack("{s: s}", "class", moh_class_name);
+       if (!json_object) {
+               return;
+       }
+
+       message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan),
+               ast_channel_moh_start_type(), json_object);
+       if (message) {
+               /* A channel snapshot must have been in the cache. */
+               ast_assert(((struct ast_channel_blob *) stasis_message_data(message))->snapshot != NULL);
+
+               stasis_publish(ast_channel_topic(chan), message);
+       }
+       ao2_cleanup(message);
+       ast_json_unref(json_object);
+}
+
+static void moh_post_stop(struct ast_channel *chan)
+{
+       struct stasis_message *message;
+
+       ast_verb(3, "Stopped music on hold on %s\n", ast_channel_name(chan));
+
+       message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan),
+               ast_channel_moh_stop_type(), NULL);
+       if (message) {
+               /* A channel snapshot must have been in the cache. */
+               ast_assert(((struct ast_channel_blob *) stasis_message_data(message))->snapshot != NULL);
+
+               stasis_publish(ast_channel_topic(chan), message);
+       }
+       ao2_cleanup(message);
+}
+
 static void moh_files_release(struct ast_channel *chan, void *data)
 {
        struct moh_files_state *state;
@@ -278,13 +288,17 @@ static void moh_files_release(struct ast_channel *chan, void *data)
                ast_closestream(ast_channel_stream(chan));
                ast_channel_stream_set(chan, NULL);
        }
-       
-       ast_verb(3, "Stopped music on hold on %s\n", ast_channel_name(chan));
 
-       ast_format_clear(&state->mohwfmt); /* make sure to clear this format before restoring the original format. */
-       if (state->origwfmt.id && ast_set_write_format(chan, &state->origwfmt)) {
-               ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%s'\n", ast_channel_name(chan), ast_getformatname(&state->origwfmt));
+       moh_post_stop(chan);
+
+       ao2_ref(state->mohwfmt, -1);
+       state->mohwfmt = NULL; /* make sure to clear this format before restoring the original format */
+       if (state->origwfmt && ast_set_write_format(chan, state->origwfmt)) {
+               ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%s'\n", ast_channel_name(chan),
+                       ast_format_get_name(state->origwfmt));
        }
+       ao2_cleanup(state->origwfmt);
+       state->origwfmt = NULL;
 
        state->save_pos = state->pos;
        state->announcement = 0;
@@ -325,7 +339,7 @@ static int ast_moh_files_next(struct ast_channel *chan)
                /* If a specific file has been saved confirm it still exists and that it is still valid */
                state->pos = state->save_pos;
                state->save_pos = -1;
-       } else if (ast_test_flag(state->class, MOH_RANDOMIZE)) {
+       } else if (ast_test_flag(state->class, MOH_SORTMODE) == MOH_RANDOMIZE) {
                /* Get a random file and ensure we can open it */
                for (tries = 0; tries < 20; tries++) {
                        state->pos = ast_random() % state->class->total_files;
@@ -397,15 +411,15 @@ static void moh_files_write_format_change(struct ast_channel *chan, void *data)
        /* In order to prevent a recursive call to this function as a result
         * of setting the moh write format back on the channel. Clear
         * the moh write format before setting the write format on the channel.*/
-       if (&state->origwfmt.id) {
-               struct ast_format tmp;
+       if (state->origwfmt) {
+               struct ast_format *tmp;
 
-               ast_format_copy(&tmp, ast_channel_writeformat(chan));
-               if (state->mohwfmt.id) {
-                       ast_format_clear(&state->origwfmt);
-                       ast_set_write_format(chan, &state->mohwfmt);
+               tmp = ao2_bump(ast_channel_writeformat(chan));
+               ao2_replace(state->origwfmt, NULL);
+               if (state->mohwfmt) {
+                       ast_set_write_format(chan, state->mohwfmt);
                }
-               ast_format_copy(&state->origwfmt, &tmp);
+               state->origwfmt = tmp;
        }
 }
 
@@ -419,28 +433,29 @@ static int moh_files_generator(struct ast_channel *chan, void *data, int len, in
 
        while (state->sample_queue > 0) {
                ast_channel_lock(chan);
-               if ((f = moh_files_readframe(chan))) {
-                       /* We need to be sure that we unlock
-                        * the channel prior to calling
-                        * ast_write. Otherwise, the recursive locking
-                        * that occurs can cause deadlocks when using
-                        * indirect channels, like local channels
-                        */
-                       ast_channel_unlock(chan);
-                       state->samples += f->samples;
-                       state->sample_queue -= f->samples;
-                       if (ast_format_cmp(&f->subclass.format, &state->mohwfmt) == AST_FORMAT_CMP_NOT_EQUAL) {
-                               ast_format_copy(&state->mohwfmt, &f->subclass.format);
-                       }
-                       res = ast_write(chan, f);
-                       ast_frfree(f);
-                       if (res < 0) {
-                               ast_log(LOG_WARNING, "Failed to write frame to '%s': %s\n", ast_channel_name(chan), strerror(errno));
-                               return -1;
-                       }
-               } else {
-                       ast_channel_unlock(chan);
-                       return -1;      
+               f = moh_files_readframe(chan);
+
+               /* We need to be sure that we unlock
+                * the channel prior to calling
+                * ast_write. Otherwise, the recursive locking
+                * that occurs can cause deadlocks when using
+                * indirect channels, like local channels
+                */
+               ast_channel_unlock(chan);
+               if (!f) {
+                       return -1;
+               }
+
+               state->samples += f->samples;
+               state->sample_queue -= f->samples;
+               if (ast_format_cmp(f->subclass.format, state->mohwfmt) == AST_FORMAT_CMP_NOT_EQUAL) {
+                       ao2_replace(state->mohwfmt, f->subclass.format);
+               }
+               res = ast_write(chan, f);
+               ast_frfree(f);
+               if (res < 0) {
+                       ast_log(LOG_WARNING, "Failed to write frame to '%s': %s\n", ast_channel_name(chan), strerror(errno));
+                       return -1;
                }
        }
        return res;
@@ -451,11 +466,11 @@ static void *moh_files_alloc(struct ast_channel *chan, void *params)
        struct moh_files_state *state;
        struct mohclass *class = params;
 
-       if (!ast_channel_music_state(chan) && (state = ast_calloc(1, sizeof(*state)))) {
+       state = ast_channel_music_state(chan);
+       if (!state && (state = ast_calloc(1, sizeof(*state)))) {
                ast_channel_music_state_set(chan, state);
                ast_module_ref(ast_module_info->self);
        } else {
-               state = ast_channel_music_state(chan);
                if (!state) {
                        return NULL;
                }
@@ -465,12 +480,11 @@ static void *moh_files_alloc(struct ast_channel *chan, void *params)
                }
        }
 
-       /* LOGIC: Comparing an unrefcounted pointer is a really bad idea, because
-        * malloc may allocate a different class to the same memory block.  This
-        * might only happen when two reloads are generated in a short period of
-        * time, but it's still important to protect against.
-        * PROG: Compare the quick operation first, to save CPU. */
+       /* Resume MOH from where we left off last time or start from scratch? */
        if (state->save_total != class->total_files || strcmp(state->name, class->name) != 0) {
+               /* Start MOH from scratch. */
+               ao2_cleanup(state->origwfmt);
+               ao2_cleanup(state->mohwfmt);
                memset(state, 0, sizeof(*state));
                if (ast_test_flag(class, MOH_RANDOMIZE) && class->total_files) {
                        state->pos = ast_random() % class->total_files;
@@ -478,16 +492,16 @@ static void *moh_files_alloc(struct ast_channel *chan, void *params)
        }
 
        state->class = mohclass_ref(class, "Reffing music class for channel");
-       ast_format_copy(&state->origwfmt, ast_channel_writeformat(chan));
-       ast_format_copy(&state->mohwfmt, ast_channel_writeformat(chan));
-
+       /* it's possible state is not a new allocation, don't leak old refs */
+       ao2_replace(state->origwfmt, ast_channel_writeformat(chan));
+       ao2_replace(state->mohwfmt, ast_channel_writeformat(chan));
        /* For comparison on restart of MOH (see above) */
        ast_copy_string(state->name, class->name, sizeof(state->name));
        state->save_total = class->total_files;
 
-       ast_verb(3, "Started music on hold, class '%s', on %s\n", class->name, ast_channel_name(chan));
-       
-       return ast_channel_music_state(chan);
+       moh_post_start(chan, class->name);
+
+       return state;
 }
 
 static int moh_digit_match(void *obj, void *arg, int flags)
@@ -518,8 +532,7 @@ static void moh_handle_digit(struct ast_channel *chan, char digit)
        }
 }
 
-static struct ast_generator moh_file_stream = 
-{
+static struct ast_generator moh_file_stream = {
        .alloc    = moh_files_alloc,
        .release  = moh_files_release,
        .generate = moh_files_generator,
@@ -704,7 +717,8 @@ static void *monmp3thread(void *data)
                                        ast_log(LOG_ERROR, "Failed to acknowledge timer for mp3player\n");
                                        return NULL;
                                }
-                               res = 320;
+                               /* 25 samples per second => 40ms framerate => 320 samples */
+                               res = 320; /* 320/40 = 8 samples/ms */
                        } else {
                                ast_log(LOG_WARNING, "poll() failed: %s\n", strerror(errno));
                                res = 0;
@@ -725,12 +739,16 @@ static void *monmp3thread(void *data)
                                ast_log(LOG_NOTICE, "Request to schedule in the past?!?!\n");
                                deadline = tv_tmp;
                        }
-                       res = 8 * MOH_MS_INTERVAL;      /* 8 samples per millisecond */
+                       /* 10 samples per second (MOH_MS_INTERVAL) => 100ms framerate => 800 samples */
+                       res = 8 * MOH_MS_INTERVAL; /* 800/100 = 8 samples/ms */
                }
+               /* For non-8000Hz formats, we need to alter the resolution */
+               res = res * ast_format_get_sample_rate(class->format) / 8000;
+
                if ((strncasecmp(class->dir, "http://", 7) && strcasecmp(class->dir, "nodir")) && AST_LIST_EMPTY(&class->members))
                        continue;
                /* Read mp3 audio */
-               len = ast_codec_get_len(&class->format, res);
+               len = ast_format_determine_length(class->format, res);
 
                if ((res2 = read(class->srcfd, sbuf, len)) != len) {
                        if (!res2) {
@@ -822,46 +840,6 @@ static int play_moh_exec(struct ast_channel *chan, const char *data)
        return res;
 }
 
-static int wait_moh_exec(struct ast_channel *chan, const char *data)
-{
-       static int deprecation_warning = 0;
-       int res;
-
-       if (!deprecation_warning) {
-               deprecation_warning = 1;
-               ast_log(LOG_WARNING, "WaitMusicOnHold application is deprecated and will be removed. Use MusicOnHold with duration parameter instead\n");
-       }
-
-       if (!data || !atoi(data)) {
-               ast_log(LOG_WARNING, "WaitMusicOnHold requires an argument (number of seconds to wait)\n");
-               return -1;
-       }
-       if (ast_moh_start(chan, NULL, NULL)) {
-               ast_log(LOG_WARNING, "Unable to start music on hold for %d seconds on channel %s\n", atoi(data), ast_channel_name(chan));
-               return 0;
-       }
-       res = ast_safe_sleep(chan, atoi(data) * 1000);
-       ast_moh_stop(chan);
-       return res;
-}
-
-static int set_moh_exec(struct ast_channel *chan, const char *data)
-{
-       static int deprecation_warning = 0;
-
-       if (!deprecation_warning) {
-               deprecation_warning = 1;
-               ast_log(LOG_WARNING, "SetMusicOnHold application is deprecated and will be removed. Use Set(CHANNEL(musicclass)=...) instead\n");
-       }
-
-       if (ast_strlen_zero(data)) {
-               ast_log(LOG_WARNING, "SetMusicOnHold requires an argument (class)\n");
-               return -1;
-       }
-       ast_channel_musicclass_set(chan, data);
-       return 0;
-}
-
 static int start_moh_exec(struct ast_channel *chan, const char *data)
 {
        char *parse;
@@ -899,15 +877,11 @@ static struct mohclass *_get_mohbyname(const char *name, int warn, int flags, co
 
        ast_copy_string(tmp_class.name, name, sizeof(tmp_class.name));
 
-#ifdef REF_DEBUG
-       moh = __ao2_find_debug(mohclasses, &tmp_class, flags,
+       moh = __ao2_find(mohclasses, &tmp_class, flags,
                "get_mohbyname", file, lineno, funcname);
-#else
-       moh = __ao2_find(mohclasses, &tmp_class, flags);
-#endif
 
        if (!moh && warn) {
-               ast_debug(1, "Music on Hold class '%s' not found in memory\n", name);
+               ast_log(LOG_WARNING, "Music on Hold class '%s' not found in memory. Verify your configuration.\n", name);
        }
 
        return moh;
@@ -934,7 +908,7 @@ static struct mohdata *mohalloc(struct mohclass *cl)
        fcntl(moh->pipe[1], F_SETFL, flags | O_NONBLOCK);
 
        moh->f.frametype = AST_FRAME_VOICE;
-       ast_format_copy(&moh->f.subclass.format, &cl->format);
+       moh->f.subclass.format = cl->format;
        moh->f.offset = AST_FRIENDLY_OFFSET;
 
        moh->parent = mohclass_ref(cl, "Reffing music class for mohdata parent");
@@ -950,7 +924,7 @@ static void moh_release(struct ast_channel *chan, void *data)
 {
        struct mohdata *moh = data;
        struct mohclass *class = moh->parent;
-       struct ast_format oldwfmt;
+       struct ast_format *oldwfmt;
 
        ao2_lock(class);
        AST_LIST_REMOVE(&moh->parent->members, moh, list);      
@@ -959,7 +933,7 @@ static void moh_release(struct ast_channel *chan, void *data)
        close(moh->pipe[0]);
        close(moh->pipe[1]);
 
-       ast_format_copy(&oldwfmt, &moh->origwfmt);
+       oldwfmt = moh->origwfmt;
 
        moh->parent = class = mohclass_unref(class, "unreffing moh->parent upon deactivation of generator");
 
@@ -972,13 +946,15 @@ static void moh_release(struct ast_channel *chan, void *data)
                if (state && state->class) {
                        state->class = mohclass_unref(state->class, "Unreffing channel's music class upon deactivation of generator");
                }
-               if (oldwfmt.id && ast_set_write_format(chan, &oldwfmt)) {
+               if (oldwfmt && ast_set_write_format(chan, oldwfmt)) {
                        ast_log(LOG_WARNING, "Unable to restore channel '%s' to format %s\n",
-                                       ast_channel_name(chan), ast_getformatname(&oldwfmt));
+                                       ast_channel_name(chan), ast_format_get_name(oldwfmt));
                }
 
-               ast_verb(3, "Stopped music on hold on %s\n", ast_channel_name(chan));
+               moh_post_stop(chan);
        }
+
+       ao2_cleanup(oldwfmt);
 }
 
 static void *moh_alloc(struct ast_channel *chan, void *params)
@@ -988,11 +964,11 @@ static void *moh_alloc(struct ast_channel *chan, void *params)
        struct moh_files_state *state;
 
        /* Initiating music_state for current channel. Channel should know name of moh class */
-       if (!ast_channel_music_state(chan) && (state = ast_calloc(1, sizeof(*state)))) {
+       state = ast_channel_music_state(chan);
+       if (!state && (state = ast_calloc(1, sizeof(*state)))) {
                ast_channel_music_state_set(chan, state);
                ast_module_ref(ast_module_info->self);
        } else {
-               state = ast_channel_music_state(chan);
                if (!state) {
                        return NULL;
                }
@@ -1000,19 +976,22 @@ static void *moh_alloc(struct ast_channel *chan, void *params)
                        mohclass_unref(state->class, "Uh Oh. Restarting MOH with an active class");
                        ast_log(LOG_WARNING, "Uh Oh. Restarting MOH with an active class\n");
                }
+               ao2_cleanup(state->origwfmt);
+               ao2_cleanup(state->mohwfmt);
                memset(state, 0, sizeof(*state));
        }
 
        if ((res = mohalloc(class))) {
-               ast_format_copy(&res->origwfmt, ast_channel_writeformat(chan));
-               if (ast_set_write_format(chan, &class->format)) {
-                       ast_log(LOG_WARNING, "Unable to set channel '%s' to format '%s'\n", ast_channel_name(chan), ast_codec2str(&class->format));
+               res->origwfmt = ao2_bump(ast_channel_writeformat(chan));
+               if (ast_set_write_format(chan, class->format)) {
+                       ast_log(LOG_WARNING, "Unable to set channel '%s' to format '%s'\n", ast_channel_name(chan),
+                               ast_format_get_name(class->format));
                        moh_release(NULL, res);
                        res = NULL;
                } else {
                        state->class = mohclass_ref(class, "Placing reference into state container");
+                       moh_post_start(chan, class->name);
                }
-               ast_verb(3, "Started music on hold, class '%s', on channel '%s'\n", class->name, ast_channel_name(chan));
        }
        return res;
 }
@@ -1023,7 +1002,7 @@ static int moh_generate(struct ast_channel *chan, void *data, int len, int sampl
        short buf[1280 + AST_FRIENDLY_OFFSET / 2];
        int res;
 
-       len = ast_codec_get_len(&moh->parent->format, samples);
+       len = ast_format_determine_length(moh->parent->format, samples);
 
        if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
                ast_log(LOG_WARNING, "Only doing %d of %d requested bytes on %s\n", (int)sizeof(buf), len, ast_channel_name(chan));
@@ -1035,7 +1014,7 @@ static int moh_generate(struct ast_channel *chan, void *data, int len, int sampl
 
        moh->f.datalen = res;
        moh->f.data.ptr = buf + AST_FRIENDLY_OFFSET / 2;
-       moh->f.samples = ast_codec_get_samples(&moh->f);
+       moh->f.samples = ast_codec_samples_count(&moh->f);
 
        if (ast_write(chan, &moh->f) < 0) {
                ast_log(LOG_WARNING, "Failed to write frame to '%s': %s\n", ast_channel_name(chan), strerror(errno));
@@ -1052,6 +1031,44 @@ static struct ast_generator mohgen = {
        .digit    = moh_handle_digit,
 };
 
+static void moh_parse_options(struct ast_variable *var, struct mohclass *mohclass)
+{
+       for (; var; var = var->next) {
+               if (!strcasecmp(var->name, "name")) {
+                       ast_copy_string(mohclass->name, var->value, sizeof(mohclass->name));
+               } else if (!strcasecmp(var->name, "mode")) {
+                       ast_copy_string(mohclass->mode, var->value, sizeof(mohclass->mode));
+               } else if (!strcasecmp(var->name, "directory")) {
+                       ast_copy_string(mohclass->dir, var->value, sizeof(mohclass->dir));
+               } else if (!strcasecmp(var->name, "application")) {
+                       ast_copy_string(mohclass->args, var->value, sizeof(mohclass->args));
+               } else if (!strcasecmp(var->name, "digit") && (isdigit(*var->value) || strchr("*#", *var->value))) {
+                       mohclass->digit = *var->value;
+               } else if (!strcasecmp(var->name, "random")) {
+                       static int deprecation_warning = 0;
+                       if (!deprecation_warning) {
+                               ast_log(LOG_WARNING, "Music on hold 'random' setting is deprecated in 14.  Please use 'sort=random' instead.\n");
+                               deprecation_warning = 1;
+                       }
+                       ast_set2_flag(mohclass, ast_true(var->value), MOH_RANDOMIZE);
+               } else if (!strcasecmp(var->name, "sort")) {
+                       if (!strcasecmp(var->value, "random")) {
+                               ast_set_flag(mohclass, MOH_RANDOMIZE);
+                       } else if (!strcasecmp(var->value, "alpha")) {
+                               ast_set_flag(mohclass, MOH_SORTALPHA);
+                       } else if (!strcasecmp(var->value, "randstart")) {
+                               ast_set_flag(mohclass, MOH_RANDSTART);
+                       }
+               } else if (!strcasecmp(var->name, "format")) {
+                       mohclass->format = ast_format_cache_get(var->value);
+                       if (!mohclass->format) {
+                               ast_log(LOG_WARNING, "Unknown format '%s' -- defaulting to SLIN\n", var->value);
+                               mohclass->format = ao2_bump(ast_format_slin);
+                       }
+               }
+       }
+}
+
 static int moh_add_file(struct mohclass *class, const char *filepath)
 {
        if (!class->allowed_files) {
@@ -1192,13 +1209,6 @@ static int init_files_class(struct mohclass *class)
                return -1;
        }
 
-#if 0
-       /* XXX This isn't correct.  Args is an application for custom mode. XXX */
-       if (strchr(class->args, 'r')) {
-               ast_set_flag(class, MOH_RANDOMIZE);
-       }
-#endif
-
        return 0;
 }
 
@@ -1276,7 +1286,7 @@ static int init_app_class(struct mohclass *class)
 /*!
  * \note This function owns the reference it gets to moh if unref is true
  */
-#define moh_register(a,b,c)    _moh_register(a,b,c,__FILE__,__LINE__,__PRETTY_FUNCTION__)
+#define moh_register(moh, reload, unref) _moh_register(moh, reload, unref, __FILE__, __LINE__, __PRETTY_FUNCTION__)
 static int _moh_register(struct mohclass *moh, int reload, int unref, const char *file, int line, const char *funcname)
 {
        struct mohclass *mohclass = NULL;
@@ -1336,14 +1346,16 @@ static void local_ast_moh_cleanup(struct ast_channel *chan)
        struct moh_files_state *state = ast_channel_music_state(chan);
 
        if (state) {
+               ast_channel_music_state_set(chan, NULL);
                if (state->class) {
                        /* This should never happen.  We likely just leaked some resource. */
                        state->class =
                                mohclass_unref(state->class, "Uh Oh. Cleaning up MOH with an active class");
                        ast_log(LOG_WARNING, "Uh Oh. Cleaning up MOH with an active class\n");
                }
-               ast_free(ast_channel_music_state(chan));
-               ast_channel_music_state_set(chan, NULL);
+               ao2_cleanup(state->origwfmt);
+               ao2_cleanup(state->mohwfmt);
+               ast_free(state);
                /* Only held a module reference if we had a music state */
                ast_module_unref(ast_module_info->self);
        }
@@ -1357,68 +1369,71 @@ static struct mohclass *_moh_class_malloc(const char *file, int line, const char
 {
        struct mohclass *class;
 
-       if ((class =
-#ifdef REF_DEBUG
-                       __ao2_alloc_debug(sizeof(*class), moh_class_destructor,
-                               AO2_ALLOC_OPT_LOCK_MUTEX, "Allocating new moh class", file, line, funcname, 1)
-#elif defined(__AST_DEBUG_MALLOC)
-                       __ao2_alloc_debug(sizeof(*class), moh_class_destructor,
-                               AO2_ALLOC_OPT_LOCK_MUTEX, "Allocating new moh class", file, line, funcname, 0)
-#else
-                       ao2_alloc(sizeof(*class), moh_class_destructor)
-#endif
-               )) {
-               ast_format_set(&class->format, AST_FORMAT_SLINEAR, 0);
+       class = __ao2_alloc(sizeof(*class), moh_class_destructor, AO2_ALLOC_OPT_LOCK_MUTEX,
+               "Allocating new moh class", file, line, funcname);
+       if (class) {
+               class->format = ao2_bump(ast_format_slin);
                class->srcfd = -1;
        }
 
        return class;
 }
 
+static struct ast_variable *load_realtime_musiconhold(const char *name)
+{
+       struct ast_variable *var = ast_load_realtime("musiconhold", "name", name, SENTINEL);
+       if (!var) {
+               ast_log(LOG_WARNING,
+                       "Music on Hold class '%s' not found in memory/database. "
+                       "Verify your configuration.\n",
+                       name);
+       }
+       return var;
+}
+
 static int local_ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
 {
        struct mohclass *mohclass = NULL;
        struct moh_files_state *state = ast_channel_music_state(chan);
        struct ast_variable *var = NULL;
-       RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
-       RAII_VAR(struct ast_json *, json_object, NULL, ast_json_unref);
-       int res;
+       int res = 0;
+       int i;
        int realtime_possible = ast_check_realtime("musiconhold");
+       int warn_if_not_in_memory = !realtime_possible;
+       const char *classes[] = {NULL, NULL, interpclass, "default"};
+
+       if (ast_test_flag(global_flags, MOH_PREFERCHANNELCLASS)) {
+               classes[0] = ast_channel_musicclass(chan);
+               classes[1] = mclass;
+       } else {
+               classes[0] = mclass;
+               classes[1] = ast_channel_musicclass(chan);
+       }
 
        /* The following is the order of preference for which class to use:
         * 1) The channels explicitly set musicclass, which should *only* be
         *    set by a call to Set(CHANNEL(musicclass)=whatever) in the dialplan.
+        *    Unless preferchannelclass in musiconhold.conf is false
         * 2) The mclass argument. If a channel is calling ast_moh_start() as the
         *    result of receiving a HOLD control frame, this should be the
         *    payload that came with the frame.
-        * 3) The interpclass argument. This would be from the mohinterpret
+        * 3) The channels explicitly set musicclass, which should *only* be
+        *    set by a call to Set(CHANNEL(musicclass)=whatever) in the dialplan.
+        * 4) The interpclass argument. This would be from the mohinterpret
         *    option from channel drivers. This is the same as the old musicclass
         *    option.
-        * 4) The default class.
+        * 5) The default class.
         */
-       if (!ast_strlen_zero(ast_channel_musicclass(chan))) {
-               mohclass = get_mohbyname(ast_channel_musicclass(chan), 1, 0);
-               if (!mohclass && realtime_possible) {
-                       var = ast_load_realtime("musiconhold", "name", ast_channel_musicclass(chan), SENTINEL);
-               }
-       }
-       if (!mohclass && !var && !ast_strlen_zero(mclass)) {
-               mohclass = get_mohbyname(mclass, 1, 0);
-               if (!mohclass && realtime_possible) {
-                       var = ast_load_realtime("musiconhold", "name", mclass, SENTINEL);
-               }
-       }
-       if (!mohclass && !var && !ast_strlen_zero(interpclass)) {
-               mohclass = get_mohbyname(interpclass, 1, 0);
-               if (!mohclass && realtime_possible) {
-                       var = ast_load_realtime("musiconhold", "name", interpclass, SENTINEL);
-               }
-       }
 
-       if (!mohclass && !var) {
-               mohclass = get_mohbyname("default", 1, 0);
-               if (!mohclass && realtime_possible) {
-                       var = ast_load_realtime("musiconhold", "name", "default", SENTINEL);
+       for (i = 0; i < ARRAY_LEN(classes); ++i) {
+               if (!ast_strlen_zero(classes[i])) {
+                       mohclass = get_mohbyname(classes[i], warn_if_not_in_memory, 0);
+                       if (!mohclass && realtime_possible) {
+                               var = load_realtime_musiconhold(classes[i]);
+                       }
+                       if (mohclass || var) {
+                               break;
+                       }
                }
        }
 
@@ -1426,36 +1441,12 @@ static int local_ast_moh_start(struct ast_channel *chan, const char *mclass, con
         * above guarantees that if var is non-NULL, then mohclass must be NULL.
         */
        if (var) {
-               struct ast_variable *tmp = NULL;
-
                if ((mohclass = moh_class_malloc())) {
                        mohclass->realtime = 1;
-                       for (tmp = var; tmp; tmp = tmp->next) {
-                               if (!strcasecmp(tmp->name, "name"))
-                                       ast_copy_string(mohclass->name, tmp->value, sizeof(mohclass->name));
-                               else if (!strcasecmp(tmp->name, "mode"))
-                                       ast_copy_string(mohclass->mode, tmp->value, sizeof(mohclass->mode)); 
-                               else if (!strcasecmp(tmp->name, "directory"))
-                                       ast_copy_string(mohclass->dir, tmp->value, sizeof(mohclass->dir));
-                               else if (!strcasecmp(tmp->name, "application"))
-                                       ast_copy_string(mohclass->args, tmp->value, sizeof(mohclass->args));
-                               else if (!strcasecmp(tmp->name, "digit") && (isdigit(*tmp->value) || strchr("*#", *tmp->value)))
-                                       mohclass->digit = *tmp->value;
-                               else if (!strcasecmp(tmp->name, "random"))
-                                       ast_set2_flag(mohclass, ast_true(tmp->value), MOH_RANDOMIZE);
-                               else if (!strcasecmp(tmp->name, "sort") && !strcasecmp(tmp->value, "random"))
-                                       ast_set_flag(mohclass, MOH_RANDOMIZE);
-                               else if (!strcasecmp(tmp->name, "sort") && !strcasecmp(tmp->value, "alpha")) 
-                                       ast_set_flag(mohclass, MOH_SORTALPHA);
-                               else if (!strcasecmp(tmp->name, "format")) {
-                                       ast_getformatbyname(tmp->value, &mohclass->format);
-                                       if (!mohclass->format.id) {
-                                               ast_log(LOG_WARNING, "Unknown format '%s' -- defaulting to SLIN\n", tmp->value);
-                                               ast_format_set(&mohclass->format, AST_FORMAT_SLINEAR, 0);
-                                       }
-                               }
-                       }
+
+                       moh_parse_options(var, mohclass);
                        ast_variables_destroy(var);
+
                        if (ast_strlen_zero(mohclass->dir)) {
                                if (!strcasecmp(mohclass->mode, "custom")) {
                                        strcpy(mohclass->dir, "nodir");
@@ -1481,12 +1472,6 @@ static int local_ast_moh_start(struct ast_channel *chan, const char *mclass, con
                                if (state && state->class) {
                                        /* Class already exist for this channel */
                                        ast_log(LOG_NOTICE, "This channel already has a MOH class attached (%s)!\n", state->class->name);
-                                       if (state->class->realtime && !ast_test_flag(global_flags, MOH_CACHERTCLASSES) && !strcasecmp(mohclass->name, state->class->name)) {
-                                               /* we found RT class with the same name, seems like we should continue playing existing one */
-                                               /* XXX This code is impossible to reach */
-                                               mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (channel already has a class)");
-                                               mohclass = state->class;
-                                       }
                                }
                                /* We don't want moh_register to unref the mohclass because we do it at the end of this function as well.
                                 * If we allowed moh_register to unref the mohclass,too, then the count would be off by one. The result would
@@ -1509,8 +1494,14 @@ static int local_ast_moh_start(struct ast_channel *chan, const char *mclass, con
                                                mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (moh_scan_files failed)");
                                                return -1;
                                        }
-                                       if (strchr(mohclass->args, 'r'))
+                                       if (strchr(mohclass->args, 'r')) {
+                                               static int deprecation_warning = 0;
+                                               if (!deprecation_warning) {
+                                                       ast_log(LOG_WARNING, "Music on hold 'application=r' setting is deprecated in 14.  Please use 'sort=random' instead.\n");
+                                                       deprecation_warning = 1;
+                                               }
                                                ast_set_flag(mohclass, MOH_RANDOMIZE);
+                                       }
                                } else if (!strcasecmp(mohclass->mode, "mp3") || !strcasecmp(mohclass->mode, "mp3nb") || !strcasecmp(mohclass->mode, "quietmp3") || !strcasecmp(mohclass->mode, "quietmp3nb") || !strcasecmp(mohclass->mode, "httpmp3") || !strcasecmp(mohclass->mode, "custom")) {
 
                                        if (!strcasecmp(mohclass->mode, "custom"))
@@ -1539,7 +1530,7 @@ static int local_ast_moh_start(struct ast_channel *chan, const char *mclass, con
                                                if (state->class->realtime && !ast_test_flag(global_flags, MOH_CACHERTCLASSES) && !strcasecmp(mohclass->name, state->class->name)) {
                                                        /* we found RT class with the same name, seems like we should continue playing existing one */
                                                        mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (channel already has one)");
-                                                       mohclass = state->class;
+                                                       mohclass = mohclass_ref(state->class, "using existing class from state");
                                                }
                                        } else {
                                                if (ast_pthread_create_background(&mohclass->thread, NULL, monmp3thread, mohclass)) {
@@ -1576,27 +1567,16 @@ static int local_ast_moh_start(struct ast_channel *chan, const char *mclass, con
                }
        }
 
-       ast_channel_latest_musicclass_set(chan, mohclass->name);
-       ast_set_flag(ast_channel_flags(chan), AST_FLAG_MOH);
-
-       if (mohclass->total_files) {
-               res = ast_activate_generator(chan, &moh_file_stream, mohclass);
-       } else {
-               res = ast_activate_generator(chan, &mohgen, mohclass);
-       }
-
-       json_object = ast_json_pack("{s: s}",
-                       "class", mohclass->name);
-       if (!json_object) {
-               mohclass = mohclass_unref(mohclass, "unreffing local reference to mohclass in local_ast_moh_start");
-               return -1;
+       if (!state || !state->class || strcmp(mohclass->name, state->class->name)) {
+               if (mohclass->total_files) {
+                       res = ast_activate_generator(chan, &moh_file_stream, mohclass);
+               } else {
+                       res = ast_activate_generator(chan, &mohgen, mohclass);
+               }
        }
-
-       message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan),
-                       ast_channel_moh_start_type(),
-                       json_object);
-       if (message) {
-               stasis_publish(ast_channel_topic(chan), message);
+       if (!res) {
+               ast_channel_latest_musicclass_set(chan, mohclass->name);
+               ast_set_flag(ast_channel_flags(chan), AST_FLAG_MOH);
        }
 
        mohclass = mohclass_unref(mohclass, "unreffing local reference to mohclass in local_ast_moh_start");
@@ -1606,7 +1586,6 @@ static int local_ast_moh_start(struct ast_channel *chan, const char *mclass, con
 
 static void local_ast_moh_stop(struct ast_channel *chan)
 {
-       RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
        ast_clear_flag(ast_channel_flags(chan), AST_FLAG_MOH);
        ast_deactivate_generator(chan);
 
@@ -1617,11 +1596,6 @@ static void local_ast_moh_stop(struct ast_channel *chan)
                        ast_channel_stream_set(chan, NULL);
                }
        }
-
-       message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), ast_channel_moh_stop_type(), NULL);
-       if (message) {
-               stasis_publish(ast_channel_topic(chan), message);
-       }
        ast_channel_unlock(chan);
 }
 
@@ -1635,7 +1609,7 @@ static void moh_class_destructor(void *obj)
 
        ao2_lock(class);
        while ((member = AST_LIST_REMOVE_HEAD(&class->members, list))) {
-               free(member);
+               ast_free(member);
        }
        ao2_unlock(class);
 
@@ -1696,9 +1670,9 @@ static void moh_class_destructor(void *obj)
        if (class->filearray) {
                int i;
                for (i = 0; i < class->total_files; i++) {
-                       free(class->filearray[i]);
+                       ast_free(class->filearray[i]);
                }
-               free(class->filearray);
+               ast_free(class->filearray);
                class->filearray = NULL;
        }
 
@@ -1707,6 +1681,8 @@ static void moh_class_destructor(void *obj)
                class->timer = NULL;
        }
 
+       ao2_cleanup(class->format);
+
        /* Finally, collect the exit status of the monitor thread */
        if (tid > 0) {
                pthread_join(tid, NULL);
@@ -1758,6 +1734,7 @@ static int load_moh_classes(int reload)
        }
 
        ast_clear_flag(global_flags, AST_FLAGS_ALL);
+       ast_set2_flag(global_flags, 1, MOH_PREFERCHANNELCLASS);
 
        cat = ast_category_browse(cfg, NULL);
        for (; cat; cat = ast_category_browse(cfg, cat)) {
@@ -1766,48 +1743,22 @@ static int load_moh_classes(int reload)
                        for (var = ast_variable_browse(cfg, cat); var; var = var->next) {
                                if (!strcasecmp(var->name, "cachertclasses")) {
                                        ast_set2_flag(global_flags, ast_true(var->value), MOH_CACHERTCLASSES);
+                               } else if (!strcasecmp(var->name, "preferchannelclass")) {
+                                       ast_set2_flag(global_flags, ast_true(var->value), MOH_PREFERCHANNELCLASS);
                                } else {
                                        ast_log(LOG_WARNING, "Unknown option '%s' in [general] section of musiconhold.conf\n", var->name);
                                }
                        }
                }
-               /* These names were deprecated in 1.4 and should not be used until after the next major release. */
-               if (!strcasecmp(cat, "classes") || !strcasecmp(cat, "moh_files") || 
-                               !strcasecmp(cat, "general")) {
-                       continue;
-               }
 
                if (!(class = moh_class_malloc())) {
                        break;
                }
 
+               moh_parse_options(ast_variable_browse(cfg, cat), class);
+               /* For compatibility with the past, we overwrite any name=name
+                * with the context [name]. */
                ast_copy_string(class->name, cat, sizeof(class->name));
-               for (var = ast_variable_browse(cfg, cat); var; var = var->next) {
-                       if (!strcasecmp(var->name, "mode")) {
-                               ast_copy_string(class->mode, var->value, sizeof(class->mode));
-                       } else if (!strcasecmp(var->name, "directory")) {
-                               ast_copy_string(class->dir, var->value, sizeof(class->dir));
-                       } else if (!strcasecmp(var->name, "application")) {
-                               ast_copy_string(class->args, var->value, sizeof(class->args));
-                       } else if (!strcasecmp(var->name, "announcement")) {
-                               ast_copy_string(class->announcement, var->value, sizeof(class->announcement));
-                               ast_set_flag(class, MOH_ANNOUNCEMENT);
-                       } else if (!strcasecmp(var->name, "digit") && (isdigit(*var->value) || strchr("*#", *var->value))) {
-                               class->digit = *var->value;
-                       } else if (!strcasecmp(var->name, "random")) {
-                               ast_set2_flag(class, ast_true(var->value), MOH_RANDOMIZE);
-                       } else if (!strcasecmp(var->name, "sort") && !strcasecmp(var->value, "random")) {
-                               ast_set_flag(class, MOH_RANDOMIZE);
-                       } else if (!strcasecmp(var->name, "sort") && !strcasecmp(var->value, "alpha")) {
-                               ast_set_flag(class, MOH_SORTALPHA);
-                       } else if (!strcasecmp(var->name, "format")) {
-                               ast_getformatbyname(var->value, &class->format);
-                               if (!class->format.id) {
-                                       ast_log(LOG_WARNING, "Unknown format '%s' -- defaulting to SLIN\n", var->value);
-                                       ast_format_set(&class->format, AST_FORMAT_SLINEAR, 0);
-                               }
-                       }
-               }
 
                if (ast_strlen_zero(class->dir)) {
                        if (!strcasecmp(class->mode, "custom")) {
@@ -1870,7 +1821,8 @@ static char *handle_cli_moh_reload(struct ast_cli_entry *e, int cmd, struct ast_
        if (a->argc != e->args)
                return CLI_SHOWUSAGE;
 
-       reload();
+       /* The module loader will prevent concurrent reloads from occurring, so we delegate */
+       ast_module_reload("res_musiconhold");
 
        return CLI_SUCCESS;
 }
@@ -1941,7 +1893,7 @@ static char *handle_cli_moh_show_classes(struct ast_cli_entry *e, int cmd, struc
                        ast_cli(a->fd, "\tApplication: %s\n", S_OR(class->args, "<none>"));
                }
                if (strcasecmp(class->mode, "files")) {
-                       ast_cli(a->fd, "\tFormat: %s\n", ast_getformatname(&class->format));
+                       ast_cli(a->fd, "\tFormat: %s\n", ast_format_get_name(class->format));
                }
        }
        ao2_iterator_destroy(&i);
@@ -2001,10 +1953,6 @@ static int load_module(void)
        ast_register_atexit(ast_moh_destroy);
        ast_cli_register_multiple(cli_moh, ARRAY_LEN(cli_moh));
        if (!res)
-               res = ast_register_application_xml(wait_moh, wait_moh_exec);
-       if (!res)
-               res = ast_register_application_xml(set_moh, set_moh_exec);
-       if (!res)
                res = ast_register_application_xml(start_moh, start_moh_exec);
        if (!res)
                res = ast_register_application_xml(stop_moh, stop_moh_exec);
@@ -2050,8 +1998,6 @@ static int unload_module(void)
 
        ast_moh_destroy();
        res = ast_unregister_application(play_moh);
-       res |= ast_unregister_application(wait_moh);
-       res |= ast_unregister_application(set_moh);
        res |= ast_unregister_application(start_moh);
        res |= ast_unregister_application(stop_moh);
        ast_cli_unregister_multiple(cli_moh, ARRAY_LEN(cli_moh));
@@ -2061,6 +2007,7 @@ static int unload_module(void)
 }
 
 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Music On Hold Resource",
+       .support_level = AST_MODULE_SUPPORT_CORE,
        .load = load_module,
        .unload = unload_module,
        .reload = reload,