gstspectrum.c 21.8 KB
Newer Older
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
1
/* GStreamer
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
2
 * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3
 *               <2006> Stefan Kost <ensonic@users.sf.net>
4
 *               <2007> Sebastian Dröge <slomo@circular-chaos.org>
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
21
22
/**
 * SECTION:element-spectrum
23
 * @short_description: audio spectrum analyzer
24
25
 *
 * <refsect2>
26
 * <para>
27
 * The Spectrum element analyzes the frequency spectrum of an audio signal.
28
29
 * If #GstSpectrum:message property is #TRUE it sends analysis results as
 * application message named
30
 * <classname>&quot;spectrum&quot;</classname> after each interval of time given
31
 * by the #GstSpectrum:interval property.
32
33
 * </para>
 * <para>
34
 * The message's structure contains three fields:
35
36
37
38
39
40
41
42
43
44
 * <itemizedlist>
 * <listitem>
 *   <para>
 *   #GstClockTime
 *   <classname>&quot;endtime&quot;</classname>:
 *   the end time of the buffer that triggered the message
 *   </para>
 * </listitem>
 * <listitem>
 *   <para>
45
46
 *   #GstValueList of #gfloat
 *   <classname>&quot;magnitude&quot;</classname>:
47
 *   the level for each frequency band in dB. All values below the value of the
48
 *   #GstSpectrum:threshold property will be set to the threshold.
49
50
 *   </para>
 * </listitem>
51
52
53
54
55
56
57
 * <listitem>
 *   <para>
 *   #GstValueList of #gfloat
 *   <classname>&quot;phase&quot;</classname>:
 *   the phase for each frequency band. The value is between -pi and pi.
 *   </para>
 * </listitem>
58
 * </itemizedlist>
59
60
 * </para>
 * <para>
61
62
 * This element cannot be used with the gst-launch command in a sensible way.
 * The included demo shows how to use it in an application.
63
64
 * </para>
 * <para>
65
 * Last reviewed on 2008-02-07 (0.10.6)
66
 * </para>
67
 * </refsect2>
68
 */
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
69

70
71
72
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
73
#include <string.h>
74
#include <stdlib.h>
75
#include <gst/audio/audio.h>
76
77
#include <gst/audio/gstaudiofilter.h>
#include <math.h>
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
78
79
#include "gstspectrum.h"

80
81
82
83
84
85
#include <gst/fft/gstfft.h>
#include <gst/fft/gstffts16.h>
#include <gst/fft/gstffts32.h>
#include <gst/fft/gstfftf32.h>
#include <gst/fft/gstfftf64.h>

86
87
88
GST_DEBUG_CATEGORY_STATIC (gst_spectrum_debug);
#define GST_CAT_DEFAULT gst_spectrum_debug

89
/* elementfactory information */
90
static const GstElementDetails gst_spectrum_details =
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
91
92
93
GST_ELEMENT_DETAILS ("Spectrum analyzer",
    "Filter/Analyzer/Audio",
    "Run an FFT on the audio signal, output spectrum data",
94
    "Erik Walthinsen <omega@cse.ogi.edu>, "
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    "Stefan Kost <ensonic@users.sf.net>, "
    "Sebastian Dröge <slomo@circular-chaos.org>");

#define ALLOWED_CAPS \
    "audio/x-raw-int, "                                               \
    " width = (int) 16, "                                             \
    " depth = (int) 16, "                                             \
    " signed = (boolean) true, "                                      \
    " endianness = (int) BYTE_ORDER, "                                \
    " rate = (int) [ 1, MAX ], "                                      \
    " channels = (int) [ 1, MAX ]; "                                  \
    "audio/x-raw-int, "                                               \
    " width = (int) 32, "                                             \
    " depth = (int) 32, "                                             \
    " signed = (boolean) true, "                                      \
    " endianness = (int) BYTE_ORDER, "                                \
    " rate = (int) [ 1, MAX ], "                                      \
    " channels = (int) [ 1, MAX ]; "                                  \
    "audio/x-raw-float, "                                             \
    " width = (int) { 32, 64 }, "                                     \
    " endianness = (int) BYTE_ORDER, "                                \
    " rate = (int) [ 1, MAX ], "                                      \
    " channels = (int) [ 1, MAX ]"
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
118

