Use statically-allocated thread private data
[projects/chimara/chimara.git] / libchimara / schannel.c
index 54324363ed3c208f8bbdf24b3c261bd53a4bca78..b64470db222addbcf9a30c9595f9309676e1ce14 100644 (file)
@@ -13,7 +13,9 @@
 #include "resource.h"
 #include "event.h"
 
-extern GPrivate *glk_data_key;
+#define VOLUME_TIMER_RESOLUTION 1.0 /* In milliseconds */
+
+extern GPrivate glk_data_key;
 
 #ifdef GSTREAMER_SOUND
 /* Stop any currently playing sound on this channel, and remove any
@@ -23,6 +25,11 @@ clean_up_after_playing_sound(schanid_t chan)
 {
        if(!gst_element_set_state(chan->pipeline, GST_STATE_NULL))
                WARNING_S(_("Could not set GstElement state to"), "NULL");
+       if(chan->source)
+       {
+               gst_bin_remove(GST_BIN(chan->pipeline), chan->source);
+               chan->source = NULL;
+       }
        if(chan->demux)
        {
                gst_bin_remove(GST_BIN(chan->pipeline), chan->demux);
@@ -170,13 +177,51 @@ finally:
  * Remember that it is possible that the library will be unable to create a new
  * channel, in which case glk_schannel_create() will return %NULL.
  *
+ * When you create a channel using glk_schannel_create(), it has full volume,
+ * represented by the value 0x10000. Half volume would be 0x8000, three-quarters
+ * volume would be 0xC000, and so on. A volume of zero represents silence.
+ *
+ * You can overdrive the volume of a channel by setting a volume greater than 
+ * 0x10000. However, this is not recommended; the library may be unable to 
+ * increase the volume past full, or the sound may become distorted. You should 
+ * always create sound resources with the maximum volume you will need, and then
+ * reduce the volume when appropriate using the channel-volume calls.
+ *
+ * <note><para>
+ *   Mathematically, these volume changes should be taken as linear
+ *   multiplication of a waveform represented as linear samples. As I
+ *   understand it, linear PCM encodes the sound pressure, and therefore a
+ *   volume of 0x8000 should represent a 6 dB drop.
+ * </para></note>
+ *
  * Returns: A new sound channel, or %NULL.
  */
 schanid_t 
 glk_schannel_create(glui32 rock)
