]> git.sesse.net Git - mlt/blob - src/modules/sox/filter_sox.c
Fix segfault in sox with no effect.
[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                 return error;
104
105         // Locate the effect
106         mlt_destructor effect_destructor = mlt_pool_release;
107 #ifdef SOX14
108         //fprintf(stderr, "%s: effect %s count %d\n", __FUNCTION__, tokeniser->tokens[0], tokeniser->count );
109 #if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,1,0))
110         sox_effect_handler_t const *eff_handle = sox_find_effect( tokeniser->tokens[0] );
111         if (eff_handle == NULL ) return error;
112         eff_t eff = sox_create_effect( eff_handle );
113         effect_destructor = ( mlt_destructor ) delete_effect;
114         sox_encodinginfo_t *enc = calloc( 1, sizeof( sox_encodinginfo_t ) );
115         enc->encoding = SOX_ENCODING_SIGN2;
116         enc->bits_per_sample = 16;
117         eff->in_encoding = eff->out_encoding = enc;
118 #else
119         eff_t eff = mlt_pool_alloc( sizeof( sox_effect_t ) );
120         sox_create_effect( eff, sox_find_effect( tokeniser->tokens[0] ) );
121 #endif
122         int opt_count = tokeniser->count - 1;
123 #else
124         eff_t eff = mlt_pool_alloc( sizeof( struct st_effect ) );
125         int opt_count = st_geteffect_opt( eff, tokeniser->count, tokeniser->tokens );
126 #endif
127         
128         // If valid effect
129         if ( opt_count != ST_EOF )
130         {
131                 // Supply the effect parameters
132 #ifdef SOX14
133 #if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,2,0))
134                 if ( sox_effect_options( eff, opt_count, &tokeniser->tokens[ tokeniser->count > 1 ? 1 : 0  ] ) == ST_SUCCESS )
135 #else
136                 if ( ( * eff->handler.getopts )( eff, opt_count, &tokeniser->tokens[ tokeniser->count > 1 ? 1 : 0  ] ) == ST_SUCCESS )
137 #endif
138 #else
139                 if ( ( * eff->h->getopts )( eff, opt_count, &tokeniser->tokens[ tokeniser->count - opt_count ] ) == ST_SUCCESS )
140 #endif
141                 {
142                         // Set the sox signal parameters
143 #if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,1,0))
144                         eff->in_signal.rate = frequency;
145                         eff->out_signal.rate = frequency;
146                         eff->in_signal.channels = 1;
147                         eff->out_signal.channels = 1;
148                         eff->in_signal.precision = 16;
149                         eff->out_signal.precision = 16;
150                         eff->in_signal.length = 0;
151                         eff->out_signal.length = 0;
152 #else
153                         eff->ininfo.rate = frequency;
154                         eff->outinfo.rate = frequency;
155                         eff->ininfo.channels = 1;
156                         eff->outinfo.channels = 1;
157 #endif
158                         
159                         // Start the effect
160 #ifdef SOX14
161                         if ( ( * eff->handler.start )( eff ) == ST_SUCCESS )
162 #else
163                         if ( ( * eff->h->start )( eff ) == ST_SUCCESS )
164 #endif
165                         {
166                                 // Construct id
167                                 sprintf( id, "_effect_%d_%d", count, channel );
168
169                                 // Save the effect state
170                                 mlt_properties_set_data( MLT_FILTER_PROPERTIES( this ), id, eff, 0, effect_destructor, NULL );
171                                 error = 0;
172                         }
173                 }
174         }
175         // Some error occurred so delete the temp effect state
176         if ( error == 1 )
177                 effect_destructor( eff );
178         
179         mlt_tokeniser_close( tokeniser );
180         
181         return error;
182 }
183
184 /** Get the audio.
185 */
186
187 static int filter_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
188 {
189 #if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,3,0))
190         SOX_SAMPLE_LOCALS;
191 #endif
192         // Get the filter service
193         mlt_filter filter = mlt_frame_pop_audio( frame );
194
195         // Get the filter properties
196         mlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter );
197
198         mlt_service_lock( MLT_FILTER_SERVICE( filter ) );
199
200         // Get the properties
201         st_sample_t *input_buffer;// = mlt_properties_get_data( filter_properties, "input_buffer", NULL );
202         st_sample_t *output_buffer = mlt_properties_get_data( filter_properties, "output_buffer", NULL );
203         int i; // channel
204         int count = mlt_properties_get_int( filter_properties, "_effect_count" );
205         int analysis = mlt_properties_get( filter_properties, "effect" ) && !strcmp( mlt_properties_get( filter_properties, "effect" ), "analysis" );
206
207         // Get the producer's audio
208         *format = mlt_audio_s32;
209         mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
210
211         // Even though some effects are multi-channel aware, it is not reliable
212         // We must maintain a separate effect state for each channel
213         for ( i = 0; i < *channels; i++ )
214         {
215                 char id[ 256 ];
216                 sprintf( id, "_effect_0_%d", i );
217                 
218                 // Get an existing effect state
219                 eff_t e = mlt_properties_get_data( filter_properties, id, NULL );
220                 
221                 // Validate the existing effect state
222 #if (ST_LIB_VERSION_CODE >= ST_LIB_VERSION(14,1,0))
223                 if ( e != NULL && ( e->in_signal.rate != *frequency || 
224                                                         e->out_signal.rate != *frequency ) )
225 #else
226                 if ( e != NULL && ( e->ininfo.rate != *frequency || 
227                                                         e->outinfo.rate != *frequency ) )
228 #endif
229                         e = NULL;
230                 
231                 // (Re)Create the effect state
232                 if ( e == NULL )
233                 {
234                         int j = 0;
235                         
236                         // Reset the count
237                         count = 0;
238         
239                         // Loop over all properties
240                         for ( j = 0; j < mlt_properties_count( filter_properties ); j ++ )
241                         {
242                                 // Get the name of this property
243                                 char *name = mlt_properties_get_name( filter_properties, j );
244         
245                                 // If the name does not contain a . and matches effect
246                                 if ( !strncmp( name, "effect", 6 ) )
247                                 {
248                                         // Get the effect specification
249                                         char *value = mlt_properties_get_value( filter_properties, j );
250         
251                                         // Create an instance
252                                         if ( create_effect( filter, value, count, i, *frequency ) == 0 )
253                                                 count ++;
254                                 }
255                         }
256                         
257                         // Save the number of filters
258                         mlt_properties_set_int( filter_properties, "_effect_count", count );
259                         
260                 }
261                 if ( *samples > 0 && ( count > 0 || analysis ) )
262                 {
263                         input_buffer = (st_sample_t*) *buffer + i * *samples;
264                         st_sample_t *p = input_buffer;
265                         st_size_t isamp = *samples;
266                         st_size_t osamp = *samples;
267                         int j = *samples + 1;
268                         char *normalise = mlt_properties_get( filter_properties, "normalise" );
269                         double normalised_gain = 1.0;
270                         
271                         if ( analysis )
272                         {
273                                 // Run analysis to compute a gain level to normalize the audio across entire filter duration
274                                 double max_power = mlt_properties_get_double( filter_properties, "_max_power" );
275                                 double peak = mlt_properties_get_double( filter_properties, "_max_peak" );
276                                 double use_peak = mlt_properties_get_int( filter_properties, "use_peak" );
277                                 double power = 0;
278                                 int n = *samples + 1;
279
280                                 // Compute power level of samples in this channel of this frame
281                                 while ( --n )
282                                 {
283                                         double s = fabs( *p++ );
284                                         // Track peak
285                                         if ( s > peak )
286                                         {
287                                                 peak = s;
288                                                 mlt_properties_set_double( filter_properties, "_max_peak", peak );
289                                         }
290                                         power += s * s;
291                                 }
292                                 power /= *samples;
293                                 // Track maximum power
294                                 if ( power > max_power )
295                                 {
296                                         max_power = power;
297                                         mlt_properties_set_double( filter_properties, "_max_power", max_power );
298                                 }
299
300                                 // Complete analysis the last channel of the last frame.
301                                 if ( i + 1 == *channels && mlt_filter_get_position( filter, frame ) + 1
302                                          == mlt_filter_get_length2( filter, frame ) )
303                                 {
304                                         double rms = sqrt( max_power / ST_SSIZE_MIN / ST_SSIZE_MIN );
305                                         char effect[32];
306
307                                         // Convert RMS or peak to gain
308                                         if ( use_peak )
309                                                 normalised_gain = ST_SSIZE_MIN / -peak;
310                                         else
311                                                 normalised_gain = AMPLITUDE_NORM / rms;
312
313                                         // Set properties for serialization
314                                         snprintf( effect, sizeof(effect), "vol %f", normalised_gain );
315                                         effect[31] = 0;
316                                         mlt_properties_set( filter_properties, "effect", effect );
317                                         mlt_properties_set( filter_properties, "analyze", NULL );
318
319                                         // Show output comparable to normalize --no-adjust --fractions
320                                         mlt_properties_set_double( filter_properties, "level", rms );
321                                         mlt_properties_set_double( filter_properties, "gain", normalised_gain );
322                                         mlt_properties_set_double( filter_properties, "peak", -peak / ST_SSIZE_MIN );
323                                 }
324
325                                 // restore some variables
326                                 p = input_buffer;
327                         }
328
329                         if ( normalise )
330                         {
331                                 int window = mlt_properties_get_int( filter_properties, "window" );
332                                 double *smooth_buffer = mlt_properties_get_data( filter_properties, "smooth_buffer", NULL );
333                                 double max_gain = mlt_properties_get_double( filter_properties, "max_gain" );
334                                 double rms = 0;
335
336                                 // Default the maximum gain factor to 20dBFS
337                                 if ( max_gain == 0 )
338                                         max_gain = 10.0;
339                                 
340                                 // Compute rms amplitude
341                                 while( --j )
342                                 {
343                                         rms += ( double )*p * ( double )*p;
344                                         p ++;
345                                 }
346                                 rms = sqrt( rms / *samples / ST_SSIZE_MIN / ST_SSIZE_MIN );
347
348                                 // The smoothing buffer prevents radical shifts in the gain level
349                                 if ( window > 0 && smooth_buffer != NULL )
350                                 {
351                                         int smooth_index = mlt_properties_get_int( filter_properties, "_smooth_index" );
352                                         smooth_buffer[ smooth_index ] = rms;
353                                         
354                                         // Ignore very small values that adversely affect the mean
355                                         if ( rms > AMPLITUDE_MIN )
356                                                 mlt_properties_set_int( filter_properties, "_smooth_index", ( smooth_index + 1 ) % window );
357                                         
358                                         // Smoothing is really just a mean over the past N values
359                                         normalised_gain = AMPLITUDE_NORM / mean( smooth_buffer, window );
360                                 }
361                                 else if ( rms > 0 )
362                                 {
363                                         // Determine gain to apply as current amplitude
364                                         normalised_gain = AMPLITUDE_NORM / rms;
365                                 }
366                                         
367                                 //printf("filter_sox: rms %.3f gain %.3f\n", rms, normalised_gain );
368                                 
369                                 // Govern the maximum gain
370                                 if ( normalised_gain > max_gain )
371                                         normalised_gain = max_gain;
372                         }
373                         
374                         // For each effect
375                         for ( j = 0; j < count; j++ )
376                         {
377                                 sprintf( id, "_effect_%d_%d", j, i );
378                                 e = mlt_properties_get_data( filter_properties, id, NULL );
379                                 
380                                 // We better have this guy
381                                 if ( e != NULL )
382                                 {
383                                         float saved_gain = 1.0;
384                                         
385                                         // XXX: hack to apply the normalised gain level to the vol effect
386 #ifdef SOX14
387                                         if ( normalise && strcmp( e->handler.name, "vol" ) == 0 )
388 #else
389                                         if ( normalise && strcmp( e->name, "vol" ) == 0 )
390 #endif
391                                         {
392                                                 float *f = ( float * )( e->priv );
393                                                 saved_gain = *f;
394                                                 *f = saved_gain * normalised_gain;
395                                         }
396                                         
397                                         // Apply the effect
398 #ifdef SOX14
399                                         if ( ( * e->handler.flow )( e, input_buffer, output_buffer, &isamp, &osamp ) != ST_SUCCESS )
400 #else
401                                         if ( ( * e->h->flow )( e, input_buffer, output_buffer, &isamp, &osamp ) != ST_SUCCESS )
402 #endif
403                                         {
404                                                 mlt_log_warning( MLT_FILTER_SERVICE(filter), "effect processing failed\n" );
405                                         }
406                                         
407                                         // XXX: hack to restore the original vol gain to prevent accumulation
408 #ifdef SOX14
409                                         if ( normalise && strcmp( e->handler.name, "vol" ) == 0 )
410 #else
411                                         if ( normalise && strcmp( e->name, "vol" ) == 0 )
412 #endif
413                                         {
414                                                 float *f = ( float * )( e->priv );
415                                                 *f = saved_gain;
416                                         }
417                                 }
418                         }
419
420                         // Write back
421                         memcpy( input_buffer, output_buffer, *samples * sizeof(st_sample_t) );
422                 }
423         }
424
425         mlt_service_unlock( MLT_FILTER_SERVICE( filter ) );
426
427         return 0;
428 }
429
430 /** Filter processing.
431 */
432
433 static mlt_frame filter_process( mlt_filter this, mlt_frame frame )
434 {
435         if ( mlt_frame_is_test_audio( frame ) == 0 )
436         {
437                 // Add the filter to the frame
438                 mlt_frame_push_audio( frame, this );
439                 mlt_frame_push_audio( frame, filter_get_audio );
440                 
441                 // Parse the window property and allocate smoothing buffer if needed
442                 mlt_properties properties = MLT_FILTER_PROPERTIES( this );
443                 int window = mlt_properties_get_int( properties, "window" );
444                 if ( mlt_properties_get( properties, "smooth_buffer" ) == NULL && window > 1 )
445                 {
446                         // Create a smoothing buffer for the calculated "max power" of frame of audio used in normalisation
447                         double *smooth_buffer = (double*) calloc( window, sizeof( double ) );
448                         int i;
449                         for ( i = 0; i < window; i++ )
450                                 smooth_buffer[ i ] = -1.0;
451                         mlt_properties_set_data( properties, "smooth_buffer", smooth_buffer, 0, free, NULL );
452                 }
453         }
454
455         return frame;
456 }
457
458 /** Constructor for the filter.
459 */
460
461 mlt_filter filter_sox_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg )
462 {
463         mlt_filter this = mlt_filter_new( );
464         if ( this != NULL )
465         {
466                 void *input_buffer = mlt_pool_alloc( BUFFER_LEN );
467                 void *output_buffer = mlt_pool_alloc( BUFFER_LEN );
468                 mlt_properties properties = MLT_FILTER_PROPERTIES( this );
469                 
470                 this->process = filter_process;
471                 
472                 if ( !strncmp( id, "sox.", 4 ) )
473                 {
474                         char *s = malloc( strlen( id ) + ( arg? strlen( arg ) + 2 : 1 ) );
475                         strcpy( s, id + 4 );
476                         if ( arg )
477                         {
478                                 strcat( s, " " );
479                                 strcat( s, arg );
480                         }
481                         mlt_properties_set( properties, "effect", s );
482                         free( s );
483                 }
484                 else if ( arg )
485                         mlt_properties_set( properties, "effect", arg );
486                 mlt_properties_set_data( properties, "input_buffer", input_buffer, BUFFER_LEN, mlt_pool_release, NULL );
487                 mlt_properties_set_data( properties, "output_buffer", output_buffer, BUFFER_LEN, mlt_pool_release, NULL );
488                 mlt_properties_set_int( properties, "window", 75 );
489                 mlt_properties_set( properties, "version", sox_version() );
490         }
491         return this;
492 }
493
494 // What to do when a libst internal failure occurs
495 void cleanup(void){}