summaryrefslogtreecommitdiff
path: root/apps/plugins/lua/rocklua.c
blob: 00bfd8e43e87c7d1e8d1197f0aeb1c5c9c358656 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2008 Dan Everton (safetydan)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/

#include "plugin.h"
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "rocklib.h"
#include "rockmalloc.h"
#include "luadir.h"



static const luaL_Reg lualibs[] = {
  {"",              luaopen_base},
  {LUA_TABLIBNAME,  luaopen_table},
  {LUA_STRLIBNAME,  luaopen_string},
  {LUA_OSLIBNAME,   luaopen_os},
  {LUA_ROCKLIBNAME, luaopen_rock},
  {LUA_BITLIBNAME,  luaopen_bit},
  {LUA_IOLIBNAME,   luaopen_io},
  {LUA_LOADLIBNAME, luaopen_package},
  {LUA_MATHLIBNAME, luaopen_math},
  {LUA_DIRLIBNAME,  luaopen_luadir},
  {NULL, NULL}
};

static void rocklua_openlibs(lua_State *L) {
  const luaL_Reg *lib = lualibs;
  for (; lib->func; lib++) {
    lua_pushcfunction(L, lib->func);
    lua_pushstring(L, lib->name);
    lua_call(L, 1, 0);
  }
}

/* ldlib.c */
static lua_State *getthread (lua_State *L, int *arg) {
  if (lua_isthread(L, 1)) {
    *arg = 1;
    return lua_tothread(L, 1);
  }
  else {
    *arg = 0;
    return L;
  }
}

#define LEVELS1 12      /* size of the first part of the stack */
#define LEVELS2 10      /* size of the second part of the stack */

static int db_errorfb (lua_State *L) {
  int level;
  int firstpart = 1;  /* still before eventual `...' */
  int arg;
  lua_State *L1 = getthread(L, &arg);
  lua_Debug ar;
  if (lua_isnumber(L, arg+2)) {
    level = (int)lua_tointeger(L, arg+2);
    lua_pop(L, 1);
  }
  else
    level = (L == L1) ? 1 : 0;  /* level 0 may be this own function */
  if (lua_gettop(L) == arg)
    lua_pushliteral(L, "");
  else if (!lua_isstring(L, arg+1)) return 1;  /* message is not a string */
  else lua_pushliteral(L, "\n");
  lua_pushliteral(L, "stack traceback:");
  while (lua_getstack(L1, level++, &ar)) {
    if (level > LEVELS1 && firstpart) {
      /* no more than `LEVELS2' more levels? */
      if (!lua_getstack(L1, level+LEVELS2, &ar))
        level--;  /* keep going */
      else {
        lua_pushliteral(L, "\n\t...");  /* too many levels */
        while (lua_getstack(L1, level+LEVELS2, &ar))  /* find last levels */
          level++;
      }
      firstpart = 0;
      continue;
    }
    lua_pushliteral(L, "\n\t");
    lua_getinfo(L1, "Snl", &ar);
    lua_pushfstring(L, "%s:", ar.short_src);
    if (ar.currentline > 0)
      lua_pushfstring(L, "%d:", ar.currentline);
    if (*ar.namewhat != '\0')  /* is there a name? */
        lua_pushfstring(L, " in function " LUA_QS, ar.name);
    else {
      if (*ar.what == 'm')  /* main? */
        lua_pushfstring(L, " in main chunk");
      else if (*ar.what == 'C' || *ar.what == 't')
        lua_pushliteral(L, " ?");  /* C function or tail call */
      else
        lua_pushfstring(L, " in function <%s:%d>",
                           ar.short_src, ar.linedefined);
    }
    lua_concat(L, lua_gettop(L) - arg);
  }
  lua_concat(L, lua_gettop(L) - arg);
  return 1;
}

/* lua.c */
static int traceback (lua_State *L) {
  lua_pushcfunction(L, db_errorfb);
  lua_pushvalue(L, 1);  /* pass error message */
  lua_pushinteger(L, 2);  /* skip this function and traceback */
  lua_call(L, 2, 1);  /* call debug.traceback */
  return 1;
}

