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