drop 'req' from gas macro, not available in binutils 2.16
[kugel-rb.git] / apps / plugins / midi / synth.c
blobf2fbe063e782c1197274b6b0a9d1b651d0e55da5
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 Stepan Moskovchenko
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include "plugin.h"
22 #include "guspat.h"
23 #include "midiutil.h"
24 #include "synth.h"
26 void readTextBlock(int file, char * buf)
28 char c = 0;
31 c = readChar(file);
32 } while(c == '\n' || c == ' ' || c=='\t');
34 rb->lseek(file, -1, SEEK_CUR);
35 int cp = 0;
38 c = readChar(file);
39 buf[cp] = c;
40 cp++;
41 } while (c != '\n' && c != ' ' && c != '\t' && !eof(file));
42 buf[cp-1]=0;
43 rb->lseek(file, -1, SEEK_CUR);
46 void resetControllers()
48 int a=0;
49 for(a=0; a<MAX_VOICES; a++)
51 voices[a].cp=0;
52 voices[a].vol=0;
53 voices[a].ch=0;
54 voices[a].isUsed=false;
55 voices[a].note=0;
58 for(a=0; a<16; a++)
60 chVol[a]=100; /* Default, not quite full blast.. */
61 chPan[a]=64; /* Center */
62 chPat[a]=0; /* Ac Gr Piano */
63 chPW[a]=256; /* .. not .. bent ? */
64 chPBDepth[a]=2; /* Default bend value is 2 */
65 chPBNoteOffset[a]=0; /* No offset */
66 chPBFractBend[a]=65536; /* Center.. no bend */
67 chLastCtrlMSB[a]=0; /* Set to pitch bend depth */
68 chLastCtrlLSB[a]=0; /* Set to pitch bend depth */
72 /* Filename is the name of the config file */
73 /* The MIDI file should have been loaded at this point */
74 int initSynth(struct MIDIfile * mf, char * filename, char * drumConfig)
76 char patchUsed[128];
77 char drumUsed[128];
78 int a=0;
80 resetControllers();
82 for(a=0; a<128; a++)
84 patchSet[a]=NULL;
85 drumSet[a]=NULL;
86 patchUsed[a]=0;
87 drumUsed[a]=0;
91 * Always load the piano.
92 * Some files will assume its loaded without specifically
93 * issuing a Patch command... then we wonder why we can't hear anything
95 patchUsed[0]=1;
97 /* Scan the file to see what needs to be loaded */
98 if(mf != NULL)
100 for(a=0; a<mf->numTracks; a++)
102 unsigned int ts=0;
104 if(mf->tracks[a] == NULL)
106 printf("NULL TRACK !!!");
107 rb->splash(HZ*2, "Null Track in loader.");
108 return -1;
111 for(ts=0; ts<mf->tracks[a]->numEvents; ts++)
114 if((getEvent(mf->tracks[a], ts)->status) == (MIDI_NOTE_ON+9))
115 drumUsed[getEvent(mf->tracks[a], ts)->d1]=1;
117 if( (getEvent(mf->tracks[a], ts)->status & 0xF0) == MIDI_PRGM)
118 patchUsed[getEvent(mf->tracks[a], ts)->d1]=1;
121 } else
123 /* Initialize the whole drum set */
124 for(a=0; a<128; a++)
125 drumUsed[a]=1;
129 int file = rb->open(filename, O_RDONLY);
130 if(file < 0)
132 printf("");
133 printf("No MIDI patchset found.");
134 printf("Please install the instruments.");
135 printf("See Rockbox page for more info.");
137 rb->splash(HZ*2, "No Instruments");
138 return -1;
141 char name[40];
142 char fn[40];
144 /* Scan our config file and load the right patches as needed */
145 int c = 0;
146 name[0] = '\0';
147 printf("Loading instruments");
148 for(a=0; a<128; a++)
150 while(readChar(file)!=' ' && !eof(file));
151 readTextBlock(file, name);
153 rb->snprintf(fn, 40, ROCKBOX_DIR "/patchset/%s.pat", name);
154 /* printf("\nLOADING: <%s> ", fn); */
156 if(patchUsed[a]==1)
158 patchSet[a]=gusload(fn);
160 if(patchSet[a] == NULL) /* There was an error loading it */
161 return -1;
164 while((c != '\n'))
165 c = readChar(file);
167 rb->close(file);
169 file = rb->open(drumConfig, O_RDONLY);
170 if(file < 0)
172 rb->splash(HZ*2, "Bad drum config. Did you install the patchset?");
173 return -1;
176 /* Scan our config file and load the drum data */
177 int idx=0;
178 char number[30];
179 printf("Loading drums");
180 while(!eof(file))
182 readTextBlock(file, number);
183 readTextBlock(file, name);
184 rb->snprintf(fn, 40, ROCKBOX_DIR "/patchset/%s.pat", name);
186 idx = rb->atoi(number);
187 if(idx == 0)
188 break;
190 if(drumUsed[idx]==1)
192 drumSet[idx]=gusload(fn);
193 if(drumSet[idx] == NULL) /* Error loading patch */
194 return -1;
197 while((c != '\n') && (c != 255) && (!eof(file)))
198 c = readChar(file);
200 rb->close(file);
201 return 0;
204 #define getSample(s,wf) ((short *)(wf)->data)[s]
206 void setPoint(struct SynthObject * so, int pt) ICODE_ATTR;
207 void setPoint(struct SynthObject * so, int pt)
209 if(so->ch==9) /* Drums, no ADSR */
211 so->curOffset = 1<<27;
212 so->curRate = 1;
213 return;
216 if(so->wf==NULL)
218 printf("Crap... null waveform...");
219 exit(1);
221 if(so->wf->envRate==NULL)
223 printf("Waveform has no envelope set");
224 exit(1);
227 so->curPoint = pt;
229 int r;
230 int rate = so->wf->envRate[pt];
232 r=3-((rate>>6) & 0x3); /* Some blatant Timidity code for rate conversion... */
233 r*=3;
234 r = (rate & 0x3f) << r;
237 * Okay. This is the rate shift. Timidity defaults to 9, and sets
238 * it to 10 if you use the fast decay option. Slow decay sounds better
239 * on some files, except on some other files... you get chords that aren't
240 * done decaying yet.. and they dont harmonize with the next chord and it
241 * sounds like utter crap. Yes, even Timitidy does that. So I'm going to
242 * default this to 10, and maybe later have an option to set it to 9
243 * for longer decays.
245 so->curRate = r<<10;
248 * Do this here because the patches assume a 44100 sampling rate
249 * We've halved our sampling rate, ergo the ADSR code will be
250 * called half the time. Ergo, double the rate to keep stuff
251 * sounding right.
253 * Or just move the 1 up one line to optimize a tiny bit.
255 /* so->curRate = so->curRate << 1; */
258 so->targetOffset = so->wf->envOffset[pt]<<(20);
259 if(pt==0)
260 so->curOffset = 0;
263 static inline void synthVoice(struct SynthObject * so, int32_t * out, unsigned int samples)
265 struct GWaveform * wf;
266 register int s1;
267 register int s2;
269 register unsigned int cp_temp = so->cp;
271 wf = so->wf;
273 const unsigned int pan = chPan[so->ch];
274 const int volscale = so->volscale;
276 const int mode_mask24 = wf->mode&24;
277 const int mode_mask28 = wf->mode&28;
278 const int mode_mask_looprev = wf->mode&LOOP_REVERSE;
280 const unsigned int num_samples = (wf->numSamples-1) << FRACTSIZE;
282 const unsigned int end_loop = wf->endLoop << FRACTSIZE;
283 const unsigned int start_loop = wf->startLoop << FRACTSIZE;
284 const int diff_loop = end_loop-start_loop;
286 bool rampdown = (so->state == STATE_RAMPDOWN);
287 const bool ch_9 = (so->ch == 9);
289 while(LIKELY(samples-- > 0))
291 /* Is voice being ramped? */
292 if(UNLIKELY(rampdown))
294 if(so->decay != 0) /* Ramp has been started */
296 so->decay = so->decay / 2;
298 if(so->decay < 10 && so->decay > -10)
299 so->isUsed = false;
301 s1 = so->decay;
302 s2 = s1 * pan;
303 s1 = (s1 << 7) -s2;
304 *(out++) += ((s1 << 9) & 0xFFFF0000) | ((s2 >> 7) &0xFFFF);
305 continue;
307 } else /* OK to advance voice */
309 cp_temp += so->delta;
312 s2 = getSample((cp_temp >> FRACTSIZE)+1, wf);
314 if(LIKELY(mode_mask28))
316 /* LOOP_REVERSE|LOOP_PINGPONG = 24 */
317 if(UNLIKELY(mode_mask24 && so->loopState == STATE_LOOPING && (cp_temp < start_loop)))
319 if(UNLIKELY(mode_mask_looprev))
321 cp_temp += diff_loop;
322 s2=getSample((cp_temp >> FRACTSIZE), wf);
324 else
326 so->delta = -so->delta; /* At this point cp_temp is wrong. We need to take a step */
330 if(UNLIKELY(cp_temp >= end_loop))
332 so->loopState = STATE_LOOPING;
333 if(UNLIKELY(!mode_mask24))
335 cp_temp -= diff_loop;
336 s2=getSample((cp_temp >> FRACTSIZE), wf);
338 else
340 so->delta = -so->delta;
345 /* Have we overrun? */
346 if(UNLIKELY(cp_temp >= num_samples))
348 cp_temp -= so->delta;
349 s2 = getSample((cp_temp >> FRACTSIZE)+1, wf);
351 if (!rampdown) /* stop voice */
353 rampdown = true;
354 so->decay = 0;
358 /* Better, working, linear interpolation */
359 s1=getSample((cp_temp >> FRACTSIZE), wf);
361 s1 +=((signed)((s2 - s1) * (cp_temp & ((1<<FRACTSIZE)-1)))>>FRACTSIZE);
363 if(UNLIKELY(so->curRate == 0))
365 if (!rampdown) /* stop voice */
367 rampdown = true;
368 so->decay = 0;
370 // so->isUsed = false;
373 if(LIKELY(!ch_9 && !rampdown)) /* Stupid ADSR code... and don't do ADSR for drums */
375 if(UNLIKELY(so->curOffset < so->targetOffset))
377 so->curOffset += (so->curRate);
378 if(UNLIKELY(so -> curOffset > so->targetOffset && so->curPoint != 2))
380 if(UNLIKELY(so->curPoint != 5))
382 setPoint(so, so->curPoint+1);
384 else if (!rampdown) /* stop voice */
386 rampdown = true;
387 so->decay = 0;
390 } else
392 so->curOffset -= (so->curRate);
393 if(UNLIKELY(so -> curOffset < so->targetOffset && so->curPoint != 2))
395 if(UNLIKELY(so->curPoint != 5))
397 setPoint(so, so->curPoint+1);
399 else if (!rampdown) /* stop voice */
401 rampdown = true;
402 so->decay = 0;
409 if(UNLIKELY(so->curOffset < 0))
411 so->curOffset = so->targetOffset;
412 if (!rampdown)
414 rampdown = true;
415 so->decay = 0;
419 s1 = s1 * (so->curOffset >> 22) >> 8;
421 /* Scaling by channel volume and note volume is done in sequencer.c */
422 /* That saves us some multiplication and pointer operations */
423 s1 = s1 * volscale >> 14;
425 /* need to set ramp beginning */
426 if(UNLIKELY(rampdown && so->decay == 0))
428 so->decay = s1;
429 if(so->decay == 0)
430 so->decay = 1; /* stupid junk.. */
433 s2 = s1 * pan;
434 s1 = (s1 << 7) - s2;
435 *(out++) += ((s1 << 9) & 0xFFFF0000) | ((s2 >> 7) &0xFFFF);
438 /* store these again */
439 if (rampdown)
440 so->state = STATE_RAMPDOWN;
441 so->cp = cp_temp;
442 return;
445 /* buffer to hold all the samples for the current tick, this is a hack
446 neccesary for coldfire targets as pcm_play_data uses the dma which cannot
447 access iram */
448 int32_t samp_buf[512] IBSS_ATTR;
450 /* synth num_samples samples and write them to the */
451 /* buffer pointed to by buf_ptr */
452 void synthSamples(int32_t *buf_ptr, unsigned int num_samples) ICODE_ATTR;
453 void synthSamples(int32_t *buf_ptr, unsigned int num_samples)
455 if (UNLIKELY(num_samples > 512))
456 DEBUGF("num_samples is too big!\n");
457 else
459 int i;
460 struct SynthObject *voicept;
462 rb->memset(samp_buf, 0, num_samples*4);
464 for(i=0; i < MAX_VOICES; i++)
466 voicept=&voices[i];
467 if(voicept->isUsed)
469 synthVoice(voicept, samp_buf, num_samples);
473 rb->memcpy(buf_ptr, samp_buf, num_samples*4);
476 /* TODO: Automatic Gain Control, anyone? */
477 /* Or, should this be implemented on the DSP's output volume instead? */
479 return; /* No more ghetto lowpass filter. Linear interpolation works well. */