]> git.sesse.net Git - vlc/blob - modules/demux/mod.c
macosx: Update progress dialog on the main thread, make check thread safe
[vlc] / modules / demux / mod.c
1 /*****************************************************************************
2  * mod.c: MOD file demuxer (using libmodplug)
3  *****************************************************************************
4  * Copyright (C) 2004-2009 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  * Konstanty Bialkowski <konstanty@ieee.org>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_demux.h>
36 #include <vlc_meta.h>
37 #include <vlc_charset.h>
38 #include <assert.h>
39
40 #include <libmodplug/modplug.h>
41
42 /* TODO:
43  *  - extend demux control to query meta data (demuxer should NEVER touch
44  *      playlist itself)
45  *  - FIXME test endian of samples
46  *  - ...
47  */
48
49 /*****************************************************************************
50  * Module descriptor
51  *****************************************************************************/
52 static int  Open    ( vlc_object_t * );
53 static void Close  ( vlc_object_t * );
54
55 #define NOISE_LONGTEXT N_("Enable noise reduction algorithm.")
56 #define REVERB_LONGTEXT N_("Enable reverberation" )
57 #define REVERB_LEVEL_LONGTEXT N_( "Reverberation level (from 0 " \
58                 "to 100, default value is 0)." )
59 #define REVERB_DELAY_LONGTEXT N_("Reverberation delay, in ms." \
60                 " Usual values are from to 40 to 200ms." )
61 #define MEGABASS_LONGTEXT N_( "Enable megabass mode" )
62 #define MEGABASS_LEVEL_LONGTEXT N_("Megabass mode level (from 0 to 100, " \
63                 "default value is 0)." )
64 #define MEGABASS_RANGE_LONGTEXT N_("Megabass mode cutoff frequency, in Hz. " \
65                 "This is the maximum frequency for which the megabass " \
66                 "effect applies. Valid values are from 10 to 100 Hz." )
67 #define SURROUND_LEVEL_LONGTEXT N_( "Surround effect level (from 0 to 100, " \
68                 "default value is 0)." )
69 #define SURROUND_DELAY_LONGTEXT N_("Surround delay, in ms. Usual values are " \
70                 "from 5 to 40 ms." )
71
72 vlc_module_begin ()
73     set_shortname( "MOD")
74     set_description( N_("MOD demuxer (libmodplug)" ) )
75     set_capability( "demux", 10 )
76     set_category( CAT_INPUT )
77     set_subcategory( SUBCAT_INPUT_DEMUX )
78
79     add_bool( "mod-noisereduction", true, N_("Noise reduction"),
80               NOISE_LONGTEXT, false )
81
82     add_bool( "mod-reverb", false, N_("Reverb"),
83               REVERB_LONGTEXT, false )
84     add_integer_with_range( "mod-reverb-level", 0, 0, 100,
85              N_("Reverberation level"), REVERB_LEVEL_LONGTEXT, true )
86     add_integer_with_range( "mod-reverb-delay", 40, 0, 1000,
87              N_("Reverberation delay"), REVERB_DELAY_LONGTEXT, true )
88
89     add_bool( "mod-megabass", false, N_("Mega bass"),
90                     MEGABASS_LONGTEXT, false )
91     add_integer_with_range( "mod-megabass-level", 0, 0, 100,
92               N_("Mega bass level"), MEGABASS_LEVEL_LONGTEXT, true )
93     add_integer_with_range( "mod-megabass-range", 10, 10, 100,
94               N_("Mega bass cutoff"), MEGABASS_RANGE_LONGTEXT, true )
95
96     add_bool( "mod-surround", false, N_("Surround"), N_("Surround"),
97                false )
98     add_integer_with_range( "mod-surround-level", 0, 0, 100,
99               N_("Surround level"), SURROUND_LEVEL_LONGTEXT, true )
100     add_integer_with_range( "mod-surround-delay", 5, 0, 1000,
101               N_("Surround delay (ms)"), SURROUND_DELAY_LONGTEXT, true )
102
103     set_callbacks( Open, Close )
104     add_shortcut( "mod" )
105 vlc_module_end ()
106
107 /*****************************************************************************
108  * Local prototypes
109  *****************************************************************************/
110 static vlc_mutex_t libmodplug_lock = VLC_STATIC_MUTEX;
111
112 struct demux_sys_t
113 {
114     es_format_t  fmt;
115     es_out_id_t *es;
116
117     date_t      pts;
118     int64_t     i_length;
119
120     int         i_data;
121     uint8_t     *p_data;
122     ModPlugFile *f;
123 };
124
125 static int Demux  ( demux_t *p_demux );
126 static int Control( demux_t *p_demux, int i_query, va_list args );
127
128 static int Validate( demux_t *p_demux, const char *psz_ext );
129
130 /* We load the complete file in memory, put a higher bound
131  * of 500 Mo (which is really big anyway) */
132 #define MOD_MAX_FILE_SIZE (500*1000*1000)
133
134 /*****************************************************************************
135  * Open
136  *****************************************************************************/
137 static int Open( vlc_object_t *p_this )
138 {
139     demux_t     *p_demux = (demux_t*)p_this;
140     demux_sys_t *p_sys;
141     ModPlug_Settings settings;
142
143     /* We accept file based on extension match */
144     if( !p_demux->b_force )
145     {
146         const char *psz_ext = p_demux->psz_file ? strrchr( p_demux->psz_file, '.' )
147                                                 : NULL;
148         if( psz_ext )
149             psz_ext++;
150
151         if( Validate( p_demux, psz_ext ) )
152         {
153             msg_Dbg( p_demux, "MOD validation failed (ext=%s)", psz_ext ? psz_ext : "");
154             return VLC_EGENERIC;
155         }
156     }
157
158     const int64_t i_size = stream_Size( p_demux->s );
159     if( i_size <= 0 || i_size >= MOD_MAX_FILE_SIZE )
160         return VLC_EGENERIC;
161
162     /* Fill p_demux field */
163     p_demux->pf_demux = Demux;
164     p_demux->pf_control = Control;
165     p_demux->p_sys = p_sys = malloc( sizeof( *p_sys ) );
166     if( !p_sys )
167         return VLC_ENOMEM;
168
169     msg_Dbg( p_demux, "loading complete file (could be long)" );
170     p_sys->i_data = i_size;
171     p_sys->p_data = malloc( p_sys->i_data );
172     if( p_sys->p_data )
173         p_sys->i_data = stream_Read( p_demux->s, p_sys->p_data, p_sys->i_data );
174     if( p_sys->i_data <= 0 || !p_sys->p_data )
175     {
176         msg_Err( p_demux, "failed to read the complete file" );
177         free( p_sys->p_data );
178         free( p_sys );
179         return VLC_EGENERIC;
180     }
181
182     /* Configure modplug before loading the file */
183     vlc_mutex_lock( &libmodplug_lock );
184     ModPlug_GetSettings( &settings );
185     settings.mFlags = MODPLUG_ENABLE_OVERSAMPLING;
186     settings.mChannels = 2;
187     settings.mBits = 16;
188     settings.mFrequency = 44100;
189     settings.mResamplingMode = MODPLUG_RESAMPLE_FIR;
190
191     if( var_InheritBool( p_demux, "mod-noisereduction" ) )
192         settings.mFlags |= MODPLUG_ENABLE_NOISE_REDUCTION;
193
194     if( var_InheritBool( p_demux, "mod-reverb" ) )
195         settings.mFlags |= MODPLUG_ENABLE_REVERB;
196     settings.mReverbDepth = var_InheritInteger( p_demux, "mod-reverb-level" );
197     settings.mReverbDelay = var_InheritInteger( p_demux, "mod-reverb-delay" );
198
199     if( var_InheritBool( p_demux, "mod-megabass" ) )
200         settings.mFlags |= MODPLUG_ENABLE_MEGABASS;
201     settings.mBassAmount = var_InheritInteger( p_demux, "mod-megabass-level" );
202     settings.mBassRange = var_InheritInteger( p_demux, "mod-megabass-range" );
203
204     if( var_InheritBool( p_demux, "mod-surround" ) )
205         settings.mFlags |= MODPLUG_ENABLE_SURROUND;
206     settings.mSurroundDepth = var_InheritInteger( p_demux, "mod-surround-level" );
207     settings.mSurroundDelay = var_InheritInteger( p_demux, "mod-surround-delay" );
208
209     ModPlug_SetSettings( &settings );
210
211     p_sys->f = ModPlug_Load( p_sys->p_data, p_sys->i_data );
212     vlc_mutex_unlock( &libmodplug_lock );
213
214     if( !p_sys->f )
215     {
216         msg_Err( p_demux, "failed to understand the file" );
217         /* we try to seek to recover for other plugin */
218         stream_Seek( p_demux->s, 0 );
219         free( p_sys->p_data );
220         free( p_sys );
221         return VLC_EGENERIC;
222     }
223
224     /* init time */
225     date_Init( &p_sys->pts, settings.mFrequency, 1 );
226     date_Set( &p_sys->pts, 0 );
227     p_sys->i_length = ModPlug_GetLength( p_sys->f ) * INT64_C(1000);
228
229     msg_Dbg( p_demux, "MOD loaded name=%s lenght=%"PRId64"ms",
230              ModPlug_GetName( p_sys->f ),
231              p_sys->i_length );
232
233 #ifdef WORDS_BIGENDIAN
234     es_format_Init( &p_sys->fmt, AUDIO_ES, VLC_FOURCC( 't', 'w', 'o', 's' ) );
235 #else
236     es_format_Init( &p_sys->fmt, AUDIO_ES, VLC_FOURCC( 'a', 'r', 'a', 'w' ) );
237 #endif
238     p_sys->fmt.audio.i_rate = settings.mFrequency;
239     p_sys->fmt.audio.i_channels = settings.mChannels;
240     p_sys->fmt.audio.i_bitspersample = settings.mBits;
241     p_sys->es = es_out_Add( p_demux->out, &p_sys->fmt );
242
243     return VLC_SUCCESS;
244 }
245
246 /*****************************************************************************
247  * Close
248  *****************************************************************************/
249 static void Close( vlc_object_t *p_this )
250 {
251     demux_t     *p_demux = (demux_t*)p_this;
252     demux_sys_t *p_sys = p_demux->p_sys;
253
254     ModPlug_Unload( p_sys->f );
255     free( p_sys->p_data );
256     free( p_sys );
257 }
258
259
260 /*****************************************************************************
261  * Demux:
262  *****************************************************************************/
263 static int Demux( demux_t *p_demux )
264 {
265     demux_sys_t *p_sys = p_demux->p_sys;
266     block_t     *p_frame;
267     const int i_bk = ( p_sys->fmt.audio.i_bitspersample / 8 ) *
268                        p_sys->fmt.audio.i_channels;
269
270     p_frame = block_Alloc( p_sys->fmt.audio.i_rate / 10 * i_bk );
271     if( !p_frame )
272         return -1;
273
274     const int i_read = ModPlug_Read( p_sys->f, p_frame->p_buffer, p_frame->i_buffer );
275     if( i_read <= 0 )
276     {
277         /* EOF */
278         block_Release( p_frame );
279         return 0;
280     }
281     p_frame->i_buffer = i_read;
282     p_frame->i_dts =
283     p_frame->i_pts = VLC_TS_0 + date_Get( &p_sys->pts );
284
285     /* Set PCR */
286     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_frame->i_pts );
287
288     /* Send data */
289     es_out_Send( p_demux->out, p_sys->es, p_frame );
290
291     date_Increment( &p_sys->pts, i_read / i_bk );
292
293     return 1;
294 }
295
296 /*****************************************************************************
297  * Control:
298  *****************************************************************************/
299 static int Control( demux_t *p_demux, int i_query, va_list args )
300 {
301     demux_sys_t *p_sys = p_demux->p_sys;
302     double f, *pf;
303     int64_t i64, *pi64;
304
305     switch( i_query )
306     {
307     case DEMUX_GET_POSITION:
308         pf = (double*) va_arg( args, double* );
309         if( p_sys->i_length > 0 )
310         {
311             double current = date_Get( &p_sys->pts );
312             double length = p_sys->i_length;
313             *pf = current / length;
314             return VLC_SUCCESS;
315         }
316         return VLC_EGENERIC;
317
318     case DEMUX_SET_POSITION:
319         f = (double) va_arg( args, double );
320
321         i64 = f * p_sys->i_length;
322         if( i64 >= 0 && i64 <= p_sys->i_length )
323         {
324             ModPlug_Seek( p_sys->f, i64 / 1000 );
325             date_Set( &p_sys->pts, i64 );
326
327             return VLC_SUCCESS;
328         }
329         return VLC_EGENERIC;
330
331     case DEMUX_GET_TIME:
332         pi64 = (int64_t*)va_arg( args, int64_t * );
333         *pi64 = date_Get( &p_sys->pts );
334         return VLC_SUCCESS;
335
336     case DEMUX_GET_LENGTH:
337         pi64 = (int64_t*)va_arg( args, int64_t * );
338         *pi64 = p_sys->i_length;
339         return VLC_SUCCESS;
340
341     case DEMUX_SET_TIME:
342         i64 = (int64_t)va_arg( args, int64_t );
343
344         if( i64 >= 0 && i64 <= p_sys->i_length )
345         {
346             ModPlug_Seek( p_sys->f, i64 / 1000 );
347             date_Set( &p_sys->pts, i64 );
348
349             return VLC_SUCCESS;
350         }
351         return VLC_EGENERIC;
352
353     case DEMUX_HAS_UNSUPPORTED_META:
354     {
355         bool *pb_bool = (bool*)va_arg( args, bool* );
356         *pb_bool = false; /* FIXME I am not sure of this one */
357         return VLC_SUCCESS;
358     }
359     case DEMUX_GET_META:
360     {
361         vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t* );
362         unsigned i_num_samples = ModPlug_NumSamples( p_sys->f ),
363                  i_num_instruments = ModPlug_NumInstruments( p_sys->f );
364         unsigned i_num_patterns = ModPlug_NumPatterns( p_sys->f ),
365                  i_num_channels = ModPlug_NumChannels( p_sys->f );
366         //      unsigned modType = ModPlug_GetModuleType( p_sys->f );
367
368         char psz_temp[2048]; /* 32 * 240 max, but only need start  */
369         char *psz_module_info, *psz_instrument_info;
370         unsigned i_temp_index = 0;
371         const char *psz_name = ModPlug_GetName( p_sys->f );
372         if( psz_name && *psz_name && IsUTF8( psz_name ) )
373             vlc_meta_SetTitle( p_meta, psz_name );
374
375         /* Comment field from artist - not in every type of MOD */
376         psz_name = ModPlug_GetMessage( p_sys->f );
377         if( psz_name && *psz_name && IsUTF8( psz_name ) )
378             vlc_meta_SetDescription( p_meta, psz_name );
379
380         /* Instruments only in newer MODs - so don't show if 0 */
381         if( asprintf( &psz_instrument_info, ", %i Instruments",
382                       i_num_instruments ) >= 0 )
383         {
384             if( asprintf( &psz_module_info,
385                           "%i Channels, %i Patterns\n"
386                           "%i Samples%s\n",
387                           i_num_channels, i_num_patterns, i_num_samples,
388                           ( i_num_instruments ? psz_instrument_info : "" ) ) >= 0 )
389             {
390                 vlc_meta_AddExtra( p_meta, "Module Information",
391                                    psz_module_info );
392                 free( psz_module_info );
393             }
394
395             free( psz_instrument_info );
396         }
397
398         /* Make list of instruments (XM, IT, etc) */
399         if( i_num_instruments )
400         {
401             i_temp_index = 0;
402             for( unsigned i = 0; i < i_num_instruments && i_temp_index < sizeof(psz_temp); i++ )
403             {
404                 char lBuffer[33];
405                 ModPlug_InstrumentName( p_sys->f, i, lBuffer );
406                 if ( !lBuffer[0] || !IsUTF8( lBuffer ) ) continue;
407                 i_temp_index += snprintf( &psz_temp[i_temp_index], sizeof(psz_temp) - i_temp_index, "%s\n", lBuffer );
408             }
409
410             vlc_meta_AddExtra( p_meta, "Instruments", psz_temp );
411         }
412
413         /* Make list of samples */
414         for( unsigned int i = 0; i < i_num_samples && i_temp_index < sizeof(psz_temp); i++ )
415         {
416             char psz_buffer[33];
417             ModPlug_SampleName( p_sys->f, i, psz_buffer );
418             if ( !psz_buffer[0] || !IsUTF8( psz_buffer ) ) continue;
419             i_temp_index += snprintf( &psz_temp[i_temp_index], sizeof(psz_temp) - i_temp_index, "%s\n", psz_buffer );
420         }
421
422         vlc_meta_AddExtra( p_meta, "Samples", psz_temp );
423
424         return VLC_SUCCESS;
425     }
426
427     case DEMUX_GET_FPS: /* meaningless */
428     default:
429         return VLC_EGENERIC;
430     }
431 }
432
433 /*****************************************************************************
434  * Validate: try to ensure it is really a mod file.
435  * The tests are not robust enough to replace extension checks in the general
436  * cases.
437  * TODO: maybe it should return a score, which will be used to bypass the
438  * extension checks when high enough.
439  *****************************************************************************/
440 static int Validate( demux_t *p_demux, const char *psz_ext )
441 {
442     static const struct
443     {
444         int i_offset;
445         const char *psz_marker;
446     } p_marker[] = {
447         {  0, "ziRCONia" },             /* MMCMP files */
448         {  0, "Extended Module" },      /* XM */
449         { 44, "SCRM" },                 /* S3M */
450         {  0, "IMPM" },                 /* IT */
451         {  0, "GF1PATCH110" },          /* PAT */
452         { 20, "!SCREAM!" },             /* STM */
453         { 20, "!Scream!" },             /* STM */
454         { 20, "BMOD2STM" },             /* STM */
455         {  0, "MMD0" },                 /* MED v0 */
456         {  0, "MMD1" },                 /* MED v1 */
457         {  0, "MMD2" },                 /* MED v2 */
458         {  0, "MMD3" },                 /* MED v3 */
459         {  0, "MTM" },                  /* MTM */
460         {  0, "DMDL" },                 /* MDL */
461         {  0, "DBM0" },                 /* DBM */
462         {  0, "if" },                   /* 669 */
463         {  0, "JN" },                   /* 669 */
464         {  0, "FAR\xfe" },              /* FAR */
465         {  0, "Extreme" },              /* AMS */
466         {  0, "OKTASONGCMOD" },         /* OKT */
467         { 44, "PTMF" },                 /* PTM */
468         {  0, "MAS_UTrack_V00" },       /* Ult */
469         {  0, "DDMF" },                 /* DMF */
470         {  8, "DSMFSONG" },             /* DSM */
471         {  0, "\xc1\x83\x2a\x9e" },     /* UMX */
472         {  0, "ASYLUM Music Format V1.0" }, /* AMF Type 0 */
473         {  0, "AMF" },                  /* AMF */
474         {  0, "PSM\xfe" },              /* PSM */
475         {  0, "PSM " },                 /* PSM */
476         {  0, "MT20" },                 /* MT2 */
477
478         { 1080, "M.K." },               /* MOD */
479         { 1080, "M!K!" },
480         { 1080, "M&K!" },
481         { 1080, "N.T." },
482         { 1080, "CD81" },
483         { 1080, "OKTA" },
484         { 1080, "16CN" },
485         { 1080, "32CN" },
486         { 1080, "FLT4" },
487         { 1080, "FLT8" },
488         { 1080, "6CHN" },
489         { 1080, "8CHN" },
490         { 1080, "FLT" },
491         { 1080, "TDZ" },
492         { 1081, "CHN" },
493         { 1082, "CH" },
494
495         {  -1, NULL }
496     };
497     static const char *ppsz_mod_ext[] =
498     {
499         "mod", "s3m", "xm",  "it",  "669", "amf", "ams", "dbm", "dmf", "dsm",
500         "far", "mdl", "med", "mtm", "okt", "ptm", "stm", "ult", "umx", "mt2",
501         "psm", "abc", NULL
502     };
503     bool has_valid_extension = false;
504     if( psz_ext )
505     {
506         for( int i = 0; ppsz_mod_ext[i] != NULL; i++ )
507         {
508             has_valid_extension |= !strcasecmp( psz_ext, ppsz_mod_ext[i] );
509             if( has_valid_extension )
510                 break;
511         }
512     }
513
514     const uint8_t *p_peek;
515     const int i_peek = stream_Peek( p_demux->s, &p_peek, 2048 );
516     if( i_peek < 4 )
517         return VLC_EGENERIC;
518
519     for( int i = 0; p_marker[i].i_offset >= 0; i++ )
520     {
521         const char *psz_marker = p_marker[i].psz_marker;
522         const int i_size = strlen( psz_marker );
523         const int i_offset = p_marker[i].i_offset;
524
525         if( i_peek < i_offset + i_size )
526             continue;
527
528         if( !memcmp( &p_peek[i_offset], psz_marker, i_size ) )
529         {
530             if( i_size >= 4 || has_valid_extension )
531                 return VLC_SUCCESS;
532         }
533     }
534
535     /* The only two format left untested are ABC and MOD(old version)
536      * ant they are difficult to test :( */
537
538     /* Check for ABC
539      * TODO i_peek = 2048 is too big for such files */
540     if( psz_ext && !strcasecmp( psz_ext, "abc" ) )
541     {
542         bool b_k = false;
543         bool b_tx = false;
544
545         for( int i = 0; i < i_peek-1; i++ )
546         {
547             b_k |= p_peek[i+0] == 'K' && p_peek[i+1] == ':';
548             b_tx |= ( p_peek[i+0] == 'X' || p_peek[i+0] == 'T') && p_peek[i+1] == ':';
549         }
550         if( !b_k || !b_tx )
551             return VLC_EGENERIC;
552         return VLC_SUCCESS;
553     }
554
555     /* Check for MOD */
556     if( psz_ext && !strcasecmp( psz_ext, "mod" ) && i_peek >= 20 + 15 * 30 )
557     {
558         /* Check that the name is correctly null padded */
559         const uint8_t *p = memchr( p_peek, '\0', 20 );
560         if( p )
561         {
562             for( ; p < &p_peek[20]; p++ )
563             {
564                 if( *p )
565                     return VLC_EGENERIC;
566             }
567         }
568
569         for( int i = 0; i < 15; i++ )
570         {
571             const uint8_t *p_sample = &p_peek[20 + i*30];
572
573             /* Check correct null padding */
574             const uint8_t *p = memchr( &p_sample[0], '\0', 22 );
575             if( p )
576             {
577                 for( ; p < &p_sample[22]; p++ )
578                 {
579                     if( *p )
580                         return VLC_EGENERIC;
581                 }
582             }
583
584             if( p_sample[25] > 64 ) /* Volume value */
585                 return VLC_EGENERIC;
586         }
587         return VLC_SUCCESS;
588     }
589     return VLC_EGENERIC;
590 }