static int docall (lua_State *L) {
  int status;
  int base = lua_gettop(L);  /* function index */
  lua_pushcfunction(L, traceback);  /* push traceback function */
  lua_insert(L, base);  /* put it under chunk and args */
  status = lua_pcall(L, 0, 0, base);
  lua_remove(L, base);  /* remove traceback function */
  /* force a complete garbage collection in case of errors */
  if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
  return status;
}


/***************** Plugin Entry Point *****************/
enum plugin_status plugin_start(const void* parameter)
{
    const char* filename;
    int status;

    if (parameter == NULL)
    {
        rb->splash(HZ, "Play a .lua file!");
        return PLUGIN_ERROR;
    }
    else
    {
        filename = (char*) parameter;

        lua_State *L = luaL_newstate();

        rocklua_openlibs(L);
        status = luaL_loadfile(L, filename);
        if (!status) {
            rb->lcd_clear_display();
            status = docall(L);
        }

        dlmalloc_stats();

        if (status) {
            DEBUGF("%s\n", lua_tostring(L, -1));
            rb->splashf(5 * HZ, "%s", lua_tostring(L, -1));
            lua_pop(L, 1);
        }

        lua_close(L);
    }

    return PLUGIN_OK;
}

849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * MOD Codec for rockbox
 *
 * Written from scratch by Rainer Sinsch
 *         exclusivly for Rockbox in February 2008
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/

 /**************
  * This version supports large files directly from internal memory management.
  * There is a drawback however: It may happen that a song is not completely
  * loaded when the internal rockbox-ringbuffer (approx. 28MB) is filled up
  * As a workaround make sure you don't have directories with mods larger
  * than a total of 28MB
  *************/

#include "debug.h"
#include "codeclib.h"
#include <inttypes.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>


CODEC_HEADER

#define CHUNK_SIZE (1024*2)


/* This codec supports MOD Files:
 *
 */

static int32_t samples[CHUNK_SIZE] IBSS_ATTR;   /* The sample buffer */

/* Instrument Data */
struct s_instrument {
    /* Sample name / description */
    /*char description[22];*/

    /* Sample length in bytes */
    unsigned short length;

    /* Sample finetuning (-8 - +7) */
    signed char finetune;

    /* Sample volume (0 - 64) */
    signed char volume;

    /* Sample Repeat Position */
    unsigned short repeatoffset;

    /* Sample Repeat Length  */
    unsigned short repeatlength;

    /* Offset to sample data */
    unsigned int sampledataoffset;
};

/* Song Data */
struct s_song {
    /* Song name / title description */
    /*char szTitle[20];*/

    /* No. of channels in song */
    unsigned char noofchannels;

    /* No. of instruments used (either 15 or 31) */
    unsigned char noofinstruments;

    /* How many patterns are beeing played? */
    unsigned char songlength;

    /* Where to jump after the song end? */
    unsigned char songendjumpposition;

    /* Pointer to the Pattern Order Table */
    unsigned char *patternordertable;

    /* Pointer to the pattern data  */
    void *patterndata;

    /* Pointer to the sample buffer */
    signed char *sampledata;

    /* Instrument data  */
    struct s_instrument instrument[31];
};

struct s_modchannel {
    /* Current Volume */
    signed char volume;

    /* Current Offset to period in PeriodTable of notebeeing played
       (can be temporarily negative) */
    short periodtableoffset;

    /* Current Period beeing played */
    short period;

    /* Current effect */
    unsigned char effect;

    /* Current parameters of effect */
    unsigned char effectparameter;

    /* Current Instrument beeing played */
    unsigned char instrument;

    /* Current Vibrato Speed */
    unsigned char vibratospeed;

    /* Current Vibrato Depth */
    unsigned char vibratodepth;

    /* Current Position for Vibrato in SinTable */
    unsigned char vibratosinpos;

    /* Current Tremolo Speed */
    unsigned char tremolospeed;

    /* Current Tremolo Depth */
    unsigned char tremolodepth;

    /* Current Position for Tremolo in SinTable */
    unsigned char tremolosinpos;

    /* Current Speed of Effect "Slide Note up" */
    unsigned char slideupspeed;

    /* Current Speed of Effect "Slide Note down" */
    unsigned char slidedownspeed;

    /* Current Speed of the "Slide to Note" effect */
    unsigned char slidetonotespeed;

    /* Current Period of the "Slide to Note" effect */
    unsigned short slidetonoteperiod;
};

