~ubuntu-branches/ubuntu/hoary/kdemultimedia/hoary

« back to all changes in this revision

Viewing changes to kmidi/sndfont.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Martin Schulze
  • Date: 2003-01-22 15:00:51 UTC
  • Revision ID: james.westby@ubuntu.com-20030122150051-uihwkdoxf15mi1tn
Tags: upstream-2.2.2
ImportĀ upstreamĀ versionĀ 2.2.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*================================================================
 
2
 * SoundFont file extension
 
3
 *      written by Takashi Iwai <iwai@dragon.mm.t.u-tokyo.ac.jp>
 
4
 *================================================================*/
 
5
 
 
6
#include <stdio.h>
 
7
#include <string.h>
 
8
#include <stdlib.h>
 
9
#include <math.h>
 
10
#include "config.h"
 
11
#ifdef LITTLE_ENDIAN
 
12
#define USE_POSIX_MAPPED_FILES
 
13
#endif
 
14
#define READ_WHOLE_SF_FILE
 
15
#ifdef READ_WHOLE_SF_FILE
 
16
#include <sys/stat.h>
 
17
#endif
 
18
#ifdef USE_POSIX_MAPPED_FILES
 
19
#include <sys/mman.h>
 
20
#endif
 
21
#include "common.h"
 
22
#include "tables.h"
 
23
#include "instrum.h"
 
24
#include "playmidi.h"
 
25
#include "controls.h"
 
26
#include "sbk.h"
 
27
#include "sflayer.h"
 
28
#include "output.h"
 
29
#include "filter.h"
 
30
#include "resample.h"
 
31
 
 
32
/*----------------------------------------------------------------
 
33
 * compile flags
 
34
 *----------------------------------------------------------------*/
 
35
 
 
36
/* use some modifications from TiMidity++ */
 
37
#define tplussbkuse
 
38
 
 
39
/*#define GREGSTEST*/
 
40
 
 
41
#ifdef ADAGIO
 
42
#define SF_SUPPRESS_VIBRATO
 
43
#endif
 
44
 
 
45
 
 
46
/*----------------------------------------------------------------
 
47
 * local parameters
 
48
 *----------------------------------------------------------------*/
 
49
 
 
50
typedef struct _Layer {
 
51
        int16 val[PARM_SIZE];
 
52
        int8 set[PARM_SIZE];
 
53
} Layer;
 
54
 
 
55
typedef struct _SampleList {
 
56
        Sample v;
 
57
        struct _SampleList *next;
 
58
        uint32 startsample, endsample;
 
59
        uint32 cutoff_freq;
 
60
        FLOAT_T resonance;
 
61
} SampleList;
 
62
 
 
63
typedef struct _InstList {
 
64
        int bank, preset, keynote;
 
65
        int inum, velrange;
 
66
        int samples, rsamples;
 
67
        int already_loaded;
 
68
        char *fname;
 
69
        FILE *fd;
 
70
#ifdef READ_WHOLE_SF_FILE
 
71
        unsigned char *contents;
 
72
        int size_of_contents;
 
73
#endif
 
74
        SampleList *slist, *rslist;
 
75
        struct _InstList *next;
 
76
} InstList;
 
77
 
 
78
typedef struct SFInsts {
 
79
        char *fname;
 
80
        FILE *fd;
 
81
        uint16 version, minorversion;
 
82
        int32 samplepos, samplesize;
 
83
#ifdef READ_WHOLE_SF_FILE
 
84
        unsigned char *contents;
 
85
        int size_of_contents;
 
86
#endif
 
87
        InstList *instlist;
 
88
} SFInsts;
 
89
 
 
90
 
 
91
/*----------------------------------------------------------------*/
 
92
 
 
93
static int load_one_side(SFInsts *rec, SampleList *sp, int sample_count, Sample *base_sample, int amp);
 
94
static Instrument *load_from_file(SFInsts *rec, InstList *ip, int amp);
 
95
static void parse_preset(SFInsts *rec, SFInfo *sf, int preset);
 
96
static void parse_gen(Layer *lay, tgenrec *gen);
 
97
static void parse_preset_layer(Layer *lay, SFInfo *sf, int idx);
 
98
static void merge_layer(Layer *dst, Layer *src);
 
99
static int search_inst(Layer *lay);
 
100
static void parse_inst(SFInsts *rec, Layer *pr_lay, SFInfo *sf, int preset, int inst, int inum, int num_i);
 
101
static void parse_inst_layer(Layer *lay, SFInfo *sf, int idx);
 
102
static int search_sample(Layer *lay);
 
103
static void append_layer(Layer *dst, Layer *src, SFInfo *sf);
 
104
static void make_inst(SFInsts *rec, Layer *lay, SFInfo *sf, int pr_idx, int in_idx, int inum,
 
105
        uint16 pk_range, uint16 pv_range, int num_i, int program);
 
106
static int32 calc_root_pitch(Layer *lay, SFInfo *sf, SampleList *sp, int32 cfg_tuning);
 
107
static void convert_volume_envelope(Layer *lay, SFInfo *sf, SampleList *sp, int banknum, int preset);
 
108
static void convert_modulation_envelope(Layer *lay, SFInfo *sf, SampleList *sp, int banknum, int preset);
 
109
static uint32 to_offset(uint32 offset);
 
110
static uint32 calc_rate(uint32 diff, double msec);
 
111
static double to_msec(Layer *lay, SFInfo *sf, int index);
 
112
static FLOAT_T calc_volume(Layer *lay, SFInfo *sf);
 
113
static uint32 calc_sustain(Layer *lay, SFInfo *sf, int banknum, int preset);
 
114
static uint32 calc_modulation_sustain(Layer *lay, SFInfo *sf, int banknum, int preset);
 
115
#ifndef SF_SUPPRESS_TREMOLO
 
116
static void convert_tremolo(Layer *lay, SFInfo *sf, SampleList *sp);
 
117
static void convert_lfo(Layer *lay, SFInfo *sf, SampleList *sp);
 
118
#endif
 
119
#ifndef SF_SUPPRESS_VIBRATO
 
120
static void convert_vibrato(Layer *lay, SFInfo *sf, SampleList *sp);
 
121
#endif
 
122
static void calc_cutoff(Layer *lay, SFInfo *sf, SampleList *sp);
 
123
static void calc_filterQ(Layer *lay, SFInfo *sf, SampleList *sp);
 
124
 
 
125
/*----------------------------------------------------------------*/
 
126
 
 
127
#define MAX_SF_FILES 40
 
128
static int current_sf_index = 0;
 
129
static int last_sf_index = 0;
 
130
 
 
131
static SFInsts sfrec[MAX_SF_FILES];
 
132
 
 
133
int cutoff_allowed = 0;
 
134
int command_cutoff_allowed = 0;
 
135
 
 
136
 
 
137
#ifdef GREGSTEST
 
138
static char *getname(char *p)
 
139
{
 
140
        static char buf[21];
 
141
        strncpy(buf, p, 20);
 
142
        buf[20] = 0;
 
143
        return buf;
 
144
}
 
145
#endif
 
146
 
 
147
static SFInfo sfinfo;
 
148
 
 
149
 
 
150
#ifdef READ_WHOLE_SF_FILE
 
151
static int sf_size_of_contents;
 
152
 
 
153
#ifndef USE_POSIX_MAPPED_FILES
 
154
static unsigned char *read_whole_sf(FILE *fd) {
 
155
#else
 
156
static unsigned char *read_whole_sf() {
 
157
#endif
 
158
    struct stat info;
 
159
    unsigned char *sf_contents;
 
160
 
 
161
    sf_size_of_contents = 0;
 
162
 
 
163
#ifndef LITTLE_ENDIAN
 
164
    return 0;
 
165
#else
 
166
 
 
167
#ifndef USE_POSIX_MAPPED_FILES
 
168
#ifndef KMIDI
 
169
    if (have_commandline_midis < 3) return 0;
 
170
#endif
 
171
#endif
 
172
    if (stat(current_filename, &info)) {
 
173
        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Can't find file `%s'.", current_filename);
 
174
        return 0;
 
175
    }
 
176
/* check here if size less than what we are allowed */
 
177
    if (info.st_size + current_patch_memory > max_patch_memory) {
 
178
        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "File `%s' at %d bytes is too big to read all at once.",
 
179
                 current_filename, info.st_size);
 
180
        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "  (I will try to read it one patch at a time.)");
 
181
        return 0;
 
182
    }
 
183
 
 
184
#ifdef USE_POSIX_MAPPED_FILES
 
185
    sf_contents = (unsigned char *)mmap(0, info.st_size,  PROT_READ,
 
186
         MAP_SHARED, current_filedescriptor, 0);
 
187
 
 
188
    if (sf_contents == (unsigned char *)(-1)) {
 
189
        ctl->cmsg(CMSG_INFO, VERB_NOISY, "Couldn't mmap `%s'.", current_filename);
 
190
        return 0;
 
191
    }
 
192
#else
 
193
    sf_contents = (unsigned char *)malloc(info.st_size);
 
194
 
 
195
    if (!sf_contents) {
 
196
        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Couldn't get memory for entire file `%s'.", current_filename);
 
197
        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "  (I will try to read it one patch at a time.)");
 
198
        return 0;
 
199
    }
 
200
    rewind(fd);
 
201
    if (!fread(sf_contents, info.st_size, 1, fd)) {
 
202
        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Couldn't read `%s'.", current_filename);
 
203
        free(sf_contents);
 
204
        return 0;
 
205
    }
 
206
#endif
 
207
    sf_size_of_contents = info.st_size;
 
208
    current_patch_memory += info.st_size;
 
209
    ctl->cmsg(CMSG_INFO, VERB_NOISY, "File `%s' required %d bytes of memory.", current_filename, sf_size_of_contents);
 
210
    return sf_contents;
 
211
#endif
 
212
}
 
213
#endif
 
214
 
 
215
/*
 
216
 * init_soundfont
 
217
 *      fname: name of soundfont file
 
218
 *      newbank: toneset # or, if >255, drumset # + 256
 
219
 *      oldbank: same as newbank unless cfg file has "sf <name> oldbank=<num>",
 
220
 *              in which case oldbank=<num>
 
221
 *      level: nesting level of cfg file (what is this for?)
 
222
 */
 
223
void init_soundfont(char *fname, int oldbank, int newbank, int level)
 
224
{
 
225
        int i;
 
226
        InstList *ip;
 
227
#ifdef READ_WHOLE_SF_FILE
 
228
        unsigned char *sf_contents = 0;
 
229
        int whole_sf_already_read = 0;
 
230
#endif
 
231
 
 
232
        ctl->cmsg(CMSG_INFO, VERB_NOISY, "init soundfont `%s'", fname);
 
233
 
 
234
        current_sf_index = -1;
 
235
        for (i = 0; i < last_sf_index; i++) if (sfrec[i].fname && !strcmp(sfrec[i].fname, fname)) {
 
236
                current_sf_index = i;
 
237
                rewind(sfrec[i].fd);
 
238
#ifdef READ_WHOLE_SF_FILE
 
239
                whole_sf_already_read = 1;
 
240
#endif
 
241
                break;
 
242
        }
 
243
 
 
244
        if (current_sf_index == -1) {
 
245
            if (last_sf_index >= MAX_SF_FILES) {
 
246
                ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
 
247
                          "Too many soundfont files to load %s.", fname);
 
248
                return;
 
249
            }
 
250
            current_sf_index = last_sf_index;
 
251
 
 
252
            if ((sfrec[current_sf_index].fd = open_file(fname, 1, OF_VERBOSE, level)) == NULL) {
 
253
                ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
 
254
                          "Can't open soundfont file %s.", fname);
 
255
                return;
 
256
            }
 
257
            last_sf_index++;
 
258
            sfrec[current_sf_index].fname = strcpy((char*)safe_malloc(strlen(fname)+1), fname);
 
259
        }
 
260
 
 
261
        load_sbk(sfrec[current_sf_index].fd, &sfinfo);
 
262
 
 
263
        for (i = 0; i < sfinfo.nrpresets-1; i++) {
 
264
                /* if substituting banks, only parse matching bank */
 
265
                if (oldbank != newbank) {
 
266
                        int bank = sfinfo.presethdr[i].bank;
 
267
                        int preset = sfinfo.presethdr[i].preset;
 
268
                        /* is it a matching percussion preset? */
 
269
                        if (newbank >= 256 && bank == 128 && preset == oldbank) {
 
270
                                preset = sfinfo.presethdr[i].sub_preset = newbank - 256;
 
271
                                parse_preset(&sfrec[current_sf_index], &sfinfo, i);
 
272
                        }
 
273
                        /* is it a matching melodic bank? */
 
274
                        else if (bank == oldbank) {
 
275
                                bank = sfinfo.presethdr[i].sub_bank = newbank;
 
276
                                parse_preset(&sfrec[current_sf_index], &sfinfo, i);
 
277
                        }
 
278
                }
 
279
                /* but if not substituting banks, parse them all */
 
280
                else parse_preset(&sfrec[current_sf_index], &sfinfo, i);
 
281
        }
 
282
 
 
283
        /* copy header info */
 
284
        sfrec[current_sf_index].version = sfinfo.version;
 
285
        sfrec[current_sf_index].minorversion = sfinfo.minorversion;
 
286
        sfrec[current_sf_index].samplepos = sfinfo.samplepos;
 
287
        sfrec[current_sf_index].samplesize = sfinfo.samplesize;
 
288
 
 
289
        free_sbk(&sfinfo);
 
290
 
 
291
 
 
292
#ifdef READ_WHOLE_SF_FILE
 
293
        if (whole_sf_already_read) {
 
294
                sf_contents = sfrec[current_sf_index].contents;
 
295
                sf_size_of_contents = sfrec[current_sf_index].size_of_contents;
 
296
        }
 
297
        else
 
298
#ifndef USE_POSIX_MAPPED_FILES
 
299
        sf_contents = read_whole_sf(sfrec[current_sf_index].fd);
 
