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