struct s_modplayer {
    /* Ticks per Line */
    unsigned char ticksperline;

    /* Beats per Minute */
    unsigned char bpm;

    /* Position of the Song in the Pattern Table (0-127) */
    unsigned char patterntableposition;

    /* Current Line (may be temporarily < 0) */
    signed char currentline;

    /* Current Tick */
    signed char currenttick;

    /* How many samples are required to calculate for each tick? */
    unsigned int samplespertick;

    /* Information about the channels */
    struct s_modchannel modchannel[8];

    /* The Amiga Period Table
       (+1 because we use index 0 for period 0 = no new note) */
    unsigned short periodtable[37*8+1];

    /* The sinus table [-255,255] */
    signed short sintable[0x40];

    /* Is the glissando effect enabled? */
    bool glissandoenabled;

    /* Is the Amiga Filter enabled? */
    bool amigafilterenabled;

    /* The pattern-line where the loop is carried out (set with e6 command) */
    unsigned char loopstartline;

    /* Number of times to loop */
    unsigned char looptimes;
};

struct s_channel {
    /* Panning (0 = left, 16 = right) */
    unsigned char panning;

    /* Sample frequency of the channel */
    unsigned short frequency;

    /* Position of the sample currently played */
    unsigned int samplepos;

    /* Fractual Position of the sample currently player */
    unsigned int samplefractpos;

    /* Loop Sample */
    bool loopsample;

    /* Loop Position Start */
    unsigned int loopstart;

    /* Loop Position End */
    unsigned int loopend;

    /* Is The channel beeing played? */
    bool channelactive;

    /* The Volume (0..64) */
    signed char volume;

    /* The last sampledata beeing played (required for interpolation) */
    signed short lastsampledata;
};

struct s_mixer {
    /* The channels */
    struct s_channel channel[32];
};

struct s_song modsong IDATA_ATTR;               /* The Song */
struct s_modplayer modplayer IDATA_ATTR;        /* The Module Player */
struct s_mixer mixer IDATA_ATTR;

const unsigned short mixingrate = 44100;

STATICIRAM void mixer_playsample(int channel, int instrument) ICODE_ATTR;
void mixer_playsample(int channel, int instrument)
{
    struct s_channel *p_channel = &mixer.channel[channel];
    struct s_instrument *p_instrument = &modsong.instrument[instrument];

    p_channel->channelactive = true;
    p_channel->samplepos = p_instrument->sampledataoffset;
    p_channel->samplefractpos = 0;
    p_channel->loopsample = (p_instrument->repeatlength > 2) ? true : false;
    if (p_channel->loopsample) {
        p_channel->loopstart = p_instrument->repeatoffset +
            p_instrument->sampledataoffset;
        p_channel->loopend = p_channel->loopstart +
            p_instrument->repeatlength;
    }
    else p_channel->loopend = p_instrument->length +
            p_instrument->sampledataoffset;

    /* Remember the instrument */
    modplayer.modchannel[channel].instrument = instrument;
}

inline void mixer_stopsample(int channel)
{
    mixer.channel[channel].channelactive = false;
}

inline void mixer_continuesample(int channel)
{
    mixer.channel[channel].channelactive = true;
}

inline void mixer_setvolume(int channel, int volume)
{
    mixer.channel[channel].volume = volume;
}

inline void mixer_setpanning(int channel, int panning)
{
    mixer.channel[channel].panning = panning;
}

inline void mixer_setamigaperiod(int channel, int amigaperiod)
{
    /* Just to make sure we don't devide by zero
     * amigaperiod shouldn't 0 anyway - if it is the case
     * then something terribly went wrong */
    if (amigaperiod == 0)
        return;

    mixer.channel[channel].frequency = 3579546 / amigaperiod;
}