119
/* Spectrum properties */
120
#define DEFAULT_SIGNAL_SPECTRUM		TRUE
121
122
#define DEFAULT_SIGNAL_MAGNITUDE	TRUE
#define DEFAULT_SIGNAL_PHASE		FALSE
123
124
125
126
#define DEFAULT_SIGNAL_INTERVAL		(GST_SECOND / 10)
#define DEFAULT_BANDS			128
#define DEFAULT_THRESHOLD		-60

127
128
129
#define SPECTRUM_WINDOW_BASE 9
#define SPECTRUM_WINDOW_LEN (1 << (SPECTRUM_WINDOW_BASE+1))

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
130
131
enum
{
132
133
  PROP_0,
  PROP_SIGNAL_SPECTRUM,
134
135
  PROP_SIGNAL_MAGNITUDE,
  PROP_SIGNAL_PHASE,
136
137
138
  PROP_SIGNAL_INTERVAL,
  PROP_BANDS,
  PROP_THRESHOLD
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
139
140
};

141
142
GST_BOILERPLATE (GstSpectrum, gst_spectrum, GstAudioFilter,
    GST_TYPE_AUDIO_FILTER);
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
143

144
static void gst_spectrum_dispose (GObject * object);
145
static void gst_spectrum_finalize (GObject * object);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
146
147
static void gst_spectrum_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);
148
149
150
static void gst_spectrum_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);
static gboolean gst_spectrum_start (GstBaseTransform * trans);
151
152
static gboolean gst_spectrum_stop (GstBaseTransform * trans);
static gboolean gst_spectrum_event (GstBaseTransform * trans, GstEvent * event);
153
154
static GstFlowReturn gst_spectrum_transform_ip (GstBaseTransform * trans,
    GstBuffer * in);
155
156
static gboolean gst_spectrum_setup (GstAudioFilter * base,
    GstRingBufferSpec * format);
157

158
159
160
161
static void process_s16 (GstSpectrum * spectrum, const gint16 * samples);
static void process_s32 (GstSpectrum * spectrum, const gint32 * samples);
static void process_f32 (GstSpectrum * spectrum, const gfloat * samples);
static void process_f64 (GstSpectrum * spectrum, const gdouble * samples);
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
162

Benjamin Otte's avatar
Benjamin Otte committed
163
164
165
166
static void
gst_spectrum_base_init (gpointer g_class)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
167
  GstCaps *caps;
Benjamin Otte's avatar
Benjamin Otte committed
168
169

  gst_element_class_set_details (element_class, &gst_spectrum_details);
170
171
172
173
174

  caps = gst_caps_from_string (ALLOWED_CAPS);
  gst_audio_filter_class_add_pad_templates (GST_AUDIO_FILTER_CLASS (g_class),
      caps);
  gst_caps_unref (caps);
