Merge commit 'f9207722ca8fd8dcc1e7215d8af85efe4debfdf4' into 0.11
[platform/upstream/gst-plugins-good.git] / gst / level / gstlevel.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  * Copyright (C) 2000,2001,2002,2003,2005
4  *           Thomas Vander Stichele <thomas at apestaart dot org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:element-level
24  *
25  * Level analyses incoming audio buffers and, if the #GstLevel:message property
26  * is #TRUE, generates an element message named
27  * <classname>&quot;level&quot;</classname>:
28  * after each interval of time given by the #GstLevel:interval property.
29  * The message's structure contains these fields:
30  * <itemizedlist>
31  * <listitem>
32  *   <para>
33  *   #GstClockTime
34  *   <classname>&quot;timestamp&quot;</classname>:
35  *   the timestamp of the buffer that triggered the message.
36  *   </para>
37  * </listitem>
38  * <listitem>
39  *   <para>
40  *   #GstClockTime
41  *   <classname>&quot;stream-time&quot;</classname>:
42  *   the stream time of the buffer.
43  *   </para>
44  * </listitem>
45  * <listitem>
46  *   <para>
47  *   #GstClockTime
48  *   <classname>&quot;running-time&quot;</classname>:
49  *   the running_time of the buffer.
50  *   </para>
51  * </listitem>
52  * <listitem>
53  *   <para>
54  *   #GstClockTime
55  *   <classname>&quot;duration&quot;</classname>:
56  *   the duration of the buffer.
57  *   </para>
58  * </listitem>
59  * <listitem>
60  *   <para>
61  *   #GstClockTime
62  *   <classname>&quot;endtime&quot;</classname>:
63  *   the end time of the buffer that triggered the message as stream time (this
64  *   is deprecated, as it can be calculated from stream-time + duration)
65  *   </para>
66  * </listitem>
67  * <listitem>
68  *   <para>
69  *   #GValueArray of #gdouble
70  *   <classname>&quot;peak&quot;</classname>:
71  *   the peak power level in dB for each channel
72  *   </para>
73  * </listitem>
74  * <listitem>
75  *   <para>
76  *   #GValueArray of #gdouble
77  *   <classname>&quot;decay&quot;</classname>:
78  *   the decaying peak power level in dB for each channel
79  *   the decaying peak level follows the peak level, but starts dropping
80  *   if no new peak is reached after the time given by
81  *   the <link linkend="GstLevel--peak-ttl">the time to live</link>.
82  *   When the decaying peak level drops, it does so at the decay rate
83  *   as specified by the
84  *   <link linkend="GstLevel--peak-falloff">the peak falloff rate</link>.
85  *   </para>
86  * </listitem>
87  * <listitem>
88  *   <para>
89  *   #GValueArray of #gdouble
90  *   <classname>&quot;rms&quot;</classname>:
91  *   the Root Mean Square (or average power) level in dB for each channel
92  *   </para>
93  * </listitem>
94  * </itemizedlist>
95  *
96  * <refsect2>
97  * <title>Example application</title>
98  * |[
99  * <xi:include xmlns:xi="http://www.w3.org/2003/XInclude" parse="text" href="../../../../tests/examples/level/level-example.c" />
100  * ]|
101  * </refsect2>
102  */
103
104 #ifdef HAVE_CONFIG_H
105 #include "config.h"
106 #endif
107
108 /* FIXME 0.11: suppress warnings for deprecated API such as GValueArray
109  * with newer GLib versions (>= 2.31.0) */
110 #define GLIB_DISABLE_DEPRECATION_WARNINGS
111
112 #include <string.h>
113 #include <math.h>
114 #include <gst/gst.h>
115 #include <gst/audio/audio.h>
116
117 #include "gstlevel.h"
118
119 GST_DEBUG_CATEGORY_STATIC (level_debug);
120 #define GST_CAT_DEFAULT level_debug
121
122 #define EPSILON 1e-35f
123
124 static GstStaticPadTemplate sink_template_factory =
125 GST_STATIC_PAD_TEMPLATE ("sink",
126     GST_PAD_SINK,
127     GST_PAD_ALWAYS,
128     GST_STATIC_CAPS ("audio/x-raw, "
129         "format = (string) { S8, " GST_AUDIO_NE (S16) ", " GST_AUDIO_NE (S32)
130         GST_AUDIO_NE (F32) "," GST_AUDIO_NE (F64) " },"
131         "layout = (string) interleaved, "
132         "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]")
133     );
134
135 static GstStaticPadTemplate src_template_factory =
136 GST_STATIC_PAD_TEMPLATE ("src",
137     GST_PAD_SRC,
138     GST_PAD_ALWAYS,
139     GST_STATIC_CAPS ("audio/x-raw, "
140         "format = (string) { S8, " GST_AUDIO_NE (S16) ", " GST_AUDIO_NE (S32)
141         GST_AUDIO_NE (F32) "," GST_AUDIO_NE (F64) " },"
142         "layout = (string) interleaved, "
143         "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]")
144     );
145
146 enum
147 {
148   PROP_0,
149   PROP_SIGNAL_LEVEL,
150   PROP_SIGNAL_INTERVAL,
151   PROP_PEAK_TTL,
152   PROP_PEAK_FALLOFF
153 };
154
155 #define gst_level_parent_class parent_class
156 G_DEFINE_TYPE (GstLevel, gst_level, GST_TYPE_BASE_TRANSFORM);
157
158 static void gst_level_set_property (GObject * object, guint prop_id,
159     const GValue * value, GParamSpec * pspec);
160 static void gst_level_get_property (GObject * object, guint prop_id,
161     GValue * value, GParamSpec * pspec);
162 static void gst_level_finalize (GObject * obj);
163
164 static gboolean gst_level_set_caps (GstBaseTransform * trans, GstCaps * in,
165     GstCaps * out);
166 static gboolean gst_level_start (GstBaseTransform * trans);
167 static GstFlowReturn gst_level_transform_ip (GstBaseTransform * trans,
168     GstBuffer * in);
169
170
171 static void
172 gst_level_class_init (GstLevelClass * klass)
173 {
174   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
175   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
176   GstBaseTransformClass *trans_class = GST_BASE_TRANSFORM_CLASS (klass);
177
178   gobject_class->set_property = gst_level_set_property;
179   gobject_class->get_property = gst_level_get_property;
180   gobject_class->finalize = gst_level_finalize;
181
182   g_object_class_install_property (gobject_class, PROP_SIGNAL_LEVEL,
183       g_param_spec_boolean ("message", "message",
184           "Post a level message for each passed interval",
185           TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
186   g_object_class_install_property (gobject_class, PROP_SIGNAL_INTERVAL,
187       g_param_spec_uint64 ("interval", "Interval",
188           "Interval of time between message posts (in nanoseconds)",
189           1, G_MAXUINT64, GST_SECOND / 10,
190           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
191   g_object_class_install_property (gobject_class, PROP_PEAK_TTL,
192       g_param_spec_uint64 ("peak-ttl", "Peak TTL",
193           "Time To Live of decay peak before it falls back (in nanoseconds)",
194           0, G_MAXUINT64, GST_SECOND / 10 * 3,
195           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
196   g_object_class_install_property (gobject_class, PROP_PEAK_FALLOFF,
197       g_param_spec_double ("peak-falloff", "Peak Falloff",
198           "Decay rate of decay peak after TTL (in dB/sec)",
199           0.0, G_MAXDOUBLE, 10.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
200
201   GST_DEBUG_CATEGORY_INIT (level_debug, "level", 0, "Level calculation");
202
203   gst_element_class_add_pad_template (element_class,
204       gst_static_pad_template_get (&sink_template_factory));
205   gst_element_class_add_pad_template (element_class,
206       gst_static_pad_template_get (&src_template_factory));
207   gst_element_class_set_details_simple (element_class, "Level",
208       "Filter/Analyzer/Audio",
209       "RMS/Peak/Decaying Peak Level messager for audio/raw",
210       "Thomas Vander Stichele <thomas at apestaart dot org>");
211
212   trans_class->set_caps = GST_DEBUG_FUNCPTR (gst_level_set_caps);
213   trans_class->start = GST_DEBUG_FUNCPTR (gst_level_start);
214   trans_class->transform_ip = GST_DEBUG_FUNCPTR (gst_level_transform_ip);
215   trans_class->passthrough_on_same_caps = TRUE;
216 }
217
218 static void
219 gst_level_init (GstLevel * filter)
220 {
221   filter->CS = NULL;
222   filter->peak = NULL;
223
224   gst_audio_info_init (&filter->info);
225
226   filter->interval = GST_SECOND / 10;
227   filter->decay_peak_ttl = GST_SECOND / 10 * 3;
228   filter->decay_peak_falloff = 10.0;    /* dB falloff (/sec) */
229
230   filter->message = TRUE;
231
232   filter->process = NULL;
233
234   gst_base_transform_set_gap_aware (GST_BASE_TRANSFORM (filter), TRUE);
235 }
236
237 static void
238 gst_level_finalize (GObject * obj)
239 {
240   GstLevel *filter = GST_LEVEL (obj);
241
242   g_free (filter->CS);
243   g_free (filter->peak);
244   g_free (filter->last_peak);
245   g_free (filter->decay_peak);
246   g_free (filter->decay_peak_base);
247   g_free (filter->decay_peak_age);
248
249   filter->CS = NULL;
250   filter->peak = NULL;
251   filter->last_peak = NULL;
252   filter->decay_peak = NULL;
253   filter->decay_peak_base = NULL;
254   filter->decay_peak_age = NULL;
255
256   G_OBJECT_CLASS (parent_class)->finalize (obj);
257 }
258
259 static void
260 gst_level_set_property (GObject * object, guint prop_id,
261     const GValue * value, GParamSpec * pspec)
262 {
263   GstLevel *filter = GST_LEVEL (object);
264
265   switch (prop_id) {
266     case PROP_SIGNAL_LEVEL:
267       filter->message = g_value_get_boolean (value);
268       break;
269     case PROP_SIGNAL_INTERVAL:
270       filter->interval = g_value_get_uint64 (value);
271       if (GST_AUDIO_INFO_RATE (&filter->info)) {
272         filter->interval_frames =
273             GST_CLOCK_TIME_TO_FRAMES (filter->interval,
274             GST_AUDIO_INFO_RATE (&filter->info));
275       }
276       break;
277     case PROP_PEAK_TTL:
278       filter->decay_peak_ttl =
279           gst_guint64_to_gdouble (g_value_get_uint64 (value));
280       break;
281     case PROP_PEAK_FALLOFF:
282       filter->decay_peak_falloff = g_value_get_double (value);
283       break;
284     default:
285       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
286       break;
287   }
288 }
289
290 static void
291 gst_level_get_property (GObject * object, guint prop_id,
292     GValue * value, GParamSpec * pspec)
293 {
294   GstLevel *filter = GST_LEVEL (object);
295
296   switch (prop_id) {
297     case PROP_SIGNAL_LEVEL:
298       g_value_set_boolean (value, filter->message);
299       break;
300     case PROP_SIGNAL_INTERVAL:
301       g_value_set_uint64 (value, filter->interval);
302       break;
303     case PROP_PEAK_TTL:
304       g_value_set_uint64 (value, filter->decay_peak_ttl);
305       break;
306     case PROP_PEAK_FALLOFF:
307       g_value_set_double (value, filter->decay_peak_falloff);
308       break;
309     default:
310       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
311       break;
312   }
313 }
314
315
316 /* process one (interleaved) channel of incoming samples
317  * calculate square sum of samples
318  * normalize and average over number of samples
319  * returns a normalized cumulative square value, which can be averaged
320  * to return the average power as a double between 0 and 1
321  * also returns the normalized peak power (square of the highest amplitude)
322  *
323  * caller must assure num is a multiple of channels
324  * samples for multiple channels are interleaved
325  * input sample data enters in *in_data as 8 or 16 bit data
326  * this filter only accepts signed audio data, so mid level is always 0
327  *
328  * for 16 bit, this code considers the non-existant 32768 value to be
329  * full-scale; so 32767 will not map to 1.0
330  */
331
332 #define DEFINE_INT_LEVEL_CALCULATOR(TYPE, RESOLUTION)                         \
333 static void inline                                                            \
334 gst_level_calculate_##TYPE (gpointer data, guint num, guint channels,         \
335                             gdouble *NCS, gdouble *NPS)                       \
336 {                                                                             \
337   TYPE * in = (TYPE *)data;                                                   \
338   register guint j;                                                           \
339   gdouble squaresum = 0.0;           /* square sum of the integer samples */  \
340   register gdouble square = 0.0;     /* Square */                             \
341   register gdouble peaksquare = 0.0; /* Peak Square Sample */                 \
342   gdouble normalizer;               /* divisor to get a [-1.0, 1.0] range */  \
343                                                                               \
344   /* *NCS = 0.0; Normalized Cumulative Square */                              \
345   /* *NPS = 0.0; Normalized Peask Square */                                   \
346                                                                               \
347   normalizer = (gdouble) (G_GINT64_CONSTANT(1) << (RESOLUTION * 2));          \
348                                                                               \
349   /* oil_squaresum_shifted_s16(&squaresum,in,num); */                         \
350   for (j = 0; j < num; j += channels)                                         \
351   {                                                                           \
352     square = ((gdouble) in[j]) * in[j];                                       \
353     if (square > peaksquare) peaksquare = square;                             \
354     squaresum += square;                                                      \
355   }                                                                           \
356                                                                               \
357   *NCS = squaresum / normalizer;                                              \
358   *NPS = peaksquare / normalizer;                                             \
359 }
360
361 DEFINE_INT_LEVEL_CALCULATOR (gint32, 31);
362 DEFINE_INT_LEVEL_CALCULATOR (gint16, 15);
363 DEFINE_INT_LEVEL_CALCULATOR (gint8, 7);
364
365 #define DEFINE_FLOAT_LEVEL_CALCULATOR(TYPE)                                   \
366 static void inline                                                            \
367 gst_level_calculate_##TYPE (gpointer data, guint num, guint channels,         \
368                             gdouble *NCS, gdouble *NPS)                       \
369 {                                                                             \
370   TYPE * in = (TYPE *)data;                                                   \
371   register guint j;                                                           \
372   gdouble squaresum = 0.0;           /* square sum of the integer samples */  \
373   register gdouble square = 0.0;     /* Square */                             \
374   register gdouble peaksquare = 0.0; /* Peak Square Sample */                 \
375                                                                               \
376   /* *NCS = 0.0; Normalized Cumulative Square */                              \
377   /* *NPS = 0.0; Normalized Peask Square */                                   \
378                                                                               \
379   /* oil_squaresum_f64(&squaresum,in,num); */                                 \
380   for (j = 0; j < num; j += channels)                                         \
381   {                                                                           \
382     square = ((gdouble) in[j]) * in[j];                                       \
383     if (square > peaksquare) peaksquare = square;                             \
384     squaresum += square;                                                      \
385   }                                                                           \
386                                                                               \
387   *NCS = squaresum;                                                           \
388   *NPS = peaksquare;                                                          \
389 }
390
391 DEFINE_FLOAT_LEVEL_CALCULATOR (gfloat);
392 DEFINE_FLOAT_LEVEL_CALCULATOR (gdouble);
393
394 /* we would need stride to deinterleave also
395 static void inline
396 gst_level_calculate_gdouble (gpointer data, guint num, guint channels,
397                             gdouble *NCS, gdouble *NPS)
398 {
399   oil_squaresum_f64(NCS,(gdouble *)data,num);
400   *NPS = 0.0;
401 }
402 */
403
404
405 static gboolean
406 gst_level_set_caps (GstBaseTransform * trans, GstCaps * in, GstCaps * out)
407 {
408   GstLevel *filter = GST_LEVEL (trans);
409   GstAudioInfo info;
410   gint i, channels, rate;
411
412   if (!gst_audio_info_from_caps (&info, in))
413     return FALSE;
414
415   switch (GST_AUDIO_INFO_FORMAT (&info)) {
416     case GST_AUDIO_FORMAT_S8:
417       filter->process = gst_level_calculate_gint8;
418       break;
419     case GST_AUDIO_FORMAT_S16:
420       filter->process = gst_level_calculate_gint16;
421       break;
422     case GST_AUDIO_FORMAT_S32:
423       filter->process = gst_level_calculate_gint32;
424       break;
425     case GST_AUDIO_FORMAT_F32:
426       filter->process = gst_level_calculate_gfloat;
427       break;
428     case GST_AUDIO_FORMAT_F64:
429       filter->process = gst_level_calculate_gdouble;
430       break;
431     default:
432       filter->process = NULL;
433       break;
434   }
435
436   filter->info = info;
437
438   channels = GST_AUDIO_INFO_CHANNELS (&info);
439   rate = GST_AUDIO_INFO_RATE (&info);
440
441   /* allocate channel variable arrays */
442   g_free (filter->CS);
443   g_free (filter->peak);
444   g_free (filter->last_peak);
445   g_free (filter->decay_peak);
446   g_free (filter->decay_peak_base);
447   g_free (filter->decay_peak_age);
448   filter->CS = g_new (gdouble, channels);
449   filter->peak = g_new (gdouble, channels);
450   filter->last_peak = g_new (gdouble, channels);
451   filter->decay_peak = g_new (gdouble, channels);
452   filter->decay_peak_base = g_new (gdouble, channels);
453
454   filter->decay_peak_age = g_new (GstClockTime, channels);
455
456   for (i = 0; i < channels; ++i) {
457     filter->CS[i] = filter->peak[i] = filter->last_peak[i] =
458         filter->decay_peak[i] = filter->decay_peak_base[i] = 0.0;
459     filter->decay_peak_age[i] = G_GUINT64_CONSTANT (0);
460   }
461
462   filter->interval_frames = GST_CLOCK_TIME_TO_FRAMES (filter->interval, rate);
463
464   return TRUE;
465 }
466
467 static gboolean
468 gst_level_start (GstBaseTransform * trans)
469 {
470   GstLevel *filter = GST_LEVEL (trans);
471
472   filter->num_frames = 0;
473
474   return TRUE;
475 }
476
477 static GstMessage *
478 gst_level_message_new (GstLevel * level, GstClockTime timestamp,
479     GstClockTime duration)
480 {
481   GstBaseTransform *trans = GST_BASE_TRANSFORM_CAST (level);
482   GstStructure *s;
483   GValue v = { 0, };
484   GstClockTime endtime, running_time, stream_time;
485
486   running_time = gst_segment_to_running_time (&trans->segment, GST_FORMAT_TIME,
487       timestamp);
488   stream_time = gst_segment_to_stream_time (&trans->segment, GST_FORMAT_TIME,
489       timestamp);
490   /* endtime is for backwards compatibility */
491   endtime = stream_time + duration;
492
493   s = gst_structure_new ("level",
494       "endtime", GST_TYPE_CLOCK_TIME, endtime,
495       "timestamp", G_TYPE_UINT64, timestamp,
496       "stream-time", G_TYPE_UINT64, stream_time,
497       "running-time", G_TYPE_UINT64, running_time,
498       "duration", G_TYPE_UINT64, duration, NULL);
499
500   g_value_init (&v, G_TYPE_VALUE_ARRAY);
501   g_value_take_boxed (&v, g_value_array_new (0));
502   gst_structure_take_value (s, "rms", &v);
503
504   g_value_init (&v, G_TYPE_VALUE_ARRAY);
505   g_value_take_boxed (&v, g_value_array_new (0));
506   gst_structure_take_value (s, "peak", &v);
507
508   g_value_init (&v, G_TYPE_VALUE_ARRAY);
509   g_value_take_boxed (&v, g_value_array_new (0));
510   gst_structure_take_value (s, "decay", &v);
511
512   return gst_message_new_element (GST_OBJECT (level), s);
513 }
514
515 static void
516 gst_level_message_append_channel (GstMessage * m, gdouble rms, gdouble peak,
517     gdouble decay)
518 {
519   const GValue *array_val;
520   GstStructure *s;
521   GValueArray *arr;
522   GValue v = { 0, };
523
524   g_value_init (&v, G_TYPE_DOUBLE);
525
526   s = (GstStructure *) gst_message_get_structure (m);
527
528   array_val = gst_structure_get_value (s, "rms");
529   arr = (GValueArray *) g_value_get_boxed (array_val);
530   g_value_set_double (&v, rms);
531   g_value_array_append (arr, &v);       /* copies by value */
532
533   array_val = gst_structure_get_value (s, "peak");
534   arr = (GValueArray *) g_value_get_boxed (array_val);
535   g_value_set_double (&v, peak);
536   g_value_array_append (arr, &v);       /* copies by value */
537
538   array_val = gst_structure_get_value (s, "decay");
539   arr = (GValueArray *) g_value_get_boxed (array_val);
540   g_value_set_double (&v, decay);
541   g_value_array_append (arr, &v);       /* copies by value */
542
543   g_value_unset (&v);
544 }
545
546 static GstFlowReturn
547 gst_level_transform_ip (GstBaseTransform * trans, GstBuffer * in)
548 {
549   GstLevel *filter;
550   GstMapInfo map;
551   guint8 *in_data;
552   gsize in_size;
553   gdouble CS;
554   guint i;
555   guint num_frames = 0;
556   guint num_int_samples = 0;    /* number of interleaved samples
557                                  * ie. total count for all channels combined */
558   GstClockTimeDiff falloff_time;
559   gint channels, rate, bps;
560
561   filter = GST_LEVEL (trans);
562
563   channels = GST_AUDIO_INFO_CHANNELS (&filter->info);
564   bps = GST_AUDIO_INFO_BPS (&filter->info);
565   rate = GST_AUDIO_INFO_RATE (&filter->info);
566
567   gst_buffer_map (in, &map, GST_MAP_READ);
568   in_data = map.data;
569   in_size = map.size;
570
571   num_int_samples = in_size / bps;
572
573   GST_LOG_OBJECT (filter, "analyzing %u sample frames at ts %" GST_TIME_FORMAT,
574       num_int_samples, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (in)));
575
576   g_return_val_if_fail (num_int_samples % channels == 0, GST_FLOW_ERROR);
577
578   num_frames = num_int_samples / channels;
579
580   for (i = 0; i < channels; ++i) {
581     if (!GST_BUFFER_FLAG_IS_SET (in, GST_BUFFER_FLAG_GAP)) {
582       filter->process (in_data, num_int_samples, channels, &CS,
583           &filter->peak[i]);
584       GST_LOG_OBJECT (filter,
585           "channel %d, cumulative sum %f, peak %f, over %d samples/%d channels",
586           i, CS, filter->peak[i], num_int_samples, channels);
587       filter->CS[i] += CS;
588     } else {
589       filter->peak[i] = 0.0;
590     }
591     in_data += bps;
592
593     filter->decay_peak_age[i] += GST_FRAMES_TO_CLOCK_TIME (num_frames, rate);
594     GST_LOG_OBJECT (filter, "filter peak info [%d]: decay peak %f, age %"
595         GST_TIME_FORMAT, i,
596         filter->decay_peak[i], GST_TIME_ARGS (filter->decay_peak_age[i]));
597
598     /* update running peak */
599     if (filter->peak[i] > filter->last_peak[i])
600       filter->last_peak[i] = filter->peak[i];
601
602     /* make decay peak fall off if too old */
603     falloff_time =
604         GST_CLOCK_DIFF (gst_gdouble_to_guint64 (filter->decay_peak_ttl),
605         filter->decay_peak_age[i]);
606     if (falloff_time > 0) {
607       gdouble falloff_dB;
608       gdouble falloff;
609       gdouble length;           /* length of falloff time in seconds */
610
611       length = (gdouble) falloff_time / (gdouble) GST_SECOND;
612       falloff_dB = filter->decay_peak_falloff * length;
613       falloff = pow (10, falloff_dB / -20.0);
614
615       GST_LOG_OBJECT (filter,
616           "falloff: current %f, base %f, interval %" GST_TIME_FORMAT
617           ", dB falloff %f, factor %e",
618           filter->decay_peak[i], filter->decay_peak_base[i],
619           GST_TIME_ARGS (falloff_time), falloff_dB, falloff);
620       filter->decay_peak[i] = filter->decay_peak_base[i] * falloff;
621       GST_LOG_OBJECT (filter,
622           "peak is %" GST_TIME_FORMAT " old, decayed with factor %e to %f",
623           GST_TIME_ARGS (filter->decay_peak_age[i]), falloff,
624           filter->decay_peak[i]);
625     } else {
626       GST_LOG_OBJECT (filter, "peak not old enough, not decaying");
627     }
628
629     /* if the peak of this run is higher, the decay peak gets reset */
630     if (filter->peak[i] >= filter->decay_peak[i]) {
631       GST_LOG_OBJECT (filter, "new peak, %f", filter->peak[i]);
632       filter->decay_peak[i] = filter->peak[i];
633       filter->decay_peak_base[i] = filter->peak[i];
634       filter->decay_peak_age[i] = G_GINT64_CONSTANT (0);
635     }
636   }
637
638   if (G_UNLIKELY (!filter->num_frames)) {
639     /* remember start timestamp for message */
640     filter->message_ts = GST_BUFFER_TIMESTAMP (in);
641   }
642   filter->num_frames += num_frames;
643
644   /* do we need to message ? */
645   if (filter->num_frames >= filter->interval_frames) {
646     if (filter->message) {
647       GstMessage *m;
648       GstClockTime duration =
649           GST_FRAMES_TO_CLOCK_TIME (filter->num_frames, rate);
650
651       m = gst_level_message_new (filter, filter->message_ts, duration);
652
653       GST_LOG_OBJECT (filter,
654           "message: ts %" GST_TIME_FORMAT ", num_frames %d",
655           GST_TIME_ARGS (filter->message_ts), filter->num_frames);
656
657       for (i = 0; i < channels; ++i) {
658         gdouble RMS;
659         gdouble RMSdB, lastdB, decaydB;
660
661         RMS = sqrt (filter->CS[i] / filter->num_frames);
662         GST_LOG_OBJECT (filter,
663             "message: channel %d, CS %f, num_frames %d, RMS %f",
664             i, filter->CS[i], filter->num_frames, RMS);
665         GST_LOG_OBJECT (filter,
666             "message: last_peak: %f, decay_peak: %f",
667             filter->last_peak[i], filter->decay_peak[i]);
668         /* RMS values are calculated in amplitude, so 20 * log 10 */
669         RMSdB = 20 * log10 (RMS + EPSILON);
670         /* peak values are square sums, ie. power, so 10 * log 10 */
671         lastdB = 10 * log10 (filter->last_peak[i] + EPSILON);
672         decaydB = 10 * log10 (filter->decay_peak[i] + EPSILON);
673
674         if (filter->decay_peak[i] < filter->last_peak[i]) {
675           /* this can happen in certain cases, for example when
676            * the last peak is between decay_peak and decay_peak_base */
677           GST_DEBUG_OBJECT (filter,
678               "message: decay peak dB %f smaller than last peak dB %f, copying",
679               decaydB, lastdB);
680           filter->decay_peak[i] = filter->last_peak[i];
681         }
682         GST_LOG_OBJECT (filter,
683             "message: RMS %f dB, peak %f dB, decay %f dB",
684             RMSdB, lastdB, decaydB);
685
686         gst_level_message_append_channel (m, RMSdB, lastdB, decaydB);
687
688         /* reset cumulative and normal peak */
689         filter->CS[i] = 0.0;
690         filter->last_peak[i] = 0.0;
691       }
692
693       gst_element_post_message (GST_ELEMENT (filter), m);
694     }
695     filter->num_frames = 0;
696   }
697
698   gst_buffer_unmap (in, &map);
699
700   return GST_FLOW_OK;
701 }
702
703 static gboolean
704 plugin_init (GstPlugin * plugin)
705 {
706   /*oil_init (); */
707
708   return gst_element_register (plugin, "level", GST_RANK_NONE, GST_TYPE_LEVEL);
709 }
710
711 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
712     GST_VERSION_MINOR,
713     "level",
714     "Audio level plugin",
715     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);