gst/replaygain/rganalysis.c: Fix wrong ifdef for visual C++. Fixes: #437403.
[platform/upstream/gst-plugins-good.git] / gst / replaygain / rganalysis.c
1 /* GStreamer ReplayGain analysis
2  *
3  * Copyright (C) 2006 Rene Stadler <mail@renestadler.de>
4  * Copyright (C) 2001 David Robinson <David@Robinson.org>
5  *                    Glen Sawyer <glensawyer@hotmail.com>
6  *
7  * rganalysis.c: Analyze raw audio data in accordance with ReplayGain
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1 of
12  * the License, or (at your option) any later version.
13  * 
14  * This library is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  * 
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA
23  */
24
25 /* Based on code with Copyright (C) 2001 David Robinson
26  * <David@Robinson.org> and Glen Sawyer <glensawyer@hotmail.com>,
27  * which is distributed under the LGPL as part of the vorbisgain
28  * program.  The original code also mentions Frank Klemm
29  * (http://www.uni-jena.de/~pfk/mpp/) for having contributed lots of
30  * good code.  Specifically, this is based on the file
31  * "gain_analysis.c" from vorbisgain version 0.34.
32  */
33
34 /* Room for future improvement: Mono data is currently in fact copied
35  * to two channels which get processed normally.  This means that mono
36  * input data is processed twice.
37  */
38
39 /* Helpful information for understanding this code: The two IIR
40  * filters depend on previous input _and_ previous output samples (up
41  * to the filter's order number of samples).  This explains the whole
42  * lot of memcpy'ing done in rg_analysis_analyze and why the context
43  * holds so many buffers.
44  */
45
46 #include <math.h>
47 #include <string.h>
48 #include <glib.h>
49
50 #include "rganalysis.h"
51
52 #define YULE_ORDER         10
53 #define BUTTER_ORDER        2
54 /* Percentile which is louder than the proposed level: */
55 #define RMS_PERCENTILE     95
56 /* Duration of RMS window in milliseconds: */
57 #define RMS_WINDOW_MSECS   50
58 /* Histogram array elements per dB: */
59 #define STEPS_PER_DB      100
60 /* Histogram upper bound in dB (normal max. values in the wild are
61  * assumed to be around 70, 80 dB): */
62 #define MAX_DB            120
63 /* Calibration value: */
64 #define PINK_REF           64.82        /* 298640883795 */
65
66 #define MAX_ORDER         MAX (BUTTER_ORDER, YULE_ORDER)
67 #define MAX_SAMPLE_RATE   48000
68 /* The + 999 has the effect of ceil()ing: */
69 #define MAX_SAMPLE_WINDOW (guint) \
70   ((MAX_SAMPLE_RATE * RMS_WINDOW_MSECS + 999) / 1000)
71
72 /* Analysis result accumulator. */
73
74 struct _RgAnalysisAcc
75 {
76   guint32 histogram[STEPS_PER_DB * MAX_DB];
77   gdouble peak;
78 };
79
80 typedef struct _RgAnalysisAcc RgAnalysisAcc;
81
82 /* Analysis context. */
83
84 struct _RgAnalysisCtx
85 {
86   /* Filter buffers for left channel. */
87   gfloat inprebuf_l[MAX_ORDER * 2];
88   gfloat *inpre_l;
89   gfloat stepbuf_l[MAX_SAMPLE_WINDOW + MAX_ORDER];
90   gfloat *step_l;
91   gfloat outbuf_l[MAX_SAMPLE_WINDOW + MAX_ORDER];
92   gfloat *out_l;
93   /* Filter buffers for right channel. */
94   gfloat inprebuf_r[MAX_ORDER * 2];
95   gfloat *inpre_r;
96   gfloat stepbuf_r[MAX_SAMPLE_WINDOW + MAX_ORDER];
97   gfloat *step_r;
98   gfloat outbuf_r[MAX_SAMPLE_WINDOW + MAX_ORDER];
99   gfloat *out_r;
100
101   /* Number of samples to reach duration of the RMS window: */
102   guint window_n_samples;
103   /* Progress of the running window: */
104   guint window_n_samples_done;
105   gdouble window_square_sum;
106
107   gint sample_rate;
108   gint sample_rate_index;
109
110   RgAnalysisAcc track;
111   RgAnalysisAcc album;
112 };
113
114 /* Filter coefficients for the IIR filters that form the equal
115  * loudness filter.  XFilter[ctx->sample_rate_index] gives the array
116  * of the X coefficients (A or B) for the configured sample rate. */
117
118 #ifdef _MSC_VER
119 /* Disable double-to-float warning: */
120 /* A better solution would be to append 'f' to each constant, but that
121  * makes the code ugly. */
122 #pragma warning ( disable : 4305 )
123 #endif
124
125 static const gfloat AYule[9][11] = {
126   {1., -3.84664617118067, 7.81501653005538, -11.34170355132042,
127         13.05504219327545, -12.28759895145294, 9.48293806319790,
128         -5.87257861775999, 2.75465861874613, -0.86984376593551,
129       0.13919314567432},
130   {1., -3.47845948550071, 6.36317777566148, -8.54751527471874, 9.47693607801280,
131         -8.81498681370155, 6.85401540936998, -4.39470996079559,
132       2.19611684890774, -0.75104302451432, 0.13149317958808},
133   {1., -2.37898834973084, 2.84868151156327, -2.64577170229825, 2.23697657451713,
134         -1.67148153367602, 1.00595954808547, -0.45953458054983,
135       0.16378164858596, -0.05032077717131, 0.02347897407020},
136   {1., -1.61273165137247, 1.07977492259970, -0.25656257754070,
137         -0.16276719120440, -0.22638893773906, 0.39120800788284,
138         -0.22138138954925, 0.04500235387352, 0.02005851806501,
139       0.00302439095741},
140   {1., -1.49858979367799, 0.87350271418188, 0.12205022308084, -0.80774944671438,
141         0.47854794562326, -0.12453458140019, -0.04067510197014,
142       0.08333755284107, -0.04237348025746, 0.02977207319925},
143   {1., -0.62820619233671, 0.29661783706366, -0.37256372942400, 0.00213767857124,
144         -0.42029820170918, 0.22199650564824, 0.00613424350682, 0.06747620744683,
145       0.05784820375801, 0.03222754072173},
146   {1., -1.04800335126349, 0.29156311971249, -0.26806001042947, 0.00819999645858,
147         0.45054734505008, -0.33032403314006, 0.06739368333110,
148       -0.04784254229033, 0.01639907836189, 0.01807364323573},
149   {1., -0.51035327095184, -0.31863563325245, -0.20256413484477,
150         0.14728154134330, 0.38952639978999, -0.23313271880868,
151         -0.05246019024463, -0.02505961724053, 0.02442357316099,
152       0.01818801111503},
153   {1., -0.25049871956020, -0.43193942311114, -0.03424681017675,
154         -0.04678328784242, 0.26408300200955, 0.15113130533216,
155         -0.17556493366449, -0.18823009262115, 0.05477720428674,
156       0.04704409688120}
157 };
158
159 static const gfloat BYule[9][11] = {
160   {0.03857599435200, -0.02160367184185, -0.00123395316851, -0.00009291677959,
161         -0.01655260341619, 0.02161526843274, -0.02074045215285,
162       0.00594298065125, 0.00306428023191, 0.00012025322027, 0.00288463683916},
163   {0.05418656406430, -0.02911007808948, -0.00848709379851, -0.00851165645469,
164         -0.00834990904936, 0.02245293253339, -0.02596338512915,
165         0.01624864962975, -0.00240879051584, 0.00674613682247,
166       -0.00187763777362},
167   {0.15457299681924, -0.09331049056315, -0.06247880153653, 0.02163541888798,
168         -0.05588393329856, 0.04781476674921, 0.00222312597743, 0.03174092540049,
169       -0.01390589421898, 0.00651420667831, -0.00881362733839},
170   {0.30296907319327, -0.22613988682123, -0.08587323730772, 0.03282930172664,
171         -0.00915702933434, -0.02364141202522, -0.00584456039913,
172         0.06276101321749, -0.00000828086748, 0.00205861885564,
173       -0.02950134983287},
174   {0.33642304856132, -0.25572241425570, -0.11828570177555, 0.11921148675203,
175         -0.07834489609479, -0.00469977914380, -0.00589500224440,
176         0.05724228140351, 0.00832043980773, -0.01635381384540,
177       -0.01760176568150},
178   {0.44915256608450, -0.14351757464547, -0.22784394429749, -0.01419140100551,
179         0.04078262797139, -0.12398163381748, 0.04097565135648, 0.10478503600251,
180       -0.01863887810927, -0.03193428438915, 0.00541907748707},
181   {0.56619470757641, -0.75464456939302, 0.16242137742230, 0.16744243493672,
182         -0.18901604199609, 0.30931782841830, -0.27562961986224,
183         0.00647310677246, 0.08647503780351, -0.03788984554840,
184       -0.00588215443421},
185   {0.58100494960553, -0.53174909058578, -0.14289799034253, 0.17520704835522,
186         0.02377945217615, 0.15558449135573, -0.25344790059353, 0.01628462406333,
187       0.06920467763959, -0.03721611395801, -0.00749618797172},
188   {0.53648789255105, -0.42163034350696, -0.00275953611929, 0.04267842219415,
189         -0.10214864179676, 0.14590772289388, -0.02459864859345,
190         -0.11202315195388, -0.04060034127000, 0.04788665548180,
191       -0.02217936801134}
192 };
193
194 static const gfloat AButter[9][3] = {
195   {1., -1.97223372919527, 0.97261396931306},
196   {1., -1.96977855582618, 0.97022847566350},
197   {1., -1.95835380975398, 0.95920349965459},
198   {1., -1.95002759149878, 0.95124613669835},
199   {1., -1.94561023566527, 0.94705070426118},
200   {1., -1.92783286977036, 0.93034775234268},
201   {1., -1.91858953033784, 0.92177618768381},
202   {1., -1.91542108074780, 0.91885558323625},
203   {1., -1.88903307939452, 0.89487434461664}
204 };
205
206 static const gfloat BButter[9][3] = {
207   {0.98621192462708, -1.97242384925416, 0.98621192462708},
208   {0.98500175787242, -1.97000351574484, 0.98500175787242},
209   {0.97938932735214, -1.95877865470428, 0.97938932735214},
210   {0.97531843204928, -1.95063686409857, 0.97531843204928},
211   {0.97316523498161, -1.94633046996323, 0.97316523498161},
212   {0.96454515552826, -1.92909031105652, 0.96454515552826},
213   {0.96009142950541, -1.92018285901082, 0.96009142950541},
214   {0.95856916599601, -1.91713833199203, 0.95856916599601},
215   {0.94597685600279, -1.89195371200558, 0.94597685600279}
216 };
217
218 #ifdef _MSC_VER
219 #pragma warning ( default : 4305 )
220 #endif
221
222 /* Filter functions.  These access elements with negative indices of
223  * the input and output arrays (up to the filter's order). */
224
225 /* For much better performance, the function below has been
226  * implemented by unrolling the inner loop for our two use cases. */
227
228 /*
229  * static inline void
230  * apply_filter (const gfloat * input, gfloat * output, guint n_samples,
231  *     const gfloat * a, const gfloat * b, guint order)
232  * {
233  *   gfloat y;
234  *   gint i, k;
235  * 
236  *   for (i = 0; i < n_samples; i++) {
237  *     y = input[i] * b[0];
238  *     for (k = 1; k <= order; k++)
239  *       y += input[i - k] * b[k] - output[i - k] * a[k];
240  *     output[i] = y;
241  *   }
242  * }
243  */
244
245 static inline void
246 yule_filter (const gfloat * input, gfloat * output,
247     const gfloat * a, const gfloat * b)
248 {
249   output[0] = input[0] * b[0]
250       + input[-1] * b[1] - output[-1] * a[1]
251       + input[-2] * b[2] - output[-2] * a[2]
252       + input[-3] * b[3] - output[-3] * a[3]
253       + input[-4] * b[4] - output[-4] * a[4]
254       + input[-5] * b[5] - output[-5] * a[5]
255       + input[-6] * b[6] - output[-6] * a[6]
256       + input[-7] * b[7] - output[-7] * a[7]
257       + input[-8] * b[8] - output[-8] * a[8]
258       + input[-9] * b[9] - output[-9] * a[9]
259       + input[-10] * b[10] - output[-10] * a[10];
260 }
261
262 static inline void
263 butter_filter (const gfloat * input, gfloat * output,
264     const gfloat * a, const gfloat * b)
265 {
266   output[0] = input[0] * b[0]
267       + input[-1] * b[1] - output[-1] * a[1]
268       + input[-2] * b[2] - output[-2] * a[2];
269 }
270
271 /* Because butter_filter and yule_filter are inlined, this function is
272  * a bit blown-up (code-size wise), but not inlining gives a ca. 40%
273  * performance penalty. */
274
275 static inline void
276 apply_filters (const RgAnalysisCtx * ctx, const gfloat * input_l,
277     const gfloat * input_r, guint n_samples)
278 {
279   const gfloat *ayule = AYule[ctx->sample_rate_index];
280   const gfloat *byule = BYule[ctx->sample_rate_index];
281   const gfloat *abutter = AButter[ctx->sample_rate_index];
282   const gfloat *bbutter = BButter[ctx->sample_rate_index];
283   gint pos = ctx->window_n_samples_done;
284   gint i;
285
286   for (i = 0; i < n_samples; i++, pos++) {
287     yule_filter (input_l + i, ctx->step_l + pos, ayule, byule);
288     butter_filter (ctx->step_l + pos, ctx->out_l + pos, abutter, bbutter);
289
290     yule_filter (input_r + i, ctx->step_r + pos, ayule, byule);
291     butter_filter (ctx->step_r + pos, ctx->out_r + pos, abutter, bbutter);
292   }
293 }
294
295 /* Clear filter buffer state and current RMS window. */
296
297 static void
298 reset_filters (RgAnalysisCtx * ctx)
299 {
300   gint i;
301
302   for (i = 0; i < MAX_ORDER; i++) {
303
304     ctx->inprebuf_l[i] = 0.;
305     ctx->stepbuf_l[i] = 0.;
306     ctx->outbuf_l[i] = 0.;
307
308     ctx->inprebuf_r[i] = 0.;
309     ctx->stepbuf_r[i] = 0.;
310     ctx->outbuf_r[i] = 0.;
311   }
312
313   ctx->window_square_sum = 0.;
314   ctx->window_n_samples_done = 0;
315 }
316
317 /* Accumulator functions. */
318
319 /* Add two accumulators in-place.  The sum is defined as the result of
320  * the vector sum of the histogram array and the maximum value of the
321  * peak field.  Thus "adding" the accumulators for all tracks yields
322  * the correct result for obtaining the album gain and peak. */
323
324 static void
325 accumulator_add (RgAnalysisAcc * acc, const RgAnalysisAcc * acc_other)
326 {
327   gint i;
328
329   for (i = 0; i < G_N_ELEMENTS (acc->histogram); i++)
330     acc->histogram[i] += acc_other->histogram[i];
331
332   acc->peak = MAX (acc->peak, acc_other->peak);
333 }
334
335 /* Reset an accumulator to zero. */
336
337 static void
338 accumulator_clear (RgAnalysisAcc * acc)
339 {
340   memset (acc->histogram, 0, sizeof (acc->histogram));
341   acc->peak = 0.;
342 }
343
344 /* Obtain final analysis result from an accumulator.  Returns TRUE on
345  * success, FALSE on error (if accumulator is still zero). */
346
347 static gboolean
348 accumulator_result (const RgAnalysisAcc * acc, gdouble * result_gain,
349     gdouble * result_peak)
350 {
351   guint32 sum = 0;
352   guint32 upper;
353   guint i;
354
355   for (i = 0; i < G_N_ELEMENTS (acc->histogram); i++)
356     sum += acc->histogram[i];
357
358   if (sum == 0)
359     /* All entries are 0: We got less than 50ms of data. */
360     return FALSE;
361
362   upper = (guint32) ceil (sum * (1. - (gdouble) (RMS_PERCENTILE / 100.)));
363
364   for (i = G_N_ELEMENTS (acc->histogram); i--;) {
365     if (upper <= acc->histogram[i])
366       break;
367     upper -= acc->histogram[i];
368   }
369
370   if (result_peak != NULL)
371     *result_peak = acc->peak;
372   if (result_gain != NULL)
373     *result_gain = PINK_REF - (gdouble) i / STEPS_PER_DB;
374
375   return TRUE;
376 }
377
378 /* Functions that operate on contexts, for external usage. */
379
380 /* Create a new context.  Before it can be used, a sample rate must be
381  * configured using rg_analysis_set_sample_rate. */
382
383 RgAnalysisCtx *
384 rg_analysis_new (void)
385 {
386   RgAnalysisCtx *ctx;
387
388   ctx = g_new (RgAnalysisCtx, 1);
389
390   ctx->inpre_l = ctx->inprebuf_l + MAX_ORDER;
391   ctx->step_l = ctx->stepbuf_l + MAX_ORDER;
392   ctx->out_l = ctx->outbuf_l + MAX_ORDER;
393
394   ctx->inpre_r = ctx->inprebuf_r + MAX_ORDER;
395   ctx->step_r = ctx->stepbuf_r + MAX_ORDER;
396   ctx->out_r = ctx->outbuf_r + MAX_ORDER;
397
398   ctx->sample_rate = 0;
399
400   accumulator_clear (&ctx->track);
401   accumulator_clear (&ctx->album);
402
403   return ctx;
404 }
405
406 /* Adapt to given sample rate.  Does nothing if already the current
407  * rate (returns TRUE then).  Returns FALSE only if given sample rate
408  * is not supported.  If the configured rate changes, the last
409  * unprocessed incomplete 50ms chunk of data is dropped because the
410  * filters are reset. */
411
412 gboolean
413 rg_analysis_set_sample_rate (RgAnalysisCtx * ctx, gint sample_rate)
414 {
415   g_return_val_if_fail (ctx != NULL, FALSE);
416
417   if (ctx->sample_rate == sample_rate)
418     return TRUE;
419
420   switch (sample_rate) {
421     case 48000:
422       ctx->sample_rate_index = 0;
423       break;
424     case 44100:
425       ctx->sample_rate_index = 1;
426       break;
427     case 32000:
428       ctx->sample_rate_index = 2;
429       break;
430     case 24000:
431       ctx->sample_rate_index = 3;
432       break;
433     case 22050:
434       ctx->sample_rate_index = 4;
435       break;
436     case 16000:
437       ctx->sample_rate_index = 5;
438       break;
439     case 12000:
440       ctx->sample_rate_index = 6;
441       break;
442     case 11025:
443       ctx->sample_rate_index = 7;
444       break;
445     case 8000:
446       ctx->sample_rate_index = 8;
447       break;
448     default:
449       return FALSE;
450   }
451
452   ctx->sample_rate = sample_rate;
453   /* The + 999 has the effect of ceil()ing: */
454   ctx->window_n_samples = (guint) ((sample_rate * RMS_WINDOW_MSECS + 999)
455       / 1000);
456
457   reset_filters (ctx);
458
459   return TRUE;
460 }
461
462 void
463 rg_analysis_destroy (RgAnalysisCtx * ctx)
464 {
465   g_free (ctx);
466 }
467
468 /* Entry points for analyzing sample data in common raw data formats.
469  * The stereo format functions expect interleaved frames.  It is
470  * possible to pass data in different formats for the same context,
471  * there are no restrictions.  All functions have the same signature;
472  * the depth argument for the float functions is not variable and must
473  * be given the value 32. */
474
475 void
476 rg_analysis_analyze_mono_float (RgAnalysisCtx * ctx, gconstpointer data,
477     gsize size, guint depth)
478 {
479   gfloat conv_samples[512];
480   const gfloat *samples = (gfloat *) data;
481   guint n_samples = size / sizeof (gfloat);
482   gint i;
483
484   g_return_if_fail (depth == 32);
485   g_return_if_fail (size % sizeof (gfloat) == 0);
486
487   while (n_samples) {
488     gint n = MIN (n_samples, G_N_ELEMENTS (conv_samples));
489
490     n_samples -= n;
491     memcpy (conv_samples, samples, n * sizeof (gfloat));
492     for (i = 0; i < n; i++) {
493       ctx->track.peak = MAX (ctx->track.peak, fabs (conv_samples[i]));
494       conv_samples[i] *= 32768.;
495     }
496     samples += n;
497     rg_analysis_analyze (ctx, conv_samples, NULL, n);
498   }
499 }
500
501 void
502 rg_analysis_analyze_stereo_float (RgAnalysisCtx * ctx, gconstpointer data,
503     gsize size, guint depth)
504 {
505   gfloat conv_samples_l[256];
506   gfloat conv_samples_r[256];
507   const gfloat *samples = (gfloat *) data;
508   guint n_frames = size / (sizeof (gfloat) * 2);
509   gint i;
510
511   g_return_if_fail (depth == 32);
512   g_return_if_fail (size % (sizeof (gfloat) * 2) == 0);
513
514   while (n_frames) {
515     gint n = MIN (n_frames, G_N_ELEMENTS (conv_samples_l));
516
517     n_frames -= n;
518     for (i = 0; i < n; i++) {
519       gfloat old_sample;
520
521       old_sample = samples[2 * i];
522       ctx->track.peak = MAX (ctx->track.peak, fabs (old_sample));
523       conv_samples_l[i] = old_sample * 32768.;
524
525       old_sample = samples[2 * i + 1];
526       ctx->track.peak = MAX (ctx->track.peak, fabs (old_sample));
527       conv_samples_r[i] = old_sample * 32768.;
528     }
529     samples += 2 * n;
530     rg_analysis_analyze (ctx, conv_samples_l, conv_samples_r, n);
531   }
532 }
533
534 void
535 rg_analysis_analyze_mono_int16 (RgAnalysisCtx * ctx, gconstpointer data,
536     gsize size, guint depth)
537 {
538   gfloat conv_samples[512];
539   gint32 peak_sample = 0;
540   const gint16 *samples = (gint16 *) data;
541   guint n_samples = size / sizeof (gint16);
542   gint shift = sizeof (gint16) * 8 - depth;
543   gint i;
544
545   g_return_if_fail (depth <= (sizeof (gint16) * 8));
546   g_return_if_fail (size % sizeof (gint16) == 0);
547
548   while (n_samples) {
549     gint n = MIN (n_samples, G_N_ELEMENTS (conv_samples));
550
551     n_samples -= n;
552     for (i = 0; i < n; i++) {
553       gint16 old_sample = samples[i] << shift;
554
555       peak_sample = MAX (peak_sample, ABS ((gint32) old_sample));
556       conv_samples[i] = (gfloat) old_sample;
557     }
558     samples += n;
559     rg_analysis_analyze (ctx, conv_samples, NULL, n);
560   }
561   ctx->track.peak = MAX (ctx->track.peak,
562       (gdouble) peak_sample / ((gdouble) (1u << 15)));
563 }
564
565 void
566 rg_analysis_analyze_stereo_int16 (RgAnalysisCtx * ctx, gconstpointer data,
567     gsize size, guint depth)
568 {
569   gfloat conv_samples_l[256];
570   gfloat conv_samples_r[256];
571   gint32 peak_sample = 0;
572   const gint16 *samples = (gint16 *) data;
573   guint n_frames = size / (sizeof (gint16) * 2);
574   gint shift = sizeof (gint16) * 8 - depth;
575   gint i;
576
577   g_return_if_fail (depth <= (sizeof (gint16) * 8));
578   g_return_if_fail (size % (sizeof (gint16) * 2) == 0);
579
580   while (n_frames) {
581     gint n = MIN (n_frames, G_N_ELEMENTS (conv_samples_l));
582
583     n_frames -= n;
584     for (i = 0; i < n; i++) {
585       gint16 old_sample;
586
587       old_sample = samples[2 * i] << shift;
588       peak_sample = MAX (peak_sample, ABS ((gint32) old_sample));
589       conv_samples_l[i] = (gfloat) old_sample;
590
591       old_sample = samples[2 * i + 1] << shift;
592       peak_sample = MAX (peak_sample, ABS ((gint32) old_sample));
593       conv_samples_r[i] = (gfloat) old_sample;
594     }
595     samples += 2 * n;
596     rg_analysis_analyze (ctx, conv_samples_l, conv_samples_r, n);
597   }
598   ctx->track.peak = MAX (ctx->track.peak,
599       (gdouble) peak_sample / ((gdouble) (1u << 15)));
600 }
601
602 /* Analyze the given chunk of samples.  The sample data is given in
603  * floating point format but should be scaled such that the values
604  * +/-32768.0 correspond to the -0dBFS reference amplitude.
605  *
606  * samples_l: Buffer with sample data for the left channel or of the
607  * mono channel.
608  *
609  * samples_r: Buffer with sample data for the right channel or NULL
610  * for mono.
611  *
612  * n_samples: Number of samples passed in each buffer.
613  */
614
615 void
616 rg_analysis_analyze (RgAnalysisCtx * ctx, const gfloat * samples_l,
617     const gfloat * samples_r, guint n_samples)
618 {
619   const gfloat *input_l, *input_r;
620   guint n_samples_done;
621   gint i;
622
623   g_return_if_fail (ctx != NULL);
624   g_return_if_fail (samples_l != NULL);
625   g_return_if_fail (ctx->sample_rate != 0);
626
627   if (n_samples == 0)
628     return;
629
630   if (samples_r == NULL)
631     /* Mono. */
632     samples_r = samples_l;
633
634   memcpy (ctx->inpre_l, samples_l,
635       MIN (n_samples, MAX_ORDER) * sizeof (gfloat));
636   memcpy (ctx->inpre_r, samples_r,
637       MIN (n_samples, MAX_ORDER) * sizeof (gfloat));
638
639   n_samples_done = 0;
640   while (n_samples_done < n_samples) {
641     /* Limit number of samples to be processed in this iteration to
642      * the number needed to complete the next window: */
643     guint n_samples_current = MIN (n_samples - n_samples_done,
644         ctx->window_n_samples - ctx->window_n_samples_done);
645
646     if (n_samples_done < MAX_ORDER) {
647       input_l = ctx->inpre_l + n_samples_done;
648       input_r = ctx->inpre_r + n_samples_done;
649       n_samples_current = MIN (n_samples_current, MAX_ORDER - n_samples_done);
650     } else {
651       input_l = samples_l + n_samples_done;
652       input_r = samples_r + n_samples_done;
653     }
654
655     apply_filters (ctx, input_l, input_r, n_samples_current);
656
657     /* Update the square sum. */
658     for (i = 0; i < n_samples_current; i++)
659       ctx->window_square_sum += ctx->out_l[ctx->window_n_samples_done + i]
660           * ctx->out_l[ctx->window_n_samples_done + i]
661           + ctx->out_r[ctx->window_n_samples_done + i]
662           * ctx->out_r[ctx->window_n_samples_done + i];
663
664     ctx->window_n_samples_done += n_samples_current;
665
666     g_return_if_fail (ctx->window_n_samples_done <= ctx->window_n_samples);
667
668     if (ctx->window_n_samples_done == ctx->window_n_samples) {
669       /* Get the Root Mean Square (RMS) for this set of samples. */
670       gdouble val = STEPS_PER_DB * 10. * log10 (ctx->window_square_sum /
671           ctx->window_n_samples * 0.5 + 1.e-37);
672       gint ival = CLAMP ((gint) val, 0,
673           (gint) G_N_ELEMENTS (ctx->track.histogram) - 1);
674
675       ctx->track.histogram[ival]++;
676       ctx->window_square_sum = 0.;
677       ctx->window_n_samples_done = 0;
678
679       /* No need for memmove here, the areas never overlap: Even for
680        * the smallest sample rate, the number of samples needed for
681        * the window is greater than MAX_ORDER. */
682
683       memcpy (ctx->stepbuf_l, ctx->stepbuf_l + ctx->window_n_samples,
684           MAX_ORDER * sizeof (gfloat));
685       memcpy (ctx->outbuf_l, ctx->outbuf_l + ctx->window_n_samples,
686           MAX_ORDER * sizeof (gfloat));
687
688       memcpy (ctx->stepbuf_r, ctx->stepbuf_r + ctx->window_n_samples,
689           MAX_ORDER * sizeof (gfloat));
690       memcpy (ctx->outbuf_r, ctx->outbuf_r + ctx->window_n_samples,
691           MAX_ORDER * sizeof (gfloat));
692     }
693
694     n_samples_done += n_samples_current;
695   }
696
697   if (n_samples >= MAX_ORDER) {
698
699     memcpy (ctx->inprebuf_l, samples_l + n_samples - MAX_ORDER,
700         MAX_ORDER * sizeof (gfloat));
701
702     memcpy (ctx->inprebuf_r, samples_r + n_samples - MAX_ORDER,
703         MAX_ORDER * sizeof (gfloat));
704
705   } else {
706
707     memmove (ctx->inprebuf_l, ctx->inprebuf_l + n_samples,
708         (MAX_ORDER - n_samples) * sizeof (gfloat));
709     memcpy (ctx->inprebuf_l + MAX_ORDER - n_samples, samples_l,
710         n_samples * sizeof (gfloat));
711
712     memmove (ctx->inprebuf_r, ctx->inprebuf_r + n_samples,
713         (MAX_ORDER - n_samples) * sizeof (gfloat));
714     memcpy (ctx->inprebuf_r + MAX_ORDER - n_samples, samples_r,
715         n_samples * sizeof (gfloat));
716
717   }
718 }
719
720 /* Obtain track gain and peak.  Returns TRUE on success.  Can fail if
721  * not enough samples have been processed.  Updates album accumulator.
722  * Resets track accumulator. */
723
724 gboolean
725 rg_analysis_track_result (RgAnalysisCtx * ctx, gdouble * gain, gdouble * peak)
726 {
727   gboolean result;
728
729   g_return_val_if_fail (ctx != NULL, FALSE);
730
731   accumulator_add (&ctx->album, &ctx->track);
732   result = accumulator_result (&ctx->track, gain, peak);
733   accumulator_clear (&ctx->track);
734
735   reset_filters (ctx);
736
737   return result;
738 }
739
740 /* Obtain album gain and peak.  Returns TRUE on success.  Can fail if
741  * not enough samples have been processed.  Resets album
742  * accumulator. */
743
744 gboolean
745 rg_analysis_album_result (RgAnalysisCtx * ctx, gdouble * gain, gdouble * peak)
746 {
747   gboolean result;
748
749   g_return_val_if_fail (ctx != NULL, FALSE);
750
751   result = accumulator_result (&ctx->album, gain, peak);
752   accumulator_clear (&ctx->album);
753
754   return result;
755 }
756
757 void
758 rg_analysis_reset_album (RgAnalysisCtx * ctx)
759 {
760   accumulator_clear (&ctx->album);
761 }
762
763 /* Reset internal buffers as well as track and album accumulators.
764  * Configured sample rate is kept intact. */
765
766 void
767 rg_analysis_reset (RgAnalysisCtx * ctx)
768 {
769   g_return_if_fail (ctx != NULL);
770
771   reset_filters (ctx);
772   accumulator_clear (&ctx->track);
773   accumulator_clear (&ctx->album);
774 }