]> git.sesse.net Git - ffmpeg/blob - libavformat/libmodplug.c
mxfdec: Move FooterPartition to MXFContext and make sure it's never set to zero
[ffmpeg] / libavformat / libmodplug.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 /**
20 * @file
21 * ModPlug demuxer
22 * @todo better probing than extensions matching
23 */
24
25 #include <libmodplug/modplug.h>
26 #include "libavutil/avstring.h"
27 #include "libavutil/eval.h"
28 #include "libavutil/opt.h"
29 #include "avformat.h"
30
31 typedef struct ModPlugContext {
32     const AVClass *class;
33     ModPlugFile *f;
34     uint8_t *buf; ///< input file content
35
36     /* options */
37     int noise_reduction;
38     int reverb_depth;
39     int reverb_delay;
40     int bass_amount;
41     int bass_range;
42     int surround_depth;
43     int surround_delay;
44
45     int max_size; ///< max file size to allocate
46
47     /* optional video stream */
48     double ts_per_packet; ///< used to define the pts/dts using packet_count;
49     int packet_count;     ///< total number of audio packets
50     int print_textinfo;   ///< bool flag for printing speed, tempo, order, ...
51     int video_stream;     ///< 1 if the user want a video stream, otherwise 0
52     int w;                ///< video stream width  in char (one char = 8x8px)
53     int h;                ///< video stream height in char (one char = 8x8px)
54     int video_switch;     ///< 1 if current packet is video, otherwise 0
55     int fsize;            ///< constant frame size
56     int linesize;         ///< line size in bytes
57     char *color_eval;     ///< color eval user input expression
58     int eval_err;         ///< 1 if eval failed once, otherwise 0 (used to disable video)
59 } ModPlugContext;
60
61 static const char *var_names[] = {
62     "E", "PHI", "PI",
63     "x", "y",
64     "w", "h",
65     "t",
66     "speed", "tempo", "order", "pattern", "row",
67     NULL
68 };
69
70 enum var_name {
71     VAR_E, VAR_PHI, VAR_PI,
72     VAR_X, VAR_Y,
73     VAR_W, VAR_H,
74     VAR_TIME,
75     VAR_SPEED, VAR_TEMPO, VAR_ORDER, VAR_PATTERN, VAR_ROW,
76     VAR_VARS_NB
77 };
78
79 #define FF_MODPLUG_MAX_FILE_SIZE (100 * 1<<20) // 100M
80 #define FF_MODPLUG_DEF_FILE_SIZE (  5 * 1<<20) //   5M
81
82 #define OFFSET(x) offsetof(ModPlugContext, x)
83 #define D AV_OPT_FLAG_DECODING_PARAM
84 static const AVOption options[] = {
85     {"noise_reduction", "Enable noise reduction 0(off)-1(on)",  OFFSET(noise_reduction), FF_OPT_TYPE_INT, {.dbl = 0}, 0,       1, D},
86     {"reverb_depth",    "Reverb level 0(quiet)-100(loud)",      OFFSET(reverb_depth),    FF_OPT_TYPE_INT, {.dbl = 0}, 0,     100, D},
87     {"reverb_delay",    "Reverb delay in ms, usually 40-200ms", OFFSET(reverb_delay),    FF_OPT_TYPE_INT, {.dbl = 0}, 0, INT_MAX, D},
88     {"bass_amount",     "XBass level 0(quiet)-100(loud)",       OFFSET(bass_amount),     FF_OPT_TYPE_INT, {.dbl = 0}, 0,     100, D},
89     {"bass_range",      "XBass cutoff in Hz 10-100",            OFFSET(bass_range),      FF_OPT_TYPE_INT, {.dbl = 0}, 0,     100, D},
90     {"surround_depth",  "Surround level 0(quiet)-100(heavy)",   OFFSET(surround_depth),  FF_OPT_TYPE_INT, {.dbl = 0}, 0,     100, D},
91     {"surround_delay",  "Surround delay in ms, usually 5-40ms", OFFSET(surround_delay),  FF_OPT_TYPE_INT, {.dbl = 0}, 0, INT_MAX, D},
92     {"max_size",        "Max file size supported (in bytes). Default is 5MB. Set to 0 for no limit (not recommended)",
93      OFFSET(max_size), FF_OPT_TYPE_INT, {.dbl = FF_MODPLUG_DEF_FILE_SIZE}, 0, FF_MODPLUG_MAX_FILE_SIZE, D},
94     {"video_stream_expr", "Color formula",                                  OFFSET(color_eval),     FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, D},
95     {"video_stream",      "Make demuxer output a video stream",             OFFSET(video_stream),   FF_OPT_TYPE_INT, {.dbl = 0},   0,   1, D},
96     {"video_stream_w",    "Video stream width in char (one char = 8x8px)",  OFFSET(w),              FF_OPT_TYPE_INT, {.dbl = 30}, 20, 512, D},
97     {"video_stream_h",    "Video stream height in char (one char = 8x8px)", OFFSET(h),              FF_OPT_TYPE_INT, {.dbl = 30}, 20, 512, D},
98     {"video_stream_ptxt", "Print speed, tempo, order, ... in video stream", OFFSET(print_textinfo), FF_OPT_TYPE_INT, {.dbl = 1},   0,   1, D},
99     {NULL},
100 };
101
102 #define SET_OPT_IF_REQUESTED(libopt, opt, flag) do {        \
103     if (modplug->opt) {                                     \
104         settings.libopt  = modplug->opt;                    \
105         settings.mFlags |= flag;                            \
106     }                                                       \
107 } while (0)
108
109 #define ADD_META_MULTIPLE_ENTRIES(entry_name, fname) do {                      \
110     if (n_## entry_name ##s) {                                                 \
111         unsigned i, n = 0;                                                     \
112                                                                                \
113         for (i = 0; i < n_## entry_name ##s; i++) {                            \
114             char item_name[64] = {0};                                          \
115             fname(f, i, item_name);                                            \
116             if (!*item_name)                                                   \
117                 continue;                                                      \
118             if (n)                                                             \
119                 av_dict_set(&s->metadata, #entry_name, "\n", AV_DICT_APPEND);  \
120             av_dict_set(&s->metadata, #entry_name, item_name, AV_DICT_APPEND); \
121             n++;                                                               \
122         }                                                                      \
123                                                                                \
124         extra = av_asprintf(", %u/%u " #entry_name "%s",                       \
125                             n, n_## entry_name ##s, n > 1 ? "s" : "");         \
126         if (!extra)                                                            \
127             return AVERROR(ENOMEM);                                            \
128         av_dict_set(&s->metadata, "extra info", extra, AV_DICT_APPEND);        \
129         av_free(extra);                                                        \
130     }                                                                          \
131 } while (0)
132
133 static int modplug_load_metadata(AVFormatContext *s)
134 {
135     ModPlugContext *modplug = s->priv_data;
136     ModPlugFile *f = modplug->f;
137     char *extra;
138     const char *name = ModPlug_GetName(f);
139     const char *msg  = ModPlug_GetMessage(f);
140
141     unsigned n_instruments = ModPlug_NumInstruments(f);
142     unsigned n_samples     = ModPlug_NumSamples(f);
143     unsigned n_patterns    = ModPlug_NumPatterns(f);
144     unsigned n_channels    = ModPlug_NumChannels(f);
145
146     if (name && *name) av_dict_set(&s->metadata, "name",    name, 0);
147     if (msg  && *msg)  av_dict_set(&s->metadata, "message", msg,  0);
148
149     extra = av_asprintf("%u pattern%s, %u channel%s",
150                         n_patterns, n_patterns > 1 ? "s" : "",
151                         n_channels, n_channels > 1 ? "s" : "");
152     if (!extra)
153         return AVERROR(ENOMEM);
154     av_dict_set(&s->metadata, "extra info", extra, AV_DICT_DONT_STRDUP_VAL);
155
156     ADD_META_MULTIPLE_ENTRIES(instrument, ModPlug_InstrumentName);
157     ADD_META_MULTIPLE_ENTRIES(sample,     ModPlug_SampleName);
158
159     return 0;
160 }
161
162 #define AUDIO_PKT_SIZE 512
163
164 static int modplug_read_header(AVFormatContext *s, AVFormatParameters *ap)
165 {
166     AVStream *st;
167     AVIOContext *pb = s->pb;
168     ModPlug_Settings settings;
169     ModPlugContext *modplug = s->priv_data;
170     int sz = avio_size(pb);
171
172     if (sz < 0) {
173         av_log(s, AV_LOG_WARNING, "Could not determine file size\n");
174         sz = modplug->max_size;
175     } else if (modplug->max_size && sz > modplug->max_size) {
176         sz = modplug->max_size;
177         av_log(s, AV_LOG_WARNING, "Max file size reach%s, allocating %dB "
178                "but demuxing is likely to fail due to incomplete buffer\n",
179                sz == FF_MODPLUG_DEF_FILE_SIZE ? " (see -max_size)" : "", sz);
180     }
181     modplug->buf = av_malloc(modplug->max_size);
182     if (!modplug->buf)
183         return AVERROR(ENOMEM);
184     sz = avio_read(pb, modplug->buf, sz);
185
186     ModPlug_GetSettings(&settings);
187     settings.mChannels       = 2;
188     settings.mBits           = 16;
189     settings.mFrequency      = 44100;
190     settings.mResamplingMode = MODPLUG_RESAMPLE_FIR; // best quality
191     settings.mLoopCount      = 0; // prevents looping forever
192
193     if (modplug->noise_reduction) settings.mFlags     |= MODPLUG_ENABLE_NOISE_REDUCTION;
194     SET_OPT_IF_REQUESTED(mReverbDepth,   reverb_depth,   MODPLUG_ENABLE_REVERB);
195     SET_OPT_IF_REQUESTED(mReverbDelay,   reverb_delay,   MODPLUG_ENABLE_REVERB);
196     SET_OPT_IF_REQUESTED(mBassAmount,    bass_amount,    MODPLUG_ENABLE_MEGABASS);
197     SET_OPT_IF_REQUESTED(mBassRange,     bass_range,     MODPLUG_ENABLE_MEGABASS);
198     SET_OPT_IF_REQUESTED(mSurroundDepth, surround_depth, MODPLUG_ENABLE_SURROUND);
199     SET_OPT_IF_REQUESTED(mSurroundDelay, surround_delay, MODPLUG_ENABLE_SURROUND);
200
201     if (modplug->reverb_depth)   settings.mReverbDepth   = modplug->reverb_depth;
202     if (modplug->reverb_delay)   settings.mReverbDelay   = modplug->reverb_delay;
203     if (modplug->bass_amount)    settings.mBassAmount    = modplug->bass_amount;
204     if (modplug->bass_range)     settings.mBassRange     = modplug->bass_range;
205     if (modplug->surround_depth) settings.mSurroundDepth = modplug->surround_depth;
206     if (modplug->surround_delay) settings.mSurroundDelay = modplug->surround_delay;
207
208     ModPlug_SetSettings(&settings);
209
210     modplug->f = ModPlug_Load(modplug->buf, sz);
211     if (!modplug->f)
212         return AVERROR_INVALIDDATA;
213
214     st = av_new_stream(s, 0);
215     if (!st)
216         return AVERROR(ENOMEM);
217     av_set_pts_info(st, 64, 1, 1000);
218     st->duration = ModPlug_GetLength(modplug->f);
219     st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
220     st->codec->codec_id    = CODEC_ID_PCM_S16LE;
221     st->codec->channels    = settings.mChannels;
222     st->codec->sample_rate = settings.mFrequency;
223
224     // timebase = 1/1000, 2ch 16bits 44.1kHz-> 2*2*44100
225     modplug->ts_per_packet = 1000*AUDIO_PKT_SIZE / (4*44100.);
226
227     if (modplug->video_stream) {
228         AVStream *vst = av_new_stream(s, 1);
229         if (!vst)
230             return AVERROR(ENOMEM);
231         av_set_pts_info(vst, 64, 1, 1000);
232         vst->duration = st->duration;
233         vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
234         vst->codec->codec_id   = CODEC_ID_XBIN;
235         vst->codec->width      = modplug->w << 3;
236         vst->codec->height     = modplug->h << 3;
237         modplug->linesize = modplug->w * 3;
238         modplug->fsize    = modplug->linesize * modplug->h;
239     }
240
241     return modplug_load_metadata(s);
242 }
243
244 static void write_text(uint8_t *dst, const char *s, int linesize, int x, int y)
245 {
246     int i;
247     dst += y*linesize + x*3;
248     for (i = 0; s[i]; i++, dst += 3) {
249         dst[0] = 0x0;   // count - 1
250         dst[1] = s[i];  // char
251         dst[2] = 0x0f;  // background / foreground
252     }
253 }
254
255 #define PRINT_INFO(line, name, idvalue) do {                            \
256     snprintf(intbuf, sizeof(intbuf), "%.0f", var_values[idvalue]);      \
257     write_text(pkt->data, name ":", modplug->linesize,  0+1, line+1);   \
258     write_text(pkt->data, intbuf,   modplug->linesize, 10+1, line+1);   \
259 } while (0)
260
261 static int modplug_read_packet(AVFormatContext *s, AVPacket *pkt)
262 {
263     ModPlugContext *modplug = s->priv_data;
264
265     if (modplug->video_stream) {
266         modplug->video_switch ^= 1; // one video packet for one audio packet
267         if (modplug->video_switch) {
268             double var_values[VAR_VARS_NB];
269
270             var_values[VAR_E      ] = M_E;
271             var_values[VAR_PHI    ] = M_PHI;
272             var_values[VAR_PI     ] = M_PI;
273             var_values[VAR_W      ] = modplug->w;
274             var_values[VAR_H      ] = modplug->h;
275             var_values[VAR_TIME   ] = modplug->packet_count * modplug->ts_per_packet;
276             var_values[VAR_SPEED  ] = ModPlug_GetCurrentSpeed  (modplug->f);
277             var_values[VAR_TEMPO  ] = ModPlug_GetCurrentTempo  (modplug->f);
278             var_values[VAR_ORDER  ] = ModPlug_GetCurrentOrder  (modplug->f);
279             var_values[VAR_PATTERN] = ModPlug_GetCurrentPattern(modplug->f);
280             var_values[VAR_ROW    ] = ModPlug_GetCurrentRow    (modplug->f);
281
282             if (av_new_packet(pkt, modplug->fsize) < 0)
283                 return AVERROR(ENOMEM);
284             pkt->stream_index = 1;
285             memset(pkt->data, 0, modplug->fsize);
286
287             if (modplug->print_textinfo) {
288                 char intbuf[32];
289                 PRINT_INFO(0, "speed",   VAR_SPEED);
290                 PRINT_INFO(1, "tempo",   VAR_TEMPO);
291                 PRINT_INFO(2, "order",   VAR_ORDER);
292                 PRINT_INFO(3, "pattern", VAR_PATTERN);
293                 PRINT_INFO(4, "row",     VAR_ROW);
294                 PRINT_INFO(5, "ts",      VAR_TIME);
295             }
296
297             if (modplug->color_eval && !modplug->eval_err) {
298                 int x, y;
299                 for (y = 0; y < modplug->h; y++) {
300                     for (x = 0; x < modplug->w; x++) {
301                         double color;
302
303                         var_values[VAR_X] = x;
304                         var_values[VAR_Y] = y;
305                         if (av_expr_parse_and_eval(&color, modplug->color_eval,
306                                                    var_names, var_values,
307                                                    NULL, NULL, NULL, NULL, NULL, 0, s) < 0) {
308                             av_log(s, AV_LOG_ERROR,
309                                    "Error while evaluating the expression '%s' with x=%d y=%d\n",
310                                    modplug->color_eval, x, y);
311                             modplug->eval_err = 1;
312                             return 0;
313                         }
314                         pkt->data[y*modplug->linesize + x*3 + 2] |= av_clip((int)color, 0, 0xf)<<4;
315                     }
316                 }
317             }
318             pkt->pts = pkt->dts = var_values[VAR_TIME];
319             pkt->flags |= AV_PKT_FLAG_KEY;
320             return 0;
321         }
322     }
323
324     if (av_new_packet(pkt, AUDIO_PKT_SIZE) < 0)
325         return AVERROR(ENOMEM);
326
327     if (modplug->video_stream)
328         pkt->pts = pkt->dts = modplug->packet_count++ * modplug->ts_per_packet;
329
330     pkt->size = ModPlug_Read(modplug->f, pkt->data, AUDIO_PKT_SIZE);
331     if (pkt->size <= 0) {
332         av_free_packet(pkt);
333         return pkt->size == 0 ? AVERROR_EOF : AVERROR(EIO);
334     }
335     return 0;
336 }
337
338 static int modplug_read_close(AVFormatContext *s)
339 {
340     ModPlugContext *modplug = s->priv_data;
341     ModPlug_Unload(modplug->f);
342     av_freep(&modplug->buf);
343     return 0;
344 }
345
346 static int modplug_read_seek(AVFormatContext *s, int stream_idx, int64_t ts, int flags)
347 {
348     ModPlugContext *modplug = s->priv_data;
349     ModPlug_Seek(modplug->f, (int)ts);
350     if (modplug->video_stream)
351         modplug->packet_count = ts / modplug->ts_per_packet;
352     return 0;
353 }
354
355 static const AVClass modplug_class = {
356     .class_name = "ModPlug demuxer",
357     .item_name  = av_default_item_name,
358     .option     = options,
359     .version    = LIBAVUTIL_VERSION_INT,
360 };
361
362 AVInputFormat ff_libmodplug_demuxer = {
363     .name           = "libmodplug",
364     .long_name      = NULL_IF_CONFIG_SMALL("ModPlug demuxer"),
365     .priv_data_size = sizeof(ModPlugContext),
366     .read_header    = modplug_read_header,
367     .read_packet    = modplug_read_packet,
368     .read_close     = modplug_read_close,
369     .read_seek      = modplug_read_seek,
370     .extensions     = "669,abc,amf,ams,dbm,dmf,dsm,far,it,mdl,med,mid,mod,mt2,mtm,okt,psm,ptm,s3m,stm,ult,umx,xm"
371                       ",itgz,itr,itz,mdgz,mdr,mdz,s3gz,s3r,s3z,xmgz,xmr,xmz", // compressed mods
372     .priv_class     = &modplug_class,
373 };