libmodplug.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. * @file
  20. * ModPlug demuxer
  21. * @todo better probing than extensions matching
  22. */
  23. #include <libmodplug/modplug.h>
  24. #include "libavutil/avstring.h"
  25. #include "libavutil/eval.h"
  26. #include "libavutil/opt.h"
  27. #include "avformat.h"
  28. typedef struct ModPlugContext {
  29. const AVClass *class;
  30. ModPlugFile *f;
  31. uint8_t *buf; ///< input file content
  32. /* options */
  33. int noise_reduction;
  34. int reverb_depth;
  35. int reverb_delay;
  36. int bass_amount;
  37. int bass_range;
  38. int surround_depth;
  39. int surround_delay;
  40. int max_size; ///< max file size to allocate
  41. /* optional video stream */
  42. double ts_per_packet; ///< used to define the pts/dts using packet_count;
  43. int packet_count; ///< total number of audio packets
  44. int print_textinfo; ///< bool flag for printing speed, tempo, order, ...
  45. int video_stream; ///< 1 if the user want a video stream, otherwise 0
  46. int w; ///< video stream width in char (one char = 8x8px)
  47. int h; ///< video stream height in char (one char = 8x8px)
  48. int video_switch; ///< 1 if current packet is video, otherwise 0
  49. int fsize; ///< constant frame size
  50. int linesize; ///< line size in bytes
  51. char *color_eval; ///< color eval user input expression
  52. AVExpr *expr; ///< parsed color eval expression
  53. } ModPlugContext;
  54. static const char *var_names[] = {
  55. "x", "y",
  56. "w", "h",
  57. "t",
  58. "speed", "tempo", "order", "pattern", "row",
  59. NULL
  60. };
  61. enum var_name {
  62. VAR_X, VAR_Y,
  63. VAR_W, VAR_H,
  64. VAR_TIME,
  65. VAR_SPEED, VAR_TEMPO, VAR_ORDER, VAR_PATTERN, VAR_ROW,
  66. VAR_VARS_NB
  67. };
  68. #define FF_MODPLUG_MAX_FILE_SIZE (100 * 1<<20) // 100M
  69. #define FF_MODPLUG_DEF_FILE_SIZE ( 5 * 1<<20) // 5M
  70. #define OFFSET(x) offsetof(ModPlugContext, x)
  71. #define D AV_OPT_FLAG_DECODING_PARAM
  72. static const AVOption options[] = {
  73. {"noise_reduction", "Enable noise reduction 0(off)-1(on)", OFFSET(noise_reduction), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 1, D},
  74. {"reverb_depth", "Reverb level 0(quiet)-100(loud)", OFFSET(reverb_depth), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 100, D},
  75. {"reverb_delay", "Reverb delay in ms, usually 40-200ms", OFFSET(reverb_delay), AV_OPT_TYPE_INT, {.dbl = 0}, 0, INT_MAX, D},
  76. {"bass_amount", "XBass level 0(quiet)-100(loud)", OFFSET(bass_amount), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 100, D},
  77. {"bass_range", "XBass cutoff in Hz 10-100", OFFSET(bass_range), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 100, D},
  78. {"surround_depth", "Surround level 0(quiet)-100(heavy)", OFFSET(surround_depth), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 100, D},
  79. {"surround_delay", "Surround delay in ms, usually 5-40ms", OFFSET(surround_delay), AV_OPT_TYPE_INT, {.dbl = 0}, 0, INT_MAX, D},
  80. {"max_size", "Max file size supported (in bytes). Default is 5MB. Set to 0 for no limit (not recommended)",
  81. OFFSET(max_size), AV_OPT_TYPE_INT, {.dbl = FF_MODPLUG_DEF_FILE_SIZE}, 0, FF_MODPLUG_MAX_FILE_SIZE, D},
  82. {"video_stream_expr", "Color formula", OFFSET(color_eval), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, D},
  83. {"video_stream", "Make demuxer output a video stream", OFFSET(video_stream), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 1, D},
  84. {"video_stream_w", "Video stream width in char (one char = 8x8px)", OFFSET(w), AV_OPT_TYPE_INT, {.dbl = 30}, 20, 512, D},
  85. {"video_stream_h", "Video stream height in char (one char = 8x8px)", OFFSET(h), AV_OPT_TYPE_INT, {.dbl = 30}, 20, 512, D},
  86. {"video_stream_ptxt", "Print speed, tempo, order, ... in video stream", OFFSET(print_textinfo), AV_OPT_TYPE_INT, {.dbl = 1}, 0, 1, D},
  87. {NULL},
  88. };
  89. #define SET_OPT_IF_REQUESTED(libopt, opt, flag) do { \
  90. if (modplug->opt) { \
  91. settings.libopt = modplug->opt; \
  92. settings.mFlags |= flag; \
  93. } \
  94. } while (0)
  95. #define ADD_META_MULTIPLE_ENTRIES(entry_name, fname) do { \
  96. if (n_## entry_name ##s) { \
  97. unsigned i, n = 0; \
  98. \
  99. for (i = 0; i < n_## entry_name ##s; i++) { \
  100. char item_name[64] = {0}; \
  101. fname(f, i, item_name); \
  102. if (!*item_name) \
  103. continue; \
  104. if (n) \
  105. av_dict_set(&s->metadata, #entry_name, "\n", AV_DICT_APPEND); \
  106. av_dict_set(&s->metadata, #entry_name, item_name, AV_DICT_APPEND); \
  107. n++; \
  108. } \
  109. \
  110. extra = av_asprintf(", %u/%u " #entry_name "%s", \
  111. n, n_## entry_name ##s, n > 1 ? "s" : ""); \
  112. if (!extra) \
  113. return AVERROR(ENOMEM); \
  114. av_dict_set(&s->metadata, "extra info", extra, AV_DICT_APPEND); \
  115. av_free(extra); \
  116. } \
  117. } while (0)
  118. static int modplug_load_metadata(AVFormatContext *s)
  119. {
  120. ModPlugContext *modplug = s->priv_data;
  121. ModPlugFile *f = modplug->f;
  122. char *extra;
  123. const char *name = ModPlug_GetName(f);
  124. const char *msg = ModPlug_GetMessage(f);
  125. unsigned n_instruments = ModPlug_NumInstruments(f);
  126. unsigned n_samples = ModPlug_NumSamples(f);
  127. unsigned n_patterns = ModPlug_NumPatterns(f);
  128. unsigned n_channels = ModPlug_NumChannels(f);
  129. if (name && *name) av_dict_set(&s->metadata, "name", name, 0);
  130. if (msg && *msg) av_dict_set(&s->metadata, "message", msg, 0);
  131. extra = av_asprintf("%u pattern%s, %u channel%s",
  132. n_patterns, n_patterns > 1 ? "s" : "",
  133. n_channels, n_channels > 1 ? "s" : "");
  134. if (!extra)
  135. return AVERROR(ENOMEM);
  136. av_dict_set(&s->metadata, "extra info", extra, AV_DICT_DONT_STRDUP_VAL);
  137. ADD_META_MULTIPLE_ENTRIES(instrument, ModPlug_InstrumentName);
  138. ADD_META_MULTIPLE_ENTRIES(sample, ModPlug_SampleName);
  139. return 0;
  140. }
  141. #define AUDIO_PKT_SIZE 512
  142. static int modplug_read_header(AVFormatContext *s, AVFormatParameters *ap)
  143. {
  144. AVStream *st;
  145. AVIOContext *pb = s->pb;
  146. ModPlug_Settings settings;
  147. ModPlugContext *modplug = s->priv_data;
  148. int sz = avio_size(pb);
  149. if (sz < 0) {
  150. av_log(s, AV_LOG_WARNING, "Could not determine file size\n");
  151. sz = modplug->max_size;
  152. } else if (modplug->max_size && sz > modplug->max_size) {
  153. sz = modplug->max_size;
  154. av_log(s, AV_LOG_WARNING, "Max file size reach%s, allocating %dB "
  155. "but demuxing is likely to fail due to incomplete buffer\n",
  156. sz == FF_MODPLUG_DEF_FILE_SIZE ? " (see -max_size)" : "", sz);
  157. }
  158. if (modplug->color_eval) {
  159. int r = av_expr_parse(&modplug->expr, modplug->color_eval, var_names,
  160. NULL, NULL, NULL, NULL, 0, s);
  161. if (r < 0)
  162. return r;
  163. }
  164. modplug->buf = av_malloc(modplug->max_size);
  165. if (!modplug->buf)
  166. return AVERROR(ENOMEM);
  167. sz = avio_read(pb, modplug->buf, sz);
  168. ModPlug_GetSettings(&settings);
  169. settings.mChannels = 2;
  170. settings.mBits = 16;
  171. settings.mFrequency = 44100;
  172. settings.mResamplingMode = MODPLUG_RESAMPLE_FIR; // best quality
  173. settings.mLoopCount = 0; // prevents looping forever
  174. if (modplug->noise_reduction) settings.mFlags |= MODPLUG_ENABLE_NOISE_REDUCTION;
  175. SET_OPT_IF_REQUESTED(mReverbDepth, reverb_depth, MODPLUG_ENABLE_REVERB);
  176. SET_OPT_IF_REQUESTED(mReverbDelay, reverb_delay, MODPLUG_ENABLE_REVERB);
  177. SET_OPT_IF_REQUESTED(mBassAmount, bass_amount, MODPLUG_ENABLE_MEGABASS);
  178. SET_OPT_IF_REQUESTED(mBassRange, bass_range, MODPLUG_ENABLE_MEGABASS);
  179. SET_OPT_IF_REQUESTED(mSurroundDepth, surround_depth, MODPLUG_ENABLE_SURROUND);
  180. SET_OPT_IF_REQUESTED(mSurroundDelay, surround_delay, MODPLUG_ENABLE_SURROUND);
  181. if (modplug->reverb_depth) settings.mReverbDepth = modplug->reverb_depth;
  182. if (modplug->reverb_delay) settings.mReverbDelay = modplug->reverb_delay;
  183. if (modplug->bass_amount) settings.mBassAmount = modplug->bass_amount;
  184. if (modplug->bass_range) settings.mBassRange = modplug->bass_range;
  185. if (modplug->surround_depth) settings.mSurroundDepth = modplug->surround_depth;
  186. if (modplug->surround_delay) settings.mSurroundDelay = modplug->surround_delay;
  187. ModPlug_SetSettings(&settings);
  188. modplug->f = ModPlug_Load(modplug->buf, sz);
  189. if (!modplug->f)
  190. return AVERROR_INVALIDDATA;
  191. st = av_new_stream(s, 0);
  192. if (!st)
  193. return AVERROR(ENOMEM);
  194. av_set_pts_info(st, 64, 1, 1000);
  195. st->duration = ModPlug_GetLength(modplug->f);
  196. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  197. st->codec->codec_id = CODEC_ID_PCM_S16LE;
  198. st->codec->channels = settings.mChannels;
  199. st->codec->sample_rate = settings.mFrequency;
  200. // timebase = 1/1000, 2ch 16bits 44.1kHz-> 2*2*44100
  201. modplug->ts_per_packet = 1000*AUDIO_PKT_SIZE / (4*44100.);
  202. if (modplug->video_stream) {
  203. AVStream *vst = av_new_stream(s, 1);
  204. if (!vst)
  205. return AVERROR(ENOMEM);
  206. av_set_pts_info(vst, 64, 1, 1000);
  207. vst->duration = st->duration;
  208. vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  209. vst->codec->codec_id = CODEC_ID_XBIN;
  210. vst->codec->width = modplug->w << 3;
  211. vst->codec->height = modplug->h << 3;
  212. modplug->linesize = modplug->w * 3;
  213. modplug->fsize = modplug->linesize * modplug->h;
  214. }
  215. return modplug_load_metadata(s);
  216. }
  217. static void write_text(uint8_t *dst, const char *s, int linesize, int x, int y)
  218. {
  219. int i;
  220. dst += y*linesize + x*3;
  221. for (i = 0; s[i]; i++, dst += 3) {
  222. dst[0] = 0x0; // count - 1
  223. dst[1] = s[i]; // char
  224. dst[2] = 0x0f; // background / foreground
  225. }
  226. }
  227. #define PRINT_INFO(line, name, idvalue) do { \
  228. snprintf(intbuf, sizeof(intbuf), "%.0f", var_values[idvalue]); \
  229. write_text(pkt->data, name ":", modplug->linesize, 0+1, line+1); \
  230. write_text(pkt->data, intbuf, modplug->linesize, 10+1, line+1); \
  231. } while (0)
  232. static int modplug_read_packet(AVFormatContext *s, AVPacket *pkt)
  233. {
  234. ModPlugContext *modplug = s->priv_data;
  235. if (modplug->video_stream) {
  236. modplug->video_switch ^= 1; // one video packet for one audio packet
  237. if (modplug->video_switch) {
  238. double var_values[VAR_VARS_NB];
  239. var_values[VAR_W ] = modplug->w;
  240. var_values[VAR_H ] = modplug->h;
  241. var_values[VAR_TIME ] = modplug->packet_count * modplug->ts_per_packet;
  242. var_values[VAR_SPEED ] = ModPlug_GetCurrentSpeed (modplug->f);
  243. var_values[VAR_TEMPO ] = ModPlug_GetCurrentTempo (modplug->f);
  244. var_values[VAR_ORDER ] = ModPlug_GetCurrentOrder (modplug->f);
  245. var_values[VAR_PATTERN] = ModPlug_GetCurrentPattern(modplug->f);
  246. var_values[VAR_ROW ] = ModPlug_GetCurrentRow (modplug->f);
  247. if (av_new_packet(pkt, modplug->fsize) < 0)
  248. return AVERROR(ENOMEM);
  249. pkt->stream_index = 1;
  250. memset(pkt->data, 0, modplug->fsize);
  251. if (modplug->print_textinfo) {
  252. char intbuf[32];
  253. PRINT_INFO(0, "speed", VAR_SPEED);
  254. PRINT_INFO(1, "tempo", VAR_TEMPO);
  255. PRINT_INFO(2, "order", VAR_ORDER);
  256. PRINT_INFO(3, "pattern", VAR_PATTERN);
  257. PRINT_INFO(4, "row", VAR_ROW);
  258. PRINT_INFO(5, "ts", VAR_TIME);
  259. }
  260. if (modplug->expr) {
  261. int x, y;
  262. for (y = 0; y < modplug->h; y++) {
  263. for (x = 0; x < modplug->w; x++) {
  264. double color;
  265. var_values[VAR_X] = x;
  266. var_values[VAR_Y] = y;
  267. color = av_expr_eval(modplug->expr, var_values, NULL);
  268. pkt->data[y*modplug->linesize + x*3 + 2] |= av_clip((int)color, 0, 0xf)<<4;
  269. }
  270. }
  271. }
  272. pkt->pts = pkt->dts = var_values[VAR_TIME];
  273. pkt->flags |= AV_PKT_FLAG_KEY;
  274. return 0;
  275. }
  276. }
  277. if (av_new_packet(pkt, AUDIO_PKT_SIZE) < 0)
  278. return AVERROR(ENOMEM);
  279. if (modplug->video_stream)
  280. pkt->pts = pkt->dts = modplug->packet_count++ * modplug->ts_per_packet;
  281. pkt->size = ModPlug_Read(modplug->f, pkt->data, AUDIO_PKT_SIZE);
  282. if (pkt->size <= 0) {
  283. av_free_packet(pkt);
  284. return pkt->size == 0 ? AVERROR_EOF : AVERROR(EIO);
  285. }
  286. return 0;
  287. }
  288. static int modplug_read_close(AVFormatContext *s)
  289. {
  290. ModPlugContext *modplug = s->priv_data;
  291. ModPlug_Unload(modplug->f);
  292. av_freep(&modplug->buf);
  293. return 0;
  294. }
  295. static int modplug_read_seek(AVFormatContext *s, int stream_idx, int64_t ts, int flags)
  296. {
  297. ModPlugContext *modplug = s->priv_data;
  298. ModPlug_Seek(modplug->f, (int)ts);
  299. if (modplug->video_stream)
  300. modplug->packet_count = ts / modplug->ts_per_packet;
  301. return 0;
  302. }
  303. static const AVClass modplug_class = {
  304. .class_name = "ModPlug demuxer",
  305. .item_name = av_default_item_name,
  306. .option = options,
  307. .version = LIBAVUTIL_VERSION_INT,
  308. };
  309. AVInputFormat ff_libmodplug_demuxer = {
  310. .name = "libmodplug",
  311. .long_name = NULL_IF_CONFIG_SMALL("ModPlug demuxer"),
  312. .priv_data_size = sizeof(ModPlugContext),
  313. .read_header = modplug_read_header,
  314. .read_packet = modplug_read_packet,
  315. .read_close = modplug_read_close,
  316. .read_seek = modplug_read_seek,
  317. .extensions = "669,abc,amf,ams,dbm,dmf,dsm,far,it,mdl,med,mid,mod,mt2,mtm,okt,psm,ptm,s3m,stm,ult,umx,xm"
  318. ",itgz,itr,itz,mdgz,mdr,mdz,s3gz,s3r,s3z,xmgz,xmr,xmz", // compressed mods
  319. .priv_class = &modplug_class,
  320. };