300
#else
 
301
        sf_contents = read_whole_sf();
 
302
#endif
 
303
        sfrec[current_sf_index].contents = sf_contents;
 
304
        sfrec[current_sf_index].size_of_contents = sf_size_of_contents;
 
305
 
 
306
        for (ip = sfrec[current_sf_index].instlist; ip; ip = ip->next) {
 
307
            if (!ip->already_loaded) {
 
308
                ip->contents = sf_contents;
 
309
                ip->size_of_contents = sf_size_of_contents;
 
310
            }
 
311
            ip->already_loaded = 10000000;
 
312
        }
 
313
#else
 
314
        /* mark instruments as loaded so they won't be loaded again if we're re-called */
 
315
        for (ip = sfrec[current_sf_index].instlist; ip; ip = ip->next) ip->already_loaded = 10000000;
 
316
#endif
 
317
 
 
318
}
 
319
 
 
320
 
 
321
void end_soundfont(void)
 
322
{
 
323
    InstList *ip, *next;
 
324
    FILE *still_open;
 
325
    char *still_not_free;
 
326
    unsigned char *contents_not_free;
 
327
    int contents_size = 0;
 
328
 
 
329
    current_sf_index = 0;
 
330
 
 
331
    while (current_sf_index < last_sf_index) {
 
332
 
 
333
        if (!sfrec[current_sf_index].instlist) continue;
 
334
 
 
335
        still_open = NULL;
 
336
        still_not_free = NULL;
 
337
        contents_not_free = NULL;
 
338
 
 
339
        while (1) {
 
340
            for (ip = sfrec[current_sf_index].instlist; ip; ip = next) {
 
341
                next = ip->next;
 
342
                if (!still_open && ip->fd) {
 
343
                    still_open = ip->fd;
 
344
                    still_not_free = ip->fname;
 
345
                    contents_not_free = ip->contents;
 
346
                    contents_size = ip->size_of_contents;
 
347
                }
 
348
                if (still_open && ip->fd == still_open) ip->fd = NULL;
 
349
            }
 
350
            if (still_open) {
 
351
                fclose(still_open);
 
352
                still_open = NULL;
 
353
                if (still_not_free) free(still_not_free);
 
354
                still_not_free = NULL;
 
355
                if (contents_not_free) {
 
356
#ifdef USE_POSIX_MAPPED_FILES
 
357
                    munmap(contents_not_free, contents_size);
 
358
#else
 
359
                    free(contents_not_free);
 
360
#endif
 
361
                    current_patch_memory -= contents_size;
 
362
                }
 
363
                contents_not_free = NULL;
 
364
                contents_size = 0;
 
365
            }
 
366
            else break;
 
367
        }
 
368
 
 
369
        for (ip = sfrec[current_sf_index].instlist; ip; ip = next) {
 
370
                next = ip->next;
 
371
                free(ip);
 
372
        }
 
373
 
 
374
        sfrec[current_sf_index].version =
 
375
        sfrec[current_sf_index].minorversion =
 
376
        sfrec[current_sf_index].samplepos =
 
377
        sfrec[current_sf_index].samplesize = 0;
 
378
        sfrec[current_sf_index].instlist = NULL;
 
379
        sfrec[current_sf_index].fd = NULL;
 
380
 
 
381
        current_sf_index++;
 
382
    }
 
383
 
 
384
    current_sf_index = last_sf_index = 0;
 
385
}
 
386
 
 
387
/*----------------------------------------------------------------
 
388
 * get converted instrument info and load the wave data from file
 
389
 *----------------------------------------------------------------*/
 
390
 
 
391
/* two (high/low) 8 bit values in 16 bit parameter */
 
392
#define LO_VAL(val)     ((val) & 0xff)
 
393
#define HI_VAL(val)     (((val) >> 8) & 0xff)
 
394
#define SET_LO(vp,val)  ((vp) = ((vp) & 0xff00) | (val))
 
395
#define SET_HI(vp,val)  ((vp) = ((vp) & 0xff) | ((val) << 8))
 
396
 
 
397
static int patch_memory;
 
398
 
 
399
#ifdef ADAGIO
 
400
InstrumentLayer *load_sbk_patch(int gm_num, int tpgm, int reverb, int main_volume) {
 
401
    extern int next_wave_prog;
 
402
    char *name;
 
403
    int percussion, amp=-1, keynote, strip_loop, strip_envelope, strip_tail, bank, newmode;
 
404
#else
 
405
InstrumentLayer *load_sbk_patch(const char *name, int gm_num, int bank, int percussion,
 
406
                           int panning, int amp, int keynote, int sf_ix) {
 
407
#endif
 
408
        int preset;
 
409
        int not_done, load_index=0;
 
410
        InstList *ip;
 
411
        InstrumentLayer *lp, *nlp;
 
412
        Instrument *inst = NULL;
 
413
 
 
414
    preset = gm_num;
 
415
    if (gm_num >= 128) preset -= 128;
 
416
 
 
417
#ifdef ADAGIO
 
418
    if (!(gus_voice[tpgm].keep & SBK_FLAG)) return(0);
 
419
    bank = gus_voice[tpgm].bank & 0x7f;
 
420
    newmode = gus_voice[tpgm].modes;
 
421
    strip_loop = strip_envelope = strip_tail = amp = -1;
 
422
    percussion = (gm_num >= 128);
 
423
    name = gus_voice[tpgm].vname;
 
424
/*
 
425
    if (very_verbose) printf("load_sbk_patch(%s:bank=%d,preset=%d,tpgm=%d,reverb=%d,main_volume=%d) keep 0x%02X\n",
 
426
        name,bank,preset,tpgm,reverb,main_volume, gus_voice[tpgm].keep);
 
427
*/
 
428
#endif
 
429
 
 
430
    if (percussion) {
 
431
        keynote = preset;
 
432
        preset = bank;
 
433
        bank = 128;
 
434
    }
 
435
    else keynote = -1;
 
436
 
 
437
    if (sf_ix < 0 || sf_ix >= MAX_SF_FILES) {
 
438
        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Indexing non-existent soundfont %d.",
 
439
                sf_ix);
 
440
        return 0;
 
441
    }
 
442
    if (!sfrec[sf_ix].fname || !sfrec[sf_ix].instlist) {
 
443
        ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Indexing uninitialized soundfont %d.",
 
444
                sf_ix);
 
445
        return 0;
 
446
    }
 
447
 
 
448
    cutoff_allowed = command_cutoff_allowed;
 
449
 
 
450
    patch_memory = 0;
 
451
 
 
452
    not_done = 1;
 
453
    lp = 0;
 
454
 
 
455
    while (not_done) {
 
456
 
 
457
        for (ip = sfrec[sf_ix].instlist; ip; ip = ip->next) {
 
458
                if (ip->bank == bank && ip->preset == preset &&
 
459
                        ip->already_loaded > load_index &&
 
460
                    (keynote < 0 || keynote == ip->keynote))
 
461
                        break;
 
462
        }
 
463
        inst = 0;
 
464
        if (ip && (ip->samples || ip->rsamples)) {
 
465
                if (!load_index)
 
466
                        load_index = ip->already_loaded - 1;
 
467
                ip->already_loaded = load_index;
 
468
                sfrec[sf_ix].fname = ip->fname;
 
469
#ifdef READ_WHOLE_SF_FILE
 
470
                sfrec[sf_ix].contents = ip->contents;
 
471
#endif
 
472
                ctl->cmsg(CMSG_INFO, VERB_NOISY, "%s%s[%d,%d] %s%s (%d-%d)",
 
473
                        (percussion)? "   ":"", name,
 
474
                        (percussion)? keynote : preset, (percussion)? preset : bank,
 
475
                        (ip->rsamples)? "(2) " : "",
 
476
                        sfrec[sf_ix].fname,
 
477
                        LO_VAL(ip->velrange),
 
478
                                HI_VAL(ip->velrange)? HI_VAL(ip->velrange) : 127 );
 
479
                sfrec[sf_ix].fd = ip->fd;
 
480
                inst = load_from_file(&sfrec[sf_ix], ip, amp);
 
481
#ifdef READ_WHOLE_SF_FILE
 
482
                if (inst) inst->contents = ip->contents;
 
483
#endif
 
484
        }
 
485
        else {
 
486
                ip = 0;
 
487
                not_done = 0;
 
488
                if (!lp) {
 
489
                    ctl->cmsg(CMSG_INFO, VERB_NORMAL, "Can't find %s %s[%d,%d] in %s.",
 
490
                        (percussion)? "drum":"instrument", name,
 
491
                        (percussion)? keynote : preset, (percussion)? preset : bank, sfrec[sf_ix].fname);
 
492
                    return 0;
 
493
                }
 
494
        }
 
495
 
 
496
 
 
497
#ifdef ADAGIO
 
498
        if (inst) {
 
499
            gus_voice[tpgm].loaded |= DSP_MASK;
 
500
            gus_voice[tpgm].prog = next_wave_prog++;
 
501
        }
 
502
#endif
 
503
        if (inst) {
 
504
                nlp = lp;
 
505
                lp=(InstrumentLayer*) safe_malloc(sizeof(InstrumentLayer));
 
506
                patch_memory += sizeof(InstrumentLayer);
 
507
                lp->lo = LO_VAL(ip->velrange);
 
508
                lp->hi = HI_VAL(ip->velrange);
 
509
                lp->instrument = inst;
 
510
                lp->next = nlp;
 
511
        }
 
512
 
 
513
        lp->size = patch_memory;
 
514
        if (check_for_rc()) return lp;
 
515
        if (patch_memory + current_patch_memory > max_patch_memory) return lp;
 
516
 
 
517
    } /* while (not_done) */
 
518
 
 
519
    lp->size = patch_memory;
 
520
    return lp;
 
521
}
 
522
 
 
523
 
 
524
static Instrument *load_from_file(SFInsts *rec, InstList *ip, int amp)
 
525
{
 
526
        Instrument *inst;
 
527
        int r_amp = amp;
 
528
/*
 
529
        ctl->cmsg(CMSG_INFO, VERB_NOISY, "Loading SF bank %d prg %d note %d from %s",
 
530
                  ip->bank, ip->preset, ip->keynote, rec->fname);
 
531
*/
 
532
 
 
533
        inst = (Instrument *)safe_malloc(sizeof(Instrument));
 
534
        patch_memory += sizeof(Instrument);
 
535
        inst->type = INST_SF2;
 
536
        /* we could have set up right samples but no left ones */
 
537
        if (!ip->samples && ip->rsamples && ip->rslist) {
 
538
                ip->samples = ip->rsamples;
 
539
                ip->slist = ip->rslist;
 
540
                ip->rsamples = 0;
 
541
                ip->rslist = 0;
 
542
        }
 
543
        inst->samples = ip->samples;
 
544
        inst->sample = (Sample *)safe_malloc(sizeof(Sample)*ip->samples);
 
545
        patch_memory += sizeof(Sample)*ip->samples;
 
546
 
 
547
        inst->left_samples = inst->samples;
 
548
        inst->left_sample = inst->sample;
 
549
        inst->right_samples = ip->rsamples;
 
550
/*#define PSEUDO_STEREO*/
 
551
#ifdef PSEUDO_STEREO
 
552
        if (!ip->rsamples && ip->keynote >= 0) {
 
553
                ip->rsamples = ip->samples;
 
554
                ip->rslist = ip->slist;
 
555
                if (ip->keynote % 2) r_amp = -2;
 
556
                else r_amp = -3;
 
557
        }
 
558
#endif
 
559
        if (ip->rsamples) inst->right_sample = (Sample *)safe_malloc(sizeof(Sample)*ip->rsamples);
 
560
        else inst->right_sample = 0;
 
561
 
 
562
        if (load_one_side(rec, ip->slist, ip->samples, inst->sample, amp) &&
 
563
            load_one_side(rec, ip->rslist, ip->rsamples, inst->right_sample, r_amp))
 
564
                return inst;
 
565
 
 
566
        if (inst->right_sample) free(inst->right_sample);
 
567
        free(inst->sample);
 
568
        free(inst);
 
569
        return 0;
 
570
}
 
571
 
 
572
 
 
573
static int load_one_side(SFInsts *rec, SampleList *sp, int sample_count, Sample *base_sample, int amp)
 