Benjamin Otte's avatar
Benjamin Otte committed
175
}
176

Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
177
static void
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
178
gst_spectrum_class_init (GstSpectrumClass * klass)
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
179
{
180
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
181
  GstBaseTransformClass *trans_class = GST_BASE_TRANSFORM_CLASS (klass);
182
  GstAudioFilterClass *filter_class = GST_AUDIO_FILTER_CLASS (klass);
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
183
184

  gobject_class->set_property = gst_spectrum_set_property;
185
  gobject_class->get_property = gst_spectrum_get_property;
186
  gobject_class->dispose = gst_spectrum_dispose;
187
  gobject_class->finalize = gst_spectrum_finalize;
188

189
  trans_class->start = GST_DEBUG_FUNCPTR (gst_spectrum_start);
190
191
  trans_class->stop = GST_DEBUG_FUNCPTR (gst_spectrum_stop);
  trans_class->event = GST_DEBUG_FUNCPTR (gst_spectrum_event);
192
193
194
  trans_class->transform_ip = GST_DEBUG_FUNCPTR (gst_spectrum_transform_ip);
  trans_class->passthrough_on_same_caps = TRUE;

195
196
  filter_class->setup = GST_DEBUG_FUNCPTR (gst_spectrum_setup);

197
  g_object_class_install_property (gobject_class, PROP_SIGNAL_SPECTRUM,
198
      g_param_spec_boolean ("message", "Message",
199
          "Post a level message for each passed interval",
200
          DEFAULT_SIGNAL_SPECTRUM, G_PARAM_READWRITE));
201

202
203
204
205
206
207
208
209
210
211
  g_object_class_install_property (gobject_class, PROP_SIGNAL_MAGNITUDE,
      g_param_spec_boolean ("message-magnitude", "Magnitude",
          "Post the magnitude of the spectrum",
          DEFAULT_SIGNAL_MAGNITUDE, G_PARAM_READWRITE));

  g_object_class_install_property (gobject_class, PROP_SIGNAL_PHASE,
      g_param_spec_boolean ("message-phase", "Phase",
          "Post the phase of the spectrum",
          DEFAULT_SIGNAL_PHASE, G_PARAM_READWRITE));

212
213
214
  g_object_class_install_property (gobject_class, PROP_SIGNAL_INTERVAL,
      g_param_spec_uint64 ("interval", "Interval",
          "Interval of time between message posts (in nanoseconds)",
215
          1, G_MAXUINT64, DEFAULT_SIGNAL_INTERVAL, G_PARAM_READWRITE));
216

217
218
  g_object_class_install_property (gobject_class, PROP_BANDS,
      g_param_spec_uint ("bands", "Bands", "number of frequency bands",
219
          0, G_MAXUINT, DEFAULT_BANDS, G_PARAM_READWRITE));
220

221
  g_object_class_install_property (gobject_class, PROP_THRESHOLD,
222
      g_param_spec_int ("threshold", "Threshold",
223
224
          "dB threshold for result. All lower values will be set to this",
          G_MININT, 0, DEFAULT_THRESHOLD, G_PARAM_READWRITE));
225

226
227
  GST_DEBUG_CATEGORY_INIT (gst_spectrum_debug, "spectrum", 0,
      "audio spectrum analyser element");
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
228
229
230
}

static void
231
gst_spectrum_init (GstSpectrum * spectrum, GstSpectrumClass * g_class)
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
232
{
233
234
  spectrum->adapter = gst_adapter_new ();

235
  spectrum->message = DEFAULT_SIGNAL_SPECTRUM;
236
237
  spectrum->message_magnitude = DEFAULT_SIGNAL_MAGNITUDE;
  spectrum->message_phase = DEFAULT_SIGNAL_PHASE;
238
239
240
  spectrum->interval = DEFAULT_SIGNAL_INTERVAL;
  spectrum->bands = DEFAULT_BANDS;
  spectrum->threshold = DEFAULT_THRESHOLD;
241

242
243
  spectrum->spect_magnitude = g_new0 (gfloat, spectrum->bands);
  spectrum->spect_phase = g_new0 (gfloat, spectrum->bands);
244
245
246
247
248
249
250
}

static void
gst_spectrum_dispose (GObject * object)
{
  GstSpectrum *spectrum = GST_SPECTRUM (object);

251
252
253
254
255
  if (spectrum->adapter) {
    g_object_unref (spectrum->adapter);
    spectrum->adapter = NULL;
  }

256
257
258
259
260
261
262
263
  G_OBJECT_CLASS (parent_class)->dispose (object);
}

static void
gst_spectrum_finalize (GObject * object)
{
  GstSpectrum *spectrum = GST_SPECTRUM (object);

264
265
266
267
268
269
270
271
272
  g_free (spectrum->in);
  if (spectrum->fft_free_func) {
    spectrum->fft_free_func (spectrum->fft_ctx);
    spectrum->fft_ctx = NULL;
    spectrum->fft_free_func = NULL;
  }
  g_free (spectrum->freqdata);
  g_free (spectrum->spect_magnitude);
  g_free (spectrum->spect_phase);
273

274
275
276
277
  spectrum->in = NULL;
  spectrum->spect_magnitude = NULL;
  spectrum->spect_phase = NULL;
  spectrum->freqdata = NULL;
278

279
  G_OBJECT_CLASS (parent_class)->finalize (object);
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
280
281
282
}

