You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

374 lines
16KB

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