574
{
 
575
        int i;
 
576
        uint32 samplerate_save;
 
577
 
 
578
        for (i = 0; i < sample_count && sp; i++, sp = sp->next) {
 
579
                Sample *sample = base_sample + i;
 
580
#ifndef LITTLE_ENDIAN
 
581
                int32 j;
 
582
                int16 *tmp, s;
 
583
#endif
 
584
                memcpy(sample, &sp->v, sizeof(Sample));
 
585
/* here, if we read whole file, sample->data = rec.contents + sp->startsample */
 
586
#ifdef READ_WHOLE_SF_FILE
 
587
            if (rec->contents)
 
588
                sample->data = (sample_t *)(rec->contents + sp->startsample);
 
589
                else
 
590
#endif
 
591
                sample->data = (sample_t *) safe_malloc(sp->endsample);
 
592
#ifndef READ_WHOLE_SF_FILE
 
593
                patch_memory += sp->endsample;
 
594
#else
 
595
            if (!rec->contents)
 
596
#endif
 
597
                if (fseek(rec->fd, (int)sp->startsample, SEEK_SET)) {
 
598
                        ctl->cmsg(CMSG_INFO, VERB_NORMAL, "Can't find sample in file!\n");
 
599
                        return 0;
 
600
                }
 
601
#ifdef READ_WHOLE_SF_FILE
 
602
            if (!rec->contents)
 
603
#endif
 
604
                if (!fread(sample->data, sp->endsample, 1, rec->fd)) {
 
605
                        ctl->cmsg(CMSG_INFO, VERB_NORMAL, "Can't read sample from file!\n");
 
606
                        return 0;
 
607
                }
 
608
 
 
609
#ifndef LITTLE_ENDIAN
 
610
/* NOTE: only do this once for all samples when first loaded ?? */
 
611
                tmp = (int16*)sample->data;
 
612
                for (j = 0; j < sp->endsample/2; j++) {
 
613
                        s = LE_SHORT(*tmp);
 
614
                        *tmp++ = s;
 
615
                }
 
616
#endif
 
617
 
 
618
        /* Note: _One_ thing that keeps this from working right is that,
 
619
           apparently, zero-crossing points change so loops give clicks;
 
620
           Another problem is that have to reload voices between songs.
 
621
           The filter really ought to be in resample.c.
 
622
        */
 
623
                /* do some filtering if necessary */
 
624
                /* (moved below -- should it be here?) */
 
625
 
 
626
#ifdef PSEUDO_STEREO
 
627
        if (amp<-1) {
 
628
                if (sp->v.panning >= 64) sp->v.panning = 0;
 
629
                else sp->v.panning = 127;
 
630
                if (amp==-3) sp->v.panning = 127 - sp->v.panning;
 
631
                /*amp = 80;*/
 
632
                amp = -1;
 
633
        }
 
634
#endif
 
635
 
 
636
#ifdef ADJUST_SAMPLE_VOLUMES
 
637
      if (amp!=-1)
 
638
        sample->volume=(double)(amp) / 100.0;
 
639
      else
 
640
        {
 
641
          /* Try to determine a volume scaling factor for the sample.
 
642
             This is a very crude adjustment, but things sound more
 
643
             balanced with it. Still, this should be a runtime option. */
 
644
          uint32 i, numsamps=sp->endsample/2;
 
645
          uint32 higher=0, highcount=0;
 
646
          int16 maxamp=0,a;
 
647
          int16 *tmp=(int16 *)sample->data;
 
648
          i = numsamps;
 
649
          while (i--)
 
650
            {
 
651
              a=*tmp++;
 
652
              if (a<0) a=-a;
 
653
              if (a>maxamp)
 
654
                maxamp=a;
 
655
            }
 
656
          tmp=(int16 *)sample->data;
 
657
          i = numsamps;
 
658
          while (i--)
 
659
            {
 
660
              a=*tmp++;
 
661
              if (a<0) a=-a;
 
662
              if (a > 3*maxamp/4)
 
663
                {
 
664
                   higher += a;
 
665
                   highcount++;
 
666
                }
 
667
            }
 
668
          if (highcount) higher /= highcount;
 
669
          else higher = 10000;
 
670
          sample->volume = (32768.0 * 0.875) /  (double)higher ;
 
671
          ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * volume comp: %f", sample->volume);
 
672
        }
 
673
#else
 
674
      if (amp!=-1)
 
675
        sample->volume=(double)(amp) / 100.0;
 
676
      else
 
677
        sample->volume=1.0;
 
678
#endif
 
679
 
 
680
 
 
681
        if (antialiasing_allowed) {
 
682
                /* restore the normal value */
 
683
                sample->data_length >>= FRACTION_BITS;
 
684
                antialiasing(sample, play_mode->rate);
 
685
                /* convert again to the fractional value */
 
686
                sample->data_length <<= FRACTION_BITS;
 
687
        }
 
688
 
 
689
                /* resample it if possible */
 
690
                samplerate_save = sample->sample_rate;
 
691
    /* trim off zero data at end */
 
692
    {
 
693
        int ls = sample->loop_start>>FRACTION_BITS;
 
694
        int le = sample->loop_end>>FRACTION_BITS;
 
695
        int se = sample->data_length>>FRACTION_BITS;
 
696
        while (se > 1 && !sample->data[se-1]) se--;
 
697
        if (le > se) le = se;
 
698
        if (ls >= le) sample->modes &= ~MODES_LOOPING;
 
699
        sample->loop_end = le<<FRACTION_BITS;
 
700
        sample->data_length = se<<FRACTION_BITS;
 
701
    }
 
702
 
 
703
 
 
704
#ifndef READ_WHOLE_SF_FILE
 
705
/* NOTE: tell pre_resample not to free */
 
706
        if (sample->note_to_use && !(sample->modes & MODES_LOOPING))
 
707
                pre_resample(sample);
 
708
#endif
 
709
 
 
710
/*fprintf(stderr,"sample %d, note_to_use %d\n", i, sample->note_to_use);*/
 
711
#ifdef LOOKUP_HACK
 
712
        /* squash the 16-bit data into 8 bits. */
 
713
        {
 
714
                uint8 *gulp,*ulp;
 
715
                int16 *swp;
 
716
                int l = sample->data_length >> FRACTION_BITS;
 
717
                gulp = ulp = safe_malloc(l + 1);
 
718
                swp = (int16 *)sample->data;
 
719
                while (l--)
 
720
                        *ulp++ = (*swp++ >> 8) & 0xFF;
 
721
                free(sample->data);
 
722
                sample->data=(sample_t *)gulp;
 
723
        }
 
724
#endif
 
725
 
 
726
        if (!sample->sample_rate && !dont_filter_drums) {
 
727
                if (!i) ctl->cmsg(CMSG_INFO, VERB_DEBUG, "cutoff = %ld ; resonance = %g",
 
728
                        sp->cutoff_freq, sp->resonance);
 
729
                do_lowpass(sample, samplerate_save, sample->data, sample->data_length >> FRACTION_BITS,
 
730
                        sp->cutoff_freq, sp->resonance);
 
731
        }
 
732
 
 
733
/*
 
734
printf("loop start %ld, loop end %ld, len %d\n", sample->loop_start>>FRACTION_BITS, sample->loop_end>>FRACTION_BITS,
 
735
sample->data_length >> FRACTION_BITS);
 
736
*/
 
737
 
 
738
/* #define HANNU_CLICK_REMOVAL */
 
739
/*#define DEBUG_CLICK*/
 
740
#ifdef HANNU_CLICK_REMOVAL
 
741
    if ((sample->modes & MODES_LOOPING)) {
 
742
        int nls = sample->loop_start>>FRACTION_BITS;
 
743
        int nle = sample->loop_end>>FRACTION_BITS;
 
744
        int ipt = 0, ips = 0;
 
745
        int v1, v2, inls, inle;
 
746
        inls = nls;
 
747
        inle = nle;
 
748
        while (!ipt) {
 
749
                v1 = sample->data[nle-1];  v2 = sample->data[nle];
 
750
                if (v2==0) {
 
751
                        if (v1 < 0) ipt = 1;
 
752
                        else if (v1 > 0) ipt = 2;
 
753
                }
 
754
                else {
 
755
                        if (v1 <= 0 && v2 > 0) ipt = 1;
 
756
                        else if (v1 >= 0 && v2 < 0) ipt = 2;
 
757
                }
 
758
                if (!ipt) nle--;
 
759
                if (nle <= inls) break;
 
760
        }
 
761
        if (ipt && nls > 0) while (!ips) {
 
762
                v1 = sample->data[nls-1];  v2 = sample->data[nls];
 
763
                if (v2==0) {
 
764
                        if (ipt == 1 && v1 < 0) ips = 1;
 
765
                        else if (ipt == 2 && v1 > 0) ips = 2;
 
766
                }
 
767
                else {
 
768
                        if (ipt == 1 && v1 <= 0 && v2 > 0) ips = 1;
 
769
                        else if (ipt == 2 && v1 >= 0 && v2 < 0) ips = 2;
 
770
                }
 
771
                if (!ips) nls--;
 
772
                if (nls < 1) break;
 
773
        }
 
774
        if (ipt && ips && ipt == ips && (nle-nls) == (inle-inls)) {
 
775
#ifdef DEBUG_CLICK
 
776
printf("changing loop start from %d to %d, loop end from %d to %d, len %d to %d\n",
 
777
inls, nls,
 
778
inle, nle,
 
779
inle-inls, nle-nls);
 
780
#endif
 
781
                sample->loop_start = nls<<FRACTION_BITS;
 
782
                sample->loop_end = nle<<FRACTION_BITS;
 
783
        }
 
784
    }
 
785
#endif
 
786
        }
 
787
        return 1;
 
788
}
 
789
 
 
790
/*----------------------------------------------------------------
 
791
 * parse a preset
 
792
 *----------------------------------------------------------------*/
 
793
 
 
794
static void parse_preset(SFInsts *rec, SFInfo *sf, int preset)
 
795
{
 
796
        int from_ndx, to_ndx;
 
797
        Layer lay, glay;
 
798
        int i, inst, inum, num_i;
 
799
 
 
800
        from_ndx = sf->presethdr[preset].bagNdx;
 
801
        to_ndx = sf->presethdr[preset+1].bagNdx;
 
802
        num_i = to_ndx - from_ndx;
 
803
 
 
804
#ifdef GREGSTEST
 
805
if (to_ndx - from_ndx > 1) {
 
806
fprintf(stderr,"Preset #%d (%s) has %d(-1) instruments.\n", preset,
 
807
 getname(sf->presethdr[preset].name), to_ndx - from_ndx);
 
808
}
 
809
#endif
 
810
 
 
811
        memset(&glay, 0, sizeof(glay));
 
812
        for (i = from_ndx, inum = 0; i < to_ndx; i++) {
 
813
                memset(&lay, 0, sizeof(Layer));
 
814
                parse_preset_layer(&lay, sf, i);
 
815
                inst = search_inst(&lay);
 
816
                if (inst < 0) {/* global layer */
 
817
                        memcpy(&glay, &lay, sizeof(Layer));
 
818
                        num_i--;
 
819
                }
 
820
                else {
 
821
                        /* append_layer(&lay, &glay, sf); */
 
822
                        merge_layer(&lay, &glay);
 
823
                        parse_inst(rec, &lay, sf, preset, inst, inum, num_i);
 
824
                        inum++;
 
825
                }
 
826
        }
 
827
}
 
828
 
 
829
/* map a generator operation to the layer structure */
 
830
static void parse_gen(Layer *lay, tgenrec *gen)
 
831
{
 
832
        lay->set[gen->oper] = 1;
 
833
        lay->val[gen->oper] = gen->amount;
 
834
}
 
835
 
 
836
/* parse preset generator layers */
 
837
static void parse_preset_layer(Layer *lay, SFInfo *sf, int idx)
 
838
{
 
839
        int i;
 
840
        for (i = sf->presetbag[idx]; i < sf->presetbag[idx+1]; i++)
 
841
                parse_gen(lay, sf->presetgen + i);
 
842
}
 
843
 
 
844
 
 
845
/* merge two layers; never overrides on the destination */
 
846
static void merge_layer(Layer *dst, Layer *src)
 
847
{
 
848
        int i;
 
849
        for (i = 0; i < PARM_SIZE; i++) {
 
850
                if (src->set[i] && !dst->set[i]) {
 
851
                        dst->val[i] = src->val[i];
 
852
                        dst->set[i] = 1;
 
853
                }
 
854
        }
 
855
}
 
856
 
 
857
/* search instrument id from the layer */
 
858
static int search_inst(Layer *lay)
 
859
{
 
860
        if (lay->set[SF_instrument])
 
861
                return lay->val[SF_instrument];
 
862
        else
 
863
                return -1;
 
864
}
 
865
 
 
866
/* parse an instrument */
 
867
static void parse_inst(SFInsts *rec, Layer *pr_lay, SFInfo *sf, int preset, int inst, int inum, int num_i)
 
868
{
 
869
        int from_ndx, to_ndx;
 
870
        int i, sample;
 
871
        uint16 pv_range=0, pk_range=0;
 
872
        Layer lay, glay;
 
873
 
 
874
        from_ndx = sf->insthdr[inst].bagNdx;
 
875
        to_ndx = sf->insthdr[inst+1].bagNdx;
 
876
 
 
877
        if (pr_lay->set[SF_velRange])
 
878
                pv_range = pr_lay->val[SF_velRange];
 
879
        if (pr_lay->set[SF_keyRange])
 
880
                pk_range = pr_lay->val[SF_keyRange];
 
881
 
 
882
        memcpy(&glay, pr_lay, sizeof(Layer));
 
883
        for (i = from_ndx; i < to_ndx; i++) {
 
884
                memset(&lay, 0, sizeof(Layer));
 
885
                parse_inst_layer(&lay, sf, i);
 
886
                sample = search_sample(&lay);
 
887
                if (sample < 0) /* global layer */
 
888
                        append_layer(&glay, &lay, sf);
 
889
                else {
 
890
                        /* append_layer(&lay, &glay, sf); */
 
891
                        merge_layer(&lay, &glay);
 
892
                        make_inst(rec, &lay, sf, preset, inst, inum, pk_range, pv_range, num_i, -1);
 
893
                }
 
894
        }
 
895
}
 
896
 
 
897
/* parse instrument generator layers */
 
898
static void parse_inst_layer(Layer *lay, SFInfo *sf, int idx)
 
899
{
 
900
        int i;
 
901
        for (i = sf->instbag[idx]; i < sf->instbag[idx+1]; i++)
 
902
                parse_gen(lay, sf->instgen + i);
 
903
}
 
904
 
 
905
/* search a sample id from instrument layers */
 
906
static int search_sample(Layer *lay)
 
907
{
 
908
        if (lay->set[SF_sampleId])
 
909
                return lay->val[SF_sampleId];
 
910
        else
 
911
                return -1;
 
912
}
 
913
 
 
914
 
 
915
/* append two layers; parameters are added to the original value */
 
916
static void append_layer(Layer *dst, Layer *src, SFInfo *sf)
 
917
{
 
918
        int i;
 
919
        for (i = 0; i < PARM_SIZE; i++) {
 
920
                if (src->set[i]) {
 
921
                        if (sf->version == 1 && i == SF_instVol)
 
922
                                dst->val[i] = (src->val[i] * 127) / 127;
 
923
                        else if (i == SF_keyRange || i == SF_velRange) {
 
924
                                /* high limit */
 
925
                                if (HI_VAL(dst->val[i]) > HI_VAL(src->val[i]))
 
926
                                        SET_HI(dst->val[i], HI_VAL(src->val[i]));
 
927
                                /* low limit */
 
928
                                if (LO_VAL(dst->val[i]) < LO_VAL(src->val[i]))
 
929
                                        SET_LO(dst->val[i], LO_VAL(src->val[i]));
 
930
                        } else
 
931
                                dst->val[i] += src->val[i];
 
932
                        dst->set[i] = 1;
 
933
                }
 
934
        }
 
935
}
 