static void
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
283
284
gst_spectrum_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
285
{
286
  GstSpectrum *filter = GST_SPECTRUM (object);
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
287
288

  switch (prop_id) {
289
290
291
    case PROP_SIGNAL_SPECTRUM:
      filter->message = g_value_get_boolean (value);
      break;
292
293
294
295
296
297
    case PROP_SIGNAL_MAGNITUDE:
      filter->message_magnitude = g_value_get_boolean (value);
      break;
    case PROP_SIGNAL_PHASE:
      filter->message_phase = g_value_get_boolean (value);
      break;
298
    case PROP_SIGNAL_INTERVAL:
299
      filter->interval = g_value_get_uint64 (value);
300
301
      break;
    case PROP_BANDS:
302
      GST_BASE_TRANSFORM_LOCK (filter);
303

304
      filter->bands = g_value_get_uint (value);
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
      g_free (filter->spect_magnitude);
      g_free (filter->spect_phase);
      g_free (filter->in);
      g_free (filter->freqdata);

      if (filter->fft_free_func) {
        filter->fft_free_func (filter->fft_ctx);
        filter->fft_ctx = NULL;
        filter->fft_free_func = NULL;
      }

      filter->in = NULL;
      filter->freqdata = NULL;
      filter->spect_magnitude = g_new0 (gfloat, filter->bands);
      filter->spect_phase = g_new0 (gfloat, filter->bands);
      filter->num_frames = 0;
      filter->num_fft = 0;
322
      GST_BASE_TRANSFORM_UNLOCK (filter);
323
      GST_DEBUG_OBJECT (filter, "reallocation, spect = %p, bands =%d ",
324
          filter->spect_magnitude, filter->bands);
325
      break;
326
327
    case PROP_THRESHOLD:
      filter->threshold = g_value_get_int (value);
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
328
329
      break;
    default:
330
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
331
332
333
334
      break;
  }
}

335
336
337
338
339
340
341
342
343
344
static void
gst_spectrum_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  GstSpectrum *filter = GST_SPECTRUM (object);

  switch (prop_id) {
    case PROP_SIGNAL_SPECTRUM:
      g_value_set_boolean (value, filter->message);
      break;
345
346
347
348
349
350
    case PROP_SIGNAL_MAGNITUDE:
      g_value_set_boolean (value, filter->message_magnitude);
      break;
    case PROP_SIGNAL_PHASE:
      g_value_set_boolean (value, filter->message_phase);
      break;
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
    case PROP_SIGNAL_INTERVAL:
      g_value_set_uint64 (value, filter->interval);
      break;
    case PROP_BANDS:
      g_value_set_uint (value, filter->bands);
      break;
    case PROP_THRESHOLD:
      g_value_set_int (value, filter->threshold);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static gboolean
gst_spectrum_start (GstBaseTransform * trans)
{
  GstSpectrum *filter = GST_SPECTRUM (trans);

  filter->num_frames = 0;
372
373
  filter->num_fft = 0;
  if (filter->spect_magnitude)
374
    memset (filter->spect_magnitude, 0, filter->bands * sizeof (gfloat));
375
  if (filter->spect_phase)
376
    memset (filter->spect_phase, 0, filter->bands * sizeof (gfloat));
377
378
379
380

  return TRUE;
}

381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
static gboolean
gst_spectrum_stop (GstBaseTransform * trans)
{
  GstSpectrum *filter = GST_SPECTRUM (trans);

  gst_adapter_clear (filter->adapter);

  return TRUE;
}

static gboolean
gst_spectrum_event (GstBaseTransform * trans, GstEvent * event)
{
  GstSpectrum *filter = GST_SPECTRUM (trans);

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_FLUSH_STOP:
    case GST_EVENT_EOS:
      gst_adapter_clear (filter->adapter);
      break;
    default:
      break;
  }

  return TRUE;
}