/* Initialize the MOD Player with default values and precalc tables */
STATICIRAM void initmodplayer(void) ICODE_ATTR;
void initmodplayer(void)
{
    unsigned int i,c;

    /* Calculate Amiga Period Values
     * Start with Period 907 (= C-1 with Finetune -8) and work upwards */
    double f = 907.0f;
    /* Index 0 stands for no note (and therefore no period) */
    modplayer.periodtable[0] = 0;
    for (i=1;i<297;i++)
    {
        modplayer.periodtable[i] = (unsigned short) f;
        f /= 1.0072464122237039; /* = pow(2.0f, 1.0f/(12.0f*8.0f)); */
    }

    /*
     * This is a more accurate but also time more consuming approach
     * to calculate the amiga period table
     * Commented out for speed purposes
    const int finetuning = 8;
    const int octaves = 3;
    for (int halftone=0;halftone<=finetuning*octaves*12+7;halftone++)
        {
            float e = pow(2.0f, halftone/(12.0f*8.0f));
            float f = 906.55f/e;
            modplayer.periodtable[halfetone+1] = (int)(f+0.5f);
        }
    */

    /* Calculate Protracker Vibrato sine table
     * The routine makes use of the Harmonical Oscillator Approach
     * for calculating sine tables
     * (see http://membres.lycos.fr/amycoders/tutorials/sintables.html)
     * The routine presented here calculates a complete sine wave
     * with 64 values in range [-255,255]
     */
    float a, b, d, dd;

    d = 0.09817475f; /* = 2*PI/64 */
    dd = d*d;
    a = 0;
    b = d;

    for (i=0;i<0x40;i++)
    {
        modplayer.sintable[i] = (int)(255*a);

        a = a+b;
        b = b-dd*a;
    }

    /* Set Default Player Values */
    modplayer.currentline = 0;
    modplayer.currenttick = 0;
    modplayer.patterntableposition = 0;
    modplayer.bpm = 125;
    modplayer.ticksperline = 6;
    modplayer.glissandoenabled = false;         /* Disable glissando */
    modplayer.amigafilterenabled = false;       /* Disable the Amiga Filter */

    /* Default Panning Values */
    int panningvalues[8] = {4,12,12,4,4,12,12,4};
    for (c=0;c<8;c++)
    {
        /* Set Default Panning */
        mixer_setpanning(c, panningvalues[c]);
        /* Reset channels in the MOD Player */
        memset(&modplayer.modchannel[c], 0, sizeof(struct s_modchannel));
        /* Don't play anything */
        mixer.channel[c].channelactive = false;
    }

}