936
 
 
937
static char kvec[2][128];
 
938
static void clear_kvec()
 
939
{
 
940
        int i;
 
941
        for (i=0; i<128; i++) {
 
942
                kvec[0][i] = kvec[1][i] = 0;
 
943
        }
 
944
}
 
945
static void new_kvec(int lr)
 
946
{
 
947
        int i;
 
948
        for (i=0; i<128; i++) {
 
949
                kvec[lr][i] = 0;
 
950
        }
 
951
}
 
952
static void union_kvec(int lr, int kr)
 
953
{
 
954
        int i;
 
955
        if (!kr || kr<0) return;
 
956
        for (i=0; i<128; i++)
 
957
            if (i >= LO_VAL(kr) && i <= HI_VAL(kr)) kvec[lr][i] = 1;
 
958
 
 
959
}
 
960
static int intersect_kvec(int lr, int kr)
 
961
{
 
962
        int i;
 
963
        if (!kr || kr<0) return 0;
 
964
        for (i=0; i<128; i++)
 
965
            if (i >= LO_VAL(kr) && i <= HI_VAL(kr) && kvec[lr][i]) return 1;
 
966
        return 0;
 
967
}
 
968
static int subset_kvec(int lr, int kr)
 
969
{
 
970
        int i;
 
971
        if (!kr || kr<0) return 0;
 
972
        for (i=0; i<128; i++)
 
973
            if (i >= LO_VAL(kr) && i <= HI_VAL(kr) && !kvec[lr][i]) return 0;
 
974
        return 1;
 
975
}
 
976
 
 
977
static char vvec[2][128];
 
978
 
 
979
static void clear_vvec()
 
980
{
 
981
        int i;
 
982
        for (i=0; i<128; i++) {
 
983
                vvec[0][i] = vvec[1][i] = 0;
 
984
        }
 
985
}
 
986
static void union_vvec(int lr, int vr)
 
987
{
 
988
        int i;
 
989
        if (!vr || vr<0) return;
 
990
        for (i=0; i<128; i++)
 
991
            if (i >= LO_VAL(vr) && i <= HI_VAL(vr)) vvec[lr][i] = 1;
 
992
 
 
993
}
 
994
static int intersect_vvec(int lr, int vr)
 
995
{
 
996
        int i;
 
997
        if (!vr || vr<0) return 0;
 
998
        for (i=0; i<128; i++)
 
999
            if (i >= LO_VAL(vr) && i <= HI_VAL(vr) && vvec[lr][i]) return 1;
 
1000
        return 0;
 
1001
}
 
1002
 
 
1003
static char rvec[2][128];
 
1004
 
 
1005
static void clear_rvec()
 
1006
{
 
1007
        int i;
 
1008
        for (i=0; i<128; i++) {
 
1009
                rvec[0][i] = rvec[1][i] = 0;
 
1010
        }
 
1011
}
 
1012
static void union_rvec(int lr, int kr)
 
1013
{
 
1014
        int i;
 
1015
        if (!kr || kr<0) return;
 
1016
        for (i=0; i<128; i++)
 
1017
            if (i >= LO_VAL(kr) && i <= HI_VAL(kr)) rvec[lr][i] = 1;
 
1018
}
 
1019
static int subset_rvec(int lr, int kr)
 
1020
{
 
1021
        int i;
 
1022
        if (!kr || kr<0) return 0;
 
1023
        for (i=0; i<128; i++)
 
1024
            if (i >= LO_VAL(kr) && i <= HI_VAL(kr) && !rvec[lr][i]) return 0;
 
1025
        return 1;
 
1026
}
 
1027
static int intersect_rvec(int lr, int kr)
 
1028
{
 
1029
        int i;
 
1030
        if (!kr || kr<0) return 0;
 
1031
        for (i=0; i<128; i++)
 
1032
            if (i >= LO_VAL(kr) && i <= HI_VAL(kr) && rvec[lr][i]) return 1;
 
1033
        return 0;
 
1034
}
 
1035
/* convert layer info to timidity instrument strucutre */
 
1036
static void make_inst(SFInsts *rec, Layer *lay, SFInfo *sf, int pr_idx, int in_idx, int inum,
 
1037
        uint16 pk_range, uint16 pv_range, int num_i, int program)
 
1038
{
 
1039
        int banknum = sf->presethdr[pr_idx].bank;
 
1040
        int preset = sf->presethdr[pr_idx].preset;
 
1041
        int sub_banknum = sf->presethdr[pr_idx].sub_bank;
 
1042
        int sub_preset = sf->presethdr[pr_idx].sub_preset;
 
1043
        int keynote, truebank, note_to_use, velrange;
 
1044
        int strip_loop = 0, strip_envelope = 0,
 
1045
                strip_tail = 0, panning = 0, cfg_tuning = 0;
 
1046
#ifndef ADAGIO
 
1047
        ToneBank *bank=0;
 
1048
        const char **namep;
 
1049
#endif
 
1050
        InstList *ip;
 
1051
        tsampleinfo *sample;
 
1052
        SampleList *sp;
 
1053
#ifdef DO_LINKED_WAVES
 
1054
        int linked_wave;
 
1055
#endif
 
1056
        int sampleFlags, stereo_chan = 0, keyrange, x_chan = 0;
 
1057
        static int lastpreset = -1;
 
1058
        static int lastbanknum = -1;
 
1059
        static int lastvelrange = -1;
 
1060
        static int lastrange = -1;
 
1061
        static int last_chan = -1;
 
1062
        static int lastinum = -1;
 
1063
        static int laststereo_chan = 0;
 
1064
        static int lastpk_range = 0;
 
1065
 
 
1066
        if (pk_range) velrange = 0;
 
1067
        else if (pv_range) velrange = pv_range;
 
1068
        else if (lay->set[SF_velRange]) velrange = lay->val[SF_velRange];
 
1069
        else velrange = 0;
 
1070
 
 
1071
#ifdef GREGSTEST
 
1072
if (velrange)
 
1073
fprintf(stderr,"bank %d, preset %d, inum %d, lo %d, hi %d\n", banknum, preset, inum,
 
1074
LO_VAL(velrange), HI_VAL(velrange));
 
1075
#endif
 
1076
 
 
1077
        sample = &sf->sampleinfo[lay->val[SF_sampleId]];
 
1078
#ifdef DO_LINKED_WAVES
 
1079
        linked_wave = sample->samplelink;
 
1080
        if (linked_wave && linked_wave < sfinfo.nrinfos) {
 
1081
                if (inum == -1) sample = &sf->sampleinfo[linked_wave - 1];
 
1082
                else make_inst(rec, lay, sf, pr_idx, in_idx, -1, pk_range, velrange, num_i, -1);
 
1083
        }
 
1084
#endif
 
1085
        if (sample->sampletype & 0x8000) /* is ROM sample? */
 
1086
                return;
 
1087
 
 
1088
        if (lay->set[SF_keyRange]) keyrange = lay->val[SF_keyRange];
 
1089
        else keyrange = 0;
 
1090
 
 
1091
        /* Were we called to do later notes of a percussion range? */
 
1092
        if (program >= 0) keyrange = (program << 8) | program;
 
1093
        else if (banknum == 128 && LO_VAL(keyrange) < HI_VAL(keyrange)) {
 
1094
                int drumkey = LO_VAL(keyrange);
 
1095
                int lastdkey = HI_VAL(keyrange);
 
1096
                keyrange = (drumkey << 8) | drumkey;
 
1097
                drumkey++;
 
1098
                /* Do later notes of percussion key range. */
 
1099
                for ( ; drumkey <= lastdkey; drumkey++)
 
1100
                  make_inst(rec, lay, sf, pr_idx, in_idx, inum, pk_range, pv_range, num_i, drumkey);
 
1101
        }
 
1102
        /* set bank/preset name */
 
1103
        if (banknum == 128) {
 
1104
                truebank = sub_preset;
 
1105
                if (program == -1) program = keynote = LO_VAL(keyrange);
 
1106
                else keynote = program;
 
1107
#ifndef ADAGIO
 
1108
                bank = drumset[truebank];
 
1109
#endif
 
1110
        } else {
 
1111
                keynote = -1;
 
1112
                truebank = sub_banknum;
 
1113
                program = preset;
 
1114
#ifndef ADAGIO
 
1115
                bank = tonebank[truebank];
 
1116
#endif
 
1117
        }
 
1118
 
 
1119
#ifdef GREGSTEST
 
1120
fprintf(stderr,"Adding keynote #%d preset %d to %s (%d), bank %d (=? %d).\n", keynote, preset,
 
1121
 getname(sf->insthdr[in_idx].name), in_idx, banknum, truebank);
 
1122
#endif
 
1123
 
 
1124
 
 
1125
#ifndef ADAGIO
 
1126
        if (!bank) return;
 
1127
        namep = &bank->tone[program].name;
 
1128
#ifdef GREGSTEST
 
1129
        if (*namep) fprintf(stderr,"cfg name is %s\n", *namep);
 
1130
        else printf("NO CFG NAME!\n");
 
1131
#endif
 
1132
        /* if not declared, we don't load it */
 
1133
        if (*namep == 0) return;
 
1134
 
 
1135
        /* could be a GUS patch */
 
1136
        if (bank->tone[program].font_type != FONT_SBK) return;
 
1137
        /* note we're loading this preset from a certain soundfont */
 
1138
        if (bank->tone[program].sf_ix == -1)
 
1139
                bank->tone[program].sf_ix = current_sf_index;
 
1140
        /* has it been loaded already from a different soundfont? */
 
1141
        else if (bank->tone[program].sf_ix != current_sf_index) return;
 
1142
 
 
1143
        panning = bank->tone[program].pan;
 
1144
        strip_loop = bank->tone[program].strip_loop;
 
1145
        strip_envelope = bank->tone[program].strip_envelope;
 
1146
        strip_tail = bank->tone[program].strip_tail;
 
1147
        note_to_use = bank->tone[program].note;
 
1148
        cfg_tuning = bank->tone[program].tuning;
 
1149
        /*if (!strip_envelope) strip_envelope = (banknum == 128);*/
 
1150
#endif
 
1151
 
 
1152
        /* search current instrument list */
 
1153
        for (ip = rec->instlist; ip; ip = ip->next) {
 
1154
                if (ip->bank == sub_banknum && ip->preset == sub_preset &&
 
1155
                    (keynote < 0 || keynote == ip->keynote))
 
1156
                        break;
 
1157
        }
 
1158
        /* don't append sample when instrument completely specified */
 
1159
        if (ip && ip->already_loaded) return;
 
1160
 
 
1161
        /* search current instrument list */
 
1162
        for (ip = rec->instlist; ip; ip = ip->next) {
 
1163
                if (ip->bank == sub_banknum && ip->preset == sub_preset &&
 
1164
                    ip->velrange == velrange &&
 
1165
                    (keynote < 0 || keynote == ip->keynote))
 
1166
                        break;
 
1167
        }
 
1168
 
 
1169
/* This doesn't work for Industry Standard G. Piano, which is mono but
 
1170
   pans to the right for higher notes.
 
1171
        if (!lay->set[SF_panEffectsSend] || lay->val[SF_panEffectsSend] <= 0)
 
1172
                stereo_chan = 0;
 
1173
        else    stereo_chan = 1;
 
1174
*/
 
1175
 
 
1176
/* earlier
 
1177
        if (lay->set[SF_keyRange]) keyrange = lay->val[SF_keyRange];
 
1178
        else keyrange = 0;
 
1179
*/
 
1180
        if (lastbanknum != banknum || lastpreset != preset) {
 
1181
                lastbanknum = banknum;
 
1182
                lastpreset = preset;
 
1183
                lastvelrange = velrange;
 
1184
                lastrange = -1;
 
1185
                clear_rvec();
 
1186
                clear_vvec();
 
1187
                clear_kvec();
 
1188
        }
 
1189
        if (lastvelrange != velrange) {
 
1190
                lastvelrange = velrange;
 
1191
                clear_rvec();
 
1192
        }
 
1193
        if (inum != lastinum) {
 
1194
                lastrange = -1;
 
1195
                clear_rvec();
 
1196
                lastinum = inum;
 
1197
        }
 
1198
 
 
1199
        if (banknum < 128 && pv_range && !pk_range) {
 
1200
                if (pv_range == lastrange) x_chan = last_chan;
 
1201
                else if (!intersect_vvec(0, pv_range)) x_chan = 0;
 
1202
                else if (!intersect_vvec(1, pv_range)) x_chan = 1;
 
1203
                else {
 
1204
                ctl->cmsg(CMSG_INFO, VERB_NOISY,
 
1205
                  "sndfont: invalid velocity range in bank %d preset %d: low %d, high %d",
 
1206
                        banknum, preset, LO_VAL(pv_range), HI_VAL(pv_range));
 
1207
                return;
 
1208
                }
 
1209
                if (pv_range != lastrange) {
 
1210
                #if 0
 
1211
                ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
 
1212
                  "sndfont: x_chan %d vel range in bank %d preset %d: low %d, high %d",
 
1213
                        x_chan, banknum, preset, LO_VAL(pv_range), HI_VAL(pv_range));
 
1214
                #endif
 
1215
                        last_chan = x_chan;
 
1216
                        clear_rvec();
 
1217
                        union_vvec(x_chan, pv_range);
 
1218
                        lastrange = pv_range;
 
1219
                }
 
1220
                #if 0
 
1221
                else if (intersect_rvec(x_chan, keyrange))
 
1222
                ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
 
1223
                  "sndfont: invalid layered key range in bank %d preset %d: low %d, high %d",
 
1224
                        banknum, preset, LO_VAL(keyrange), HI_VAL(keyrange));
 