408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
static gboolean
gst_spectrum_setup (GstAudioFilter * base, GstRingBufferSpec * format)
{
  GstSpectrum *filter = GST_SPECTRUM (base);

  if (filter->in) {
    g_free (filter->in);
    filter->in = NULL;
  }

  if (filter->fft_free_func) {
    filter->fft_free_func (filter->fft_ctx);
    filter->fft_ctx = NULL;
    filter->fft_free_func = NULL;
  }

  if (filter->freqdata) {
    g_free (filter->freqdata);
    filter->freqdata = NULL;
  }

  if (format->type == GST_BUFTYPE_LINEAR && format->width == 32)
    filter->process = (GstSpectrumProcessFunc) process_s32;
  else if (format->type == GST_BUFTYPE_LINEAR && format->width == 16)
    filter->process = (GstSpectrumProcessFunc) process_s16;
  else if (format->type == GST_BUFTYPE_FLOAT && format->width == 64)
    filter->process = (GstSpectrumProcessFunc) process_f64;
  else if (format->type == GST_BUFTYPE_FLOAT && format->width == 32)
    filter->process = (GstSpectrumProcessFunc) process_f32;
  else
    g_assert_not_reached ();

  return TRUE;
}

443
444
445
446
447
448
449
static GstMessage *
gst_spectrum_message_new (GstSpectrum * spectrum, GstClockTime endtime)
{
  GstStructure *s;
  GValue v = { 0, };
  GValue *l;
  guint i;
450
451
  gfloat *spect_magnitude = spectrum->spect_magnitude;
  gfloat *spect_phase = spectrum->spect_phase;
452
453

  GST_DEBUG_OBJECT (spectrum, "preparing message, spect = %p, bands =%d ",
454
      spect_magnitude, spectrum->bands);
455
456
457
458

  s = gst_structure_new ("spectrum", "endtime", GST_TYPE_CLOCK_TIME,
      endtime, NULL);

459
460
461
462
463
464
465
466
467
468
469
470
471
472
  if (spectrum->message_magnitude) {
    g_value_init (&v, GST_TYPE_LIST);
    /* will copy-by-value */
    gst_structure_set_value (s, "magnitude", &v);
    g_value_unset (&v);

    g_value_init (&v, G_TYPE_FLOAT);
    l = (GValue *) gst_structure_get_value (s, "magnitude");
    for (i = 0; i < spectrum->bands; i++) {
      g_value_set_float (&v, spect_magnitude[i]);
      gst_value_list_append_value (l, &v);      /* copies by value */
    }
    g_value_unset (&v);
  }
473

474
475
476
477
478
479
480
481
482
483
484
485
486
  if (spectrum->message_phase) {
    g_value_init (&v, GST_TYPE_LIST);
    /* will copy-by-value */
    gst_structure_set_value (s, "phase", &v);
    g_value_unset (&v);

    g_value_init (&v, G_TYPE_FLOAT);
    l = (GValue *) gst_structure_get_value (s, "phase");
    for (i = 0; i < spectrum->bands; i++) {
      g_value_set_float (&v, spect_phase[i]);
      gst_value_list_append_value (l, &v);      /* copies by value */
    }
    g_value_unset (&v);
487
488
489
490
  }

  return gst_message_new_element (GST_OBJECT (spectrum), s);
}
491