+{
+       return glk_schannel_create_ext(rock, 0x10000);
+}
+
+/**
+ * glk_schannel_create_ext:
+ * @rock: The rock value to give the new sound channel.
+ * @volume: Integer representing the volume; 0x10000 is 100&percnt;.
+ *
+ * The glk_schannel_create_ext() call lets you create a channel with the volume
+ * already set at a given level.
+ *
+ * Not all libraries support glk_schannel_create_ext(). You should test the
+ * %gestalt_Sound2 selector before you rely on it; see <link
+ * linkend="chimara-Testing-for-Sound-Capabilities">Testing for Sound
+ * Capabilities</link>.
+ *
+ * Returns: A new sound channel, or %NULL.
+ */
+schanid_t
+glk_schannel_create_ext(glui32 rock, glui32 volume)
 {
 #ifdef GSTREAMER_SOUND
-       ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
+       ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
 
        schanid_t s = g_new0(struct glk_schannel_struct, 1);
        s->magic = MAGIC_SCHANNEL;
@@ -203,21 +248,24 @@ glk_schannel_create(glui32 rock)
        gst_object_unref(bus);
 
        /* Create GStreamer elements to put in the pipeline */
-       s->source = gst_element_factory_make("giostreamsrc", NULL);
        s->typefind = gst_element_factory_make("typefind", NULL);
        s->convert = gst_element_factory_make("audioconvert", NULL);
        s->filter = gst_element_factory_make("volume", NULL);
        s->sink = gst_element_factory_make("autoaudiosink", NULL);
-       if(!s->source || !s->typefind || !s->convert || !s->filter || !s->sink) {
+       if(!s->typefind || !s->convert || !s->filter || !s->sink) {
                WARNING(_("Could not create one or more GStreamer elements"));
                goto fail;
        }
 
+       /* Set the initial volume */
+       glk_schannel_set_volume(s, volume);
+
        /* Put the elements in the pipeline and link as many together as we can
         without knowing the type of the audio stream */
-       gst_bin_add_many(GST_BIN(s->pipeline), s->source, s->typefind, s->convert, s->filter, s->sink, NULL);
-       /* Link elements: Source -> typefinder -> ??? -> Converter -> Volume filter -> Sink */
-       if(!gst_element_link(s->source, s->typefind) || !gst_element_link_many(s->convert, s->filter, s->sink, NULL)) {
+       gst_bin_add_many(GST_BIN(s->pipeline), s->typefind, s->convert, s->filter, s->sink, NULL);
+
+       /* Link elements: ??? -> Converter -> Volume filter -> Sink */
+       if(!gst_element_link_many(s->convert, s->filter, s->sink, NULL)) {
                WARNING(_("Could not link GStreamer elements"));
                goto fail;
        }
@@ -246,7 +294,7 @@ glk_schannel_destroy(schanid_t chan)
        VALID_SCHANNEL(chan, return);
 
 #ifdef GSTREAMER_SOUND
-       ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
+       ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
 
        if(!gst_element_set_state(chan->pipeline, GST_STATE_NULL))
                WARNING_S(_("Could not set GstElement state to"), "NULL");
@@ -288,7 +336,7 @@ glk_schannel_iterate(schanid_t chan, glui32 *rockptr)
        VALID_SCHANNEL_OR_NULL(chan, return NULL);
 
 #ifdef GSTREAMER_SOUND
-       ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
+       ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
        GList *retnode;
        
        if(chan == NULL)
@@ -379,9 +427,14 @@ glk_schannel_play(schanid_t chan, glui32 snd)
  * sound is playing, there will be no notification event.
  *
  * Not all libraries support sound notification. You should test the
- * %gestalt_SoundNotify selector before you rely on it; see <link
+ * %gestalt_Sound2 selector before you rely on it; see <link
  * linkend="chimara-Testing-for-Sound-Capabilities">Testing for Sound 
  * Capabilities</link>.
+ *
+ * Note that you can play a sound on a channel whose volume is zero. This has
+ * no audible result, unless you later change the volume; but it produces
+ * notifications as usual. You can also play a sound on a paused channel; the
+ * sound is paused immediately, and does not progress.
  * 
  * Returns: 1 on success, 0 on failure.
  */
@@ -389,9 +442,8 @@ glui32
 glk_schannel_play_ext(schanid_t chan, glui32 snd, glui32 repeats, glui32 notify)
 {
        VALID_SCHANNEL(chan, return 0);
-       g_printerr("Play sound %d with repeats %d and notify %d\n", snd, repeats, notify);
 #ifdef GSTREAMER_SOUND
-       ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
+       ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
        GInputStream *stream;
 
        /* Stop the previous sound */
@@ -436,14 +488,24 @@ glk_schannel_play_ext(schanid_t chan, glui32 snd, glui32 repeats, glui32 notify)
                stream = g_memory_input_stream_new_from_data(resource.data.ptr, resource.length, NULL);
        }
 
+       chan->source = gst_element_factory_make("giostreamsrc", NULL);
+       g_object_set(chan->source, "stream", stream, NULL);
+       g_object_unref(stream); /* Now owned by GStreamer element */
+       gst_bin_add(GST_BIN(chan->pipeline), chan->source);
+       if(!gst_element_link(chan->source, chan->typefind)) {
+               WARNING(_("Could not link GStreamer elements"));
+               clean_up_after_playing_sound(chan);
+               return 0;
+       }
+
        chan->repeats = repeats;
        chan->resource = snd;
        chan->notify = notify;
-       g_object_set(chan->source, "stream", stream, NULL);
-       g_object_unref(stream); /* Now owned by GStreamer element */
        
-       if(!gst_element_set_state(chan->pipeline, GST_STATE_PLAYING)) {
-               WARNING_S(_("Could not set GstElement state to"), "PLAYING");
+       /* Play the sound; unless the channel is paused, then pause it instead */
+       if(!gst_element_set_state(chan->pipeline, chan->paused? GST_STATE_PAUSED : GST_STATE_PLAYING)) {
+               WARNING_S(_("Could not set GstElement state to"), chan->paused? "PAUSED" : "PLAYING");
+               clean_up_after_playing_sound(chan);
                return 0;
        }
        return 1;
@@ -454,13 +516,11 @@ glk_schannel_play_ext(schanid_t chan, glui32 snd, glui32 repeats, glui32 notify)
 
 /**
  * glk_schannel_play_multi:
- * @chanarray:
- * @chancount:
- * @sndarray:
- * @soundcount:
- * @notify:
- * 
- * [DRAFT SPEC]
+ * @chanarray: Array of #schanid_t structures.
+ * @chancount: Length of @chanarray.
+ * @sndarray: Array of sound resource numbers.
+ * @soundcount: Length of @sndarray, must be equal to @chanarray.
+ * @notify: If nonzero, request a notification when each sound finishes.
  *
  * This works the same as glk_schannel_play_ext(), except that you can specify
  * more than one sound. The channel references and sound resource numbers are
@@ -473,6 +533,11 @@ glk_schannel_play_ext(schanid_t chan, glui32 snd, glui32 repeats, glui32 notify)
  * a number from 0 to @soundcount.)
  *
  * <note><para>
+ *   If the @notify argument is nonzero, you will get a separate sound
+ *   notification event as each sound finishes. They will all have the same
+ *   @val2 value.
+ * </para></note>
+ * <note><para>
  *   Note that you have to supply @chancount and @soundcount as separate
  *   arguments, even though they are required to be the same. This is an awkward
  *   consequence of the way array arguments are dispatched in Glulx.
@@ -484,15 +549,96 @@ glui32
 glk_schannel_play_multi(schanid_t *chanarray, glui32 chancount, glui32 *sndarray, glui32 soundcount, glui32 notify)
 {
        g_return_val_if_fail(chancount == soundcount, 0);
-       g_return_val_if_fail(chanarray == NULL && chancount != 0, 0);
-       g_return_val_if_fail(sndarray == NULL && soundcount != 0, 0);
+       g_return_val_if_fail(chanarray != NULL || chancount == 0, 0);
+       g_return_val_if_fail(sndarray != NULL || soundcount == 0, 0);
 
        int count;
        for(count = 0; count < chancount; count++)
                VALID_SCHANNEL(chanarray[count], return 0);
-       
-       g_warning("Not implemented");
+
+#ifdef GSTREAMER_SOUND
+       ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
+       GInputStream *stream;
+
+       if(!glk_data->resource_map && !glk_data->resource_load_callback) {
+               WARNING(_("No resource map has been loaded yet."));
+               return 0;
+       }
+
+       /* We keep an array of sounds to skip if any of them have errors */
+       gboolean *skiparray = g_new0(gboolean, chancount);
+
+       /* Set up all the channels one by one */
+       for(count = 0; count < chancount; count++) {
+               /* Stop the previous sound */
+               clean_up_after_playing_sound(chanarray[count]);
+
+               /* Load the sound into a GInputStream, by whatever method */
+               if(!glk_data->resource_map) {
+                       gchar *filename = glk_data->resource_load_callback(CHIMARA_RESOURCE_SOUND, sndarray[count], glk_data->resource_load_callback_data);
+                       if(!filename) {
+                               WARNING(_("Error loading resource from alternative location."));
+                               skiparray[count] = TRUE;
+                               continue;
+                       }
+
+                       GError *err = NULL;
+                       GFile *file = g_file_new_for_path(filename);
+                       stream = G_INPUT_STREAM(g_file_read(file, NULL, &err));
+                       if(!stream) {
+                               IO_WARNING(_("Error loading resource from file"), filename, err->message);
+                               g_free(filename);
+                               g_object_unref(file);
+                               skiparray[count] = TRUE;
+                               continue;
+                       }
+                       g_free(filename);
+                       g_object_unref(file);
+               } else {
+                       giblorb_result_t resource;
+                       giblorb_err_t result = giblorb_load_resource(glk_data->resource_map, giblorb_method_Memory, &resource, giblorb_ID_Snd, sndarray[count]);
+                       if(result != giblorb_err_None) {
+                               WARNING_S( _("Error loading resource"), giblorb_get_error_message(result) );
+                               skiparray[count] = TRUE;
+                               continue;
+                       }
+                       stream = g_memory_input_stream_new_from_data(resource.data.ptr, resource.length, NULL);
+               }
+
+               chanarray[count]->source = gst_element_factory_make("giostreamsrc", NULL);
+               g_object_set(chanarray[count]->source, "stream", stream, NULL);
+               g_object_unref(stream); /* Now owned by GStreamer element */
+               gst_bin_add(GST_BIN(chanarray[count]->pipeline), chanarray[count]->source);
+               if(!gst_element_link(chanarray[count]->source, chanarray[count]->typefind)) {
+                       WARNING(_("Could not link GStreamer elements"));
+                       clean_up_after_playing_sound(chanarray[count]);
+               }
+
+               chanarray[count]->repeats = 1;
+               chanarray[count]->resource = sndarray[count];
+               chanarray[count]->notify = notify;
+       }
+
+       /* Start all the sounds as close to each other as possible. */
+       /* FIXME: Is there a way to start them exactly at the same time? */
+       glui32 successes = 0;
+       for(count = 0; count < chancount; count++) {
+               if(skiparray[count])
+                       continue;
+               /* Play the sound; unless the channel is paused, then pause it instead */
+               if(!gst_element_set_state(chanarray[count]->pipeline, chanarray[count]->paused? GST_STATE_PAUSED : GST_STATE_PLAYING)) {
+                       WARNING_S(_("Could not set GstElement state to"), chanarray[count]->paused? "PAUSED" : "PLAYING");
+                       skiparray[count] = TRUE;
+                       clean_up_after_playing_sound(chanarray[count]);
+                       continue;
+               }
+               successes++;
+       }
+       g_free(skiparray);
+       return successes;
+#else
        return 0;
+#endif
 }
 
 /**
@@ -514,9 +660,7 @@ glk_schannel_stop(schanid_t chan)
 /**
  * glk_schannel_pause:
  * @chan: Channel to pause.
- * 
- * [DRAFT SPEC]
- * 
+ *
  * Pause any sound playing in the channel. This does not generate any
  * notification events. If the channel is already paused, this does nothing.
  * 
@@ -530,24 +674,63 @@ glk_schannel_pause(schanid_t chan)
 {
        VALID_SCHANNEL(chan, return);
 
-       /* Not implemented */
+       if(chan->paused)
+               return; /* Silently do nothing */
+
+       /* Mark the channel as paused even if there is no sound playing yet */
+       chan->paused = TRUE;
+
+       GstState state;
+       if(gst_element_get_state(chan->pipeline, &state, NULL, GST_CLOCK_TIME_NONE) != GST_STATE_CHANGE_SUCCESS) {
+               WARNING(_("Could not get GstElement state"));
+               return;
+       }
+       if(state != GST_STATE_PLAYING)
+               return; /* Silently do nothing if no sound is playing */
+
+       if(!gst_element_set_state(chan->pipeline, GST_STATE_PAUSED)) {
+               WARNING_S(_("Could not set GstElement state to"), "PAUSED");
+               return;
+       }
 }
 
 /**
  * glk_schannel_unpause:
  * @chan: Channel to unpause.
- * 
- * [DRAFT SPEC]
  *
  * Unpause the channel. Any paused sounds begin playing where they left off. If
  * the channel is not already paused, this does nothing.
+ *
+ * <note><para>
+ *   This means, for example, that you can pause a channel that is currently
+ *   not playing any sounds. If you then add a sound to the channel, it will
+ *   not start playing; it will be paused at its beginning. If you later
+ *   unpaise the channel, the sound will commence.
+ * </para></note>
  */
 void
 glk_schannel_unpause(schanid_t chan)
 {
        VALID_SCHANNEL(chan, return);
 
-       /* Not implemented */
+       if(!chan->paused)
+               return; /* Silently do nothing */
+
+       /* Mark the channel as not paused in any case */
+       chan->paused = FALSE;
+
+       GstState state;
+       if(gst_element_get_state(chan->pipeline, &state, NULL, GST_CLOCK_TIME_NONE) != GST_STATE_CHANGE_SUCCESS) {
+               WARNING(_("Could not get GstElement state"));
+               return;
+       }
+       if(state != GST_STATE_PAUSED)
+               return; /* Silently do nothing */
+
+       if(!gst_element_set_state(chan->pipeline, GST_STATE_PLAYING)) {
+               WARNING_S(_("Could not set GstElement state to"), "PLAYING");
+               return;
+       }
 }
 
 /**
@@ -555,19 +738,20 @@ glk_schannel_unpause(schanid_t chan)
  * @chan: Channel to set the volume of.
  * @vol: Integer representing the volume; 0x10000 is 100&percnt;.
  *
- * Sets the volume in the channel. When you create a channel, it has full 
- * volume, represented by the value 0x10000. Half volume would be 0x8000, 
- * three-quarters volume would be 0xC000, and so on. A volume of zero represents
- * silence, although the sound is still considered to be playing.
+ * Sets the volume in the channel, from 0 (silence) to 0x10000 (full volume).
+ * Again, you can overdrive the volume by setting a value greater than 0x10000,
+ * but this is not recommended.
+ *
+ * The glk_schannel_set_volume() function does not include duration and notify
+ * values. Both are assumed to be zero: immediate change, no notification.
  *
- * You can call this function between sounds, or while a sound is playing. The 
- * effect is immediate.
+ * You can call this function between sounds, or while a sound is playing.
+ * However, a zero-duration change while a sound is playing may produce
+ * unpleasant clicks.
  * 
- * You can overdrive the volume of a channel by setting a volume greater than 
- * 0x10000. However, this is not recommended; the library may be unable to 
- * increase the volume past full, or the sound may become distorted. You should 
- * always create sound resources with the maximum volume you will need, and then
- * call glk_schannel_set_volume() to reduce the volume when appropriate.
+ * At most one volume change can be occurring on a sound channel at any time.
+ * If you call this function while a previous volume change is in progress, the
+ * previous change is interrupted.
  *
  * Not all libraries support this function. You should test the
  * %gestalt_SoundVolume selector before you rely on it; see <link
@@ -585,15 +769,52 @@ glk_schannel_set_volume(schanid_t chan, glui32 vol)
        glk_schannel_set_volume_ext(chan, vol, 0, 0);
 }
 
+static double
+volume_glk_to_gstreamer(glui32 volume_glk)
+{
+       return CLAMP(((double)volume_glk / 0x10000), 0.0, 10.0);
+}
+
+#ifdef GSTREAMER_SOUND
+static gboolean
+volume_change_timeout(schanid_t chan)
+{
+       GTimeVal now;
+       g_get_current_time(&now);
+
+       if(now.tv_sec >= chan->target_time_sec && now.tv_usec >= chan->target_time_usec) {
+               /* We're done - make sure the volume is at the requested level */
+               g_object_set(chan->filter, "volume", chan->target_volume, NULL);
+
+               if(chan->volume_notify)
+                       event_throw(chan->glk, evtype_VolumeNotify, NULL, 0, chan->volume_notify);
+
+               chan->volume_timer_id = 0;
+               return FALSE;
+       }
+
+       /* Calculate the appropriate step every time - a busy system may delay or
+        * drop timer ticks */
+       double time_left_msec = (chan->target_time_sec - now.tv_sec) * 1000.0
+               + (chan->target_time_usec - now.tv_usec) / 1000.0;
+       double steps_left = time_left_msec / VOLUME_TIMER_RESOLUTION;
+       double current_volume;
+       g_object_get(chan->filter, "volume", &current_volume, NULL);
+       double volume_step = (chan->target_volume - current_volume) / steps_left;
+
+       g_object_set(chan->filter, "volume", current_volume + volume_step, NULL);
+
+       return TRUE;
+}
+#endif /* GSTREAMER_SOUND */
+
 /**
  * glk_schannel_set_volume_ext:
  * @chan: Channel to set the volume of.
  * @vol: Integer representing the volume; 0x10000 is 100&percnt;.
  * @duration: Length of volume change in milliseconds, or 0 for immediate.
  * @notify: If nonzero, requests a notification when the volume change finishes.
- * 
- * [DRAFT SPEC]
- * 
+ *
  * Sets the volume in the channel, from 0 (silence) to 0x10000 (full volume).
  * Again, you can overdrive the volume by setting a value greater than 0x10000,
  * but this is not recommended.
@@ -606,20 +827,17 @@ glk_schannel_set_volume(schanid_t chan, glui32 vol)
  * event with type #evtype_VolumeNotify. The window will be %NULL, @val1 will be
  * zero, and @val2 will be the nonzero value you passed as @notify.
  *
- * The glk_schannel_set_volume() does not include @duration and @notify values.
- * Both are assumed to be zero: immediate change, no notification.
- *
- * You can call these functions between sounds, or while a sound is playing.
+ * You can call this function between sounds, or while a sound is playing.
  * However, a zero-duration change while a sound is playing may produce
  * unpleasant clicks.
  *
  * At most one volume change can be occurring on a sound channel at any time. If
- * you call one of these functions while a previous volume change is in
- * progress, the previous change is interrupted. The beginning point of the new
- * volume change should be wherever the previous volume change was interrupted
- * (rather than the previous change's beginning or ending point).
+ * you call this function while a previous volume change is in progress, the
+ * previous change is interrupted. The beginning point of the new volume change
+ * should be wherever the previous volume change was interrupted (rather than
+ * the previous change's beginning or ending point).
  *
- * Not all libraries support thse functions. You should test the appropriate
+ * Not all libraries support these functions. You should test the appropriate
  * gestalt selectors before you rely on them; see "Testing for Sound
  * Capabilities".
  */