1225
                #endif
 
1226
        }
 
1227
 
 
1228
        #if 0
 
1229
        if (x_chan != 0)
 
1230
                ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
 
1231
                  "sndfont: ignoring 2nd layered key range in bank %d preset %d: low %d, high %d",
 
1232
                        banknum, preset, LO_VAL(keyrange), HI_VAL(keyrange));
 
1233
        #endif
 
1234
        /* duplicated key ranges at preset level would require more than two patches per note */
 
1235
        if (x_chan != 0) return;
 
1236
 
 
1237
        if (banknum == 128 && num_i > 1 && pk_range) {
 
1238
                /*
 
1239
                 * keyranges at the preset level are to fill in for missing
 
1240
                 * patches, so if we have a patch, skip the fill in
 
1241
                 */
 
1242
                if (ip) return;
 
1243
                /*
 
1244
                 * the preset keyrange says which fill ins are to be taken from the
 
1245
                 * current instrument
 
1246
                 */
 
1247
                if (LO_VAL(keyrange) < LO_VAL(pk_range) || HI_VAL(keyrange) > HI_VAL(pk_range))
 
1248
                        return;
 
1249
        }
 
1250
 
 
1251
        /* melodic preset with multiple instruments */
 
1252
        if (banknum < 128 && num_i > 1 && (!pv_range || pk_range)) {
 
1253
                /* if no preset keyrange to tell us, put just first instrument at left */
 
1254
                if (!pk_range) {
 
1255
                    if (inum == 0) stereo_chan = 0;
 
1256
                    else stereo_chan = 1;
 
1257
                }
 
1258
                else if (pk_range == lastpk_range) {
 
1259
                    stereo_chan = laststereo_chan;
 
1260
                    if (!subset_kvec(stereo_chan, keyrange)) return;
 
1261
                }
 
1262
                else {
 
1263
                    if (!intersect_kvec(0, pk_range)) stereo_chan = 0;
 
1264
                    else {
 
1265
                        stereo_chan = 1;
 
1266
                        new_kvec(stereo_chan);
 
1267
                    }
 
1268
                    #if 0
 
1269
                    else {
 
1270
                        ctl->cmsg(CMSG_INFO, VERB_NOISY,
 
1271
                        "sndfont: invalid preset key range in bank %d preset %d: low %d, high %d",
 
1272
                                banknum, preset, LO_VAL(pk_range), HI_VAL(pk_range));
 
1273
                        return;
 
1274
                    }
 
1275
                    #endif
 
1276
                    laststereo_chan = stereo_chan;
 
1277
                    lastpk_range = pk_range;
 
1278
                    union_kvec(stereo_chan, pk_range);
 
1279
                    if (!subset_kvec(stereo_chan, keyrange)) return;
 
1280
                }
 
1281
        }
 
1282
        else if (!intersect_rvec(0, keyrange)) stereo_chan = 0;
 
1283
        else if (!intersect_rvec(1, keyrange)) stereo_chan = 1;
 
1284
        else if (!subset_rvec(0, keyrange)) stereo_chan = 0;
 
1285
        else if (!subset_rvec(1, keyrange)) stereo_chan = 1;
 
1286
        else {
 
1287
                ctl->cmsg(CMSG_INFO, VERB_DEBUG,
 
1288
                  "sndfont: invalid key range in bank %d preset %d: low %d, high %d",
 
1289
                        banknum, preset, LO_VAL(keyrange), HI_VAL(keyrange));
 
1290
                return;
 
1291
        }
 
1292
 
 
1293
        union_rvec(stereo_chan, keyrange);
 
1294
 
 
1295
#if 0
 
1296
if (pk_range)
 
1297
        ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
 
1298
          "adding chan %d in bank %d preset %d: low %d, high %d (preset low %d high %d; vel lo %d hi %d)",
 
1299
                stereo_chan, banknum, preset, LO_VAL(keyrange), HI_VAL(keyrange),
 
1300
                LO_VAL(pk_range), HI_VAL(pk_range),
 
1301
                LO_VAL(velrange), HI_VAL(velrange));
 
1302
#endif
 
1303
 
 
1304
        if (ip == NULL) {
 
1305
                ip = (InstList*)safe_malloc(sizeof(InstList));
 
1306
                ip->bank = sub_banknum;
 
1307
                ip->preset = sub_preset;
 
1308
                ip->keynote = keynote;
 
1309
                ip->inum = inum;
 
1310
                ip->velrange = velrange;
 
1311
                ip->already_loaded = 0;
 
1312
                ip->samples = 0;
 
1313
                ip->rsamples = 0;
 
1314
                ip->slist = NULL;
 
1315
                ip->rslist = NULL;
 
1316
                ip->fd = rec->fd;
 
1317
                ip->fname = rec->fname;
 
1318
                ip->next = rec->instlist;
 
1319
                rec->instlist = ip;
 
1320
        }
 
1321
 
 
1322
        /* add a sample */
 
1323
        sp = (SampleList*)safe_malloc(sizeof(SampleList));
 
1324
/* fix to check sample type for left vs. right? */
 
1325
        if (stereo_chan == 0) {
 
1326
        /* if (inum == ip->inum) { */
 
1327
                sp->next = ip->slist;
 
1328
                ip->slist = sp;
 
1329
                ip->samples++;
 
1330
        }
 
1331
        else {
 
1332
                sp->next = ip->rslist;
 
1333
                ip->rslist = sp;
 
1334
                ip->rsamples++;
 
1335
        }
 
1336
 
 
1337
 
 
1338
        /* set sample position */
 
1339
        sp->startsample = ((short)lay->val[SF_startAddrsHi] * 32768)
 
1340
                + (short)lay->val[SF_startAddrs]
 
1341
                + sample->startsample;
 
1342
        sp->endsample = ((short)lay->val[SF_endAddrsHi] * 32768)
 
1343
                + (short)lay->val[SF_endAddrs]
 
1344
                + sample->endsample - sp->startsample;
 
1345
 
 
1346
        if (sp->endsample > (1 << (32-FRACTION_BITS)))
 
1347
                ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
 
1348
                          "sndfont: patch size %ld greater than max (%ld)", sp->endsample, 1<<(32-FRACTION_BITS));
 
1349
 
 
1350
        /* set loop position */
 
1351
        sp->v.loop_start = ((short)lay->val[SF_startloopAddrsHi] * 32768)
 
1352
                + (short)lay->val[SF_startloopAddrs]
 
1353
                + sample->startloop - sp->startsample;
 
1354
        sp->v.loop_end = ((short)lay->val[SF_endloopAddrsHi] * 32768)
 
1355
                + (short)lay->val[SF_endloopAddrs]
 
1356
                + sample->endloop - sp->startsample;
 
1357
        sp->v.data_length = sp->endsample;
 
1358
#if 0
 
1359
/* debug loop point calculation */
 
1360
{
 
1361
        int32 xloop_start = sample->startloop - sp->startsample;
 
1362
        int32 xloop_end = sample->endloop - sp->startsample;
 
1363
        int yloop_start = (lay->val[SF_startloopAddrsHi] << 15) + lay->val[SF_startloopAddrs];
 
1364
        int yloop_end = (lay->val[SF_endloopAddrsHi] << 15) + lay->val[SF_endloopAddrs];
 
1365
        xloop_start += yloop_start;
 
1366
        xloop_end += yloop_end;
 
1367
        if (xloop_start > xloop_end) {
 
1368
        fprintf(stderr,"start %ld > end %ld\n", xloop_start, xloop_end);
 
1369
        fprintf(stderr,"\tstart %ld = orig %lu + yloop_start %d\n", xloop_start,
 
1370
                sp->v.loop_start, yloop_start);
 
1371
        fprintf(stderr,"\t\tyloop_start 0x%x = high 0x%x + low 0x%x\n", yloop_start,
 
1372
                (lay->val[SF_startloopAddrsHi] << 15), lay->val[SF_startloopAddrs]);
 
1373
        fprintf(stderr,"\t\tend %ld = orig %lu + yloop_end %d\n", xloop_end,
 
1374
                sp->v.loop_end, yloop_end);
 
1375
        fprintf(stderr,"\tlen %lu, startsample %lu sample startloop %lu endsample %lu\n",
 
1376
                sample->endsample - sample->startsample,
 
1377
                sample->startsample, sample->startloop, sample->endsample);
 
1378
        }
 
1379
        if (xloop_end > sp->v.data_length) {
 
1380
        fprintf(stderr,"end %ld > length %lu\n", xloop_end, sp->v.data_length);
 
1381
        fprintf(stderr,"\tend %ld = orig %lu + yloop_end %d\n", xloop_end,
 
1382
                sp->v.loop_end, yloop_end);
 
1383
        fprintf(stderr,"\t\tyloop_end 0x%x = high 0x%x + low 0x%x\n", yloop_end,
 
1384
                (lay->val[SF_endloopAddrsHi] << 15), lay->val[SF_endloopAddrs]);
 
1385
        fprintf(stderr,"\tlen %lu, startsample %lu sample endloop %lu endsample %lu\n",
 
1386
                sample->endsample - sample->startsample,
 
1387
                sample->startsample, sample->endloop, sample->endsample);
 
1388
        fprintf(stderr,"\t\tstart offset = high 0x%x + low 0x%x\n",
 
1389
                (lay->val[SF_startAddrsHi] << 15), lay->val[SF_startAddrs]);
 
1390
        fprintf(stderr,"\t\tend offset = high 0x%x + low 0x%x\n",
 
1391
                (lay->val[SF_endAddrsHi] << 15), lay->val[SF_endAddrs]);
 
1392
        }
 
1393
}
 
1394
#endif
 
1395
 
 
1396
#if 0
 
1397
        if (sp->v.loop_start < 0) {
 
1398
                ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Negative loop pointer: removing loop");
 
1399
                strip_loop = 1;
 
1400
        }
 
1401
#endif
 
1402
        if (sp->v.loop_start > sp->v.loop_end) {
 
1403
                ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Illegal loop position: removing loop");
 
1404
                strip_loop = 1;
 
1405
        }
 
1406
        if (sp->v.loop_end > sp->v.data_length) {
 
1407
                ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Illegal loop end or data size: adjusting loop");
 
1408
                if (sp->v.loop_end - sp->v.data_length > 4)
 
1409
                        sp->v.loop_end = sp->v.data_length - 4;
 
1410
                else sp->v.loop_end = sp->v.data_length;
 
1411
        }
 
1412
 
 
1413
/* debug */
 
1414
#if 0
 
1415
if (strip_loop == 1) {
 
1416
        fprintf(stderr, "orig start sample %lu, endsample %lu\n", sample->startsample, sample->endsample);
 
1417
        fprintf(stderr, "SF_startAddr %d, SF_endAddr %d\n",
 
1418
                ((short)lay->val[SF_startAddrsHi] * 32768) + (short)lay->val[SF_startAddrs],
 
1419
                ((short)lay->val[SF_endAddrsHi] * 32768) + (short)lay->val[SF_endAddrs] );
 
1420
        fprintf(stderr, "start sample %lu, length %lu\n", sp->startsample, sp->endsample);
 
1421
        fprintf(stderr, "orig loop start %lu, loop end %lu\n", sample->startloop, sample->endloop);
 
1422
        fprintf(stderr, "SF_startloopAddr %d, SF_endloopAddr %d\n",
 
1423
                ((short)lay->val[SF_startloopAddrsHi] * 32768) + (short)lay->val[SF_startloopAddrs],
 
1424
                ((short)lay->val[SF_endloopAddrsHi] * 32768) + (short)lay->val[SF_endloopAddrs] );
 
1425
        fprintf(stderr, "loop start %lu, loop end %lu\n", sp->v.loop_start, sp->v.loop_end);
 
1426
}
 
1427
#endif
 
1428
 
 
1429
 
 
1430
        sp->v.sample_rate = sample->samplerate;
 
1431
        if (lay->set[SF_keyRange]) {
 
1432
                sp->v.low_freq = freq_table[LO_VAL(lay->val[SF_keyRange])];
 
1433
                sp->v.high_freq = freq_table[HI_VAL(lay->val[SF_keyRange])];
 
1434
        } else {
 
1435
                sp->v.low_freq = freq_table[0];
 
1436
                sp->v.high_freq = freq_table[127];
 
1437
        }
 
1438
        if (lay->set[SF_keyExclusiveClass]) sp->v.exclusiveClass = lay->val[SF_keyExclusiveClass];
 
1439
        else sp->v.exclusiveClass = 0;
 
1440
 
 
1441
        /* scale tuning: 0  - 100 */
 
1442
        sp->v.scale_tuning = 100;
 
1443
        if (lay->set[SF_scaleTuning]) {
 
1444
                if (sf->version == 1)
 
1445
                        sp->v.scale_tuning = lay->val[SF_scaleTuning] ? 50 : 100;
 
1446
                else
 
1447
                        sp->v.scale_tuning = lay->val[SF_scaleTuning];
 
1448
        }
 
1449
/** --gl **/
 
1450
#if 0
 
1451
        sp->v.freq_scale = 1024;
 
1452
        sp->v.freq_center = 60;
 
1453
#endif
 
1454
        if (sp->v.scale_tuning == 100) sp->v.freq_scale = 1024;
 
1455
        else sp->v.freq_scale = (sp->v.scale_tuning * 1024) / 100;
 
1456
 
 
1457
        /* sp->v.freq_center = 60; set in calc_root_pitch */
 
1458
        sp->v.attenuation = 0;
 
1459
/**  **/
 
1460
 
 
1461
        /* root pitch */
 
1462
        sp->v.root_freq = calc_root_pitch(lay, sf, sp, cfg_tuning);
 
1463
/* *
 
1464
if (banknum < 128 && (preset == 11 || preset == 42))
 
1465
fprintf(stderr, "preset %d, root_freq %ld (scale tune %d, freq scale %d, center %d)\n", preset, sp->v.root_freq,
 
1466
sp->v.scale_tuning, sp->v.freq_scale, sp->v.freq_center);
 
1467
* */
 