/* Load the MOD File from memory */
STATICIRAM bool loadmod(void *modfile) ICODE_ATTR;
bool loadmod(void *modfile)
{
    int i;
    unsigned char *periodsconverted;

    /* We don't support PowerPacker 2.0 Files */
    if (memcmp((char*) modfile, "PP20", 4) == 0) return false;

    /* Get the File Format Tag */
    char *fileformattag = (char*)modfile + 1080;

    /* Find out how many channels and instruments are used */
    if (memcmp(fileformattag, "2CHN", 4) == 0)
        {modsong.noofchannels = 2; modsong.noofinstruments = 31;}
    else if (memcmp(fileformattag, "M.K.", 4) == 0)
        {modsong.noofchannels = 4; modsong.noofinstruments = 31;}
    else if (memcmp(fileformattag, "M!K!", 4) == 0)
        {modsong.noofchannels = 4; modsong.noofinstruments = 31;}
    else if (memcmp(fileformattag, "4CHN", 4) == 0)
        {modsong.noofchannels = 4; modsong.noofinstruments = 31;}
    else if (memcmp(fileformattag, "FLT4", 4) == 0)
        {modsong.noofchannels = 4; modsong.noofinstruments = 31;}
    else if (memcmp(fileformattag, "6CHN", 4) == 0)
        {modsong.noofchannels = 6; modsong.noofinstruments = 31;}
    else if (memcmp(fileformattag, "8CHN", 4) == 0)
        {modsong.noofchannels = 8; modsong.noofinstruments = 31;}
    else if (memcmp(fileformattag, "OKTA", 4) == 0)
        {modsong.noofchannels = 8; modsong.noofinstruments = 31;}
    else if (memcmp(fileformattag, "CD81", 4) == 0)
        {modsong.noofchannels = 8; modsong.noofinstruments = 31;}
    else {
        /* The file has no format tag, so most likely soundtracker */
        modsong.noofchannels = 4;
        modsong.noofinstruments = 15;
    }

    /* Get the Song title
     * Skipped here
     * strncpy(modsong.szTitle, (char*)pMODFile, 20); */

    /* Get the Instrument information */
    for (i=0;i<modsong.noofinstruments;i++)
    {
        struct s_instrument *instrument = &modsong.instrument[i];
        unsigned char *p = (unsigned char *)modfile + 20 + i*30;

        /*strncpy(instrument->description, (char*)p, 22); */
        p += 22;
        instrument->length = (((p[0])<<8) + p[1]) << 1; p+=2;
        instrument->finetune = *p++ & 0x0f;
        /* Treat finetuning as signed nibble */
        if (instrument->finetune > 7) instrument->finetune -= 16;
        instrument->volume = *p++;
        instrument->repeatoffset = (((p[0])<<8) + p[1]) << 1; p+= 2;
        instrument->repeatlength = (((p[0])<<8) + p[1]) << 1;
    }

    /* Get the pattern information */
    unsigned char *p = (unsigned char *)modfile + 20 +
        modsong.noofinstruments*30;
    modsong.songlength = *p++;
    modsong.songendjumpposition = *p++;
    modsong.patternordertable = p;

    /* Find out how many patterns are used within this song */
    int maxpatterns = 0;
    for (i=0;i<128;i++)
        if (modsong.patternordertable[i] > maxpatterns)
            maxpatterns = modsong.patternordertable[i];
    maxpatterns++;

    /* use 'restartposition' (historically set to 127) which is not used here
       as a marker that periods have already been converted */
       
    periodsconverted = (char*)modfile + 20 + modsong.noofinstruments*30 + 1; 

    /* Get the pattern data; ST doesn't have fileformattag, so 4 bytes less */
    modsong.patterndata = periodsconverted + 
                          (modsong.noofinstruments==15 ? 129 : 133); 
 
    /* Convert the period values in the mod file to offsets
     * in our periodtable (but only, if we haven't done this yet) */
    p = (unsigned char *) modsong.patterndata;
    if (*periodsconverted != 0xfe)
    {
        int note, note2, channel;
        for (note=0;note<maxpatterns*64;note++)
            for (channel=0;channel<modsong.noofchannels;channel++)
            {
                int period = ((p[0] & 0x0f) << 8) | p[1];
                int periodoffset = 0;

                /* Find the offset of the current period */
                for (note2 = 1; note2 < 12*3+1; note2++)
                    if (abs(modplayer.periodtable[note2*8+1]-period) < 4)
                    {
                        periodoffset = note2*8+1;
                        break;
                    }
                /* Write back the period offset */
                p[0] = (periodoffset >> 8) | (p[0] & 0xf0);
                p[1] = periodoffset & 0xff;
                p += 4;
            }
        /* Remember that we already converted the periods,
         * in case the file gets reloaded by rewinding 
         * with 0xfe (arbitary magic value > 127) */
        *periodsconverted = 0xfe;  
    }

    /* Get the samples
     * Calculation: The Samples come after the pattern data
     * We know that there are nMaxPatterns and each pattern requires
     * 4 bytes per note and per channel.
     * And of course there are always lines in each channel */
    modsong.sampledata = (signed char*) modsong.patterndata +
                          maxpatterns*4*modsong.noofchannels*64;
    int sampledataoffset = 0;
    for (i=0;i<modsong.noofinstruments;i++)
    {
        modsong.instrument[i].sampledataoffset = sampledataoffset;
        sampledataoffset += modsong.instrument[i].length;
    }

    return true;
}

/* Apply vibrato to channel */
STATICIRAM void vibrate(int channel) ICODE_ATTR;
void vibrate(int channel)
{
    struct s_modchannel *p_modchannel = &modplayer.modchannel[channel];

    /* Apply Vibrato
     * >> 7 is used in the original protracker source code */
    mixer_setamigaperiod(channel, p_modchannel->period+
        ((p_modchannel->vibratodepth *
        modplayer.sintable[p_modchannel->vibratosinpos])>>7));

    /* Foward in Sine Table */
    p_modchannel->vibratosinpos += p_modchannel->vibratospeed;
    p_modchannel->vibratosinpos &= 0x3f;
}

/* Apply tremolo to channel
 * (same as vibrato, but only apply on volume instead of pitch) */