@@ -628,14 +846,35 @@ glk_schannel_set_volume_ext(schanid_t chan, glui32 vol, glui32 duration, glui32
 {
        VALID_SCHANNEL(chan, return);
        /* Silently ignore out-of-range volume values */
-       
+
 #ifdef GSTREAMER_SOUND
-       gdouble volume_gst = (gdouble)vol / 0x10000;
-       g_printerr("Volume set to: %f\n", volume_gst);
-       g_object_set(chan->filter, "volume", CLAMP(volume_gst, 0.0, 10.0), NULL);
-#endif
+       /* Interrupt a previous volume change */
+       if(chan->volume_timer_id > 0)
+               g_source_remove(chan->volume_timer_id);
+       
+       double target_volume = volume_glk_to_gstreamer(vol);
 
-       /* Not implemented */
+       if(duration == 0) {
+               g_object_set(chan->filter, "volume", target_volume, NULL);
+
+               if(notify != 0)
+                       event_throw(chan->glk, evtype_VolumeNotify, NULL, 0, notify);
+
+               return;
+       }
+
+       GTimeVal target_time;
+       g_get_current_time(&target_time);
+       g_time_val_add(&target_time, (long)duration * 1000);
+
+       chan->target_volume = target_volume;
+       chan->target_time_sec = target_time.tv_sec;
+       chan->target_time_usec = target_time.tv_usec;
+       chan->volume_notify = notify;
+
+       /* Set up a timer for the volume */
+       chan->volume_timer_id = g_timeout_add(VOLUME_TIMER_RESOLUTION, (GSourceFunc)volume_change_timeout, chan);
+#endif
 }
 
 /**
@@ -655,7 +894,7 @@ void
 glk_sound_load_hint(glui32 snd, glui32 flag)
 {
 #ifdef GSTREAMER_SOUND
-       ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
+       ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
        giblorb_result_t resource;
        giblorb_err_t result;