1468
        /* volume envelope & total volume */
 
1469
        sp->v.volume = 1.0; /* was calc_volume(lay,sf) */
 
1470
 
 
1471
        if (lay->set[SF_sampleFlags]) sampleFlags = lay->val[SF_sampleFlags];
 
1472
        else sampleFlags = 0;
 
1473
 
 
1474
        sp->v.modes = MODES_16BIT | MODES_ENVELOPE;
 
1475
 
 
1476
 
 
1477
        if (sampleFlags == 3) sp->v.modes |= MODES_FAST_RELEASE;
 
1478
 
 
1479
        /* arbitrary adjustments (look at sustain of vol envelope? ) */
 
1480
        if (sampleFlags && lay->val[SF_sustainEnv2] == 0) sampleFlags = 3;
 
1481
        else if (sampleFlags && lay->val[SF_sustainEnv2] >= 1000) sampleFlags = 1;
 
1482
        else if (banknum != 128) {
 
1483
                /* organs, accordians */
 
1484
                if (program >= 16 && program <= 23) sampleFlags = 3;
 
1485
                /* strings */
 
1486
                else if (program >= 40 && program <= 44) sampleFlags = 3;
 
1487
                /* strings, voice */
 
1488
                else if (program >= 48 && program <= 54) sampleFlags = 3;
 
1489
                /* horns, woodwinds */
 
1490
                else if (program >= 56 && program <= 79) sampleFlags = 3;
 
1491
                /* lead, pad, fx */
 
1492
                else if (program >= 80 && program <=103) sampleFlags = 3;
 
1493
                /* bagpipe, fiddle, shanai */
 
1494
                else if (program >=109 && program <=111) sampleFlags = 3;
 
1495
                /* breath noise, ... telephone, helicopter */
 
1496
                else if (program >=121 && program <=125) sampleFlags = 3;
 
1497
                /* applause */
 
1498
                else if (program ==126) sampleFlags = 3;
 
1499
        }
 
1500
 
 
1501
 
 
1502
        if (sampleFlags == 2) sampleFlags = 0;
 
1503
 
 
1504
        if (sampleFlags == 1 || sampleFlags == 3)
 
1505
                sp->v.modes |= MODES_LOOPING;
 
1506
        if (sampleFlags == 3)
 
1507
                sp->v.modes |= MODES_SUSTAIN;
 
1508
 
 
1509
 
 
1510
        convert_volume_envelope(lay, sf, sp, banknum, program);
 
1511
        convert_modulation_envelope(lay, sf, sp, banknum, program);
 
1512
 
 
1513
        if (strip_tail == 1) sp->v.data_length = sp->v.loop_end + 1;
 
1514
 
 
1515
      /* Strip any loops and envelopes we're permitted to */
 
1516
      if ((strip_loop==1) && 
 
1517
          (sp->v.modes & (MODES_SUSTAIN | MODES_LOOPING | 
 
1518
                        MODES_PINGPONG | MODES_REVERSE)))
 
1519
        {
 
1520
          ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing loop and/or sustain");
 
1521
          sp->v.modes &=~(MODES_SUSTAIN | MODES_LOOPING | 
 
1522
                        MODES_PINGPONG | MODES_REVERSE);
 
1523
        }
 
1524
 
 
1525
      if (strip_envelope==1)
 
1526
        {
 
1527
          if (sp->v.modes & MODES_ENVELOPE)
 
1528
            ctl->cmsg(CMSG_INFO, VERB_DEBUG, " - Removing envelope");
 
1529
          sp->v.modes &= ~MODES_ENVELOPE;
 
1530
        }
 
1531
 
 
1532
        /* if (banknum == 128 && !(sp->v.modes&(MODES_LOOPING|MODES_SUSTAIN))) sp->v.modes |= MODES_FAST_RELEASE; */
 
1533
 
 
1534
 
 
1535
        /* panning position: 0 to 127 */
 
1536
        if (panning != -1) sp->v.panning=(uint8)(panning & 0x7F);
 
1537
        else if (lay->set[SF_panEffectsSend]) {
 
1538
#ifdef tplussbk
 
1539
                    int val;
 
1540
                    /* panning position: 0 to 127 */
 
1541
                    val = (int)tbl->val[SF_panEffectsSend];
 
1542
                    if(val <= -500)
 
1543
                        sp->v.panning = 0;
 
1544
                    else if(val >= 500)
 
1545
                        sp->v.panning = 127;
 
1546
                    else
 
1547
                        sp->v.panning = (int8)((val + 500) * 127 / 1000);
 
1548
#else
 
1549
                if (sf->version == 1)
 
1550
                        sp->v.panning = (int8)lay->val[SF_panEffectsSend];
 
1551
                else
 
1552
                        sp->v.panning = (int8)(((int)lay->val[SF_panEffectsSend] + 500) * 127 / 1000);
 
1553
#endif
 
1554
        }
 
1555
        else sp->v.panning = 64;
 
1556
 
 
1557
        if (lay->set[SF_chorusEffectsSend]) {
 
1558
                if (sf->version == 1)
 
1559
                        sp->v.chorusdepth = (int8)lay->val[SF_chorusEffectsSend];
 
1560
                else
 
1561
                        sp->v.chorusdepth = (int8)((int)lay->val[SF_chorusEffectsSend] * 127 / 1000);
 
1562
        }
 
1563
        else sp->v.chorusdepth = 0;
 
1564
 
 
1565
        if (lay->set[SF_reverbEffectsSend]) {
 
1566
                if (sf->version == 1)
 
1567
                        sp->v.reverberation = (int8)lay->val[SF_reverbEffectsSend];
 
1568
                else
 
1569
                        sp->v.reverberation = (int8)((int)lay->val[SF_reverbEffectsSend] * 127 / 1000);
 
1570
        }
 
1571
        else sp->v.reverberation = 0;
 
1572
 
 
1573
        /* tremolo & vibrato */
 
1574
        sp->v.tremolo_sweep_increment = 0;
 
1575
        sp->v.tremolo_phase_increment = 0;
 
1576
        sp->v.tremolo_depth = 0;
 
1577
#ifndef SF_SUPPRESS_TREMOLO
 
1578
        convert_tremolo(lay, sf, sp);
 
1579
#endif
 
1580
        sp->v.lfo_sweep_increment = 0;
 
1581
        sp->v.lfo_phase_increment = 0;
 
1582
        sp->v.modLfoToFilterFc = 0;
 
1583
#ifndef SF_SUPPRESS_TREMOLO
 
1584
        convert_lfo(lay, sf, sp);
 
1585
#endif
 
1586
        sp->v.vibrato_sweep_increment = 0;
 
1587
        sp->v.vibrato_control_ratio = 0;
 
1588
        sp->v.vibrato_depth = 0;
 
1589
        sp->v.vibrato_delay = 0;
 
1590
#ifndef SF_SUPPRESS_VIBRATO
 
1591
        convert_vibrato(lay, sf, sp);
 
1592
#endif
 
1593
 
 
1594
        /* set note to use for drum voices */
 
1595
        if (note_to_use!=-1)
 
1596
                sp->v.note_to_use = (uint8)note_to_use;
 
1597
        else if (banknum == 128)
 
1598
                sp->v.note_to_use = keynote;
 
1599
        else
 
1600
                sp->v.note_to_use = 0;
 
1601
 
 
1602
        /* convert to fractional samples */
 
1603
        sp->v.data_length <<= FRACTION_BITS;
 
1604
        sp->v.loop_start <<= FRACTION_BITS;
 
1605
        sp->v.loop_end <<= FRACTION_BITS;
 
1606
 
 
1607
        /* point to the file position */
 
1608
        sp->startsample = sp->startsample * 2 + sf->samplepos;
 
1609
        sp->endsample *= 2;
 
1610
 
 
1611
        /* set cutoff frequency */
 
1612
        if (lay->set[SF_initialFilterFc] || lay->set[SF_env1ToFilterFc])
 
1613
                calc_cutoff(lay, sf, sp);
 
1614
        else sp->cutoff_freq = 0;
 
1615
/*
 
1616
if (sp->cutoff_freq)
 
1617
printf("bank %d, program %d, f= %d (%d)\n", banknum, program, sp->cutoff_freq, lay->val[SF_initialFilterFc]);
 
1618
*/
 
1619
        if (lay->set[SF_initialFilterQ])
 
1620
                calc_filterQ(lay, sf, sp);
 
1621
        sp->v.cutoff_freq = sp->cutoff_freq;
 
1622
        sp->v.resonance = sp->resonance;
 
1623
}
 
1624
 
 
1625
/* calculate root pitch */
 
1626
static int32 calc_root_pitch(Layer *lay, SFInfo *sf, SampleList *sp, int32 cfg_tuning)
 
1627
{
 
1628
        int32 root, tune;
 
1629
        tsampleinfo *sample;
 
1630
 
 
1631
        sample = &sf->sampleinfo[lay->val[SF_sampleId]];
 
1632
 
 
1633
        root = sample->originalPitch;
 
1634
        /* sp->v.freq_center = root; */
 
1635
 
 
1636
        tune = sample->pitchCorrection;
 
1637
        if (sf->version == 1) {
 
1638
                if (lay->set[SF_samplePitch]) {
 
1639
                        root = lay->val[SF_samplePitch] / 100;
 
1640
                        tune = -lay->val[SF_samplePitch] % 100;
 
1641
                        if (tune <= -50) {
 
1642
                                root++;
 
1643
                                tune = 100 + tune;
 
1644
                        }
 
1645
                        if (sp->v.scale_tuning == 50)
 
1646
                                tune /= 2;
 
1647
                }
 
1648
                /* orverride root key */
 
1649
                if (lay->set[SF_rootKey])
 
1650
                        root += lay->val[SF_rootKey] - 60;
 
1651
                /* tuning */
 
1652
                tune += lay->val[SF_coarseTune] * sp->v.scale_tuning +
 
1653
                        lay->val[SF_fineTune] * sp->v.scale_tuning / 100;
 
1654
        } else {
 
1655
                /* override root key */
 
1656
                if (lay->set[SF_rootKey])
 
1657
                        root = lay->val[SF_rootKey];
 
1658
                /* tuning */
 
1659
#ifdef tplussbk
 
1660
                tune += lay->val[SF_coarseTune] * sp->v.scale_tuning
 
1661
                        + (int)lay->val[SF_fineTune] * (int)sp->v.scale_tuning / 100;
 
1662
#else
 
1663
                tune += lay->val[SF_coarseTune] * 100
 
1664
                        + lay->val[SF_fineTune];
 
1665
#endif
 
1666
        }
 
1667
 
 
1668
        tune += cfg_tuning;
 
1669
 
 
1670
        /* it's too high.. */
 
1671
        if (lay->set[SF_keyRange] &&
 
1672
            root >= HI_VAL(lay->val[SF_keyRange]) + 60)
 
1673
                root -= 60;
 
1674
 
 
1675
        while (tune <= -100) {
 
1676
                root++;
 
1677
                tune += 100;
 
1678
        }
 
1679
        while (tune > 0) {
 
1680
                root--;
 
1681
                tune -= 100;
 
1682
        }
 
1683
 
 
1684
    if (root > 0) sp->v.freq_center = root;
 
1685
    else sp->v.freq_center = 60;
 
1686
/* have to adjust for rate ... */
 
1687
        /* sp->v.sample_rate */
 
1688
        /* play_mode->rate */
 
1689
#ifdef tplussbkuse
 
1690
 
 
1691
    /* -100 < tune <= 0 */
 
1692
    tune = (-tune * 256) / 100;
 
1693
    /* 256 > tune >= 0 */
 
1694
    /* 1.059 >= bend_fine[tune] >= 1.0 */
 
1695
 
 
1696
    if(root > 127)
 
1697
        return (int32)((FLOAT_T)freq_table[127] *
 
1698
                                  bend_coarse[root - 127] * bend_fine[tune]);
 
1699
                                  
 
1700
    else if(root < 0)
 
1701
        return (int32)((FLOAT_T)freq_table[0] /
 
1702
                                  bend_coarse[-root] * bend_fine[tune]);
 
1703
    else
 
1704
        return (int32)((FLOAT_T)freq_table[root] * bend_fine[tune]);
 
1705
 
 
1706
#else
 
1707
        return (int32)((double)freq_table[root] * bend_fine[(-tune*255)/100]);
 
1708
#endif
 
1709
}
 
1710
 
 
1711
 
 
1712
/* #define EXAMINE_SOME_ENVELOPES */
 
1713
/*----------------------------------------------------------------
 
1714
 * convert volume envelope
 
1715
 *----------------------------------------------------------------*/
 
1716
 
 
1717
static void convert_volume_envelope(Layer *lay, SFInfo *sf, SampleList *sp, int banknum, int preset)
 
