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