...Because we are using pointer arithmetic with float pointers
[vlc.git] / modules / audio_filter / resampler / bandlimited.c
1 /*****************************************************************************
2  * bandlimited.c : band-limited interpolation resampler
3  *****************************************************************************
4  * Copyright (C) 2002, 2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@netcourrier.com>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble:
26  *
27  * This implementation of the band-limited interpolationis based on the
28  * following paper:
29  * http://ccrma-www.stanford.edu/~jos/resample/resample.html
30  *
31  * It uses a Kaiser-windowed sinc-function low-pass filter and the width of the
32  * filter is 13 samples.
33  *
34  *****************************************************************************/
35
36 #ifdef HAVE_CONFIG_H
37 # include "config.h"
38 #endif
39
40 #include <vlc_common.h>
41 #include <vlc_plugin.h>
42 #include <vlc_aout.h>
43 #include <vlc_filter.h>
44 #include <vlc_block.h>
45
46 #include "bandlimited.h"
47
48 /*****************************************************************************
49  * Local prototypes
50  *****************************************************************************/
51
52 /* audio filter */
53 static int  OpenFilter ( vlc_object_t * );
54 static void CloseFilter( vlc_object_t * );
55 static block_t *Resample( filter_t *, block_t * );
56
57
58 static void FilterFloatUP( const float Imp[], const float ImpD[], uint16_t Nwing,
59                            float *f_in, float *f_out, uint32_t ui_remainder,
60                            uint32_t ui_output_rate, int16_t Inc,
61                            int i_nb_channels );
62
63 static void FilterFloatUD( const float Imp[], const float ImpD[], uint16_t Nwing,
64                            float *f_in, float *f_out, uint32_t ui_remainder,
65                            uint32_t ui_output_rate, uint32_t ui_input_rate,
66                            int16_t Inc, int i_nb_channels );
67
68 /*****************************************************************************
69  * Local structures
70  *****************************************************************************/
71 struct filter_sys_t
72 {
73     int32_t *p_buf;                        /* this filter introduces a delay */
74     size_t i_buf_size;
75
76     double d_old_factor;
77     int i_old_wing;
78
79     unsigned int i_remainder;                /* remainder of previous sample */
80     bool b_first;
81
82     date_t end_date;
83 };
84
85 /*****************************************************************************
86  * Module descriptor
87  *****************************************************************************/
88 vlc_module_begin ()
89     set_category( CAT_AUDIO )
90     set_subcategory( SUBCAT_AUDIO_MISC )
91     set_description( N_("Audio filter for band-limited interpolation resampling") )
92     set_capability( "audio filter", 20 )
93     set_callbacks( OpenFilter, CloseFilter )
94 vlc_module_end ()
95
96 /*****************************************************************************
97  * Resample: convert a buffer
98  *****************************************************************************/
99 static block_t *Resample( filter_t * p_filter, block_t * p_in_buf )
100 {
101     if( !p_in_buf || !p_in_buf->i_nb_samples )
102     {
103         if( p_in_buf )
104             block_Release( p_in_buf );
105         return NULL;
106     }
107
108     filter_sys_t *p_sys = p_filter->p_sys;
109     unsigned int i_out_rate = p_filter->fmt_out.audio.i_rate;
110     int i_nb_channels = aout_FormatNbChannels( &p_filter->fmt_in.audio );
111
112     /* Check if we really need to run the resampler */
113     if( i_out_rate == p_filter->fmt_in.audio.i_rate )
114     {
115         if( !(p_in_buf->i_flags & BLOCK_FLAG_DISCONTINUITY) &&
116             p_sys->i_old_wing )
117         {
118             /* output the whole thing with the samples from last time */
119             p_in_buf = block_Realloc( p_in_buf,
120                 p_sys->i_old_wing * p_filter->fmt_in.audio.i_bytes_per_frame,
121                 p_in_buf->i_buffer );
122             if( !p_in_buf )
123                 return NULL;
124             memcpy( p_in_buf->p_buffer, p_sys->p_buf +
125                     i_nb_channels * p_sys->i_old_wing,
126                     p_sys->i_old_wing *
127                     p_filter->fmt_in.audio.i_bytes_per_frame );
128
129             p_in_buf->i_nb_samples += p_sys->i_old_wing;
130
131             p_in_buf->i_pts = date_Get( &p_sys->end_date );
132             p_in_buf->i_length =
133                 date_Increment( &p_sys->end_date,
134                                 p_in_buf->i_nb_samples ) - p_in_buf->i_pts;
135         }
136         p_sys->i_old_wing = 0;
137         p_sys->b_first = true;
138         return p_in_buf;
139     }
140
141     unsigned i_bytes_per_frame = p_filter->fmt_out.audio.i_channels *
142                                  p_filter->fmt_out.audio.i_bitspersample / 8;
143     size_t i_out_size = i_bytes_per_frame * ( 1 + ( p_in_buf->i_nb_samples *
144               p_filter->fmt_out.audio.i_rate / p_filter->fmt_in.audio.i_rate) )
145             + p_filter->p_sys->i_buf_size;
146     block_t *p_out_buf = filter_NewAudioBuffer( p_filter, i_out_size );
147     if( !p_out_buf )
148         return NULL;
149     float *p_out = (float *)p_out_buf->p_buffer;
150
151     if( (p_in_buf->i_flags & BLOCK_FLAG_DISCONTINUITY) || p_sys->b_first )
152     {
153         /* Continuity in sound samples has been broken, we'd better reset
154          * everything. */
155         p_out_buf->i_flags |= BLOCK_FLAG_DISCONTINUITY;
156         p_sys->i_remainder = 0;
157         date_Init( &p_sys->end_date, i_out_rate, 1 );
158         date_Set( &p_sys->end_date, p_in_buf->i_pts );
159         p_sys->d_old_factor = 1;
160         p_sys->i_old_wing   = 0;
161         p_sys->b_first = false;
162     }
163
164     int i_in_nb = p_in_buf->i_nb_samples;
165     int i_in, i_out = 0;
166     double d_factor, d_scale_factor, d_old_scale_factor;
167     int i_filter_wing;
168
169 #if 0
170     msg_Err( p_filter, "old rate: %i, old factor: %f, old wing: %i, i_in: %i",
171              p_sys->i_old_rate, p_sys->d_old_factor,
172              p_sys->i_old_wing, i_in_nb );
173 #endif
174
175     /* Prepare the source buffer */
176     i_in_nb += (p_sys->i_old_wing * 2);
177
178     float p_in_orig[i_in_nb * p_filter->fmt_in.audio.i_bytes_per_frame / 4],
179          *p_in = p_in_orig;
180
181     /* Copy all our samples in p_in */
182     if( p_sys->i_old_wing )
183     {
184         vlc_memcpy( p_in, p_sys->p_buf,
185                     p_sys->i_old_wing * 2 *
186                       p_filter->fmt_in.audio.i_bytes_per_frame );
187     }
188     vlc_memcpy( p_in + p_sys->i_old_wing * 2 * i_nb_channels,
189                 p_in_buf->p_buffer,
190                 p_in_buf->i_nb_samples * p_filter->fmt_in.audio.i_bytes_per_frame );
191     block_Release( p_in_buf );
192
193     /* Make sure the output buffer is reset */
194     memset( p_out, 0, p_out_buf->i_buffer );
195
196     /* Calculate the new length of the filter wing */
197     d_factor = (double)i_out_rate / p_filter->fmt_in.audio.i_rate;
198     i_filter_wing = ((SMALL_FILTER_NMULT+1)/2.0) * __MAX(1.0,1.0/d_factor) + 1;
199
200     /* Account for increased filter gain when using factors less than 1 */
201     d_old_scale_factor = SMALL_FILTER_SCALE *
202         p_sys->d_old_factor + 0.5;
203     d_scale_factor = SMALL_FILTER_SCALE * d_factor + 0.5;
204
205     /* Apply the old rate until we have enough samples for the new one */
206     i_in = p_sys->i_old_wing;
207     p_in += p_sys->i_old_wing * i_nb_channels;
208     for( ; i_in < i_filter_wing &&
209            (i_in + p_sys->i_old_wing) < i_in_nb; i_in++ )
210     {
211         if( p_sys->d_old_factor == 1 )
212         {
213             /* Just copy the samples */
214             memcpy( p_out, p_in,
215                     p_filter->fmt_in.audio.i_bytes_per_frame );
216             p_in += i_nb_channels;
217             p_out += i_nb_channels;
218             i_out++;
219             continue;
220         }
221
222         while( p_sys->i_remainder < p_filter->fmt_out.audio.i_rate )
223         {
224
225             if( p_sys->d_old_factor >= 1 )
226             {
227                 /* FilterFloatUP() is faster if we can use it */
228
229                 /* Perform left-wing inner product */
230                 FilterFloatUP( SMALL_FILTER_FLOAT_IMP, SMALL_FILTER_FLOAT_IMPD,
231                                SMALL_FILTER_NWING, p_in, p_out,
232                                p_sys->i_remainder,
233                                p_filter->fmt_out.audio.i_rate,
234                                -1, i_nb_channels );
235                 /* Perform right-wing inner product */
236                 FilterFloatUP( SMALL_FILTER_FLOAT_IMP, SMALL_FILTER_FLOAT_IMPD,
237                                SMALL_FILTER_NWING, p_in + i_nb_channels, p_out,
238                                p_filter->fmt_out.audio.i_rate -
239                                p_sys->i_remainder,
240                                p_filter->fmt_out.audio.i_rate,
241                                1, i_nb_channels );
242
243 #if 0
244                 /* Normalize for unity filter gain */
245                 for( i = 0; i < i_nb_channels; i++ )
246                 {
247                     *(p_out+i) *= d_old_scale_factor;
248                 }
249 #endif
250
251                 /* Sanity check */
252                 if( p_out_buf->i_buffer/p_filter->fmt_in.audio.i_bytes_per_frame
253                     <= (unsigned int)i_out+1 )
254                 {
255                     p_out += i_nb_channels;
256                     i_out++;
257                     p_sys->i_remainder += p_filter->fmt_in.audio.i_rate;
258                     break;
259                 }
260             }
261             else
262             {
263                 /* Perform left-wing inner product */
264                 FilterFloatUD( SMALL_FILTER_FLOAT_IMP, SMALL_FILTER_FLOAT_IMPD,
265                                SMALL_FILTER_NWING, p_in, p_out,
266                                p_sys->i_remainder,
267                                p_filter->fmt_out.audio.i_rate, p_filter->fmt_in.audio.i_rate,
268                                -1, i_nb_channels );
269                 /* Perform right-wing inner product */
270                 FilterFloatUD( SMALL_FILTER_FLOAT_IMP, SMALL_FILTER_FLOAT_IMPD,
271                                SMALL_FILTER_NWING, p_in + i_nb_channels, p_out,
272                                p_filter->fmt_out.audio.i_rate -
273                                p_sys->i_remainder,
274                                p_filter->fmt_out.audio.i_rate, p_filter->fmt_in.audio.i_rate,
275                                1, i_nb_channels );
276             }
277
278             p_out += i_nb_channels;
279             i_out++;
280
281             p_sys->i_remainder += p_filter->fmt_in.audio.i_rate;
282         }
283
284         p_in += i_nb_channels;
285         p_sys->i_remainder -= p_filter->fmt_out.audio.i_rate;
286     }
287
288     /* Apply the new rate for the rest of the samples */
289     if( i_in < i_in_nb - i_filter_wing )
290     {
291         p_sys->d_old_factor = d_factor;
292         p_sys->i_old_wing   = i_filter_wing;
293     }
294     for( ; i_in < i_in_nb - i_filter_wing; i_in++ )
295     {
296         while( p_sys->i_remainder < p_filter->fmt_out.audio.i_rate )
297         {
298
299             if( d_factor >= 1 )
300             {
301                 /* FilterFloatUP() is faster if we can use it */
302
303                 /* Perform left-wing inner product */
304                 FilterFloatUP( SMALL_FILTER_FLOAT_IMP, SMALL_FILTER_FLOAT_IMPD,
305                                SMALL_FILTER_NWING, p_in, p_out,
306                                p_sys->i_remainder,
307                                p_filter->fmt_out.audio.i_rate,
308                                -1, i_nb_channels );
309
310                 /* Perform right-wing inner product */
311                 FilterFloatUP( SMALL_FILTER_FLOAT_IMP, SMALL_FILTER_FLOAT_IMPD,
312                                SMALL_FILTER_NWING, p_in + i_nb_channels, p_out,
313                                p_filter->fmt_out.audio.i_rate -
314                                p_sys->i_remainder,
315                                p_filter->fmt_out.audio.i_rate,
316                                1, i_nb_channels );
317
318 #if 0
319                 /* Normalize for unity filter gain */
320                 for( int i = 0; i < i_nb_channels; i++ )
321                 {
322                     *(p_out+i) *= d_old_scale_factor;
323                 }
324 #endif
325                 /* Sanity check */
326                 if( p_out_buf->i_buffer/p_filter->fmt_in.audio.i_bytes_per_frame
327                     <= (unsigned int)i_out+1 )
328                 {
329                     p_out += i_nb_channels;
330                     i_out++;
331                     p_sys->i_remainder += p_filter->fmt_in.audio.i_rate;
332                     break;
333                 }
334             }
335             else
336             {
337                 /* Perform left-wing inner product */
338                 FilterFloatUD( SMALL_FILTER_FLOAT_IMP, SMALL_FILTER_FLOAT_IMPD,
339                                SMALL_FILTER_NWING, p_in, p_out,
340                                p_sys->i_remainder,
341                                p_filter->fmt_out.audio.i_rate, p_filter->fmt_in.audio.i_rate,
342                                -1, i_nb_channels );
343                 /* Perform right-wing inner product */
344                 FilterFloatUD( SMALL_FILTER_FLOAT_IMP, SMALL_FILTER_FLOAT_IMPD,
345                                SMALL_FILTER_NWING, p_in + i_nb_channels, p_out,
346                                p_filter->fmt_out.audio.i_rate -
347                                p_sys->i_remainder,
348                                p_filter->fmt_out.audio.i_rate, p_filter->fmt_in.audio.i_rate,
349                                1, i_nb_channels );
350             }
351
352             p_out += i_nb_channels;
353             i_out++;
354
355             p_sys->i_remainder += p_filter->fmt_in.audio.i_rate;
356         }
357
358         p_in += i_nb_channels;
359         p_sys->i_remainder -= p_filter->fmt_out.audio.i_rate;
360     }
361
362     /* Finalize aout buffer */
363     p_out_buf->i_nb_samples = i_out;
364     p_out_buf->i_pts = date_Get( &p_sys->end_date );
365     p_out_buf->i_length = date_Increment( &p_sys->end_date,
366                                   p_out_buf->i_nb_samples ) - p_out_buf->i_pts;
367
368     p_out_buf->i_buffer = p_out_buf->i_nb_samples *
369         i_nb_channels * sizeof(int32_t);
370
371     /* Buffer i_filter_wing * 2 samples for next time */
372     if( p_sys->i_old_wing )
373     {
374         size_t newsize = p_sys->i_old_wing * 2
375                          * p_filter->fmt_in.audio.i_bytes_per_frame;
376         if( newsize > p_sys->i_buf_size )
377         {
378             free( p_sys->p_buf );
379             p_sys->p_buf = malloc( newsize );
380             if( p_sys->p_buf != NULL )
381                 p_sys->i_buf_size = newsize;
382             else
383             {
384                 p_sys->i_buf_size = p_sys->i_old_wing = 0; /* oops! */
385                 return p_out_buf;
386             }
387         }
388         memcpy( p_sys->p_buf,
389                 p_in_orig + (i_in_nb - 2 * p_sys->i_old_wing) *
390                 i_nb_channels, (2 * p_sys->i_old_wing) *
391                 p_filter->fmt_in.audio.i_bytes_per_frame );
392     }
393
394 #if 0
395     msg_Err( p_filter, "p_out size: %i, nb bytes out: %i", p_out_buf->i_buffer,
396              i_out * p_filter->fmt_in.audio.i_bytes_per_frame );
397 #endif
398
399     return p_out_buf;
400 }
401
402 /*****************************************************************************
403  * OpenFilter:
404  *****************************************************************************/
405 static int OpenFilter( vlc_object_t *p_this )
406 {
407     filter_t *p_filter = (filter_t *)p_this;
408     filter_sys_t *p_sys;
409     unsigned int i_out_rate  = p_filter->fmt_out.audio.i_rate;
410
411     if ( p_filter->fmt_in.audio.i_rate == p_filter->fmt_out.audio.i_rate
412       || p_filter->fmt_in.audio.i_format != p_filter->fmt_out.audio.i_format
413       || p_filter->fmt_in.audio.i_physical_channels
414               != p_filter->fmt_out.audio.i_physical_channels
415       || p_filter->fmt_in.audio.i_original_channels
416               != p_filter->fmt_out.audio.i_original_channels
417       || p_filter->fmt_in.audio.i_format != VLC_CODEC_FL32 )
418     {
419         return VLC_EGENERIC;
420     }
421
422 #if !defined( SYS_DARWIN )
423     if( !var_InheritInteger( p_this, "hq-resampling" ) )
424     {
425         return VLC_EGENERIC;
426     }
427 #endif
428
429     /* Allocate the memory needed to store the module's structure */
430     p_filter->p_sys = p_sys = malloc( sizeof(struct filter_sys_t) );
431     if( p_sys == NULL )
432         return VLC_ENOMEM;
433
434     p_sys->p_buf = NULL;
435     p_sys->i_buf_size = 0;
436
437     p_sys->i_old_wing = 0;
438     p_sys->b_first = true;
439     p_filter->pf_audio_filter = Resample;
440
441     msg_Dbg( p_this, "%4.4s/%iKHz/%i->%4.4s/%iKHz/%i",
442              (char *)&p_filter->fmt_in.i_codec,
443              p_filter->fmt_in.audio.i_rate,
444              p_filter->fmt_in.audio.i_channels,
445              (char *)&p_filter->fmt_out.i_codec,
446              p_filter->fmt_out.audio.i_rate,
447              p_filter->fmt_out.audio.i_channels);
448
449     p_filter->fmt_out = p_filter->fmt_in;
450     p_filter->fmt_out.audio.i_rate = i_out_rate;
451
452     return 0;
453 }
454
455 /*****************************************************************************
456  * CloseFilter : deallocate data structures
457  *****************************************************************************/
458 static void CloseFilter( vlc_object_t *p_this )
459 {
460     filter_t *p_filter = (filter_t *)p_this;
461     free( p_filter->p_sys->p_buf );
462     free( p_filter->p_sys );
463 }
464
465 void FilterFloatUP( const float Imp[], const float ImpD[], uint16_t Nwing, float *p_in,
466                     float *p_out, uint32_t ui_remainder,
467                     uint32_t ui_output_rate, int16_t Inc, int i_nb_channels )
468 {
469     const float *Hp, *Hdp, *End;
470     float t, temp;
471     uint32_t ui_linear_remainder;
472     int i;
473
474     Hp = &Imp[(ui_remainder<<Nhc)/ui_output_rate];
475     Hdp = &ImpD[(ui_remainder<<Nhc)/ui_output_rate];
476
477     End = &Imp[Nwing];
478
479     ui_linear_remainder = (ui_remainder<<Nhc) -
480                             (ui_remainder<<Nhc)/ui_output_rate*ui_output_rate;
481
482     if (Inc == 1)               /* If doing right wing...              */
483     {                           /* ...drop extra coeff, so when Ph is  */
484         End--;                  /*    0.5, we don't do too many mult's */
485         if (ui_remainder == 0)  /* If the phase is zero...           */
486         {                       /* ...then we've already skipped the */
487             Hp += Npc;          /*    first sample, so we must also  */
488             Hdp += Npc;         /*    skip ahead in Imp[] and ImpD[] */
489         }
490     }
491
492     while (Hp < End) {
493         t = *Hp;                /* Get filter coeff */
494                                 /* t is now interp'd filter coeff */
495         t += *Hdp * ui_linear_remainder / ui_output_rate / Npc;
496         for( i = 0; i < i_nb_channels; i++ )
497         {
498             temp = t;
499             temp *= *(p_in+i);  /* Mult coeff by input sample */
500             *(p_out+i) += temp; /* The filter output */
501         }
502         Hdp += Npc;             /* Filter coeff differences step */
503         Hp += Npc;              /* Filter coeff step */
504         p_in += (Inc * i_nb_channels); /* Input signal step */
505     }
506 }
507
508 void FilterFloatUD( const float Imp[], const float ImpD[], uint16_t Nwing, float *p_in,
509                     float *p_out, uint32_t ui_remainder,
510                     uint32_t ui_output_rate, uint32_t ui_input_rate,
511                     int16_t Inc, int i_nb_channels )
512 {
513     const float *Hp, *Hdp, *End;
514     float t, temp;
515     uint32_t ui_linear_remainder;
516     int i, ui_counter = 0;
517
518     Hp = Imp + (ui_remainder<<Nhc) / ui_input_rate;
519     Hdp = ImpD  + (ui_remainder<<Nhc) / ui_input_rate;
520
521     End = &Imp[Nwing];
522
523     if (Inc == 1)               /* If doing right wing...              */
524     {                           /* ...drop extra coeff, so when Ph is  */
525         End--;                  /*    0.5, we don't do too many mult's */
526         if (ui_remainder == 0)  /* If the phase is zero...           */
527         {                       /* ...then we've already skipped the */
528             Hp = Imp +          /* first sample, so we must also  */
529                   (ui_output_rate << Nhc) / ui_input_rate;
530             Hdp = ImpD +        /* skip ahead in Imp[] and ImpD[] */
531                   (ui_output_rate << Nhc) / ui_input_rate;
532             ui_counter++;
533         }
534     }
535
536     while (Hp < End) {
537         t = *Hp;                /* Get filter coeff */
538                                 /* t is now interp'd filter coeff */
539         ui_linear_remainder =
540           ((ui_output_rate * ui_counter + ui_remainder)<< Nhc) -
541           ((ui_output_rate * ui_counter + ui_remainder)<< Nhc) /
542           ui_input_rate * ui_input_rate;
543         t += *Hdp * ui_linear_remainder / ui_input_rate / Npc;
544         for( i = 0; i < i_nb_channels; i++ )
545         {
546             temp = t;
547             temp *= *(p_in+i);  /* Mult coeff by input sample */
548             *(p_out+i) += temp; /* The filter output */
549         }
550
551         ui_counter++;
552
553         /* Filter coeff step */
554         Hp = Imp + ((ui_output_rate * ui_counter + ui_remainder)<< Nhc)
555                     / ui_input_rate;
556         /* Filter coeff differences step */
557         Hdp = ImpD + ((ui_output_rate * ui_counter + ui_remainder)<< Nhc)
558                      / ui_input_rate;
559
560         p_in += (Inc * i_nb_channels); /* Input signal step */
561     }
562 }