STATICIRAM void tremolo(int channel) ICODE_ATTR;
void tremolo(int channel)
{
    struct s_modchannel *p_modchannel = &modplayer.modchannel[channel];

    /* Apply Tremolo
     * >> 6 is used in the original protracker source code */
    int volume = (p_modchannel->volume *
        modplayer.sintable[p_modchannel->tremolosinpos])>>6;
    if (volume > 64) volume = 64;
    else if (volume < 0) volume = 0;
    mixer_setvolume(channel, volume);

    /* Foward in Sine Table */
    p_modchannel->tremolosinpos += p_modchannel->tremolosinpos;
    p_modchannel->tremolosinpos &= 0x3f;
}

/* Apply Slide to Note effect to channel */
STATICIRAM void slidetonote(int channel) ICODE_ATTR;
void slidetonote(int channel)
{
    struct s_modchannel *p_modchannel = &modplayer.modchannel[channel];

    /* If there hasn't been any slide-to note set up, then return */
    if (p_modchannel->slidetonoteperiod == 0) return;

    /* Slide note up */
    if (p_modchannel->slidetonoteperiod > p_modchannel->period)
    {
        p_modchannel->period += p_modchannel->slidetonotespeed;
        if (p_modchannel->period > p_modchannel->slidetonoteperiod)
            p_modchannel->period = p_modchannel->slidetonoteperiod;
    }
    /* Slide note down */
    else if (p_modchannel->slidetonoteperiod < p_modchannel->period)
    {
        p_modchannel->period -= p_modchannel->slidetonotespeed;
        if (p_modchannel->period < p_modchannel->slidetonoteperiod)
            p_modchannel->period = p_modchannel->slidetonoteperiod;
    }
    mixer_setamigaperiod(channel, p_modchannel->period);
}

/* Apply Slide to Note effect on channel,
 * but this time with glissando enabled */
STATICIRAM void slidetonoteglissando(int channel) ICODE_ATTR;
void slidetonoteglissando(int channel)
{
    struct s_modchannel *p_modchannel = &modplayer.modchannel[channel];

    /* Slide note up */
    if (p_modchannel->slidetonoteperiod > p_modchannel->period)
    {
        p_modchannel->period =
            modplayer.periodtable[p_modchannel->periodtableoffset+=8];
        if (p_modchannel->period > p_modchannel->slidetonoteperiod)
            p_modchannel->period = p_modchannel->slidetonoteperiod;
    }
    /* Slide note down */
    else
    {
        p_modchannel->period =
            modplayer.periodtable[p_modchannel->periodtableoffset-=8];
        if (p_modchannel->period < p_modchannel->slidetonoteperiod)
            p_modchannel->period = p_modchannel->slidetonoteperiod;
    }
    mixer_setamigaperiod(channel, p_modchannel->period);
}

/* Apply Volume Slide */
STATICIRAM void volumeslide(int channel, int effectx, int effecty) ICODE_ATTR;
void volumeslide(int channel, int effectx, int effecty)
{
    struct s_modchannel *p_modchannel = &modplayer.modchannel[channel];

    /* If both X and Y Parameters are non-zero, then the y value is ignored */
    if (effectx > 0) {
        p_modchannel->volume += effectx;
        if (p_modchannel->volume > 64) p_modchannel->volume = 64;
    }
    else {
        p_modchannel->volume -= effecty;
        if (p_modchannel->volume < 0) p_modchannel->volume = 0;
    }

    mixer_setvolume(channel, p_modchannel->volume);
}