492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
#define DEFINE_PROCESS_FUNC_INT(width,next_width,max) \
static void \
process_s##width (GstSpectrum *spectrum, const gint##width *samples) \
{ \
  gfloat *spect_magnitude = spectrum->spect_magnitude; \
  gfloat *spect_phase = spectrum->spect_phase; \
  gint channels = GST_AUDIO_FILTER (spectrum)->format.channels; \
  gint i, j, k; \
  gint##next_width acc; \
  GstFFTS##width##Complex *freqdata; \
  GstFFTS##width *ctx; \
  gint##width *in; \
  gint nfft = 2 * spectrum->bands - 2; \
  \
  if (!spectrum->in) \
    spectrum->in = (guint8 *) g_new (gint##width, nfft); \
  \
  in = (gint##width *) spectrum->in; \
  \
  for (i = 0, j = 0; i < nfft; i++) { \
    /* convert to mono */ \
    for (k = 0, acc = 0; k < channels; k++) \
      acc += samples[j++]; \
    in[i] = (gint##width) (acc / channels); \
  } \
  \
  if (!spectrum->fft_ctx) { \
    spectrum->fft_ctx = gst_fft_s##width##_new (nfft, FALSE); \
    spectrum->fft_free_func = (GstSpectrumFFTFreeFunc) gst_fft_s##width##_free; \
  } \
  ctx = spectrum->fft_ctx; \
  \
  gst_fft_s##width##_window (ctx, in, GST_FFT_WINDOW_HAMMING); \
  \
  if (!spectrum->freqdata) \
    spectrum->freqdata = g_new (GstFFTS##width##Complex, spectrum->bands); \
  \
  freqdata = (GstFFTS##width##Complex *) spectrum->freqdata; \
  \
  gst_fft_s##width##_fft (ctx, in, freqdata); \
  spectrum->num_fft++; \
  \
  /* Calculate magnitude in db */ \
  for (i = 0; i < spectrum->bands; i++) { \
536
    gdouble val = 0.0; \
537
538
539
540
    val = (gdouble) freqdata[i].r * (gdouble) freqdata[i].r; \
    val += (gdouble) freqdata[i].i * (gdouble) freqdata[i].i; \
    val /= max*max; \
    val = 10.0 * log10 (val); \
541
542
    if (val < spectrum->threshold) \
      val = spectrum->threshold; \
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
    spect_magnitude[i] += val; \
  } \
   \
  /* Calculate phase */ \
  for (i = 0; i < spectrum->bands; i++) \
    spect_phase[i] += atan2 (freqdata[i].i, freqdata[i].r); \
   \
}

DEFINE_PROCESS_FUNC_INT (16, 32, 32767.0);
DEFINE_PROCESS_FUNC_INT (32, 64, 2147483647.0);

#define DEFINE_PROCESS_FUNC_FLOAT(width,type) \
static void \
process_f##width (GstSpectrum *spectrum, const g##type *samples) \
{ \
  gfloat *spect_magnitude = spectrum->spect_magnitude; \
  gfloat *spect_phase = spectrum->spect_phase; \
  gint channels = GST_AUDIO_FILTER (spectrum)->format.channels; \
  gint i, j, k; \
  g##type acc; \
  GstFFTF##width##Complex *freqdata; \
  GstFFTF##width *ctx; \
  g##type *in; \
  gint nfft = 2 * spectrum->bands - 2; \
  \
  if (!spectrum->in) \
    spectrum->in = (guint8 *) g_new (g##type, nfft); \
  \
  in = (g##type *) spectrum->in; \
  \
  for (i = 0, j = 0; i < nfft; i++) { \
    /* convert to mono */ \
    for (k = 0, acc = 0; k < channels; k++) \
      acc += samples[j++]; \
    in[i] = (g##type) (acc / channels); \
    if (abs (in[i]) > 1.0) \
      g_assert_not_reached(); \
  } \
  \
  if (!spectrum->fft_ctx) { \
    spectrum->fft_ctx = gst_fft_f##width##_new (nfft, FALSE); \
    spectrum->fft_free_func = (GstSpectrumFFTFreeFunc) gst_fft_f##width##_free; \
  } \
  ctx = spectrum->fft_ctx; \
  \
  gst_fft_f##width##_window (ctx, in, GST_FFT_WINDOW_HAMMING); \
  \
  if (!spectrum->freqdata) \
    spectrum->freqdata = g_new (GstFFTF##width##Complex, spectrum->bands); \
  \
  freqdata = (GstFFTF##width##Complex *) spectrum->freqdata; \
  \
  gst_fft_f##width##_fft (ctx, in, freqdata); \
  spectrum->num_fft++; \
  \
  /* Calculate magnitude in db */ \
  for (i = 0; i < spectrum->bands; i++) { \
601
    gdouble val = 0.0; \
602
603
    val = freqdata[i].r * freqdata[i].r; \
    val += freqdata[i].i * freqdata[i].i; \
604
    val /= nfft*nfft; \
605
    val = 10.0 * log10 (val); \
606
607
    if (val < spectrum->threshold) \
      val = spectrum->threshold; \
608
609
610
611
612
613
614
615
616
617
618
619
    spect_magnitude[i] += val; \
  } \
   \
  /* Calculate phase */ \
  for (i = 0; i < spectrum->bands; i++) \
    spect_phase[i] += atan2 (freqdata[i].i, freqdata[i].r); \
   \
}

DEFINE_PROCESS_FUNC_FLOAT (32, float);
DEFINE_PROCESS_FUNC_FLOAT (64, double);

620
static GstFlowReturn
621
gst_spectrum_transform_ip (GstBaseTransform * trans, GstBuffer * in)
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
622
{
623
  GstSpectrum *spectrum = GST_SPECTRUM (trans);
624
  gint wanted;
625
626
627
628
629
630
631
  gint i;
  gfloat *spect_magnitude = spectrum->spect_magnitude;
  gfloat *spect_phase = spectrum->spect_phase;
  gint rate = GST_AUDIO_FILTER (spectrum)->format.rate;
  gint channels = GST_AUDIO_FILTER (spectrum)->format.channels;
  gint width = GST_AUDIO_FILTER (spectrum)->format.width / 8;
  gint nfft = 2 * spectrum->bands - 2;
632

633
  GstClockTime endtime =
Stefan Kost's avatar
Stefan Kost committed
634
      gst_segment_to_running_time (&trans->segment, GST_FORMAT_TIME,
635
      GST_BUFFER_TIMESTAMP (in));
636
  GstClockTime blktime = GST_FRAMES_TO_CLOCK_TIME (nfft, rate);
637

638
  GST_LOG_OBJECT (spectrum, "input size: %d bytes", GST_BUFFER_SIZE (in));
639

640
641
  /* can we do this nicer? */
  gst_adapter_push (spectrum->adapter, gst_buffer_copy (in));
642
  /* required number of bytes */
643
  wanted = channels * nfft * width;
644

645
  while (gst_adapter_available (spectrum->adapter) >= wanted) {
646
    const guint8 *samples;
647

648
    samples = gst_adapter_peek (spectrum->adapter, wanted);
649

650
    spectrum->process (spectrum, samples);
651

652
    spectrum->num_frames += nfft;
653
654
655
    endtime += blktime;
    /* do we need to message ? */
    if (spectrum->num_frames >=
656
        GST_CLOCK_TIME_TO_FRAMES (spectrum->interval, rate)) {
657
      if (spectrum->message) {
658
659
660
661
662
663
664
665
666
        GstMessage *m;

        /* Calculate average */
        for (i = 0; i < spectrum->bands; i++) {
          spect_magnitude[i] /= spectrum->num_fft;
          spect_phase[i] /= spectrum->num_fft;
        }

        m = gst_spectrum_message_new (spectrum, endtime);
667
668
669

        gst_element_post_message (GST_ELEMENT (spectrum), m);
      }
670
671
      memset (spect_magnitude, 0, spectrum->bands * sizeof (gfloat));
      memset (spect_phase, 0, spectrum->bands * sizeof (gfloat));
672
      spectrum->num_frames = 0;
673
      spectrum->num_fft = 0;
674
    }
675
676

    gst_adapter_flush (spectrum->adapter, wanted);
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
677
678
  }

679
  return GST_FLOW_OK;
680
681
}

Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
682
static gboolean
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
683
plugin_init (GstPlugin * plugin)
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
684
{
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
685
686
  return gst_element_register (plugin, "spectrum", GST_RANK_NONE,
      GST_TYPE_SPECTRUM);
Andy Wingo Wingo's avatar
Andy Wingo Wingo committed
687
688
}

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
689
690
691
692
GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
    "spectrum",
    "Run an FFT on the audio signal, output spectrum data",
693
    plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)