port to more audio api changes
[platform/upstream/gst-plugins-good.git] / gst / replaygain / gstrgvolume.c
1 /* GStreamer ReplayGain volume adjustment
2  *
3  * Copyright (C) 2007 Rene Stadler <mail@renestadler.de>
4  * 
5  * gstrgvolume.c: Element to apply ReplayGain volume adjustment
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public License
9  * as published by the Free Software Foundation; either version 2.1 of
10  * the License, or (at your option) any later version.
11  * 
12  * This library is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  * 
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20  * 02110-1301 USA
21  */
22
23 /**
24  * SECTION:element-rgvolume
25  * @see_also: #GstRgLimiter, #GstRgAnalysis
26  *
27  * This element applies volume changes to streams as lined out in the proposed
28  * <ulink url="http://replaygain.org">ReplayGain standard</ulink>.  It
29  * interprets the ReplayGain meta data tags and carries out the adjustment (by
30  * using a volume element internally).  The relevant tags are:
31  * <itemizedlist>
32  * <listitem>#GST_TAG_TRACK_GAIN</listitem>
33  * <listitem>#GST_TAG_TRACK_PEAK</listitem>
34  * <listitem>#GST_TAG_ALBUM_GAIN</listitem>
35  * <listitem>#GST_TAG_ALBUM_PEAK</listitem>
36  * <listitem>#GST_TAG_REFERENCE_LEVEL</listitem>
37  * </itemizedlist>
38  * The information carried by these tags must have been calculated beforehand by
39  * performing the ReplayGain analysis.  This is implemented by the <link
40  * linkend="GstRgAnalysis">rganalysis</link> element.
41  * 
42  * The signal compression/limiting recommendations outlined in the proposed
43  * standard are not implemented by this element.  This has to be handled by
44  * separate elements because applications might want to have additional filters
45  * between the volume adjustment and the limiting stage.  A basic limiter is
46  * included with this plugin: The <link linkend="GstRgLimiter">rglimiter</link>
47  * element applies -6 dB hard limiting as mentioned in the ReplayGain standard.
48  * 
49  * <refsect2>
50  * <title>Example launch line</title>
51  * |[
52  * gst-launch filesrc location=filename.ext ! decodebin ! audioconvert \
53  *     ! rgvolume ! audioconvert ! audioresample ! alsasink
54  * ]| Playback of a file
55  * </refsect2>
56  */
57
58 #ifdef HAVE_CONFIG_H
59 #include <config.h>
60 #endif
61
62 #include <gst/gst.h>
63 #include <gst/pbutils/pbutils.h>
64 #include <gst/audio/audio.h>
65 #include <math.h>
66
67 #include "gstrgvolume.h"
68 #include "replaygain.h"
69
70 GST_DEBUG_CATEGORY_STATIC (gst_rg_volume_debug);
71 #define GST_CAT_DEFAULT gst_rg_volume_debug
72
73 enum
74 {
75   PROP_0,
76   PROP_ALBUM_MODE,
77   PROP_HEADROOM,
78   PROP_PRE_AMP,
79   PROP_FALLBACK_GAIN,
80   PROP_TARGET_GAIN,
81   PROP_RESULT_GAIN
82 };
83
84 #define DEFAULT_ALBUM_MODE TRUE
85 #define DEFAULT_HEADROOM 0.0
86 #define DEFAULT_PRE_AMP 0.0
87 #define DEFAULT_FALLBACK_GAIN 0.0
88
89 #define DB_TO_LINEAR(x) pow (10., (x) / 20.)
90 #define LINEAR_TO_DB(x) (20. * log10 (x))
91
92 #define GAIN_FORMAT "+.02f dB"
93 #define PEAK_FORMAT ".06f"
94
95 #define VALID_GAIN(x) ((x) > -60.00 && (x) < 60.00)
96 #define VALID_PEAK(x) ((x) > 0.)
97
98 /* Same template caps as GstVolume, for I don't like having just ANY caps. */
99
100 #define FORMAT "{ "GST_AUDIO_NE(F32)","GST_AUDIO_NE(S16)" }"
101
102 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
103     GST_PAD_SINK,
104     GST_PAD_ALWAYS,
105     GST_STATIC_CAPS ("audio/x-raw, "
106         "format = (string) " FORMAT ", "
107         "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]"));
108
109 static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
110     GST_PAD_SRC,
111     GST_PAD_ALWAYS,
112     GST_STATIC_CAPS ("audio/x-raw, "
113         "format = (string) " FORMAT ", "
114         "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]"));
115
116 #define gst_rg_volume_parent_class parent_class
117 G_DEFINE_TYPE (GstRgVolume, gst_rg_volume, GST_TYPE_BIN);
118
119 static void gst_rg_volume_set_property (GObject * object, guint prop_id,
120     const GValue * value, GParamSpec * pspec);
121 static void gst_rg_volume_get_property (GObject * object, guint prop_id,
122     GValue * value, GParamSpec * pspec);
123 static void gst_rg_volume_dispose (GObject * object);
124
125 static GstStateChangeReturn gst_rg_volume_change_state (GstElement * element,
126     GstStateChange transition);
127 static gboolean gst_rg_volume_sink_event (GstPad * pad, GstEvent * event);
128
129 static GstEvent *gst_rg_volume_tag_event (GstRgVolume * self, GstEvent * event);
130 static void gst_rg_volume_reset (GstRgVolume * self);
131 static void gst_rg_volume_update_gain (GstRgVolume * self);
132 static inline void gst_rg_volume_determine_gain (GstRgVolume * self,
133     gdouble * target_gain, gdouble * result_gain);
134
135 static void
136 gst_rg_volume_class_init (GstRgVolumeClass * klass)
137 {
138   GObjectClass *gobject_class;
139   GstElementClass *element_class;
140   GstBinClass *bin_class;
141
142   gobject_class = (GObjectClass *) klass;
143
144   gobject_class->set_property = gst_rg_volume_set_property;
145   gobject_class->get_property = gst_rg_volume_get_property;
146   gobject_class->dispose = gst_rg_volume_dispose;
147
148   /**
149    * GstRgVolume:album-mode:
150    *
151    * Whether to prefer album gain over track gain.
152    *
153    * If set to %TRUE, use album gain instead of track gain if both are
154    * available.  This keeps the relative loudness levels of tracks from the same
155    * album intact.
156    *
157    * If set to %FALSE, track mode is used instead.  This effectively leads to
158    * more extensive normalization.
159    *
160    * If album mode is enabled but the album gain tag is absent in the stream,
161    * the track gain is used instead.  If both gain tags are missing, the value
162    * of the <link linkend="GstRgVolume--fallback-gain">fallback-gain</link>
163    * property is used instead.
164    */
165   g_object_class_install_property (gobject_class, PROP_ALBUM_MODE,
166       g_param_spec_boolean ("album-mode", "Album mode",
167           "Prefer album over track gain", DEFAULT_ALBUM_MODE,
168           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
169   /**
170    * GstRgVolume:headroom:
171    *
172    * Extra headroom [dB].  This controls the amount by which the output can
173    * exceed digital full scale.
174    *
175    * Only set this to a value greater than 0.0 if signal compression/limiting of
176    * a suitable form is applied to the output (or output is brought into the
177    * correct range by some other transformation).
178    *
179    * This element internally uses a volume element, which also supports
180    * operating on integer audio formats.  These formats do not allow exceeding
181    * digital full scale.  If extra headroom is used, make sure that the raw
182    * audio data format is floating point (F32).  Otherwise,
183    * clipping distortion might be introduced as part of the volume adjustment
184    * itself.
185    */
186   g_object_class_install_property (gobject_class, PROP_HEADROOM,
187       g_param_spec_double ("headroom", "Headroom", "Extra headroom [dB]",
188           0., 60., DEFAULT_HEADROOM,
189           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
190   /**
191    * GstRgVolume:pre-amp:
192    *
193    * Additional gain to apply globally [dB].  This controls the trade-off
194    * between uniformity of normalization and utilization of available dynamic
195    * range.
196    *
197    * Note that the default value is 0 dB because the ReplayGain reference value
198    * was adjusted by +6 dB (from 83 to 89 dB).  At the time of this writing, the
199    * <ulink url="http://replaygain.org">webpage</ulink> is still outdated and
200    * does not reflect this change however.  Where the original proposal states
201    * that a proper default pre-amp value is +6 dB, this translates to the used 0
202    * dB.
203    */
204   g_object_class_install_property (gobject_class, PROP_PRE_AMP,
205       g_param_spec_double ("pre-amp", "Pre-amp", "Extra gain [dB]",
206           -60., 60., DEFAULT_PRE_AMP,
207           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
208   /**
209    * GstRgVolume:fallback-gain:
210    *
211    * Fallback gain [dB] for streams missing ReplayGain tags.
212    */
213   g_object_class_install_property (gobject_class, PROP_FALLBACK_GAIN,
214       g_param_spec_double ("fallback-gain", "Fallback gain",
215           "Gain for streams missing tags [dB]",
216           -60., 60., DEFAULT_FALLBACK_GAIN,
217           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
218   /**
219    * GstRgVolume:result-gain:
220    *
221    * Applied gain [dB].  This gain is applied to processed buffer data.
222    *
223    * This is set to the <link linkend="GstRgVolume--target-gain">target
224    * gain</link> if amplification by that amount can be applied safely.
225    * "Safely" means that the volume adjustment does not inflict clipping
226    * distortion.  Should this not be the case, the result gain is set to an
227    * appropriately reduced value (by applying peak normalization).  The proposed
228    * standard calls this "clipping prevention".
229    *
230    * The difference between target and result gain reflects the necessary amount
231    * of reduction.  Applications can make use of this information to temporarily
232    * reduce the <link linkend="GstRgVolume--pre-amp">pre-amp</link> for
233    * subsequent streams, as recommended by the ReplayGain standard.
234    *
235    * Note that target and result gain differing for a great majority of streams
236    * indicates a problem: What happens in this case is that most streams receive
237    * peak normalization instead of amplification by the ideal replay gain.  To
238    * prevent this, the <link linkend="GstRgVolume--pre-amp">pre-amp</link> has
239    * to be lowered and/or a limiter has to be used which facilitates the use of
240    * <link linkend="GstRgVolume--headroom">headroom</link>.
241    */
242   g_object_class_install_property (gobject_class, PROP_RESULT_GAIN,
243       g_param_spec_double ("result-gain", "Result-gain", "Applied gain [dB]",
244           -120., 120., 0., G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
245   /**
246    * GstRgVolume:target-gain:
247    *
248    * Applicable gain [dB].  This gain is supposed to be applied.
249    *
250    * Depending on the value of the <link
251    * linkend="GstRgVolume--album-mode">album-mode</link> property and the
252    * presence of ReplayGain tags in the stream, this is set according to one of
253    * these simple formulas:
254    *
255    * <itemizedlist>
256    * <listitem><link linkend="GstRgVolume--pre-amp">pre-amp</link> + album gain
257    * of the stream</listitem>
258    * <listitem><link linkend="GstRgVolume--pre-amp">pre-amp</link> + track gain
259    * of the stream</listitem>
260    * <listitem><link linkend="GstRgVolume--pre-amp">pre-amp</link> + <link
261    * linkend="GstRgVolume--fallback-gain">fallback gain</link></listitem>
262    * </itemizedlist>
263    */
264   g_object_class_install_property (gobject_class, PROP_TARGET_GAIN,
265       g_param_spec_double ("target-gain", "Target-gain",
266           "Applicable gain [dB]", -120., 120., 0.,
267           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
268
269   element_class = (GstElementClass *) klass;
270   element_class->change_state = GST_DEBUG_FUNCPTR (gst_rg_volume_change_state);
271
272   bin_class = (GstBinClass *) klass;
273   /* Setting these to NULL makes gst_bin_add and _remove refuse to let anyone
274    * mess with our internals. */
275   bin_class->add_element = NULL;
276   bin_class->remove_element = NULL;
277
278   gst_element_class_add_pad_template (element_class,
279       gst_static_pad_template_get (&src_template));
280   gst_element_class_add_pad_template (element_class,
281       gst_static_pad_template_get (&sink_template));
282   gst_element_class_set_details_simple (element_class, "ReplayGain volume",
283       "Filter/Effect/Audio",
284       "Apply ReplayGain volume adjustment",
285       "Ren\xc3\xa9 Stadler <mail@renestadler.de>");
286
287   GST_DEBUG_CATEGORY_INIT (gst_rg_volume_debug, "rgvolume", 0,
288       "ReplayGain volume element");
289 }
290
291 static void
292 gst_rg_volume_init (GstRgVolume * self)
293 {
294   GObjectClass *volume_class;
295   GstPad *volume_pad, *ghost_pad;
296
297   self->album_mode = DEFAULT_ALBUM_MODE;
298   self->headroom = DEFAULT_HEADROOM;
299   self->pre_amp = DEFAULT_PRE_AMP;
300   self->fallback_gain = DEFAULT_FALLBACK_GAIN;
301   self->target_gain = 0.0;
302   self->result_gain = 0.0;
303
304   self->volume_element = gst_element_factory_make ("volume", "rgvolume-volume");
305   if (G_UNLIKELY (self->volume_element == NULL)) {
306     GstMessage *msg;
307
308     GST_WARNING_OBJECT (self, "could not create volume element");
309     msg = gst_missing_element_message_new (GST_ELEMENT_CAST (self), "volume");
310     gst_element_post_message (GST_ELEMENT_CAST (self), msg);
311
312     /* Nothing else to do, we will refuse the state change from NULL to READY to
313      * indicate that something went very wrong.  It is doubtful that someone
314      * attempts changing our state though, since we end up having no pads! */
315     return;
316   }
317
318   volume_class = G_OBJECT_GET_CLASS (G_OBJECT (self->volume_element));
319   self->max_volume = G_PARAM_SPEC_DOUBLE
320       (g_object_class_find_property (volume_class, "volume"))->maximum;
321
322   GST_BIN_CLASS (parent_class)->add_element (GST_BIN_CAST (self),
323       self->volume_element);
324
325   volume_pad = gst_element_get_static_pad (self->volume_element, "sink");
326   ghost_pad = gst_ghost_pad_new_from_template ("sink", volume_pad,
327       gst_pad_get_pad_template (volume_pad));
328   gst_object_unref (volume_pad);
329   gst_pad_set_event_function (ghost_pad, gst_rg_volume_sink_event);
330   gst_element_add_pad (GST_ELEMENT_CAST (self), ghost_pad);
331
332   volume_pad = gst_element_get_static_pad (self->volume_element, "src");
333   ghost_pad = gst_ghost_pad_new_from_template ("src", volume_pad,
334       gst_pad_get_pad_template (volume_pad));
335   gst_object_unref (volume_pad);
336   gst_element_add_pad (GST_ELEMENT_CAST (self), ghost_pad);
337 }
338
339 static void
340 gst_rg_volume_set_property (GObject * object, guint prop_id,
341     const GValue * value, GParamSpec * pspec)
342 {
343   GstRgVolume *self = GST_RG_VOLUME (object);
344
345   switch (prop_id) {
346     case PROP_ALBUM_MODE:
347       self->album_mode = g_value_get_boolean (value);
348       break;
349     case PROP_HEADROOM:
350       self->headroom = g_value_get_double (value);
351       break;
352     case PROP_PRE_AMP:
353       self->pre_amp = g_value_get_double (value);
354       break;
355     case PROP_FALLBACK_GAIN:
356       self->fallback_gain = g_value_get_double (value);
357       break;
358     default:
359       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
360       break;
361   }
362
363   gst_rg_volume_update_gain (self);
364 }
365
366 static void
367 gst_rg_volume_get_property (GObject * object, guint prop_id,
368     GValue * value, GParamSpec * pspec)
369 {
370   GstRgVolume *self = GST_RG_VOLUME (object);
371
372   switch (prop_id) {
373     case PROP_ALBUM_MODE:
374       g_value_set_boolean (value, self->album_mode);
375       break;
376     case PROP_HEADROOM:
377       g_value_set_double (value, self->headroom);
378       break;
379     case PROP_PRE_AMP:
380       g_value_set_double (value, self->pre_amp);
381       break;
382     case PROP_FALLBACK_GAIN:
383       g_value_set_double (value, self->fallback_gain);
384       break;
385     case PROP_TARGET_GAIN:
386       g_value_set_double (value, self->target_gain);
387       break;
388     case PROP_RESULT_GAIN:
389       g_value_set_double (value, self->result_gain);
390       break;
391     default:
392       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
393       break;
394   }
395 }
396
397 static void
398 gst_rg_volume_dispose (GObject * object)
399 {
400   GstRgVolume *self = GST_RG_VOLUME (object);
401
402   if (self->volume_element != NULL) {
403     /* Manually remove our child using the bin implementation of remove_element.
404      * This is needed because we prevent gst_bin_remove from working, which the
405      * parent dispose handler would use if we had any children left. */
406     GST_BIN_CLASS (parent_class)->remove_element (GST_BIN_CAST (self),
407         self->volume_element);
408     self->volume_element = NULL;
409   }
410
411   G_OBJECT_CLASS (parent_class)->dispose (object);
412 }
413
414 static GstStateChangeReturn
415 gst_rg_volume_change_state (GstElement * element, GstStateChange transition)
416 {
417   GstRgVolume *self = GST_RG_VOLUME (element);
418   GstStateChangeReturn res;
419
420   switch (transition) {
421     case GST_STATE_CHANGE_NULL_TO_READY:
422
423       if (G_UNLIKELY (self->volume_element == NULL)) {
424         /* Creating our child volume element in _init failed. */
425         return GST_STATE_CHANGE_FAILURE;
426       }
427       break;
428
429     case GST_STATE_CHANGE_READY_TO_PAUSED:
430
431       gst_rg_volume_reset (self);
432       break;
433
434     default:
435       break;
436   }
437
438   res = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
439
440   return res;
441 }
442
443 /* Event function for the ghost sink pad. */
444 static gboolean
445 gst_rg_volume_sink_event (GstPad * pad, GstEvent * event)
446 {
447   GstRgVolume *self;
448   GstPad *volume_sink_pad;
449   GstEvent *send_event = event;
450   gboolean res;
451
452   self = GST_RG_VOLUME (gst_pad_get_parent_element (pad));
453   volume_sink_pad = gst_ghost_pad_get_target (GST_GHOST_PAD (pad));
454
455   switch (GST_EVENT_TYPE (event)) {
456     case GST_EVENT_TAG:
457
458       GST_LOG_OBJECT (self, "received tag event");
459
460       send_event = gst_rg_volume_tag_event (self, event);
461
462       if (send_event == NULL)
463         GST_LOG_OBJECT (self, "all tags handled, dropping event");
464
465       break;
466
467     case GST_EVENT_EOS:
468
469       gst_rg_volume_reset (self);
470       break;
471
472     default:
473       break;
474   }
475
476   if (G_LIKELY (send_event != NULL))
477     res = gst_pad_send_event (volume_sink_pad, send_event);
478   else
479     res = TRUE;
480
481   gst_object_unref (volume_sink_pad);
482   gst_object_unref (self);
483   return res;
484 }
485
486 static GstEvent *
487 gst_rg_volume_tag_event (GstRgVolume * self, GstEvent * event)
488 {
489   GstTagList *tag_list;
490   gboolean has_track_gain, has_track_peak, has_album_gain, has_album_peak;
491   gboolean has_ref_level;
492
493   g_return_val_if_fail (event != NULL, NULL);
494   g_return_val_if_fail (GST_EVENT_TYPE (event) == GST_EVENT_TAG, event);
495
496   gst_event_parse_tag (event, &tag_list);
497
498   if (gst_tag_list_is_empty (tag_list))
499     return event;
500
501   has_track_gain = gst_tag_list_get_double (tag_list, GST_TAG_TRACK_GAIN,
502       &self->track_gain);
503   has_track_peak = gst_tag_list_get_double (tag_list, GST_TAG_TRACK_PEAK,
504       &self->track_peak);
505   has_album_gain = gst_tag_list_get_double (tag_list, GST_TAG_ALBUM_GAIN,
506       &self->album_gain);
507   has_album_peak = gst_tag_list_get_double (tag_list, GST_TAG_ALBUM_PEAK,
508       &self->album_peak);
509   has_ref_level = gst_tag_list_get_double (tag_list, GST_TAG_REFERENCE_LEVEL,
510       &self->reference_level);
511
512   if (!has_track_gain && !has_track_peak && !has_album_gain && !has_album_peak)
513     return event;
514
515   if (has_ref_level && (has_track_gain || has_album_gain)
516       && (ABS (self->reference_level - RG_REFERENCE_LEVEL) > 1.e-6)) {
517     /* Log a message stating the amount of adjustment that is applied below. */
518     GST_DEBUG_OBJECT (self,
519         "compensating for reference level difference by %" GAIN_FORMAT,
520         RG_REFERENCE_LEVEL - self->reference_level);
521   }
522   if (has_track_gain) {
523     self->track_gain += RG_REFERENCE_LEVEL - self->reference_level;
524   }
525   if (has_album_gain) {
526     self->album_gain += RG_REFERENCE_LEVEL - self->reference_level;
527   }
528
529   /* Ignore values that are obviously invalid. */
530   if (G_UNLIKELY (has_track_gain && !VALID_GAIN (self->track_gain))) {
531     GST_DEBUG_OBJECT (self,
532         "ignoring bogus track gain value %" GAIN_FORMAT, self->track_gain);
533     has_track_gain = FALSE;
534   }
535   if (G_UNLIKELY (has_track_peak && !VALID_PEAK (self->track_peak))) {
536     GST_DEBUG_OBJECT (self,
537         "ignoring bogus track peak value %" PEAK_FORMAT, self->track_peak);
538     has_track_peak = FALSE;
539   }
540   if (G_UNLIKELY (has_album_gain && !VALID_GAIN (self->album_gain))) {
541     GST_DEBUG_OBJECT (self,
542         "ignoring bogus album gain value %" GAIN_FORMAT, self->album_gain);
543     has_album_gain = FALSE;
544   }
545   if (G_UNLIKELY (has_album_peak && !VALID_PEAK (self->album_peak))) {
546     GST_DEBUG_OBJECT (self,
547         "ignoring bogus album peak value %" PEAK_FORMAT, self->album_peak);
548     has_album_peak = FALSE;
549   }
550
551   /* Clamp peaks >1.0.  Float based decoders can produce spurious samples >1.0,
552    * cutting these files back to 1.0 should not cause any audible distortion.
553    * This is most often seen with Vorbis files. */
554   if (has_track_peak && self->track_peak > 1.) {
555     GST_DEBUG_OBJECT (self,
556         "clamping track peak %" PEAK_FORMAT " to 1.0", self->track_peak);
557     self->track_peak = 1.0;
558   }
559   if (has_album_peak && self->album_peak > 1.) {
560     GST_DEBUG_OBJECT (self,
561         "clamping album peak %" PEAK_FORMAT " to 1.0", self->album_peak);
562     self->album_peak = 1.0;
563   }
564
565   self->has_track_gain |= has_track_gain;
566   self->has_track_peak |= has_track_peak;
567   self->has_album_gain |= has_album_gain;
568   self->has_album_peak |= has_album_peak;
569
570   event = (GstEvent *) gst_mini_object_make_writable (GST_MINI_OBJECT (event));
571   gst_event_parse_tag (event, &tag_list);
572
573   gst_tag_list_remove_tag (tag_list, GST_TAG_TRACK_GAIN);
574   gst_tag_list_remove_tag (tag_list, GST_TAG_TRACK_PEAK);
575   gst_tag_list_remove_tag (tag_list, GST_TAG_ALBUM_GAIN);
576   gst_tag_list_remove_tag (tag_list, GST_TAG_ALBUM_PEAK);
577   gst_tag_list_remove_tag (tag_list, GST_TAG_REFERENCE_LEVEL);
578
579   gst_rg_volume_update_gain (self);
580
581   if (gst_tag_list_is_empty (tag_list)) {
582     gst_event_unref (event);
583     event = NULL;
584   }
585
586   return event;
587 }
588
589 static void
590 gst_rg_volume_reset (GstRgVolume * self)
591 {
592   self->has_track_gain = FALSE;
593   self->has_track_peak = FALSE;
594   self->has_album_gain = FALSE;
595   self->has_album_peak = FALSE;
596
597   self->reference_level = RG_REFERENCE_LEVEL;
598
599   gst_rg_volume_update_gain (self);
600 }
601
602 static void
603 gst_rg_volume_update_gain (GstRgVolume * self)
604 {
605   gdouble target_gain, result_gain, result_volume;
606   gboolean target_gain_changed, result_gain_changed;
607
608   gst_rg_volume_determine_gain (self, &target_gain, &result_gain);
609
610   result_volume = DB_TO_LINEAR (result_gain);
611
612   /* Ensure that the result volume is within the range that the volume element
613    * can handle.  Currently, the limit is 10. (+20 dB), which should not be
614    * restrictive. */
615   if (G_UNLIKELY (result_volume > self->max_volume)) {
616     GST_INFO_OBJECT (self,
617         "cannot handle result gain of %" GAIN_FORMAT " (%0.6f), adjusting",
618         result_gain, result_volume);
619
620     result_volume = self->max_volume;
621     result_gain = LINEAR_TO_DB (result_volume);
622   }
623
624   /* Direct comparison is OK in this case. */
625   if (target_gain == result_gain) {
626     GST_INFO_OBJECT (self,
627         "result gain is %" GAIN_FORMAT " (%0.6f), matching target",
628         result_gain, result_volume);
629   } else {
630     GST_INFO_OBJECT (self,
631         "result gain is %" GAIN_FORMAT " (%0.6f), target is %" GAIN_FORMAT,
632         result_gain, result_volume, target_gain);
633   }
634
635   target_gain_changed = (self->target_gain != target_gain);
636   result_gain_changed = (self->result_gain != result_gain);
637
638   self->target_gain = target_gain;
639   self->result_gain = result_gain;
640
641   g_object_set (self->volume_element, "volume", result_volume, NULL);
642
643   if (target_gain_changed)
644     g_object_notify ((GObject *) self, "target-gain");
645   if (result_gain_changed)
646     g_object_notify ((GObject *) self, "result-gain");
647 }
648
649 static inline void
650 gst_rg_volume_determine_gain (GstRgVolume * self, gdouble * target_gain,
651     gdouble * result_gain)
652 {
653   gdouble gain, peak;
654
655   if (!self->has_track_gain && !self->has_album_gain) {
656
657     GST_DEBUG_OBJECT (self, "using fallback gain");
658     gain = self->fallback_gain;
659     peak = 1.0;
660
661   } else if ((self->album_mode && self->has_album_gain)
662       || (!self->album_mode && !self->has_track_gain)) {
663
664     gain = self->album_gain;
665     if (G_LIKELY (self->has_album_peak)) {
666       peak = self->album_peak;
667     } else {
668       GST_DEBUG_OBJECT (self, "album peak missing, assuming 1.0");
669       peak = 1.0;
670     }
671     /* Falling back from track to album gain shouldn't really happen. */
672     if (G_UNLIKELY (!self->album_mode))
673       GST_INFO_OBJECT (self, "falling back to album gain");
674
675   } else {
676     /* !album_mode && !has_album_gain || album_mode && has_track_gain */
677
678     gain = self->track_gain;
679     if (G_LIKELY (self->has_track_peak)) {
680       peak = self->track_peak;
681     } else {
682       GST_DEBUG_OBJECT (self, "track peak missing, assuming 1.0");
683       peak = 1.0;
684     }
685     if (self->album_mode)
686       GST_INFO_OBJECT (self, "falling back to track gain");
687   }
688
689   gain += self->pre_amp;
690
691   *target_gain = gain;
692   *result_gain = gain;
693
694   if (LINEAR_TO_DB (peak) + gain > self->headroom) {
695     *result_gain = LINEAR_TO_DB (1. / peak) + self->headroom;
696   }
697 }