1718
{
 
1719
        uint32 sustain = calc_sustain(lay, sf, banknum, preset);
 
1720
        double delay = to_msec(lay, sf, SF_delayEnv2);
 
1721
        double attack = to_msec(lay, sf, SF_attackEnv2);
 
1722
        double hold = to_msec(lay, sf, SF_holdEnv2);
 
1723
        double decay = to_msec(lay, sf, SF_decayEnv2);
 
1724
        double release = to_msec(lay, sf, SF_releaseEnv2);
 
1725
        FLOAT_T vol = calc_volume(lay,sf);
 
1726
        uint32 volume;
 
1727
        /* int milli = play_mode->rate/1000; */
 
1728
#ifdef EXAMINE_SOME_ENVELOPES
 
1729
        static int no_shown = 0;
 
1730
no_shown = banknum==128 && preset == 25;
 
1731
if (no_shown) {
 
1732
printf("PRESET %d\n",preset);
 
1733
        printf("sustainEnv2 %d delayEnv2 %d attackEnv2 %d holdEnv2 %d decayEnv2 %d releaseEnv2 %d\n",
 
1734
        lay->val[SF_sustainEnv2],
 
1735
        lay->val[SF_delayEnv2],
 
1736
        lay->val[SF_attackEnv2],
 
1737
        lay->val[SF_holdEnv2],
 
1738
        lay->val[SF_decayEnv2],
 
1739
        lay->val[SF_releaseEnv2] );
 
1740
        printf("attack %f hold %f sustain %ld decay %f release %f delay %f\n", attack, hold, sustain,
 
1741
                decay, release, delay);
 
1742
}
 
1743
#endif
 
1744
 
 
1745
        if (vol > 255.0) volume = 255;
 
1746
        else if (vol < 1.0) volume = 0;
 
1747
        else volume = (uint32)vol;
 
1748
 
 
1749
        if (!lay->set[SF_releaseEnv2] && banknum < 128) release = 400;
 
1750
        if (!lay->set[SF_decayEnv2] && banknum < 128) decay = 400;
 
1751
 
 
1752
#define HOLD_EXCURSION 1
 
1753
#define ENV_BOTTOM 0
 
1754
 
 
1755
/* ramp from 0 to <volume> in <attack> msecs */
 
1756
        sp->v.envelope_offset[ATTACK] = to_offset(volume);
 
1757
        sp->v.envelope_rate[ATTACK] = calc_rate(volume, attack);
 
1758
 
 
1759
/* ramp down HOLD_EXCURSION in <hold> msecs */
 
1760
        sp->v.envelope_offset[HOLD] = to_offset(volume-HOLD_EXCURSION);
 
1761
        sp->v.envelope_rate[HOLD] = calc_rate(HOLD_EXCURSION, hold);
 
1762
 
 
1763
/* ramp down by <sustain> in <decay> msecs */
 
1764
        if(sustain <= ENV_BOTTOM) sustain = ENV_BOTTOM;
 
1765
        if(sustain > volume - HOLD_EXCURSION) sustain = volume - HOLD_EXCURSION;
 
1766
 
 
1767
        sp->v.envelope_offset[DECAY] = to_offset(sustain);
 
1768
        sp->v.envelope_rate[DECAY] = calc_rate(volume - HOLD_EXCURSION - sustain, decay);
 
1769
        if (fast_decay) sp->v.envelope_rate[DECAY] *= 2;
 
1770
 
 
1771
/* ramp to ENV_BOTTOM in ?? msec */
 
1772
        sp->v.envelope_offset[RELEASE] = to_offset(ENV_BOTTOM);
 
1773
        sp->v.envelope_rate[RELEASE] = calc_rate(255, release);
 
1774
        if (fast_decay) sp->v.envelope_rate[RELEASE] *= 2;
 
1775
 
 
1776
        sp->v.envelope_offset[RELEASEB] = to_offset(ENV_BOTTOM);
 
1777
        sp->v.envelope_rate[RELEASEB] = to_offset(200);
 
1778
        sp->v.envelope_offset[RELEASEC] = to_offset(ENV_BOTTOM);
 
1779
        sp->v.envelope_rate[RELEASEC] = to_offset(200);
 
1780
 
 
1781
        /* pc400.sf2 has bad delay times for soprano sax */
 
1782
        if (delay > 5) delay = 5;
 
1783
 
 
1784
        sp->v.envelope_rate[DELAY] = (int32)( (delay*play_mode->rate) / 1000 );
 
1785
 
 
1786
        sp->v.modes |= MODES_ENVELOPE;
 
1787
#ifdef EXAMINE_SOME_ENVELOPES
 
1788
if (no_shown) {
 
1789
        /*no_shown++;*/
 
1790
        printf(" attack(0): off %ld  rate %ld\n",
 
1791
                sp->v.envelope_offset[0] >>(7+15), sp->v.envelope_rate[0] >>(7+15));
 
1792
        printf("   hold(1): off %ld  rate %ld\n",
 
1793
                sp->v.envelope_offset[1] >>(7+15), sp->v.envelope_rate[1] >>(7+15));
 
1794
        printf("sustain(2): off %ld  rate %ld\n",
 
1795
                sp->v.envelope_offset[2] >>(7+15), sp->v.envelope_rate[2] >>(7+15));
 
1796
        printf("release(3): off %ld  rate %ld\n",
 
1797
                sp->v.envelope_offset[3] >>(7+15), sp->v.envelope_rate[3] >>(7+15));
 
1798
        printf("  decay(4): off %ld  rate %ld\n",
 
1799
                sp->v.envelope_offset[4] >>(7+15), sp->v.envelope_rate[4] >>(7+15));
 
1800
        printf("    die(5): off %ld  rate %ld\n",
 
1801
                sp->v.envelope_offset[5] >>(7+15), sp->v.envelope_rate[5] >>(7+15));
 
1802
        printf("  delay(6): off %ld  rate %ld\n",
 
1803
                sp->v.envelope_offset[6], sp->v.envelope_rate[6]);
 
1804
}
 
1805
#endif
 
1806
}
 
1807
 
 
1808
static void convert_modulation_envelope(Layer *lay, SFInfo *sf, SampleList *sp, int banknum, int preset)
 
1809
{
 
1810
        uint32 sustain = calc_modulation_sustain(lay, sf, banknum, preset);
 
1811
        double delay = to_msec(lay, sf, SF_delayEnv1);
 
1812
        double attack = to_msec(lay, sf, SF_attackEnv1);
 
1813
        double hold = to_msec(lay, sf, SF_holdEnv1);
 
1814
        double decay = to_msec(lay, sf, SF_decayEnv1);
 
1815
        double release = to_msec(lay, sf, SF_releaseEnv1);
 
1816
        FLOAT_T vol = calc_volume(lay,sf);
 
1817
        uint32 volume;
 
1818
#ifdef EXAMINE_SOME_ENVELOPES
 
1819
        static int no_shown = 0;
 
1820
no_shown = banknum==0 && (preset == 11 || preset == 64);
 
1821
if (no_shown) {
 
1822
printf("PRESET %d\n",preset);
 
1823
        printf("sustainEnv1 %d delayEnv1 %d attackEnv1 %d holdEnv1 %d decayEnv1 %d releaseEnv1 %d\n",
 
1824
        lay->val[SF_sustainEnv1],
 
1825
        lay->val[SF_delayEnv1],
 
1826
        lay->val[SF_attackEnv1],
 
1827
        lay->val[SF_holdEnv1],
 
1828
        lay->val[SF_decayEnv1],
 
1829
        lay->val[SF_releaseEnv1] );
 
1830
        printf("attack %f hold %f sustain %ld decay %f release %f delay %f\n", attack, hold, sustain,
 
1831
                decay, release, delay);
 
1832
}
 
1833
#endif
 
1834
 
 
1835
        if (vol > 255.0) volume = 255;
 
1836
        else if (vol < 1.0) volume = 0;
 
1837
        else volume = (uint32)vol;
 
1838
 
 
1839
 
 
1840
/* ramp from 0 to <volume> in <attack> msecs */
 
1841
        sp->v.modulation_offset[ATTACK] = to_offset(volume);
 
1842
        sp->v.modulation_rate[ATTACK] = calc_rate(volume, attack);
 
1843
 
 
1844
/* ramp down HOLD_EXCURSION in <hold> msecs */
 
1845
        sp->v.modulation_offset[HOLD] = to_offset(volume-HOLD_EXCURSION);
 
1846
        sp->v.modulation_rate[HOLD] = calc_rate(HOLD_EXCURSION, hold);
 
1847
 
 
1848
/* ramp down by <sustain> in <decay> msecs */
 
1849
        if(sustain <= ENV_BOTTOM) sustain = ENV_BOTTOM;
 
1850
        if(sustain > volume - HOLD_EXCURSION) sustain = volume - HOLD_EXCURSION;
 
1851
 
 
1852
        sp->v.modulation_offset[DECAY] = to_offset(sustain);
 
1853
        sp->v.modulation_rate[DECAY] = calc_rate(volume - HOLD_EXCURSION - sustain, decay);
 
1854
        if (fast_decay) sp->v.modulation_rate[DECAY] *= 2;
 
1855
 
 
1856
/* ramp to ENV_BOTTOM in ?? msec */
 
1857
        sp->v.modulation_offset[RELEASE] = to_offset(ENV_BOTTOM);
 
1858
        sp->v.modulation_rate[RELEASE] = calc_rate(255, release);
 
1859
        if (fast_decay) sp->v.modulation_rate[RELEASE] *= 2;
 
1860
 
 
1861
        sp->v.modulation_offset[RELEASEB] = to_offset(ENV_BOTTOM);
 
1862
        sp->v.modulation_rate[RELEASEB] = to_offset(200);
 
1863
        sp->v.modulation_offset[RELEASEC] = to_offset(ENV_BOTTOM);
 
1864
        sp->v.modulation_rate[RELEASEC] = to_offset(200);
 
1865
 
 
1866
        if (delay > 5) delay = 5;
 
1867
 
 
1868
        sp->v.modulation_rate[DELAY] = (int32)( (delay*play_mode->rate) / 1000 );
 
1869
 
 
1870
#ifdef EXAMINE_SOME_ENVELOPES
 
1871
if (no_shown) {
 
1872
        /*no_shown++;*/
 
1873
        printf(" attack(0): off %ld  rate %ld\n",
 
1874
                sp->v.modulation_offset[0] >>(7+15), sp->v.modulation_rate[0] >>(7+15));
 
1875
        printf("   hold(1): off %ld  rate %ld\n",
 
1876
                sp->v.modulation_offset[1] >>(7+15), sp->v.modulation_rate[1] >>(7+15));
 
1877
        printf("sustain(2): off %ld  rate %ld\n",
 
1878
                sp->v.modulation_offset[2] >>(7+15), sp->v.modulation_rate[2] >>(7+15));
 
1879
        printf("release(3): off %ld  rate %ld\n",
 
1880
                sp->v.modulation_offset[3] >>(7+15), sp->v.modulation_rate[3] >>(7+15));
 
1881
        printf("  decay(4): off %ld  rate %ld\n",
 
1882
                sp->v.modulation_offset[4] >>(7+15), sp->v.modulation_rate[4] >>(7+15));
 
1883
        printf("    die(5): off %ld  rate %ld\n",
 
1884
                sp->v.modulation_offset[5] >>(7+15), sp->v.modulation_rate[5] >>(7+15));
 
1885
        printf("  delay(6): off %ld  rate %ld\n",
 
1886
                sp->v.modulation_offset[6], sp->v.modulation_rate[6]);
 
1887
}
 
1888
#endif
 
1889
}
 
1890
 
 
1891
/* convert from 8bit value to fractional offset (15.15) */
 
1892
static uint32 to_offset(uint32 offset)
 
1893
{
 
1894
        if (offset >255) return 255 << (7+15);
 
1895
        return (uint32)offset << (7+15);
 
1896
}
 
1897
 
 
1898
/* calculate ramp rate in fractional unit;
 
1899
 * diff = 8bit, time = msec
 
1900
 */
 
1901
static uint32 calc_rate(uint32 diff, double msec)
 
1902
{
 
1903
    double rate;
 
1904
 
 
1905
    diff <<= (7+15);
 
1906
    /* rate = ((double)diff / play_mode->rate) * control_ratio * 1000.0 / msec; */
 
1907
    /** rate = ( (double)diff * 1000.0 ) / (msec * CONTROLS_PER_SECOND); **/
 
1908
    /** rate = ( (double)diff * 1000.0 ) / CONTROLS_PER_SECOND; **/
 
1909
    rate = ( (double)diff * 1000.0 ) / (msec * CONTROLS_PER_SECOND);
 
1910
    /* rate *= 2;  ad hoc adjustment ?? */
 
1911
    if (rate < 10.0) return 10;
 
1912
    return (uint32)rate;
 
1913
 
 
1914
/*
 
1915
 *      control_ratio = play_mode->rate / CONTROLS_PER_SECOND;
 
1916
 *      samples per control = (samples per sec) / (controls per sec)
 
1917
 *      rate is amp-change per control
 
1918
 *              diff per msec
 
1919
 *              diff*1000 per sec
 
1920
 *              (diff*1000 per sec) / (controls per sec) = amp change per control
 
1921
 *                      diff/(msec/1000) = (diff * 1000) / msec = amp change per sec
 
1922
 *                      ((diff * 1000)/msec) / CONTROLS_PER_SECOND = amp change per control
 
1923
 *                      = (diff * 1000) / (msec * CONTROLS_PER_SECOND)
 
1924
 */
 
1925
}
 
1926
 
 
1927
#define TO_MSEC(tcents) (int32)(1000 * pow(2.0, (double)(tcents) / 1200.0))
 
1928
#define TO_MHZ(abscents) (int32)(8176.0 * pow(2.0,(double)(abscents)/1200.0))
 
1929
#define TO_HZ(abscents) (int32)(8.176 * pow(2.0,(double)(abscents)/1200.0))
 
1930
/* #define TO_HZ(abscents) (int32)(8176 * pow(2.0,(double)(abscents)/12000.0)) */
 
1931
#define TO_LINEAR(centibel) pow(10.0, -(double)(centibel)/200.0)
 
1932
/* #define TO_VOLUME(centibel) (uint8)(255 * (1.0 - (centibel) / (1200.0 * log10(2.0)))); */
 
1933
#define TO_VOLUME(centibel) (uint8)(255 * pow(10.0, -(double)(centibel)/200.0))
 
1934
 
 
1935
/* convert the value to milisecs */
 
1936
static double to_msec(Layer *lay, SFInfo *sf, int index)
 
1937
{
 
1938
        int16 value;
 
1939
        double msec;
 
1940
 
 
1941
        if (sf->version == 1) {
 
1942
                if (! lay->set[index])
 
1943
                        return 1.0;  /* 6msec minimum */
 
1944
                value = lay->val[index];
 
1945
                return (double)value;
 
1946
        }
 
1947
 
 
1948
        if (lay->set[index]) value = lay->val[index];
 
1949
        else value = -12000;
 
1950
 
 
1951
        msec = (double)(1000 * pow(2.0, (double)( value ) / 1200.0));
 
1952
        return msec;
 
1953
}
 