/* Play the current line (at tick 0) */
STATICIRAM void playline(int pattern, int line) ICODE_ATTR;
void playline(int pattern, int line)
{
    int c;

    /* Get pointer to the current pattern */
    unsigned char *p_line = (unsigned char*)modsong.patterndata;
    p_line += pattern*64*4*modsong.noofchannels;
    p_line += line*4*modsong.noofchannels;

    /* Only allow one Patternbreak Commando per Line */
    bool patternbreakdone = false;

    for (c=0;c<modsong.noofchannels;c++)
    {
        struct s_modchannel *p_modchannel = &modplayer.modchannel[c];
        unsigned char *p_note = p_line + c*4;
        unsigned char samplenumber = (p_note[0] & 0xf0) | (p_note[2] >> 4);
        short periodtableoffset = ((p_note[0] & 0x0f) << 8) | p_note[1];

        p_modchannel->effect = p_note[2] & 0x0f;
        p_modchannel->effectparameter = p_note[3];

        /* Remember Instrument and set Volume if new Instrument triggered */
        if (samplenumber > 0)
        {
            /* And trigger new sample, if new instrument was set */
            if (samplenumber-1 != p_modchannel->instrument)
            {
                /* Advance the new sample to the same offset
                 * the old sample was beeing played */
                int oldsampleoffset = mixer.channel[c].samplepos -
                    modsong.instrument[
                    p_modchannel->instrument].sampledataoffset;
                mixer_playsample(c, samplenumber-1);
                mixer.channel[c].samplepos += oldsampleoffset;
            }

            /* Remember last played instrument on channel */
            p_modchannel->instrument = samplenumber-1;

            /* Set Volume to standard instrument volume,
             * if not overwritten by volume effect */
            if (p_modchannel->effect != 0x0c)
            {
                p_modchannel->volume = modsong.instrument[
                    p_modchannel->instrument].volume;
                mixer_setvolume(c, p_modchannel->volume);
            }
        }
        /* Trigger new sample if note available */
        if (periodtableoffset > 0)
        {
            /* Restart instrument only when new sample triggered */
            if (samplenumber != 0)
                mixer_playsample(c, (samplenumber > 0) ?
                    samplenumber-1 : p_modchannel->instrument);

            /* Set the new amiga period
             * (but only, if there is no slide to note effect) */
            if ((p_modchannel->effect != 0x3) &&
                (p_modchannel->effect != 0x5))
            {
                /* Apply finetuning to sample */
                p_modchannel->periodtableoffset = periodtableoffset +
                    modsong.instrument[p_modchannel->instrument].finetune;
                p_modchannel->period = modplayer.periodtable[
                    p_modchannel->periodtableoffset];
                mixer_setamigaperiod(c, p_modchannel->period);
                /* When a new note is played without slide to note setup,
                 * then disable slide to note */
                modplayer.modchannel[c].slidetonoteperiod =
                    p_modchannel->period;
            }
        }
        int effectx = p_modchannel->effectparameter>>4;
        int effecty = p_modchannel->effectparameter&0x0f;

        switch (p_modchannel->effect)
        {
            /* Effect 0: Arpeggio */
            case 0x00:
                /* Set the base period on tick 0 */
                if (p_modchannel->effectparameter > 0)
                    mixer_setamigaperiod(c,
                        modplayer.periodtable[
                            p_modchannel->periodtableoffset]);
                break;
            /* Slide up (Portamento up) */
            case 0x01:
                if (p_modchannel->effectparameter > 0)
                    p_modchannel->slideupspeed =
                        p_modchannel->effectparameter;
                break;

            /* Slide down (Portamento down) */
            case 0x02:
                if (p_modchannel->effectparameter > 0)
                    p_modchannel->slidedownspeed =
                        p_modchannel->effectparameter;
                break;

            /* Slide to Note */
            case 0x03:
                if (p_modchannel->effectparameter > 0)
                    p_modchannel->slidetonotespeed =
                        p_modchannel->effectparameter;
                /* Get the slide to note directly from the pattern buffer */
                if (periodtableoffset > 0)
                    p_modchannel->slidetonoteperiod =
                        modplayer.periodtable[periodtableoffset +
                        modsong.instrument[
                        p_modchannel->instrument].finetune];
                /* If glissando is enabled apply the effect directly here */
                if (modplayer.glissandoenabled)
                    slidetonoteglissando(c);
                break;

            /* Set Vibrato */
            case 0x04:
                if (effectx > 0) p_modchannel->vibratospeed = effectx;
                if (effecty > 0) p_modchannel->vibratodepth = effecty;
                break;

            /* Effect 0x06: Slide to note */
            case 0x05:
                /* Get the slide to note directly from the pattern buffer */
                if (periodtableoffset > 0)
                    p_modchannel->slidetonoteperiod =
                        modplayer.periodtable[periodtableoffset +
                            modsong.instrument[
                            p_modchannel->instrument].finetune];
                break;

            /* Effect 0x06 is "Continue Effects" */
            /* It is not processed on tick 0 */
            case 0x06:
                break;

            /* Set Tremolo */
            case 0x07:
                if (effectx > 0) p_modchannel->tremolodepth = effectx;
                if (effecty > 0) p_modchannel->tremolospeed = effecty;
                break;

            /* Set fine panning */
            case 0x08:
                /* Internal panning goes from 0..15
                 * Scale the fine panning value to that range */
                mixer.channel[c].panning = p_modchannel->effectparameter>>4;
                break;

            /* Set Sample Offset */
            case 0x09:
                {
                    struct s_instrument *p_instrument =
                        &modsong.instrument[p_modchannel->instrument];
                    int sampleoffset = p_instrument->sampledataoffset;
                    if (sampleoffset > p_instrument->length)
                        sampleoffset = p_instrument->length;
                    /* Forward the new offset to the mixer */
                    mixer.channel[c].samplepos =
                        p_instrument->sampledataoffset +
                        (p_modchannel->effectparameter<<8);
                    mixer.channel[c].samplefractpos = 0;
                break;
                }

            /* Effect 0x0a (Volume slide) is not processed on tick 0 */

            /* Position Jump */
            case 0x0b:
                modplayer.currentline = -1;
                modplayer.patterntableposition = (effectx<<4)+effecty;
                break;

            /* Set Volume */
            case 0x0c:
                p_modchannel->volume = p_modchannel->effectparameter;
                mixer_setvolume(c, p_modchannel->volume);
                break;

            /* Pattern break */
            case 0x0d:
                modplayer.currentline = effectx*10 + effecty - 1;
                if (!patternbreakdone)
                {
                    patternbreakdone = true;
                    modplayer.patterntableposition++;
                }
                break;

            /* Extended Effects */
            case 0x0e:
                switch (effectx)
                {
                    /* Set Filter */
                    case 0x0:
                        modplayer.amigafilterenabled =
                            (effecty>0) ? false : true;
                        break;
                    /* Fineslide up */
                    case 0x1:
                        mixer_setamigaperiod(c, p_modchannel->period -=
                            effecty);
                        if (p_modchannel->period <
                            modplayer.periodtable[37*8]) p_modchannel->period = 100;
                        /* Find out the new offset in the period table */
                        if (p_modchannel->periodtableoffset < 36*8)
                            while (modplayer.periodtable[
                                p_modchannel->periodtableoffset+8] >= p_modchannel->period)
                                    p_modchannel->periodtableoffset+=8;
                        break;
                    /* Fineslide down */
                    case 0x2:
                        mixer_setamigaperiod(c,
                            p_modchannel->period += effecty);
                        if (p_modchannel->periodtableoffset > 8)
                            while (modplayer.periodtable[
                                p_modchannel->periodtableoffset-8]
                                <= p_modchannel->period)
                            p_modchannel->periodtableoffset-=8;
                        break;
                    /* Set glissando on/off */
                    case 0x3:
                        modplayer.glissandoenabled =
                            (effecty > 0) ? true:false;
                        break;
                    /* Set Vibrato waveform */
                    case 0x4:
                        /* Currently not implemented */
                        break;
                    /* Set Finetune value */
                    case 0x5:
                        /* Treat as signed nibble */
                        if (effecty > 7) effecty -= 16;

                        p_modchannel->periodtableoffset +=
                            effecty -
                                modsong.instrument[
                                p_modchannel->instrument].finetune;
                        p_modchannel->period =
                            modplayer.periodtable[
                            p_modchannel->periodtableoffset];
                        modsong.instrument[
                            p_modchannel->instrument].finetune = effecty;
                        break;
                    /* Pattern loop */
                    case 0x6:
                        if (effecty == 0)
                            modplayer.loopstartline = line-1;
                        else
                        {
                            if (modplayer.looptimes == 0)
                            {
                                modplayer.currentline =
                                    modplayer.loopstartline;
                                modplayer.looptimes = effecty;
                            }
                            else modplayer.looptimes--;
                            if (modplayer.looptimes > 0)
                                modplayer.currentline =
                                    modplayer.loopstartline;
                        }
                        break;
                    /* Set Tremolo waveform */
                    case 0x7:
                        /* Not yet implemented */
                        break;
                    /* Enhanced Effect 8 is not used */
                    case 0x8:
                        break;
                    /* Retrigger sample */
                    case 0x9:
                        /* Only processed on subsequent ticks */
                        break;
                    /* Fine volume slide up */
                    case 0xa:
                        p_modchannel->volume += effecty;