]> git.sesse.net Git - mlt/blob - src/modules/sox/filter_sox.c
004c2be8a83c21818044e91599dc0b3e4b4f884a
[mlt] / src / modules / sox / filter_sox.c
1 /*
2  * filter_sox.c -- apply any number of SOX effects using libst
3  * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4  * Author: Dan Dennedy <dan@dennedy.org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 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  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include <framework/mlt_filter.h>
22 #include <framework/mlt_frame.h>
23 #include <framework/mlt_tokeniser.h>
24 #include <framework/mlt_log.h>
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <math.h>
30
31 // TODO: does not support multiple effects with SoX v14.1.0+
32
33 #ifdef SOX14
34 #       include <sox.h>
35 #       define ST_EOF SOX_EOF
36 #       define ST_SUCCESS SOX_SUCCESS
37 #       define st_sample_t sox_sample_t
38 #       define eff_t sox_effect_t*
39 #       define ST_LIB_VERSION_CODE SOX_LIB_VERSION_CODE
40 #       define ST_LIB_VERSION SOX_LIB_VERSION
41 #       if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,2,0))
42 #               define st_size_t size_t
43 #       else
44 #               define st_size_t sox_size_t
45 #       endif
46 #       define ST_SIGNED_WORD_TO_SAMPLE(d,clips) SOX_SIGNED_16BIT_TO_SAMPLE(d,clips)
47 #       if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,1,0))
48 #               define ST_SSIZE_MIN SOX_SAMPLE_MIN
49 #       else
50 #               define ST_SSIZE_MIN SOX_SSIZE_MIN
51 #       endif
52 #               define ST_SAMPLE_TO_SIGNED_WORD(d,clips) SOX_SAMPLE_TO_SIGNED_16BIT(d,clips)
53 #else
54 #       include <st.h>
55 #endif
56
57 #define BUFFER_LEN 8192
58 #define AMPLITUDE_NORM 0.2511886431509580 /* -12dBFS */
59 #define AMPLITUDE_MIN 0.00001
60
61 /** Compute the mean of a set of doubles skipping unset values flagged as -1
62 */
63 static inline double mean( double *buf, int count )
64 {
65         double mean = 0;
66         int i;
67         int j = 0;
68         
69         for ( i = 0; i < count; i++ )
70         {
71                 if ( buf[ i ] != -1.0 )
72                 {
73                         mean += buf[ i ];
74                         j ++;
75                 }
76         }
77         if ( j > 0 )
78                 mean /= j;
79         
80         return mean;
81 }
82
83 #if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,1,0))
84 static void delete_effect( eff_t effp )
85 {
86         free( effp->priv );
87         free( (void*)effp->in_encoding );
88         free( effp );
89 }
90 #endif
91
92 /** Create an effect state instance for a channels
93 */
94 static int create_effect( mlt_filter this, char *value, int count, int channel, int frequency )
95 {
96         mlt_tokeniser tokeniser = mlt_tokeniser_init();
97         char id[ 256 ];
98         int error = 1;
99
100         // Tokenise the effect specification
101         mlt_tokeniser_parse_new( tokeniser, value, " " );
102         if ( tokeniser->count < 1 )
103         {
104                 mlt_tokeniser_close( tokeniser );
105                 return error;
106         }
107
108         // Locate the effect
109         mlt_destructor effect_destructor = mlt_pool_release;
110 #ifdef SOX14
111         //fprintf(stderr, "%s: effect %s count %d\n", __FUNCTION__, tokeniser->tokens[0], tokeniser->count );
112 #if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,1,0))
113         sox_effect_handler_t const *eff_handle = sox_find_effect( tokeniser->tokens[0] );
114         if (eff_handle == NULL ) return error;
115         eff_t eff = sox_create_effect( eff_handle );
116         effect_destructor = ( mlt_destructor ) delete_effect;
117         sox_encodinginfo_t *enc = calloc( 1, sizeof( sox_encodinginfo_t ) );
118         enc->encoding = SOX_ENCODING_SIGN2;
119         enc->bits_per_sample = 16;
120         eff->in_encoding = eff->out_encoding = enc;
121 #else
122         eff_t eff = mlt_pool_alloc( sizeof( sox_effect_t ) );
123         sox_create_effect( eff, sox_find_effect( tokeniser->tokens[0] ) );
124 #endif
125         int opt_count = tokeniser->count - 1;
126 #else
127         eff_t eff = mlt_pool_alloc( sizeof( struct st_effect ) );
128         int opt_count = st_geteffect_opt( eff, tokeniser->count, tokeniser->tokens );
129 #endif
130         
131         // If valid effect
132         if ( opt_count != ST_EOF )
133         {
134                 // Supply the effect parameters
135 #ifdef SOX14
136 #if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,2,0))
137                 if ( sox_effect_options( eff, opt_count, &tokeniser->tokens[ tokeniser->count > 1 ? 1 : 0  ] ) == ST_SUCCESS )
138 #else
139                 if ( ( * eff->handler.getopts )( eff, opt_count, &tokeniser->tokens[ tokeniser->count > 1 ? 1 : 0  ] ) == ST_SUCCESS )
140 #endif
141 #else
142                 if ( ( * eff->h->getopts )( eff, opt_count, &tokeniser->tokens[ tokeniser->count - opt_count ] ) == ST_SUCCESS )
143 #endif
144                 {
145                         // Set the sox signal parameters
146 #if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,1,0))
147                         eff->in_signal.rate = frequency;
148                         eff->out_signal.rate = frequency;
149                         eff->in_signal.channels = 1;
150                         eff->out_signal.channels = 1;
151                         eff->in_signal.precision = 16;
152                         eff->out_signal.precision = 16;
153                         eff->in_signal.length = 0;
154                         eff->out_signal.length = 0;
155 #else
156                         eff->ininfo.rate = frequency;
157                         eff->outinfo.rate = frequency;
158                         eff->ininfo.channels = 1;
159                         eff->outinfo.channels = 1;
160 #endif
161                         
162                         // Start the effect
163 #ifdef SOX14
164                         if ( ( * eff->handler.start )( eff ) == ST_SUCCESS )
165 #else
166                         if ( ( * eff->h->start )( eff ) == ST_SUCCESS )
167 #endif
168                         {
169                                 // Construct id
170                                 sprintf( id, "_effect_%d_%d", count, channel );
171
172                                 // Save the effect state
173                                 mlt_properties_set_data( MLT_FILTER_PROPERTIES( this ), id, eff, 0, effect_destructor, NULL );
174                                 error = 0;
175                         }
176                 }
177         }
178         // Some error occurred so delete the temp effect state
179         if ( error == 1 )
180                 effect_destructor( eff );
181         
182         mlt_tokeniser_close( tokeniser );
183         
184         return error;
185 }
186
187 /** Get the audio.
188 */
189
190 static int filter_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
191 {
192 #if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,3,0))
193         SOX_SAMPLE_LOCALS;
194 #endif
195         // Get the filter service
196         mlt_filter filter = mlt_frame_pop_audio( frame );
197
198         // Get the filter properties
199         mlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter );
200
201         mlt_service_lock( MLT_FILTER_SERVICE( filter ) );
202
203         // Get the properties
204         st_sample_t *input_buffer;// = mlt_properties_get_data( filter_properties, "input_buffer", NULL );
205         st_sample_t *output_buffer = mlt_properties_get_data( filter_properties, "output_buffer", NULL );
206         int i; // channel
207         int count = mlt_properties_get_int( filter_properties, "_effect_count" );
208         int analysis = mlt_properties_get( filter_properties, "effect" ) && !strcmp( mlt_properties_get( filter_properties, "effect" ), "analysis" );
209
210         // Get the producer's audio
211         *format = mlt_audio_s32;
212         mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
213
214         // Even though some effects are multi-channel aware, it is not reliable
215         // We must maintain a separate effect state for each channel
216         for ( i = 0; i < *channels; i++ )
217         {
218                 char id[ 256 ];
219                 sprintf( id, "_effect_0_%d", i );
220                 
221                 // Get an existing effect state
222                 eff_t e = mlt_properties_get_data( filter_properties, id, NULL );
223                 
224                 // Validate the existing effect state
225 #if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,1,0))
226                 if ( e != NULL && ( e->in_signal.rate != *frequency || 
227                                                         e->out_signal.rate != *frequency ) )
228 #else
229                 if ( e != NULL && ( e->ininfo.rate != *frequency || 
230                                                         e->outinfo.rate != *frequency ) )
231 #endif
232                         e = NULL;
233                 
234                 // (Re)Create the effect state
235                 if ( e == NULL )
236                 {
237                         int j = 0;
238                         
239                         // Reset the count
240                         count = 0;
241         
242                         // Loop over all properties
243                         for ( j = 0; j < mlt_properties_count( filter_properties ); j ++ )
244                         {
245                                 // Get the name of this property
246                                 char *name = mlt_properties_get_name( filter_properties, j );
247         
248                                 // If the name does not contain a . and matches effect
249                                 if ( !strncmp( name, "effect", 6 ) )
250                                 {
251                                         // Get the effect specification
252                                         char *value = mlt_properties_get_value( filter_properties, j );
253         
254                                         // Create an instance
255                                         if ( create_effect( filter, value, count, i, *frequency ) == 0 )
256                                                 count ++;
257                                 }
258                         }
259                         
260                         // Save the number of filters
261                         mlt_properties_set_int( filter_properties, "_effect_count", count );
262                         
263                 }
264                 if ( *samples > 0 && ( count > 0 || analysis ) )
265                 {
266                         input_buffer = (st_sample_t*) *buffer + i * *samples;
267                         st_sample_t *p = input_buffer;
268                         st_size_t isamp = *samples;
269                         st_size_t osamp = *samples;
270                         int j = *samples + 1;
271                         char *normalise = mlt_properties_get( filter_properties, "normalise" );
272                         double normalised_gain = 1.0;
273                         
274                         if ( analysis )
275                         {
276                                 // Run analysis to compute a gain level to normalize the audio across entire filter duration
277                                 double max_power = mlt_properties_get_double( filter_properties, "_max_power" );
278                                 double peak = mlt_properties_get_double( filter_properties, "_max_peak" );
279                                 double use_peak = mlt_properties_get_int( filter_properties, "use_peak" );
280                                 double power = 0;
281                                 int n = *samples + 1;
282
283                                 // Compute power level of samples in this channel of this frame
284                                 while ( --n )
285                                 {
286                                         double s = fabs( *p++ );
287                                         // Track peak
288                                         if ( s > peak )
289                                         {
290                                                 peak = s;
291                                                 mlt_properties_set_double( filter_properties, "_max_peak", peak );
292                                         }
293                                         power += s * s;
294                                 }
295                                 power /= *samples;
296                                 // Track maximum power
297                                 if ( power > max_power )
298                                 {
299                                         max_power = power;
300                                         mlt_properties_set_double( filter_properties, "_max_power", max_power );
301                                 }
302
303                                 // Complete analysis the last channel of the last frame.
304                                 if ( i + 1 == *channels && mlt_filter_get_position( filter, frame ) + 1
305                                          == mlt_filter_get_length2( filter, frame ) )
306                                 {
307                                         double rms = sqrt( max_power / ST_SSIZE_MIN / ST_SSIZE_MIN );
308                                         char effect[32];
309
310                                         // Convert RMS or peak to gain
311                                         if ( use_peak )
312                                                 normalised_gain = ST_SSIZE_MIN / -peak;
313                                         else
314                                                 normalised_gain = AMPLITUDE_NORM / rms;
315
316                                         // Set properties for serialization
317                                         snprintf( effect, sizeof(effect), "vol %f", normalised_gain );
318                                         effect[31] = 0;
319                                         mlt_properties_set( filter_properties, "effect", effect );
320                                         mlt_properties_set( filter_properties, "analyze", NULL );
321
322                                         // Show output comparable to normalize --no-adjust --fractions
323                                         mlt_properties_set_double( filter_properties, "level", rms );
324                                         mlt_properties_set_double( filter_properties, "gain", normalised_gain );
325                                         mlt_properties_set_double( filter_properties, "peak", -peak / ST_SSIZE_MIN );
326                                 }
327
328                                 // restore some variables
329                                 p = input_buffer;
330                         }
331
332                         if ( normalise )
333                         {
334                                 int window = mlt_properties_get_int( filter_properties, "window" );
335                                 double *smooth_buffer = mlt_properties_get_data( filter_properties, "smooth_buffer", NULL );
336                                 double max_gain = mlt_properties_get_double( filter_properties, "max_gain" );
337                                 double rms = 0;
338
339                                 // Default the maximum gain factor to 20dBFS
340                                 if ( max_gain == 0 )
341                                         max_gain = 10.0;
342                                 
343                                 // Compute rms amplitude
344                                 while( --j )
345                                 {
346                                         rms += ( double )*p * ( double )*p;
347                                         p ++;
348                                 }
349                                 rms = sqrt( rms / *samples / ST_SSIZE_MIN / ST_SSIZE_MIN );
350
351                                 // The smoothing buffer prevents radical shifts in the gain level
352                                 if ( window > 0 && smooth_buffer != NULL )
353                                 {
354                                         int smooth_index = mlt_properties_get_int( filter_properties, "_smooth_index" );
355                                         smooth_buffer[ smooth_index ] = rms;
356                                         
357                                         // Ignore very small values that adversely affect the mean
358                                         if ( rms > AMPLITUDE_MIN )
359                                                 mlt_properties_set_int( filter_properties, "_smooth_index", ( smooth_index + 1 ) % window );
360                                         
361                                         // Smoothing is really just a mean over the past N values
362                                         normalised_gain = AMPLITUDE_NORM / mean( smooth_buffer, window );
363                                 }
364                                 else if ( rms > 0 )
365                                 {
366                                         // Determine gain to apply as current amplitude
367                                         normalised_gain = AMPLITUDE_NORM / rms;
368                                 }
369                                         
370                                 //printf("filter_sox: rms %.3f gain %.3f\n", rms, normalised_gain );
371                                 
372                                 // Govern the maximum gain
373                                 if ( normalised_gain > max_gain )
374                                         normalised_gain = max_gain;
375                         }
376                         
377                         // For each effect
378                         for ( j = 0; j < count; j++ )
379                         {
380                                 sprintf( id, "_effect_%d_%d", j, i );
381                                 e = mlt_properties_get_data( filter_properties, id, NULL );
382                                 
383                                 // We better have this guy
384                                 if ( e != NULL )
385                                 {
386                                         float saved_gain = 1.0;
387                                         
388                                         // XXX: hack to apply the normalised gain level to the vol effect
389 #ifdef SOX14
390                                         if ( normalise && strcmp( e->handler.name, "vol" ) == 0 )
391 #else
392                                         if ( normalise && strcmp( e->name, "vol" ) == 0 )
393 #endif
394                                         {
395                                                 float *f = ( float * )( e->priv );
396                                                 saved_gain = *f;
397                                                 *f = saved_gain * normalised_gain;
398                                         }
399                                         
400                                         // Apply the effect
401 #ifdef SOX14
402                                         if ( ( * e->handler.flow )( e, input_buffer, output_buffer, &isamp, &osamp ) != ST_SUCCESS )
403 #else
404                                         if ( ( * e->h->flow )( e, input_buffer, output_buffer, &isamp, &osamp ) != ST_SUCCESS )
405 #endif
406                                         {
407                                                 mlt_log_warning( MLT_FILTER_SERVICE(filter), "effect processing failed\n" );
408                                         }
409                                         
410                                         // XXX: hack to restore the original vol gain to prevent accumulation
411 #ifdef SOX14
412                                         if ( normalise && strcmp( e->handler.name, "vol" ) == 0 )
413 #else
414                                         if ( normalise && strcmp( e->name, "vol" ) == 0 )
415 #endif
416                                         {
417                                                 float *f = ( float * )( e->priv );
418                                                 *f = saved_gain;
419                                         }
420                                 }
421                         }
422
423                         // Write back
424                         memcpy( input_buffer, output_buffer, *samples * sizeof(st_sample_t) );
425                 }
426         }
427
428         mlt_service_unlock( MLT_FILTER_SERVICE( filter ) );
429
430         return 0;
431 }
432
433 /** Filter processing.
434 */
435
436 static mlt_frame filter_process( mlt_filter this, mlt_frame frame )
437 {
438         if ( mlt_frame_is_test_audio( frame ) == 0 )
439         {
440                 // Add the filter to the frame
441                 mlt_frame_push_audio( frame, this );
442                 mlt_frame_push_audio( frame, filter_get_audio );
443                 
444                 // Parse the window property and allocate smoothing buffer if needed
445                 mlt_properties properties = MLT_FILTER_PROPERTIES( this );
446                 int window = mlt_properties_get_int( properties, "window" );
447                 if ( mlt_properties_get( properties, "smooth_buffer" ) == NULL && window > 1 )
448                 {
449                         // Create a smoothing buffer for the calculated "max power" of frame of audio used in normalisation
450                         double *smooth_buffer = (double*) calloc( window, sizeof( double ) );
451                         int i;
452                         for ( i = 0; i < window; i++ )
453                                 smooth_buffer[ i ] = -1.0;
454                         mlt_properties_set_data( properties, "smooth_buffer", smooth_buffer, 0, free, NULL );
455                 }
456         }
457
458         return frame;
459 }
460
461 /** Constructor for the filter.
462 */
463
464 mlt_filter filter_sox_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
465 {
466         mlt_filter this = mlt_filter_new( );
467         if ( this != NULL )
468         {
469                 void *input_buffer = mlt_pool_alloc( BUFFER_LEN );
470                 void *output_buffer = mlt_pool_alloc( BUFFER_LEN );
471                 mlt_properties properties = MLT_FILTER_PROPERTIES( this );
472                 
473                 this->process = filter_process;
474                 
475                 if ( !strncmp( id, "sox.", 4 ) )
476                 {
477                         char *s = malloc( strlen( id ) + ( arg? strlen( arg ) + 2 : 1 ) );
478                         strcpy( s, id + 4 );
479                         if ( arg )
480                         {
481                                 strcat( s, " " );
482                                 strcat( s, arg );
483                         }
484                         mlt_properties_set( properties, "effect", s );
485                         free( s );
486                 }
487                 else if ( arg )
488                         mlt_properties_set( properties, "effect", arg );
489                 mlt_properties_set_data( properties, "input_buffer", input_buffer, BUFFER_LEN, mlt_pool_release, NULL );
490                 mlt_properties_set_data( properties, "output_buffer", output_buffer, BUFFER_LEN, mlt_pool_release, NULL );
491                 mlt_properties_set_int( properties, "window", 75 );
492                 mlt_properties_set( properties, "version", sox_version() );
493         }
494         return this;
495 }
496
497 // What to do when a libst internal failure occurs
498 void cleanup(void){}