1954
 
 
1955
#define CB_TO_VOLUME(centibel) (255 * (1.0 - ((double)(centibel)/100.0) / (1200.0 * log10(2.0)) ))
 
1956
/* convert peak volume to linear volume (0-255) */
 
1957
static FLOAT_T calc_volume(Layer *lay, SFInfo *sf)
 
1958
{
 
1959
        if (sf->version == 1)
 
1960
                return (FLOAT_T)(lay->val[SF_instVol] * 2) / 255.0;
 
1961
        else
 
1962
                return CB_TO_VOLUME((double)lay->val[SF_instVol]);
 
1963
}
 
1964
 
 
1965
/* convert sustain volume to linear volume */
 
1966
static uint32 calc_sustain(Layer *lay, SFInfo *sf, int banknum, int preset)
 
1967
{
 
1968
        int32 level;
 
1969
        if (!lay->set[SF_sustainEnv2])
 
1970
                return 250;
 
1971
        level = lay->val[SF_sustainEnv2];
 
1972
        if (sf->version == 1) {
 
1973
                if (level < 96)
 
1974
                        level = 1000 * (96 - level) / 96;
 
1975
                else
 
1976
                        return 0;
 
1977
        }
 
1978
        return TO_VOLUME(level);
 
1979
}
 
1980
/* convert sustain volume to linear volume */
 
1981
static uint32 calc_modulation_sustain(Layer *lay, SFInfo *sf, int banknum, int preset)
 
1982
{
 
1983
        int32 level;
 
1984
        if (!lay->set[SF_sustainEnv1])
 
1985
                return 250;
 
1986
        level = lay->val[SF_sustainEnv1];
 
1987
        if (sf->version == 1) {
 
1988
                if (level < 96)
 
1989
                        level = 1000 * (96 - level) / 96;
 
1990
                else
 
1991
                        return 0;
 
1992
        }
 
1993
        return TO_VOLUME(level);
 
1994
}
 
1995
 
 
1996
 
 
1997
#ifndef SF_SUPPRESS_TREMOLO
 
1998
/*----------------------------------------------------------------
 
1999
 * tremolo (LFO1) conversion
 
2000
 *----------------------------------------------------------------*/
 
2001
 
 
2002
static void convert_tremolo(Layer *lay, SFInfo *sf, SampleList *sp)
 
2003
{
 
2004
        int32 level;
 
2005
        uint32 freq;
 
2006
 
 
2007
        if (!lay->set[SF_lfo1ToVolume])
 
2008
                return;
 
2009
 
 
2010
        level = lay->val[SF_lfo1ToVolume];
 
2011
        if (!level) return;
 
2012
#if 0
 
2013
printf("(lev=%d", (int)level);
 
2014
#endif
 
2015
 
 
2016
        if (level < 0) level = -level;
 
2017
 
 
2018
        if (sf->version == 1)
 
2019
                level = (120 * level) / 64;  /* to centibel */
 
2020
        /* else level = TO_VOLUME((double)level); */
 
2021
        else level = 255 - (uint8)(255 * (1.0 - (level) / (1200.0 * log10(2.0))));
 
2022
 
 
2023
        sp->v.tremolo_depth = level;
 
2024
 
 
2025
        /* frequency in mHz */
 
2026
        if (! lay->set[SF_freqLfo1]) {
 
2027
                if (sf->version == 1)
 
2028
                        freq = TO_MHZ(-725);
 
2029
                else
 
2030
                        freq = 8;
 
2031
        } else {
 
2032
                freq = lay->val[SF_freqLfo1];
 
2033
#if 0
 
2034
printf(" freq=%d)", (int)freq);
 
2035
#endif
 
2036
                if (freq > 0 && sf->version == 1)
 
2037
                        freq = (int)(3986.0 * log10((double)freq) - 7925.0);
 
2038
                else freq = TO_HZ(freq);
 
2039
        }
 
2040
 
 
2041
#if 0
 
2042
printf(" depth=%d freq=%d\n", (int)level, (int)freq);
 
2043
#endif
 
2044
        if (freq < 1) freq = 1;
 
2045
        freq *= 20;
 
2046
        if (freq > 255) freq = 255;
 
2047
 
 
2048
        sp->v.tremolo_phase_increment = convert_tremolo_rate((uint8)freq);
 
2049
        sp->v.tremolo_sweep_increment = convert_tremolo_sweep((uint8)(freq/5));
 
2050
}
 
2051
 
 
2052
 
 
2053
static void convert_lfo(Layer *lay, SFInfo *sf, SampleList *sp)
 
2054
{
 
2055
        int32 freq=0, level;
 
2056
 
 
2057
        if (sf->version == 1) return;
 
2058
 
 
2059
        if (!lay->set[SF_lfo1ToFilterFc] || !lay->set[SF_initialFilterFc])
 
2060
                return;
 
2061
 
 
2062
        level = lay->val[SF_lfo1ToFilterFc];
 
2063
        if (!level) return;
 
2064
/* FIXME: delay not yet implemented */
 
2065
#ifdef DEBUG_CONVERT_LFO
 
2066
printf("(lev=%d", (int)level);
 
2067
#endif
 
2068
        sp->v.modLfoToFilterFc = pow(2.0, ((FLOAT_T)level/1200.0));
 
2069
 
 
2070
        /* frequency in mHz */
 
2071
        if (lay->set[SF_freqLfo1]) freq = lay->val[SF_freqLfo1];
 
2072
 
 
2073
#ifdef DEBUG_CONVERT_LFO
 
2074
printf(" freq=%d)", (int)freq);
 
2075
#endif
 
2076
        if (!freq) freq = 8;
 
2077
        else freq = TO_HZ(freq);
 
2078
 
 
2079
#ifdef DEBUG_CONVERT_LFO
 
2080
printf(" depth=%f freq=%d\n", sp->modLfoToFilterFc, (int)freq);
 
2081
#endif
 
2082
        if (freq < 1) freq = 1;
 
2083
        freq *= 20;
 
2084
        if (freq > 255) freq = 255;
 
2085
 
 
2086
        sp->v.lfo_phase_increment = convert_tremolo_rate((uint8)freq);
 
2087
        sp->v.lfo_sweep_increment = convert_tremolo_sweep((uint8)(freq/5));
 
2088
}
 
2089
#endif
 
2090
 
 
2091
 
 
2092
#ifndef SF_SUPPRESS_VIBRATO
 
2093
/*----------------------------------------------------------------
 
2094
 * vibrato (LFO2) conversion
 
2095
 * (note: my changes to Takashi's code are unprincipled --gl)
 
2096
 *----------------------------------------------------------------*/
 
2097
 
 
2098
static void convert_vibrato(Layer *lay, SFInfo *sf, SampleList *sp)
 
2099
{
 
2100
        int32 shift=0, freq=0, delay=0;
 
2101
 
 
2102
        if (lay->set[SF_lfo2ToPitch]) {
 
2103
                shift = lay->set[SF_lfo2ToPitch];
 
2104
                if (lay->set[SF_freqLfo2]) freq = lay->val[SF_freqLfo2];
 
2105
#if 0
 
2106
printf("modLfo=%d freq=%d",(int)shift, (int)freq);
 
2107
#endif
 
2108
                if (lay->set[SF_delayLfo2]) delay = (int32)to_msec(lay, sf, SF_delayLfo2);
 
2109
        }
 
2110
        else if (lay->set[SF_lfo1ToPitch]) {
 
2111
                shift = lay->set[SF_lfo1ToPitch];
 
2112
                if (lay->set[SF_freqLfo1]) freq = lay->val[SF_freqLfo1];
 
2113
#if 0
 
2114
printf("vibLfo=%d freq=%d",(int)shift, (int)freq);
 
2115
#endif
 
2116
                if (lay->set[SF_delayLfo1]) delay = (int32)to_msec(lay, sf, SF_delayLfo1);
 
2117
        }
 
2118
/*
 
2119
        else if (lay->set[SF_freqLfo2]) {
 
2120
                freq = lay->val[SF_freqLfo2];
 
2121
                shift = 1;
 
2122
        }
 
2123
*/
 
2124
 
 
2125
        if (!shift) return;
 
2126
 
 
2127
        /* pitch shift in cents (= 1/100 semitone) */
 
2128
        if (sf->version == 1)
 
2129
                shift = (1200 * shift / 64 + 1) / 2;
 
2130
 
 
2131
        /* cents to linear; 400cents = 256 */
 
2132
        /*sp->v.vibrato_depth = (int8)((int32)shift * 256 / 400);*/
 
2133
        /** sp->v.vibrato_depth = shift * 400 / 64; **/
 
2134
 
 
2135
        sp->v.vibrato_depth = (int32)(pow(2.0, ((FLOAT_T)shift/1200.0)) * VIBRATO_RATE_TUNING);
 
2136
        /* frequency in mHz */
 
2137
        if (!freq) {
 
2138
                if (sf->version == 1)
 
2139
                        freq = TO_HZ(-725);
 
2140
                else
 
2141
                        freq = 8;
 
2142
        } else {
 
2143
                if (sf->version == 1)
 
2144
                        freq = (int32)(3986.0 * log10((double)freq) - 7925.0);
 
2145
                else freq = TO_HZ(freq);
 
2146
        }
 
2147
        if (freq < 1) freq = 1;
 
2148
 
 
2149
        freq *= 20;
 
2150
        if (freq > 255) freq = 255;
 
2151
 
 
2152
        sp->v.vibrato_control_ratio = convert_vibrato_rate((uint8)freq);
 
2153
 
 
2154
        /* convert mHz to control ratio */
 
2155
#if 0
 
2156
        sp->v.vibrato_control_ratio = freq *
 
2157
                (VIBRATO_RATE_TUNING * play_mode->rate) /
 
2158
                (2 * CONTROLS_PER_SECOND * VIBRATO_SAMPLE_INCREMENTS);
 
2159
#endif
 
2160
 
 
2161
#if 0
 
2162
printf(" f=%d depth=%d (shift %d)\n", (int)freq, (int)sp->v.vibrato_depth, (int)shift);
 
2163
#endif
 
2164
        /* sp->v.vibrato_sweep_increment = 74; */
 
2165
        sp->v.vibrato_sweep_increment = convert_vibrato_sweep((uint8)(freq/5),
 
2166
                sp->v.vibrato_control_ratio);
 
2167
 
 
2168
        sp->v.vibrato_delay = delay * control_ratio;
 
2169
}
 
2170
#endif
 
2171
 
 
2172
 
 
2173
/* calculate cutoff/resonance frequency */
 
2174
static void calc_cutoff(Layer *lay, SFInfo *sf, SampleList *sp)
 
2175
{
 
2176
        int16 val;
 
2177
 
 
2178
        if (! lay->set[SF_initialFilterFc]) {
 
2179
                val = 13500;
 
2180
        } else {
 
2181
                val = lay->val[SF_initialFilterFc];
 
2182
                if (sf->version == 1) {
 
2183
                        if (val == 127)
 
2184
                                val = 14400;
 
2185
                        else if (val > 0)
 
2186
                                val = 50 * val + 4366;
 
2187
                }
 
2188
        }
 
2189
        if (lay->set[SF_env1ToFilterFc] && lay->set[SF_initialFilterFc]) {
 
2190
                sp->v.modEnvToFilterFc = pow(2.0, ((FLOAT_T)lay->val[SF_env1ToFilterFc]/1200.0));
 
2191
                /* sp->v.modEnvToFilterFc = pow(2.0, ((FLOAT_T)lay->val[SF_env1ToFilterFc]/12000.0)); */
 
2192
/* printf("val %d -> %f\n", (int)lay->val[SF_env1ToFilterFc], sp->v.modEnvToFilterFc); */
 
2193
        }
 
2194
        else sp->v.modEnvToFilterFc = 0;
 
2195
 
 
2196
        if (lay->set[SF_env1ToPitch]) {
 
2197
                sp->v.modEnvToPitch = pow(2.0, ((FLOAT_T)lay->val[SF_env1ToPitch]/1200.0));
 
2198
/* printf("mE %d -> %f\n", (int)lay->val[SF_env1ToPitch], sp->v.modEnvToPitch); */
 
2199
        }
 
2200
        else sp->v.modEnvToPitch = 0;
 
2201
 
 
2202
        sp->cutoff_freq = TO_HZ(val);
 
2203
 
 
2204
        if (lay->set[SF_autoHoldEnv1]) sp->v.keyToModEnvHold=lay->val[SF_autoHoldEnv1];
 
2205
        else sp->v.keyToModEnvHold=0;
 
2206
        if (lay->set[SF_autoDecayEnv1]) sp->v.keyToModEnvDecay=lay->val[SF_autoDecayEnv1];
 
2207
        else sp->v.keyToModEnvDecay=0;
 
2208
        if (lay->set[SF_autoHoldEnv2]) sp->v.keyToVolEnvHold=lay->val[SF_autoHoldEnv2];
 
2209
        else sp->v.keyToVolEnvHold=0;
 
2210
        if (lay->set[SF_autoDecayEnv2]) sp->v.keyToVolEnvDecay=lay->val[SF_autoDecayEnv2];
 
2211
        else sp->v.keyToVolEnvDecay=0;
 
2212
}
 
2213
 
 
2214
static void calc_filterQ(Layer *lay, SFInfo *sf, SampleList *sp)
 
2215
{
 
2216
        int16 val = lay->val[SF_initialFilterQ];
 
2217
        if (sf->version == 1)
 
2218
                val = val * 3 / 2; /* to centibels */
 
2219
        sp->resonance = pow(10.0, (double)val / 2.0 / 200.0) - 1;
 
2220
        if (sp->resonance < 0)
 
2221
                sp->resonance = 0;
 
2222
}
 
2223