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., 51 Franklin St, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 */
21
22 /**
23 * SECTION:element-level
24 * @title: level
25 *
26 * Level analyses incoming audio buffers and, if the #GstLevel:message property
27 * is %TRUE, generates an element message named
28 * `level`: after each interval of time given by the #GstLevel:interval property.
29 * The message's structure contains these fields:
30 *
31 * * #GstClockTime `timestamp`: the timestamp of the buffer that triggered the message.
32 * * #GstClockTime `stream-time`: the stream time of the buffer.
33 * * #GstClockTime `running-time`: the running_time of the buffer.
34 * * #GstClockTime `duration`: the duration of the buffer.
35 * * #GstClockTime `endtime`: the end time of the buffer that triggered the message as
36 * stream time (this is deprecated, as it can be calculated from stream-time + duration)
37 * * #GValueArray of #gdouble `peak`: the peak power level in dB for each channel
38 * * #GValueArray of #gdouble `decay`: the decaying peak power level in dB for each channel
39 * The decaying peak level follows the peak level, but starts dropping if no
40 * new peak is reached after the time given by the #GstLevel:peak-ttl.
41 * When the decaying peak level drops, it does so at the decay rate as
42 * specified by the #GstLevel:peak-falloff.
43 * * #GValueArray of #gdouble `rms`: the Root Mean Square (or average power) level in dB
44 * for each channel
45 *
46 * ## Example application
47 *
48 * {{ tests/examples/level/level-example.c }}
49 *
50 */
51
52 #ifdef HAVE_CONFIG_H
53 #include "config.h"
54 #endif
55
56 /* FIXME 0.11: suppress warnings for deprecated API such as GValueArray
57 * with newer GLib versions (>= 2.31.0) */
58 #define GLIB_DISABLE_DEPRECATION_WARNINGS
59
60 #include <string.h>
61 #include <math.h>
62 #include <gst/gst.h>
63 #include <gst/audio/audio.h>
64
65 #include "gstlevel.h"
66
67 GST_DEBUG_CATEGORY_STATIC (level_debug);
68 #define GST_CAT_DEFAULT level_debug
69
70 #define EPSILON 1e-35f
71
72 static GstStaticPadTemplate sink_template_factory =
73 GST_STATIC_PAD_TEMPLATE ("sink",
74 GST_PAD_SINK,
75 GST_PAD_ALWAYS,
76 GST_STATIC_CAPS ("audio/x-raw, "
77 "format = (string) { S8, " GST_AUDIO_NE (S16) ", " GST_AUDIO_NE (S32)
78 ", " GST_AUDIO_NE (F32) "," GST_AUDIO_NE (F64) " },"
79 "layout = (string) interleaved, "
80 "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]")
81 );
82
83 static GstStaticPadTemplate src_template_factory =
84 GST_STATIC_PAD_TEMPLATE ("src",
85 GST_PAD_SRC,
86 GST_PAD_ALWAYS,
87 GST_STATIC_CAPS ("audio/x-raw, "
88 "format = (string) { S8, " GST_AUDIO_NE (S16) ", " GST_AUDIO_NE (S32)
89 ", " GST_AUDIO_NE (F32) "," GST_AUDIO_NE (F64) " },"
90 "layout = (string) interleaved, "
91 "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]")
92 );
93
94 enum
95 {
96 PROP_0,
97 PROP_POST_MESSAGES,
98 PROP_MESSAGE,
99 PROP_INTERVAL,
100 PROP_PEAK_TTL,
101 PROP_PEAK_FALLOFF,
102 PROP_AUDIO_LEVEL_META,
103 };
104
105 #define gst_level_parent_class parent_class
106 G_DEFINE_TYPE (GstLevel, gst_level, GST_TYPE_BASE_TRANSFORM);
107 GST_ELEMENT_REGISTER_DEFINE (level, "level", GST_RANK_NONE, GST_TYPE_LEVEL);
108
109 static void gst_level_set_property (GObject * object, guint prop_id,
110 const GValue * value, GParamSpec * pspec);
111 static void gst_level_get_property (GObject * object, guint prop_id,
112 GValue * value, GParamSpec * pspec);
113 static void gst_level_finalize (GObject * obj);
114
115 static gboolean gst_level_set_caps (GstBaseTransform * trans, GstCaps * in,
116 GstCaps * out);
117 static gboolean gst_level_start (GstBaseTransform * trans);
118 static GstFlowReturn gst_level_transform_ip (GstBaseTransform * trans,
119 GstBuffer * in);
120 static void gst_level_post_message (GstLevel * filter);
121 static gboolean gst_level_sink_event (GstBaseTransform * trans,
122 GstEvent * event);
123 static void gst_level_recalc_interval_frames (GstLevel * level);
124
125 static void
gst_level_class_init(GstLevelClass * klass)126 gst_level_class_init (GstLevelClass * klass)
127 {
128 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
129 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
130 GstBaseTransformClass *trans_class = GST_BASE_TRANSFORM_CLASS (klass);
131
132 gobject_class->set_property = gst_level_set_property;
133 gobject_class->get_property = gst_level_get_property;
134 gobject_class->finalize = gst_level_finalize;
135
136 /**
137 * GstLevel:post-messages
138 *
139 * Post messages on the bus with level information.
140 *
141 * Since: 1.1.0
142 */
143 g_object_class_install_property (gobject_class, PROP_POST_MESSAGES,
144 g_param_spec_boolean ("post-messages", "Post Messages",
145 "Whether to post a 'level' element message on the bus for each "
146 "passed interval", TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
147 /* FIXME(2.0): remove this property */
148 /**
149 * GstLevel:post-messages
150 *
151 * Post messages on the bus with level information.
152 *
153 * Deprecated: use the #GstLevel:post-messages property
154 */
155 #ifndef GST_REMOVE_DEPRECATED
156 g_object_class_install_property (gobject_class, PROP_MESSAGE,
157 g_param_spec_boolean ("message", "message",
158 "Post a 'level' message for each passed interval "
159 "(deprecated, use the post-messages property instead)", TRUE,
160 G_PARAM_READWRITE | G_PARAM_DEPRECATED | G_PARAM_STATIC_STRINGS));
161 #endif
162 g_object_class_install_property (gobject_class, PROP_INTERVAL,
163 g_param_spec_uint64 ("interval", "Interval",
164 "Interval of time between message posts (in nanoseconds)",
165 1, G_MAXUINT64, GST_SECOND / 10,
166 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
167 g_object_class_install_property (gobject_class, PROP_PEAK_TTL,
168 g_param_spec_uint64 ("peak-ttl", "Peak TTL",
169 "Time To Live of decay peak before it falls back (in nanoseconds)",
170 0, G_MAXUINT64, GST_SECOND / 10 * 3,
171 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
172 g_object_class_install_property (gobject_class, PROP_PEAK_FALLOFF,
173 g_param_spec_double ("peak-falloff", "Peak Falloff",
174 "Decay rate of decay peak after TTL (in dB/sec)",
175 0.0, G_MAXDOUBLE, 10.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
176 /**
177 * GstLevel:audio-level-meta:
178 *
179 * If %TRUE, generate or update GstAudioLevelMeta on output buffers.
180 *
181 * Since: 1.20
182 */
183 g_object_class_install_property (gobject_class, PROP_AUDIO_LEVEL_META,
184 g_param_spec_boolean ("audio-level-meta", "Audio Level Meta",
185 "Set GstAudioLevelMeta on buffers", FALSE,
186 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
187
188 GST_DEBUG_CATEGORY_INIT (level_debug, "level", 0, "Level calculation");
189
190 gst_element_class_add_static_pad_template (element_class,
191 &sink_template_factory);
192 gst_element_class_add_static_pad_template (element_class,
193 &src_template_factory);
194 gst_element_class_set_static_metadata (element_class, "Level",
195 "Filter/Analyzer/Audio",
196 "RMS/Peak/Decaying Peak Level messager for audio/raw",
197 "Thomas Vander Stichele <thomas at apestaart dot org>");
198
199 trans_class->set_caps = GST_DEBUG_FUNCPTR (gst_level_set_caps);
200 trans_class->start = GST_DEBUG_FUNCPTR (gst_level_start);
201 trans_class->transform_ip = GST_DEBUG_FUNCPTR (gst_level_transform_ip);
202 trans_class->sink_event = GST_DEBUG_FUNCPTR (gst_level_sink_event);
203 }
204
205 static void
configure_passthrough(GstLevel * self,gboolean audio_level_meta)206 configure_passthrough (GstLevel * self, gboolean audio_level_meta)
207 {
208 /* can't use passthrough if audio-level-meta is enabled as we need a
209 * writable buffer to add the meta.
210 * gst_base_transform_set_passthrough() takes the object lock internally. */
211 gst_base_transform_set_passthrough (GST_BASE_TRANSFORM (self),
212 !audio_level_meta);
213 }
214
215 static void
gst_level_init(GstLevel * filter)216 gst_level_init (GstLevel * filter)
217 {
218 filter->CS = NULL;
219 filter->peak = NULL;
220 filter->last_peak = NULL;
221 filter->decay_peak = NULL;
222 filter->decay_peak_base = NULL;
223 filter->decay_peak_age = NULL;
224
225 gst_audio_info_init (&filter->info);
226
227 filter->interval = GST_SECOND / 10;
228 filter->decay_peak_ttl = GST_SECOND / 10 * 3;
229 filter->decay_peak_falloff = 10.0; /* dB falloff (/sec) */
230
231 filter->post_messages = TRUE;
232
233 filter->process = NULL;
234
235 gst_base_transform_set_gap_aware (GST_BASE_TRANSFORM (filter), TRUE);
236 configure_passthrough (filter, filter->audio_level_meta);
237 }
238
239 static void
gst_level_finalize(GObject * obj)240 gst_level_finalize (GObject * obj)
241 {
242 GstLevel *filter = GST_LEVEL (obj);
243
244 g_free (filter->CS);
245 g_free (filter->peak);
246 g_free (filter->last_peak);
247 g_free (filter->decay_peak);
248 g_free (filter->decay_peak_base);
249 g_free (filter->decay_peak_age);
250
251 filter->CS = NULL;
252 filter->peak = NULL;
253 filter->last_peak = NULL;
254 filter->decay_peak = NULL;
255 filter->decay_peak_base = NULL;
256 filter->decay_peak_age = NULL;
257
258 G_OBJECT_CLASS (parent_class)->finalize (obj);
259 }
260
261 static void
gst_level_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)262 gst_level_set_property (GObject * object, guint prop_id,
263 const GValue * value, GParamSpec * pspec)
264 {
265 GstLevel *filter = GST_LEVEL (object);
266
267 GST_OBJECT_LOCK (filter);
268
269 switch (prop_id) {
270 case PROP_POST_MESSAGES:
271 /* fall-through */
272 case PROP_MESSAGE:
273 filter->post_messages = g_value_get_boolean (value);
274 break;
275 case PROP_INTERVAL:
276 filter->interval = g_value_get_uint64 (value);
277 if (GST_AUDIO_INFO_RATE (&filter->info)) {
278 gst_level_recalc_interval_frames (filter);
279 }
280 break;
281 case PROP_PEAK_TTL:
282 filter->decay_peak_ttl =
283 gst_guint64_to_gdouble (g_value_get_uint64 (value));
284 break;
285 case PROP_PEAK_FALLOFF:
286 filter->decay_peak_falloff = g_value_get_double (value);
287 break;
288 case PROP_AUDIO_LEVEL_META:
289 filter->audio_level_meta = g_value_get_boolean (value);
290 GST_OBJECT_UNLOCK (filter);
291 configure_passthrough (filter, g_value_get_boolean (value));
292 GST_OBJECT_LOCK (filter);
293 break;
294 default:
295 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
296 break;
297 }
298
299 GST_OBJECT_UNLOCK (filter);
300 }
301
302 static void
gst_level_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)303 gst_level_get_property (GObject * object, guint prop_id,
304 GValue * value, GParamSpec * pspec)
305 {
306 GstLevel *filter = GST_LEVEL (object);
307
308 GST_OBJECT_LOCK (filter);
309
310 switch (prop_id) {
311 case PROP_POST_MESSAGES:
312 /* fall-through */
313 case PROP_MESSAGE:
314 g_value_set_boolean (value, filter->post_messages);
315 break;
316 case PROP_INTERVAL:
317 g_value_set_uint64 (value, filter->interval);
318 break;
319 case PROP_PEAK_TTL:
320 g_value_set_uint64 (value, filter->decay_peak_ttl);
321 break;
322 case PROP_PEAK_FALLOFF:
323 g_value_set_double (value, filter->decay_peak_falloff);
324 break;
325 case PROP_AUDIO_LEVEL_META:
326 g_value_set_boolean (value, filter->audio_level_meta);
327 break;
328 default:
329 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
330 break;
331 }
332
333 GST_OBJECT_UNLOCK (filter);
334 }
335
336
337 /* process one (interleaved) channel of incoming samples
338 * calculate square sum of samples
339 * normalize and average over number of samples
340 * returns a normalized cumulative square value, which can be averaged
341 * to return the average power as a double between 0 and 1
342 * also returns the normalized peak power (square of the highest amplitude)
343 *
344 * caller must assure num is a multiple of channels
345 * samples for multiple channels are interleaved
346 * input sample data enters in *in_data and is not modified
347 * this filter only accepts signed audio data, so mid level is always 0
348 *
349 * for integers, this code considers the non-existent positive max value to be
350 * full-scale; so max-1 will not map to 1.0
351 */
352
353 #define DEFINE_INT_LEVEL_CALCULATOR(TYPE, RESOLUTION) \
354 static void inline \
355 gst_level_calculate_##TYPE (gpointer data, guint num, guint channels, \
356 gdouble *NCS, gdouble *NPS) \
357 { \
358 TYPE * in = (TYPE *)data; \
359 register guint j; \
360 gdouble squaresum = 0.0; /* square sum of the input samples */ \
361 register gdouble square = 0.0; /* Square */ \
362 register gdouble peaksquare = 0.0; /* Peak Square Sample */ \
363 gdouble normalizer; /* divisor to get a [-1.0, 1.0] range */ \
364 \
365 /* *NCS = 0.0; Normalized Cumulative Square */ \
366 /* *NPS = 0.0; Normalized Peak Square */ \
367 \
368 for (j = 0; j < num; j += channels) { \
369 square = ((gdouble) in[j]) * in[j]; \
370 if (square > peaksquare) peaksquare = square; \
371 squaresum += square; \
372 } \
373 \
374 normalizer = (gdouble) (G_GINT64_CONSTANT(1) << (RESOLUTION * 2)); \
375 *NCS = squaresum / normalizer; \
376 *NPS = peaksquare / normalizer; \
377 }
378
379 DEFINE_INT_LEVEL_CALCULATOR (gint32, 31);
380 DEFINE_INT_LEVEL_CALCULATOR (gint16, 15);
381 DEFINE_INT_LEVEL_CALCULATOR (gint8, 7);
382
383 /* FIXME: use orc to calculate squaresums? */
384 #define DEFINE_FLOAT_LEVEL_CALCULATOR(TYPE) \
385 static void inline \
386 gst_level_calculate_##TYPE (gpointer data, guint num, guint channels, \
387 gdouble *NCS, gdouble *NPS) \
388 { \
389 TYPE * in = (TYPE *)data; \
390 register guint j; \
391 gdouble squaresum = 0.0; /* square sum of the input samples */ \
392 register gdouble square = 0.0; /* Square */ \
393 register gdouble peaksquare = 0.0; /* Peak Square Sample */ \
394 \
395 /* *NCS = 0.0; Normalized Cumulative Square */ \
396 /* *NPS = 0.0; Normalized Peak Square */ \
397 \
398 /* orc_level_squaresum_f64(&squaresum,in,num); */ \
399 for (j = 0; j < num; j += channels) { \
400 square = ((gdouble) in[j]) * in[j]; \
401 if (square > peaksquare) peaksquare = square; \
402 squaresum += square; \
403 } \
404 \
405 *NCS = squaresum; \
406 *NPS = peaksquare; \
407 }
408
409 DEFINE_FLOAT_LEVEL_CALCULATOR (gfloat);
410 DEFINE_FLOAT_LEVEL_CALCULATOR (gdouble);
411
412 /* we would need stride to deinterleave also
413 static void inline
414 gst_level_calculate_gdouble (gpointer data, guint num, guint channels,
415 gdouble *NCS, gdouble *NPS)
416 {
417 orc_level_squaresum_f64(NCS,(gdouble *)data,num);
418 *NPS = 0.0;
419 }
420 */
421
422 /* called with object lock */
423 static void
gst_level_recalc_interval_frames(GstLevel * level)424 gst_level_recalc_interval_frames (GstLevel * level)
425 {
426 GstClockTime interval = level->interval;
427 guint sample_rate = GST_AUDIO_INFO_RATE (&level->info);
428 guint interval_frames;
429
430 interval_frames = GST_CLOCK_TIME_TO_FRAMES (interval, sample_rate);
431
432 if (interval_frames == 0) {
433 GST_WARNING_OBJECT (level, "interval %" GST_TIME_FORMAT " is too small, "
434 "should be at least %" GST_TIME_FORMAT " for sample rate %u",
435 GST_TIME_ARGS (interval),
436 GST_TIME_ARGS (GST_FRAMES_TO_CLOCK_TIME (1, sample_rate)), sample_rate);
437 interval_frames = 1;
438 }
439
440 level->interval_frames = interval_frames;
441
442 GST_INFO_OBJECT (level, "interval_frames now %u for interval "
443 "%" GST_TIME_FORMAT " and sample rate %u", interval_frames,
444 GST_TIME_ARGS (interval), sample_rate);
445 }
446
447 static gboolean
gst_level_set_caps(GstBaseTransform * trans,GstCaps * in,GstCaps * out)448 gst_level_set_caps (GstBaseTransform * trans, GstCaps * in, GstCaps * out)
449 {
450 GstLevel *filter = GST_LEVEL (trans);
451 GstAudioInfo info;
452 gint i, channels;
453
454 if (!gst_audio_info_from_caps (&info, in))
455 return FALSE;
456
457 GST_OBJECT_LOCK (filter);
458
459 switch (GST_AUDIO_INFO_FORMAT (&info)) {
460 case GST_AUDIO_FORMAT_S8:
461 filter->process = gst_level_calculate_gint8;
462 break;
463 case GST_AUDIO_FORMAT_S16:
464 filter->process = gst_level_calculate_gint16;
465 break;
466 case GST_AUDIO_FORMAT_S32:
467 filter->process = gst_level_calculate_gint32;
468 break;
469 case GST_AUDIO_FORMAT_F32:
470 filter->process = gst_level_calculate_gfloat;
471 break;
472 case GST_AUDIO_FORMAT_F64:
473 filter->process = gst_level_calculate_gdouble;
474 break;
475 default:
476 filter->process = NULL;
477 break;
478 }
479
480 filter->info = info;
481
482 channels = GST_AUDIO_INFO_CHANNELS (&info);
483
484 /* allocate channel variable arrays */
485 g_free (filter->CS);
486 g_free (filter->peak);
487 g_free (filter->last_peak);
488 g_free (filter->decay_peak);
489 g_free (filter->decay_peak_base);
490 g_free (filter->decay_peak_age);
491 filter->CS = g_new (gdouble, channels);
492 filter->peak = g_new (gdouble, channels);
493 filter->last_peak = g_new (gdouble, channels);
494 filter->decay_peak = g_new (gdouble, channels);
495 filter->decay_peak_base = g_new (gdouble, channels);
496
497 filter->decay_peak_age = g_new (GstClockTime, channels);
498
499 for (i = 0; i < channels; ++i) {
500 filter->CS[i] = filter->peak[i] = filter->last_peak[i] =
501 filter->decay_peak[i] = filter->decay_peak_base[i] = 0.0;
502 filter->decay_peak_age[i] = G_GUINT64_CONSTANT (0);
503 }
504
505 gst_level_recalc_interval_frames (filter);
506
507 GST_OBJECT_UNLOCK (filter);
508 return TRUE;
509 }
510
511 static gboolean
gst_level_start(GstBaseTransform * trans)512 gst_level_start (GstBaseTransform * trans)
513 {
514 GstLevel *filter = GST_LEVEL (trans);
515
516 filter->num_frames = 0;
517 filter->message_ts = GST_CLOCK_TIME_NONE;
518
519 return TRUE;
520 }
521
522 static GstMessage *
gst_level_message_new(GstLevel * level,GstClockTime timestamp,GstClockTime duration)523 gst_level_message_new (GstLevel * level, GstClockTime timestamp,
524 GstClockTime duration)
525 {
526 GstBaseTransform *trans = GST_BASE_TRANSFORM_CAST (level);
527 GstStructure *s;
528 GValue v = { 0, };
529 GstClockTime endtime, running_time, stream_time;
530
531 running_time = gst_segment_to_running_time (&trans->segment, GST_FORMAT_TIME,
532 timestamp);
533 stream_time = gst_segment_to_stream_time (&trans->segment, GST_FORMAT_TIME,
534 timestamp);
535 /* endtime is for backwards compatibility */
536 endtime = stream_time + duration;
537
538 s = gst_structure_new ("level",
539 "endtime", GST_TYPE_CLOCK_TIME, endtime,
540 "timestamp", G_TYPE_UINT64, timestamp,
541 "stream-time", G_TYPE_UINT64, stream_time,
542 "running-time", G_TYPE_UINT64, running_time,
543 "duration", G_TYPE_UINT64, duration, NULL);
544
545 g_value_init (&v, G_TYPE_VALUE_ARRAY);
546 g_value_take_boxed (&v, g_value_array_new (0));
547 gst_structure_take_value (s, "rms", &v);
548
549 g_value_init (&v, G_TYPE_VALUE_ARRAY);
550 g_value_take_boxed (&v, g_value_array_new (0));
551 gst_structure_take_value (s, "peak", &v);
552
553 g_value_init (&v, G_TYPE_VALUE_ARRAY);
554 g_value_take_boxed (&v, g_value_array_new (0));
555 gst_structure_take_value (s, "decay", &v);
556
557 return gst_message_new_element (GST_OBJECT (level), s);
558 }
559
560 static void
gst_level_message_append_channel(GstMessage * m,gdouble rms,gdouble peak,gdouble decay)561 gst_level_message_append_channel (GstMessage * m, gdouble rms, gdouble peak,
562 gdouble decay)
563 {
564 const GValue *array_val;
565 GstStructure *s;
566 GValueArray *arr;
567 GValue v = { 0, };
568
569 g_value_init (&v, G_TYPE_DOUBLE);
570
571 s = (GstStructure *) gst_message_get_structure (m);
572
573 array_val = gst_structure_get_value (s, "rms");
574 arr = (GValueArray *) g_value_get_boxed (array_val);
575 g_value_set_double (&v, rms);
576 g_value_array_append (arr, &v); /* copies by value */
577
578 array_val = gst_structure_get_value (s, "peak");
579 arr = (GValueArray *) g_value_get_boxed (array_val);
580 g_value_set_double (&v, peak);
581 g_value_array_append (arr, &v); /* copies by value */
582
583 array_val = gst_structure_get_value (s, "decay");
584 arr = (GValueArray *) g_value_get_boxed (array_val);
585 g_value_set_double (&v, decay);
586 g_value_array_append (arr, &v); /* copies by value */
587
588 g_value_unset (&v);
589 }
590
591 static void
gst_level_rtp_audio_level_meta(GstLevel * self,GstBuffer * buffer,guint8 level)592 gst_level_rtp_audio_level_meta (GstLevel * self, GstBuffer * buffer,
593 guint8 level)
594 {
595 GstAudioLevelMeta *meta;
596
597 /* Update the existing meta, if any, so we can have an upstream element
598 * filling the voice activity part of the meta. */
599 meta = gst_buffer_get_audio_level_meta (buffer);
600 if (meta) {
601 meta->level = level;
602 } else {
603 /* Assume audio does not contain voice, it can be detected by another
604 * downstream element. */
605 gst_buffer_add_audio_level_meta (buffer, level, FALSE);
606 }
607 }
608
609 static GstFlowReturn
gst_level_transform_ip(GstBaseTransform * trans,GstBuffer * in)610 gst_level_transform_ip (GstBaseTransform * trans, GstBuffer * in)
611 {
612 GstLevel *filter;
613 GstMapInfo map;
614 guint8 *in_data;
615 gsize in_size;
616 gdouble CS;
617 guint i;
618 guint num_frames;
619 guint num_int_samples = 0; /* number of interleaved samples
620 * ie. total count for all channels combined */
621 guint block_size, block_int_size; /* we subdivide buffers to not skip message
622 * intervals */
623 GstClockTimeDiff falloff_time;
624 gint channels, rate, bps;
625 gdouble CS_tot = 0; /* Total Cumulative Square on all samples */
626
627 filter = GST_LEVEL (trans);
628
629 channels = GST_AUDIO_INFO_CHANNELS (&filter->info);
630 bps = GST_AUDIO_INFO_BPS (&filter->info);
631 rate = GST_AUDIO_INFO_RATE (&filter->info);
632
633 gst_buffer_map (in, &map, GST_MAP_READ);
634 in_data = map.data;
635 in_size = map.size;
636
637 num_int_samples = in_size / bps;
638
639 GST_LOG_OBJECT (filter, "analyzing %u sample frames at ts %" GST_TIME_FORMAT,
640 num_int_samples, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (in)));
641
642 g_return_val_if_fail (num_int_samples % channels == 0, GST_FLOW_ERROR);
643
644 GST_OBJECT_LOCK (filter);
645
646 if (GST_BUFFER_FLAG_IS_SET (in, GST_BUFFER_FLAG_DISCONT)) {
647 filter->message_ts = GST_BUFFER_TIMESTAMP (in);
648 filter->num_frames = 0;
649 }
650 if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (filter->message_ts))) {
651 filter->message_ts = GST_BUFFER_TIMESTAMP (in);
652 }
653
654 num_frames = num_int_samples / channels;
655 while (num_frames > 0) {
656 block_size = filter->interval_frames - filter->num_frames;
657 block_size = MIN (block_size, num_frames);
658 block_int_size = block_size * channels;
659
660 for (i = 0; i < channels; ++i) {
661 if (!GST_BUFFER_FLAG_IS_SET (in, GST_BUFFER_FLAG_GAP)) {
662 filter->process (in_data + (bps * i), block_int_size, channels, &CS,
663 &filter->peak[i]);
664 CS_tot += CS;
665 GST_LOG_OBJECT (filter,
666 "[%d]: cumulative squares %lf, over %d samples/%d channels",
667 i, CS, block_int_size, channels);
668 filter->CS[i] += CS;
669 } else {
670 filter->peak[i] = 0.0;
671 }
672
673 filter->decay_peak_age[i] += GST_FRAMES_TO_CLOCK_TIME (num_frames, rate);
674 GST_LOG_OBJECT (filter,
675 "[%d]: peak %f, last peak %f, decay peak %f, age %" GST_TIME_FORMAT,
676 i, filter->peak[i], filter->last_peak[i], filter->decay_peak[i],
677 GST_TIME_ARGS (filter->decay_peak_age[i]));
678
679 /* update running peak */
680 if (filter->peak[i] > filter->last_peak[i])
681 filter->last_peak[i] = filter->peak[i];
682
683 /* make decay peak fall off if too old */
684 falloff_time =
685 GST_CLOCK_DIFF (gst_gdouble_to_guint64 (filter->decay_peak_ttl),
686 filter->decay_peak_age[i]);
687 if (falloff_time > 0) {
688 gdouble falloff_dB;
689 gdouble falloff;
690 gdouble length; /* length of falloff time in seconds */
691
692 length = (gdouble) falloff_time / (gdouble) GST_SECOND;
693 falloff_dB = filter->decay_peak_falloff * length;
694 falloff = pow (10, falloff_dB / -20.0);
695
696 GST_LOG_OBJECT (filter,
697 "falloff: current %f, base %f, interval %" GST_TIME_FORMAT
698 ", dB falloff %f, factor %e",
699 filter->decay_peak[i], filter->decay_peak_base[i],
700 GST_TIME_ARGS (falloff_time), falloff_dB, falloff);
701 filter->decay_peak[i] = filter->decay_peak_base[i] * falloff;
702 GST_LOG_OBJECT (filter,
703 "peak is %" GST_TIME_FORMAT " old, decayed with factor %e to %f",
704 GST_TIME_ARGS (filter->decay_peak_age[i]), falloff,
705 filter->decay_peak[i]);
706 } else {
707 GST_LOG_OBJECT (filter, "peak not old enough, not decaying");
708 }
709
710 /* if the peak of this run is higher, the decay peak gets reset */
711 if (filter->peak[i] >= filter->decay_peak[i]) {
712 GST_LOG_OBJECT (filter, "new peak, %f", filter->peak[i]);
713 filter->decay_peak[i] = filter->peak[i];
714 filter->decay_peak_base[i] = filter->peak[i];
715 filter->decay_peak_age[i] = G_GINT64_CONSTANT (0);
716 }
717 }
718 in_data += block_size * bps * channels;
719
720 filter->num_frames += block_size;
721 num_frames -= block_size;
722
723 /* do we need to message ? */
724 if (filter->num_frames >= filter->interval_frames) {
725 gst_level_post_message (filter);
726 }
727 }
728
729 gst_buffer_unmap (in, &map);
730
731 if (filter->audio_level_meta) {
732 gdouble RMS = sqrt (CS_tot / num_int_samples);
733 gdouble RMSdB = 20 * log10 (RMS + EPSILON);
734
735 gst_level_rtp_audio_level_meta (filter, in, -RMSdB);
736 }
737
738 GST_OBJECT_UNLOCK (filter);
739 return GST_FLOW_OK;
740 }
741
742 /* called with object lock */
743 static void
gst_level_post_message(GstLevel * filter)744 gst_level_post_message (GstLevel * filter)
745 {
746 guint i;
747 gint channels, rate, frames = filter->num_frames;
748 GstClockTime duration;
749
750 channels = GST_AUDIO_INFO_CHANNELS (&filter->info);
751 rate = GST_AUDIO_INFO_RATE (&filter->info);
752 duration = GST_FRAMES_TO_CLOCK_TIME (frames, rate);
753
754 if (filter->post_messages) {
755 GstMessage *m =
756 gst_level_message_new (filter, filter->message_ts, duration);
757
758 GST_LOG_OBJECT (filter,
759 "message: ts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
760 ", num_frames %d", GST_TIME_ARGS (filter->message_ts),
761 GST_TIME_ARGS (duration), frames);
762
763 for (i = 0; i < channels; ++i) {
764 gdouble RMS;
765 gdouble RMSdB, peakdB, decaydB;
766
767 RMS = sqrt (filter->CS[i] / frames);
768 GST_LOG_OBJECT (filter,
769 "message: channel %d, CS %f, RMS %f", i, filter->CS[i], RMS);
770 GST_LOG_OBJECT (filter,
771 "message: last_peak: %f, decay_peak: %f",
772 filter->last_peak[i], filter->decay_peak[i]);
773 /* RMS values are calculated in amplitude, so 20 * log 10 */
774 RMSdB = 20 * log10 (RMS + EPSILON);
775 /* peak values are square sums, ie. power, so 10 * log 10 */
776 peakdB = 10 * log10 (filter->last_peak[i] + EPSILON);
777 decaydB = 10 * log10 (filter->decay_peak[i] + EPSILON);
778
779 if (filter->decay_peak[i] < filter->last_peak[i]) {
780 /* this can happen in certain cases, for example when
781 * the last peak is between decay_peak and decay_peak_base */
782 GST_DEBUG_OBJECT (filter,
783 "message: decay peak dB %f smaller than last peak dB %f, copying",
784 decaydB, peakdB);
785 filter->decay_peak[i] = filter->last_peak[i];
786 }
787 GST_LOG_OBJECT (filter,
788 "message: RMS %f dB, peak %f dB, decay %f dB",
789 RMSdB, peakdB, decaydB);
790
791 gst_level_message_append_channel (m, RMSdB, peakdB, decaydB);
792
793 /* reset cumulative and normal peak */
794 filter->CS[i] = 0.0;
795 filter->last_peak[i] = 0.0;
796 }
797
798 GST_OBJECT_UNLOCK (filter);
799 gst_element_post_message (GST_ELEMENT (filter), m);
800 GST_OBJECT_LOCK (filter);
801
802 }
803 filter->num_frames -= frames;
804 filter->message_ts += duration;
805 }
806
807
808 static gboolean
gst_level_sink_event(GstBaseTransform * trans,GstEvent * event)809 gst_level_sink_event (GstBaseTransform * trans, GstEvent * event)
810 {
811 if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) {
812 GstLevel *filter = GST_LEVEL (trans);
813
814 GST_OBJECT_LOCK (filter);
815 gst_level_post_message (filter);
816 GST_OBJECT_UNLOCK (filter);
817 }
818
819 return GST_BASE_TRANSFORM_CLASS (parent_class)->sink_event (trans, event);
820 }
821
822 static gboolean
plugin_init(GstPlugin * plugin)823 plugin_init (GstPlugin * plugin)
824 {
825 return GST_ELEMENT_REGISTER (level, plugin);
826 }
827
828 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
829 GST_VERSION_MINOR,
830 level,
831 "Audio level plugin",
832 plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);
833