libgig 4.6.1
SF.cpp
1/***************************************************************************
2 * *
3 * libsf2 - C++ cross-platform SF2 format file access library *
4 * *
5 * Copyright (C) 2009-2010 Grigor Iliev <grigor@grigoriliev.com>, *
6 * Christian Schoenebeck and Andreas Persson *
7 * *
8 * This library is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This library is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this library; if not, write to the Free Software *
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21 * MA 02111-1307 USA *
22 ***************************************************************************/
23
24#include "RIFF.h"
25
26#include "SF.h"
27
28#include "helper.h"
29#include <math.h>
30
31#define _1200TH_ROOT_OF_2 1.000577789506555
32#define _200TH_ROOT_OF_10 1.011579454259899
33
34namespace sf2 {
35 double ToSeconds(int Timecents) {
36 if (Timecents == NONE) return NONE;
37 if (Timecents == 0) return 1.0;
38 if (Timecents == -32768) return 0.0;
39 return pow(_1200TH_ROOT_OF_2, Timecents);
40 }
41
42 double ToRatio(int Centibels) {
43 if (Centibels == NONE) return NONE;
44 if (Centibels == 0) return 1.0;
45 return pow(_200TH_ROOT_OF_10, Centibels);
46 }
47
48 double ToHz(int cents) {
49 if (cents == NONE) return NONE;
50 if (cents == 0) return 8.176;
51 return pow(_1200TH_ROOT_OF_2, cents) * 8.176;
52 }
53
54 RIFF::Chunk* GetMandatoryChunk(RIFF::List* list, uint32_t chunkId) {
55 RIFF::Chunk* ck = list->GetSubChunk(chunkId);
56 if(ck == NULL) throw Exception("Mandatory chunk in RIFF list chunk not found: " + ToString(chunkId));
57 return ck;
58 }
59
60 void LoadString(RIFF::Chunk* ck, std::string& s, int strLength) {
61 if(ck == NULL) return;
62 char* buf = new char[strLength];
63 int len = 0;
64 for(int i = 0; i < strLength; i++) {
65 buf[i] = ck->ReadInt8();
66 if(buf[i] == 0 && !len) len = i;
67 }
68 if(!len) len = strLength;
69 s.assign(buf, len);
70 delete [] buf;
71 }
72
77 void VerifySize(RIFF::Chunk* ck, int size) {
78 if (ck == NULL) throw Exception("NULL chunk");
79 if (ck->GetSize() < size) {
80 throw Exception("Invalid chunk size. Chunk ID: " + ToString(ck->GetChunkID()));
81 }
82 }
83
84 Modulator::Modulator(SFModulator mod) {
85 Type = mod >> 10; // The last 6 bits
86 Polarity = mod & (1 << 9);
87 Direction = mod & (1 << 8);
88 MidiPalete = mod & (1 << 7); // two paletes - general or MIDI
89 Index = mod & 0x7f; /* index field */;
90
91 }
92
93 ModulatorItem::ModulatorItem(ModList& mod) :
94 ModSrcOper(Modulator(mod.ModSrcOper)),
95 ModAmtSrcOper(Modulator(mod.ModAmtSrcOper))
96 {
97
98 }
99
100 Version::Version(RIFF::Chunk* ck) {
101 if(ck != NULL) VerifySize(ck, 4);
102 Major = ck ? ck->ReadUint16() : 0;
103 Minor = ck ? ck->ReadUint16() : 0;
104 }
105
106 // *************** Info ***************
107 // *
108
115 Info::Info(RIFF::List* list) {
116 if (list) {
117 RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);
118 if (lstINFO) {
119 pVer = new Version(GetMandatoryChunk(lstINFO, CHUNK_ID_IFIL));
120 LoadString(CHUNK_ID_ISNG, lstINFO, SoundEngine);
121 LoadString(CHUNK_ID_INAM, lstINFO, BankName);
122 LoadString(CHUNK_ID_IROM, lstINFO, RomName);
123 pRomVer = new Version(lstINFO->GetSubChunk(CHUNK_ID_IVER));
124 LoadString(CHUNK_ID_ICRD, lstINFO, CreationDate);
125 LoadString(CHUNK_ID_IENG, lstINFO, Engineers);
126 LoadString(CHUNK_ID_IPRD, lstINFO, Product);
127 LoadString(CHUNK_ID_ICOP, lstINFO, Copyright);
128 LoadString(CHUNK_ID_ICMT, lstINFO, Comments);
129 LoadString(CHUNK_ID_ISFT, lstINFO, Software);
130
131 }
132 }
133 }
134
135 Info::~Info() {
136 delete pVer;
137 delete pRomVer;
138 }
139
145 void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {
146 RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
147 ::LoadString(ck, s); // function from helper.h
148 }
149
150 Sample::Sample(File* file, RIFF::Chunk* ck, RIFF::Chunk* pCkSmpl, RIFF::Chunk* pCkSm24) {
151 this->pFile = file;
152 this->pCkSmpl = pCkSmpl;
153 this->pCkSm24 = pCkSm24;
154
155 LoadString(ck, Name, 20);
156 Start = ck->ReadInt32();
157 End = ck->ReadInt32();
158 StartLoop = ck->ReadInt32();
159 EndLoop = ck->ReadInt32();
160 SampleRate = ck->ReadInt32();
161 OriginalPitch = ck->ReadInt8();
162 PitchCorrection = ck->ReadInt8();
163 SampleLink = ck->ReadInt16();
164 SampleType = ck->ReadInt16();
165
166 if (Start > End || !pCkSmpl || pCkSmpl->GetSize() <= End) {
167 throw Exception("Broken SF2 file (invalid sample info)");
168 }
169
170 ChannelCount = 1;
171 switch(SampleType) {
172 case 0 : // terminal sample
173 case sf2::Sample::MONO_SAMPLE :
174 case sf2::Sample::ROM_MONO_SAMPLE : break;
175 case sf2::Sample::RIGHT_SAMPLE :
176 case sf2::Sample::LEFT_SAMPLE :
177 case sf2::Sample::ROM_RIGHT_SAMPLE :
178 case sf2::Sample::ROM_LEFT_SAMPLE : ChannelCount = 2; break;
179 case sf2::Sample::LINKED_SAMPLE :
180 case sf2::Sample::ROM_LINKED_SAMPLE : std::cerr << "Linked samples not implemented yet"; break;
181 default: throw Exception("Broken SF2 file (invalid sample type)");
182 }
183
184 RAMCache.Size = 0;
185 RAMCache.pStart = NULL;
186 RAMCache.NullExtensionSize = 0;
187 }
188
189 int Sample::GetChannelCount() {
190 return ChannelCount;
191 }
192
193 long Sample::GetTotalFrameCount() {
194 return (End - Start);
195 }
196
200 int Sample::GetFrameSize() {
201 return ChannelCount * ((pCkSm24 != NULL) ? 3 : 2);
202 }
203
204 bool Sample::HasLoops() {
205 return StartLoop != 0 && EndLoop != 0;
206 }
207
234 unsigned long Sample::ReadAndLoop (
235 void* pBuffer,
236 unsigned long FrameCount,
237 PlaybackState* pPlaybackState,
238 Region* pRegion
239 ) {
240 // TODO: startAddrsCoarseOffset, endAddrsCoarseOffset
241 unsigned long samplestoread = FrameCount, totalreadsamples = 0, readsamples, samplestoloopend;
242 uint8_t* pDst = (uint8_t*) pBuffer;
243 SetPos(pPlaybackState->position);
244 if (pRegion->HasLoop) {
245 do {
246 samplestoloopend = pRegion->LoopEnd - GetPos();
247 readsamples = Read(&pDst[totalreadsamples * GetFrameSize()], Min(samplestoread, samplestoloopend));
248 samplestoread -= readsamples;
249 totalreadsamples += readsamples;
250 if (readsamples == samplestoloopend) {
251 SetPos(pRegion->LoopStart);
252 }
253 } while (samplestoread && readsamples);
254 } else {
255 totalreadsamples = Read(pBuffer, FrameCount);
256 }
257
258 pPlaybackState->position = GetPos();
259
260 return totalreadsamples;
261 }
262
263 Region::Region() {
264 pSample = NULL;
265 pInstrument = NULL;
266 pParentInstrument = NULL;
267 loKey = hiKey = NONE;
268 minVel = maxVel = NONE;
269 startAddrsOffset = startAddrsCoarseOffset = endAddrsOffset = endAddrsCoarseOffset = 0;
270 startloopAddrsOffset = startloopAddrsCoarseOffset = endloopAddrsOffset = endloopAddrsCoarseOffset = 0;
271 pan = fineTune = coarseTune = 0;
272 overridingRootKey = -1; // -1 means not used
273
274 HasLoop = false;
275 LoopStart = LoopEnd = 0;
276
277 EG1PreAttackDelay = EG1Attack = EG1Hold = EG1Decay = EG1Release = -12000;
278 EG1Sustain = 0;
279 EG2PreAttackDelay = EG2Attack = EG2Hold = EG2Decay = EG2Release = -12000;
280 EG2Sustain = 0;
281
282 modEnvToPitch = modLfoToPitch = modEnvToFilterFc = modLfoToFilterFc = modLfoToVolume = 0;
283 freqModLfo = 0;
284 delayModLfo = -12000;
285 vibLfoToPitch = 0;
286 freqVibLfo = 0;
287 delayVibLfo = -12000;
288
289 exclusiveClass = 0;
290
291 initialFilterFc = 13500;
292 initialFilterQ = 0;
293 }
294
295 int Region::GetUnityNote() {
296 return overridingRootKey != -1 ? overridingRootKey : pSample->OriginalPitch;
297 }
298
299 int CheckRange(std::string genName, int min, int max, int& gen) {
300 if (gen == NONE) return gen;
301
302 if (gen < min) {
303 std::cerr << "sf2: " << genName;
304 std::cerr << " is below the minimum allowed value (min=" << min << "): " << gen << std::endl;
305 gen = min;
306 }
307 if (gen > max) {
308 std::cerr << "sf2: " << genName;
309 std::cerr << " is above the maximum allowed value (max=" << max << "): " << gen << std::endl;
310 gen = max;
311 }
312
313 return gen;
314 }
315
316 void Region::SetGenerator(sf2::File* pFile, GenList& Gen) {
317 switch(Gen.GenOper) {
318 case START_ADDRS_OFFSET:
319 startAddrsOffset = Gen.GenAmount.wAmount;
320 break;
321 case END_ADDRS_OFFSET:
322 if (Gen.GenAmount.shAmount <= 0) {
323 endAddrsOffset = Gen.GenAmount.shAmount;
324 } else {
325 std::cerr << "Ignoring invalid endAddrsOffset" << std::endl;
326 }
327 break;
328 case STARTLOOP_ADDRS_OFFSET:
329 startloopAddrsOffset = Gen.GenAmount.shAmount;
330 LoopStart += startloopAddrsOffset;
331 break;
332 case ENDLOOP_ADDRS_OFFSET:
333 endloopAddrsOffset = Gen.GenAmount.shAmount;
334 LoopEnd += endloopAddrsOffset;
335 break;
336 case START_ADDRS_COARSE_OFFSET:
337 startAddrsCoarseOffset = Gen.GenAmount.wAmount;
338 break;
339 case MOD_LFO_TO_PITCH:
340 modLfoToPitch = Gen.GenAmount.shAmount;
341 CheckRange("modLfoToPitch", -12000, 12000, modLfoToPitch);
342 break;
343 case VIB_LFO_TO_PITCH:
344 vibLfoToPitch = Gen.GenAmount.shAmount;
345 CheckRange("vibLfoToPitch", -12000, 12000, vibLfoToPitch);
346 break;
347 case MOD_ENV_TO_PITCH:
348 modEnvToPitch = Gen.GenAmount.shAmount;
349 CheckRange("modEnvToPitch", -12000, 12000, modEnvToPitch);
350 break;
351 case INITIAL_FILTER_FC:
352 initialFilterFc = Gen.GenAmount.wAmount;
353 CheckRange("initialFilterFc", 1500, 13500, initialFilterFc);
354 break;
355 case INITIAL_FILTER_Q:
356 initialFilterQ = Gen.GenAmount.wAmount;
357 CheckRange("initialFilterQ", 0, 960, initialFilterQ);
358 break;
359 case MOD_LFO_TO_FILTER_FC:
360 modLfoToFilterFc = Gen.GenAmount.shAmount;
361 CheckRange("modLfoToFilterFc", -12000, 12000, modLfoToFilterFc);
362 break;
363 case MOD_ENV_TO_FILTER_FC:
364 modEnvToFilterFc = Gen.GenAmount.shAmount;
365 CheckRange("modEnvToFilterFc", -12000, 12000, modEnvToFilterFc);
366 break;
367 case END_ADDRS_COARSE_OFFSET:
368 endAddrsCoarseOffset = Gen.GenAmount.wAmount;
369 break;
370 case MOD_LFO_TO_VOLUME:
371 modLfoToVolume = Gen.GenAmount.shAmount;
372 CheckRange("modLfoToVolume", -960, 960, modLfoToVolume);
373 break;
374 case CHORUS_EFFECTS_SEND:
375 break;
376 case REVERB_EFFECTS_SEND:
377 break;
378 case PAN:
379 pan = Gen.GenAmount.shAmount;
380 CheckRange("pan", -500, 500, pan);
381 pan = pan * 64 / 500;
382 if (pan > 63) pan = 63;
383 break;
384 case DELAY_MOD_LFO:
385 delayModLfo = Gen.GenAmount.shAmount;
386 CheckRange("delayModLfo", -12000, 5000, delayModLfo);
387 break;
388 case FREQ_MOD_LFO:
389 freqModLfo = Gen.GenAmount.shAmount;
390 CheckRange("freqModLfo", -16000, 4500, freqModLfo);
391 break;
392 case DELAY_VIB_LFO:
393 delayVibLfo = Gen.GenAmount.shAmount;
394 CheckRange("delayVibLfo", -12000, 5000, delayVibLfo);
395 break;
396 case FREQ_VIB_LFO:
397 freqVibLfo = Gen.GenAmount.shAmount;
398 CheckRange("freqModLfo", -16000, 4500, freqModLfo);
399 break;
400 case DELAY_MOD_ENV:
401 EG2PreAttackDelay = Gen.GenAmount.shAmount;
402 CheckRange("delayModEnv", -12000, 5000, EG2PreAttackDelay);
403 break;
404 case ATTACK_MOD_ENV:
405 EG2Attack = Gen.GenAmount.shAmount;
406 CheckRange("attackModEnv", -12000, 8000, EG2Attack);
407 break;
408 case HOLD_MOD_ENV:
409 EG2Hold = Gen.GenAmount.shAmount;
410 CheckRange("holdModEnv", -12000, 5000, EG2Hold);
411 break;
412 case DECAY_MOD_ENV:
413 EG2Decay = Gen.GenAmount.shAmount;
414 CheckRange("decayModEnv", -12000, 8000, EG2Decay);
415 break;
416 case SUSTAIN_MOD_ENV:
417 EG2Sustain = Gen.GenAmount.shAmount;
418 CheckRange("sustainModEnv", 0, 1000, EG2Sustain);
419 break;
420 case RELEASE_MOD_ENV:
421 EG2Release = Gen.GenAmount.shAmount;
422 CheckRange("releaseModEnv", -12000, 8000, EG2Release);
423 break;
424 case KEYNUM_TO_MOD_ENV_HOLD:
425 break;
426 case KEYNUM_TO_MOD_ENV_DECAY:
427 break;
428 case DELAY_VOL_ENV:
429 EG1PreAttackDelay = Gen.GenAmount.shAmount;
430 CheckRange("delayVolEnv", -12000, 5000, EG1PreAttackDelay);
431 break;
432 case ATTACK_VOL_ENV:
433 EG1Attack = Gen.GenAmount.shAmount;
434 CheckRange("attackVolEnv", -12000, 8000, EG1Attack);
435 break;
436 case HOLD_VOL_ENV:
437 EG1Hold = Gen.GenAmount.shAmount;
438 CheckRange("holdVolEnv", -12000, 5000, EG1Hold);
439 break;
440 case DECAY_VOL_ENV:
441 EG1Decay = Gen.GenAmount.shAmount;
442 CheckRange("decayVolEnv", -12000, 8000, EG1Decay);
443 break;
444 case SUSTAIN_VOL_ENV:
445 EG1Sustain = Gen.GenAmount.shAmount;
446 CheckRange("sustainVolEnv", 0, 1440, EG1Sustain);
447 break;
448 case RELEASE_VOL_ENV:
449 EG1Release = Gen.GenAmount.shAmount;
450 CheckRange("releaseVolEnv", -12000, 8000, EG1Release);
451 break;
452 case KEYNUM_TO_VOL_ENV_HOLD:
453 break;
454 case KEYNUM_TO_VOL_ENV_DECAY:
455 break;
456 case INSTRUMENT: {
457 uint16_t id = Gen.GenAmount.wAmount;
458 if (id >= pFile->Instruments.size()) {
459 throw Exception("Broken SF2 file (missing instruments)");
460 }
461 pInstrument = pFile->Instruments[id];
462 break;
463 }
464 case KEY_RANGE:
465 loKey = Gen.GenAmount.ranges.byLo;
466 CheckRange("loKey", 0, 127, loKey);
467 hiKey = Gen.GenAmount.ranges.byHi;
468 CheckRange("hiKey", 0, 127, hiKey);
469 break;
470 case VEL_RANGE:
471 minVel = Gen.GenAmount.ranges.byLo;
472 CheckRange("minVel", 0, 127, minVel);
473 maxVel = Gen.GenAmount.ranges.byHi;
474 CheckRange("maxVel", 0, 127, maxVel);
475 break;
476 case STARTLOOP_ADDRS_COARSE_OFFSET:
477 startloopAddrsCoarseOffset = Gen.GenAmount.shAmount;
478 LoopStart += uint(startloopAddrsCoarseOffset) << 15;
479 break;
480 case KEYNUM:
481 break;
482 case VELOCITY:
483 break;
484 case INITIAL_ATTENUATION:
485 break;
486 case ENDLOOP_ADDRS_COARSE_OFFSET:
487 endloopAddrsCoarseOffset = Gen.GenAmount.shAmount;
488 LoopEnd += uint(endloopAddrsCoarseOffset) << 15;
489 break;
490 case COARSE_TUNE:
491 coarseTune = Gen.GenAmount.shAmount;
492 CheckRange("coarseTune", -120, 120, coarseTune);
493 break;
494 case FINE_TUNE:
495 fineTune = Gen.GenAmount.shAmount;
496 CheckRange("fineTune", -99, 99, fineTune);
497 break;
498 case SAMPLE_ID: {
499 uint16_t sid = Gen.GenAmount.wAmount;
500 if (sid >= pFile->Samples.size()) {
501 throw Exception("Broken SF2 file (missing samples)");
502 }
503 pSample = pFile->Samples[sid];
504
505 if (HasLoop) {
506 LoopStart += pSample->StartLoop;
507 LoopEnd += pSample->EndLoop;
508 if (LoopStart < pSample->Start) {
509 std::cerr << "sf2: loop start is below the sample start (min=" << pSample->Start << "): " << LoopStart << std::endl;
510 LoopStart = pSample->Start;
511 }
512 if (LoopEnd > pSample->End) {
513 std::cerr << "sf2: loop end is above the sample end (max=" << pSample->End << "): " << LoopEnd << std::endl;
514 LoopEnd = pSample->End;
515 }
516 if (LoopStart > LoopEnd) {
517 std::cerr << "sf2: loop start is above loop end (max=" << LoopEnd << "): " << LoopStart << std::endl;
518 LoopStart = LoopEnd;
519 }
520 LoopStart -= pSample->Start; // Relative to the sample start
521 LoopEnd -= pSample->Start; // Relative to the sample start
522 }
523 break;
524 }
525 case SAMPLE_MODES:
526 HasLoop = Gen.GenAmount.wAmount & 1;
527 // TODO: 3 indicates a sound which loops for the duration of key depression
528 // then proceeds to play the remainder of the sample.
529 break;
530 case SCALE_TUNING:
531 break;
532 case EXCLUSIVE_CLASS:
533 exclusiveClass = Gen.GenAmount.wAmount;
534 break;
535 case OVERRIDING_ROOT_KEY:
536 overridingRootKey = Gen.GenAmount.shAmount;
537 CheckRange("overridingRootKey", -1, 127, overridingRootKey);
538 break;
539 }
540 }
541
542 void Region::SetModulator(sf2::File* /*pFile*/, ModList& Mod) {
543 modulators.push_back(ModulatorItem(Mod));
544 /*switch(srcType) {
545 case NO_CONTROLLER:
546 break;
547 case NOTE_ON_VELOCITY:
548 break;
549 case NOTE_ON_KEY_NUMBER:
550 break;
551 case POLY_PRESSURE:
552 break;
553 case CHANNEL_PRESSURE:
554 break;
555 case PITCH_WHEEL:
556 break;
557 case PITCH_WHEEL_SENSITIVITY:
558 break;
559 case LINK:
560 break;
561 default: std::cout << "Unknown controller source: " << srcType << std::endl;
562 }*/
563 }
564
565 int Region::GetPan(Region* pPresetRegion) {
566 if (pPresetRegion == NULL) return pan;
567 int p = pPresetRegion->pan + pan;
568 if (p < -64) p = -64;
569 if (p > 63) p = 63;
570 return p;
571 }
572
573 int Region::GetFineTune(Region* pPresetRegion) {
574 if (pPresetRegion == NULL) return fineTune;
575 int t = pPresetRegion->fineTune + fineTune;
576 if (t < -99) t = -99;
577 if (t > 99) t = 99;
578 return t;
579 }
580
581 int Region::GetCoarseTune(Region* pPresetRegion) {
582 if (pPresetRegion == NULL) return coarseTune;
583 int t = pPresetRegion->coarseTune + coarseTune;
584 if (t < -120) t = -120;
585 if (t > 120) t = 120;
586 return t;
587 }
588
589 double Region::GetEG1PreAttackDelay(Region* pPresetRegion) {
590 int val = (pPresetRegion == NULL || pPresetRegion->EG1PreAttackDelay == NONE) ?
591 EG1PreAttackDelay : pPresetRegion->EG1PreAttackDelay + EG1PreAttackDelay;
592 return ToSeconds(CheckRange("GetEG1PreAttackDelay()", -12000, 5000, val));
593 }
594
595 double Region::GetEG1Attack(Region* pPresetRegion) {
596 int val = (pPresetRegion == NULL || pPresetRegion->EG1Attack == NONE) ?
597 EG1Attack : pPresetRegion->EG1Attack + EG1Attack;
598 return ToSeconds(CheckRange("GetEG1Attack()", -12000, 8000, val));
599 }
600
601 double Region::GetEG1Hold(Region* pPresetRegion) {
602 int val = (pPresetRegion == NULL || pPresetRegion->EG1Hold == NONE) ?
603 EG1Hold : pPresetRegion->EG1Hold + EG1Hold;
604 return ToSeconds(CheckRange("GetEG1Hold()", -12000, 5000, val));
605 }
606
607 double Region::GetEG1Decay(Region* pPresetRegion) {
608 int val = (pPresetRegion == NULL || pPresetRegion->EG1Decay == NONE) ?
609 EG1Decay : pPresetRegion->EG1Decay + EG1Decay;
610 return ToSeconds(CheckRange("GetEG1Decay()", -12000, 8000, val));
611 }
612
613 int Region::GetEG1Sustain(Region* pPresetRegion) {
614 int val = (pPresetRegion == NULL || pPresetRegion->EG1Sustain == NONE) ?
615 EG1Sustain : pPresetRegion->EG1Sustain + EG1Sustain;
616 return CheckRange("GetEG1Sustain()", 0, 1440, val);
617 }
618
619 double Region::GetEG1Release(Region* pPresetRegion) {
620 int val = (pPresetRegion == NULL || pPresetRegion->EG1Release == NONE) ?
621 EG1Release : pPresetRegion->EG1Release + EG1Release;
622 return ToSeconds(CheckRange("GetEG1Release()", -12000, 8000, val));
623 }
624
625 double Region::GetEG2PreAttackDelay(Region* pPresetRegion) {
626 int val = (pPresetRegion == NULL || pPresetRegion->EG2PreAttackDelay == NONE) ?
627 EG2PreAttackDelay : pPresetRegion->EG2PreAttackDelay + EG2PreAttackDelay;
628 return ToSeconds(CheckRange("GetEG2PreAttackDelay()", -12000, 5000, val));
629 }
630
631 double Region::GetEG2Attack(Region* pPresetRegion) {
632 int val = (pPresetRegion == NULL || pPresetRegion->EG2Attack == NONE) ?
633 EG2Attack : pPresetRegion->EG2Attack + EG2Attack;
634 return ToSeconds(CheckRange("GetEG2Attack()", -12000, 8000, val));
635 }
636
637 double Region::GetEG2Hold(Region* pPresetRegion) {
638 int val = (pPresetRegion == NULL || pPresetRegion->EG2Hold == NONE) ?
639 EG2Hold : pPresetRegion->EG2Hold + EG2Hold;
640 return ToSeconds(CheckRange("GetEG2Hold()", -12000, 5000, val));
641 }
642
643 double Region::GetEG2Decay(Region* pPresetRegion) {
644 int val = (pPresetRegion == NULL || pPresetRegion->EG2Decay == NONE) ?
645 EG2Decay : pPresetRegion->EG2Decay + EG2Decay;
646 return ToSeconds(CheckRange("GetEG2Decay()", -12000, 8000, val));
647 }
648
649 int Region::GetEG2Sustain(Region* pPresetRegion) {
650 int val = (pPresetRegion == NULL || pPresetRegion->EG2Sustain == NONE) ?
651 EG2Sustain : pPresetRegion->EG2Sustain + EG2Sustain;
652 return CheckRange("GetEG2Sustain()", 0, 1000, val);
653 }
654
655 double Region::GetEG2Release(Region* pPresetRegion) {
656 int val = (pPresetRegion == NULL || pPresetRegion->EG2Release == NONE) ?
657 EG2Release : pPresetRegion->EG2Release + EG2Release;
658 return ToSeconds(CheckRange("GetEG2Release()", -12000, 8000, val));
659 }
660
661 int Region::GetModEnvToPitch(Region* pPresetRegion) {
662 int val = (pPresetRegion == NULL || pPresetRegion->modEnvToPitch == NONE) ?
663 modEnvToPitch : pPresetRegion->modEnvToPitch + modEnvToPitch;
664 return CheckRange("GetModEnvToPitch()", -12000, 12000, val);
665 }
666
667 int Region::GetModLfoToPitch(Region* pPresetRegion) {
668 int val = (pPresetRegion == NULL || pPresetRegion->modLfoToPitch == NONE) ?
669 modLfoToPitch : pPresetRegion->modLfoToPitch + modLfoToPitch;
670 return CheckRange("GetModLfoToPitch()", -12000, 12000, val);
671 }
672
673 int Region::GetModEnvToFilterFc(Region* pPresetRegion) {
674 int val = (pPresetRegion == NULL || pPresetRegion->modEnvToFilterFc == NONE) ?
675 modEnvToFilterFc : pPresetRegion->modEnvToFilterFc + modEnvToFilterFc;
676 return CheckRange("GetModEnvToFilterFc()", -12000, +12000, val);
677 }
678
679 int Region::GetModLfoToFilterFc(Region* pPresetRegion) {
680 int val = (pPresetRegion == NULL || pPresetRegion->modLfoToFilterFc == NONE) ?
681 modLfoToFilterFc : pPresetRegion->modLfoToFilterFc + modLfoToFilterFc;
682 return CheckRange("GetModLfoToFilterFc()", -12000, +12000, val);
683 }
684
685 double Region::GetModLfoToVolume(Region* pPresetRegion) {
686 int val = (pPresetRegion == NULL || pPresetRegion->modLfoToVolume == NONE) ?
687 modLfoToVolume : pPresetRegion->modLfoToVolume + modLfoToVolume;
688 return CheckRange("GetModLfoToVolume()", -960, 960, val);
689 }
690
691 double Region::GetFreqModLfo(Region* pPresetRegion) {
692 int val = (pPresetRegion == NULL || pPresetRegion->freqModLfo == NONE) ?
693 freqModLfo : pPresetRegion->freqModLfo + freqModLfo;
694 return ToHz(CheckRange("GetFreqModLfo()", -16000, 4500, val));
695 }
696
697 double Region::GetDelayModLfo(Region* pPresetRegion) {
698 int val = (pPresetRegion == NULL || pPresetRegion->delayModLfo == NONE) ?
699 delayModLfo : pPresetRegion->delayModLfo + delayModLfo;
700 return ToSeconds(CheckRange("GetDelayModLfo()", -12000, 5000, val));
701 }
702
703 int Region::GetVibLfoToPitch(Region* pPresetRegion) {
704 int val = (pPresetRegion == NULL || pPresetRegion->vibLfoToPitch == NONE) ?
705 vibLfoToPitch : pPresetRegion->vibLfoToPitch + vibLfoToPitch;
706 return CheckRange("GetVibLfoToPitch()", -12000, 12000, val);
707 }
708
709 double Region::GetFreqVibLfo(Region* pPresetRegion) {
710 int val = (pPresetRegion == NULL || pPresetRegion->freqVibLfo == NONE) ?
711 freqVibLfo : pPresetRegion->freqVibLfo + freqVibLfo;
712 return ToHz(CheckRange("GetFreqVibLfo()", -16000, 4500, val));
713 }
714
715 double Region::GetDelayVibLfo(Region* pPresetRegion) {
716 int val = (pPresetRegion == NULL || pPresetRegion->delayVibLfo == NONE) ?
717 delayVibLfo : pPresetRegion->delayVibLfo + delayVibLfo;
718 return ToSeconds(CheckRange("GetDelayVibLfo()", -12000, 5000, val));
719 }
720
721 int Region::GetInitialFilterFc(Region* pPresetRegion) {
722 if (pPresetRegion == NULL || pPresetRegion->initialFilterFc == NONE) return initialFilterFc;
723 int val = pPresetRegion->initialFilterFc + initialFilterFc;
724 return CheckRange("GetInitialFilterFc()", 1500, 13500, val);
725 }
726
727 int Region::GetInitialFilterQ(Region* pPresetRegion) {
728 int val = (pPresetRegion == NULL || pPresetRegion->initialFilterQ == NONE) ?
729 initialFilterQ : pPresetRegion->initialFilterQ + initialFilterQ;
730 return CheckRange("GetInitialFilterQ()", 0, 960, val);
731 }
732
733 InstrumentBase::InstrumentBase(sf2::File* pFile) {
734 this->pFile = pFile;
735 pGlobalRegion = NULL;
736 }
737
738 InstrumentBase::~InstrumentBase() {
739 if (pGlobalRegion) delete pGlobalRegion;
740 for (ssize_t i = regions.size() - 1; i >= 0; i--) {
741 if (regions[i]) delete (regions[i]);
742 }
743 }
744
745 int InstrumentBase::GetRegionCount() {
746 return (int) regions.size();
747 }
748
749 Region* InstrumentBase::GetRegion(int idx) {
750 if (idx < 0 || idx >= GetRegionCount()) {
751 throw Exception("Region index out of bounds");
752 }
753
754 return regions[idx];
755 }
756
757 Query::Query(InstrumentBase& instrument) : instrument(instrument) {
758 i = 0;
759 }
760
761 Region* Query::next() {
762 while (i < instrument.GetRegionCount()) {
763 Region* r = instrument.GetRegion(i++);
764 if (((r->loKey == NONE && r->hiKey == NONE) || (key >= r->loKey && key <= r->hiKey)) &&
765 ((r->minVel == NONE && r->maxVel == NONE) || (vel >= r->minVel && vel <= r->maxVel))) {
766 return r;
767 }
768 }
769 return 0;
770 }
771
772 Instrument::Instrument(sf2::File* pFile, RIFF::Chunk* ck) : InstrumentBase(pFile) {
773 this->pFile = pFile;
774 LoadString(ck, Name, 20);
775 InstBagNdx = ck->ReadInt16();
776 }
777
778 Instrument::~Instrument() {
779 }
780
781 Region* Instrument::CreateRegion() {
782 Region* r = new Region;
783 r->pParentInstrument = this;
784
785 if (pGlobalRegion != NULL) {
786 r->loKey = pGlobalRegion->loKey;
787 r->hiKey = pGlobalRegion->hiKey;
788 r->minVel = pGlobalRegion->minVel;
789 r->maxVel = pGlobalRegion->maxVel;
790 r->pan = pGlobalRegion->pan;
791 r->fineTune = pGlobalRegion->fineTune;
792 r->coarseTune = pGlobalRegion->coarseTune;
793 r->overridingRootKey = pGlobalRegion->overridingRootKey;
794 r->startAddrsOffset = pGlobalRegion->startAddrsOffset;
795 r->startAddrsCoarseOffset = pGlobalRegion->startAddrsCoarseOffset;
796 r->endAddrsOffset = pGlobalRegion->endAddrsOffset;
797 r->endAddrsCoarseOffset = pGlobalRegion->endAddrsCoarseOffset;
798 r->startloopAddrsOffset = pGlobalRegion->startloopAddrsOffset;
799 r->startloopAddrsCoarseOffset = pGlobalRegion->startloopAddrsCoarseOffset;
800 r->endloopAddrsOffset = pGlobalRegion->endloopAddrsOffset;
801 r->endloopAddrsCoarseOffset = pGlobalRegion->endloopAddrsCoarseOffset;
802
803 r->EG1PreAttackDelay = pGlobalRegion->EG1PreAttackDelay;
804 r->EG1Attack = pGlobalRegion->EG1Attack;
805 r->EG1Hold = pGlobalRegion->EG1Hold;
806 r->EG1Decay = pGlobalRegion->EG1Decay;
807 r->EG1Sustain = pGlobalRegion->EG1Sustain;
808 r->EG1Release = pGlobalRegion->EG1Release;
809
810 r->EG2PreAttackDelay = pGlobalRegion->EG2PreAttackDelay;
811 r->EG2Attack = pGlobalRegion->EG2Attack;
812 r->EG2Hold = pGlobalRegion->EG2Hold;
813 r->EG2Decay = pGlobalRegion->EG2Decay;
814 r->EG2Sustain = pGlobalRegion->EG2Sustain;
815 r->EG2Release = pGlobalRegion->EG2Release;
816
817 r->modEnvToPitch = pGlobalRegion->modEnvToPitch;
818 r->modLfoToPitch = pGlobalRegion->modLfoToPitch;
819 r->modEnvToFilterFc = pGlobalRegion->modEnvToFilterFc;
820 r->modLfoToFilterFc = pGlobalRegion->modLfoToFilterFc;
821 r->modLfoToVolume = pGlobalRegion->modLfoToVolume;
822 r->freqModLfo = pGlobalRegion->freqModLfo;
823 r->delayModLfo = pGlobalRegion->delayModLfo;
824 r->vibLfoToPitch = pGlobalRegion->vibLfoToPitch;
825 r->freqVibLfo = pGlobalRegion->freqVibLfo;
826 r->delayVibLfo = pGlobalRegion->delayVibLfo;
827 r->initialFilterFc = pGlobalRegion->initialFilterFc;
828 r->initialFilterQ = pGlobalRegion->initialFilterQ;
829
830 r->HasLoop = pGlobalRegion->HasLoop;
831 r->LoopStart = pGlobalRegion->LoopStart;
832 r->LoopEnd = pGlobalRegion->LoopEnd;
833
834 r->exclusiveClass = pGlobalRegion->exclusiveClass;
835 }
836
837 return r;
838 }
839
840 void Instrument::DeleteRegion(Region* pRegion) {
841 for (int i = 0; i < regions.size(); i++) {
842 if (regions[i] == pRegion) {
843 delete pRegion;
844 regions[i] = NULL;
845 return;
846 }
847 }
848
849 std::cerr << "Can't remove unknown Region" << std::endl;
850 }
851
852 void Instrument::LoadRegions(int idx1, int idx2) {
853 for (int i = idx1; i < idx2; i++) {
854 int gIdx1 = pFile->InstBags[i].InstGenNdx;
855 int gIdx2 = pFile->InstBags[i + 1].InstGenNdx;
856
857 if (gIdx1 < 0 || gIdx2 < 0 || gIdx1 > gIdx2 || gIdx2 >= pFile->InstGenLists.size()) {
858 throw Exception("Broken SF2 file (invalid InstGenNdx)");
859 }
860
861 int mIdx1 = pFile->InstBags[i].InstModNdx;
862 int mIdx2 = pFile->InstBags[i + 1].InstModNdx;
863
864 if (mIdx1 < 0 || mIdx2 < 0 || mIdx1 > mIdx2 || mIdx2 >= pFile->InstModLists.size()) {
865 throw Exception("Broken SF2 file (invalid InstModNdx)");
866 }
867
868 Region* reg = CreateRegion();
869
870 for (int j = gIdx1; j < gIdx2; j++) {
871 reg->SetGenerator(pFile, pFile->InstGenLists[j]);
872 // TODO: ignore generators following a sampleID generator
873 }
874
875 for (int j = mIdx1; j < mIdx2; j++) {
876 reg->SetModulator(pFile, pFile->InstModLists[j]);
877 }
878
879 if (reg->pSample == NULL) {
880 if (i == idx1 && idx2 - idx1 > 1) {
881 pGlobalRegion = reg; // global zone
882 } else {
883 std::cerr << "Ignoring instrument's region without sample" << std::endl;
884 delete reg;
885 }
886 } else {
887 regions.push_back(reg);
888 }
889 }
890 }
891
892 Preset::Preset(sf2::File* pFile, RIFF::Chunk* ck): InstrumentBase(pFile) {
893 this->pFile = pFile;
894 LoadString(ck, Name, 20);
895 PresetNum = ck->ReadInt16();
896 Bank = ck->ReadInt16();
897 PresetBagNdx = ck->ReadInt16();
898 Library = ck->ReadInt32();
899 Genre = ck->ReadInt32();
900 Morphology = ck->ReadInt32();
901 }
902
903 Preset::~Preset() {
904 }
905
906 Region* Preset::CreateRegion() {
907 Region* r = new Region;
908
909 r->EG1PreAttackDelay = r->EG1Attack = r->EG1Hold = r->EG1Decay = r->EG1Sustain = r->EG1Release = NONE;
910 r->EG2PreAttackDelay = r->EG2Attack = r->EG2Hold = r->EG2Decay = r->EG2Sustain = r->EG2Release = NONE;
911 r->freqModLfo = r->delayModLfo = r->freqVibLfo = r->delayVibLfo = NONE;
912 r->initialFilterFc = r->initialFilterQ = NONE;
913
914 if (pGlobalRegion != NULL) {
915 r->pan = pGlobalRegion->pan;
916 r->fineTune = pGlobalRegion->fineTune;
917 r->coarseTune = pGlobalRegion->coarseTune;
918
919 r->EG1PreAttackDelay = pGlobalRegion->EG1PreAttackDelay;
920 r->EG1Attack = pGlobalRegion->EG1Attack;
921 r->EG1Hold = pGlobalRegion->EG1Hold;
922 r->EG1Decay = pGlobalRegion->EG1Decay;
923 r->EG1Sustain = pGlobalRegion->EG1Sustain;
924 r->EG1Release = pGlobalRegion->EG1Release;
925
926 r->EG2PreAttackDelay = pGlobalRegion->EG2PreAttackDelay;
927 r->EG2Attack = pGlobalRegion->EG2Attack;
928 r->EG2Hold = pGlobalRegion->EG2Hold;
929 r->EG2Decay = pGlobalRegion->EG2Decay;
930 r->EG2Sustain = pGlobalRegion->EG2Sustain;
931 r->EG2Release = pGlobalRegion->EG2Release;
932
933 r->modEnvToPitch = pGlobalRegion->modEnvToPitch;
934 r->modLfoToPitch = pGlobalRegion->modLfoToPitch;
935 r->modEnvToFilterFc = pGlobalRegion->modEnvToFilterFc;
936 r->modLfoToFilterFc = pGlobalRegion->modLfoToFilterFc;
937 r->modLfoToVolume = pGlobalRegion->modLfoToVolume;
938 r->freqModLfo = pGlobalRegion->freqModLfo;
939 r->delayModLfo = pGlobalRegion->delayModLfo;
940 r->vibLfoToPitch = pGlobalRegion->vibLfoToPitch;
941 r->freqVibLfo = pGlobalRegion->freqVibLfo;
942 r->delayVibLfo = pGlobalRegion->delayVibLfo;
943 r->initialFilterFc = pGlobalRegion->initialFilterFc;
944 r->initialFilterQ = pGlobalRegion->initialFilterQ;
945 }
946
947 return r;
948 }
949
950 void Preset::LoadRegions(int idx1, int idx2) {
951 for (int i = idx1; i < idx2; i++) {
952 int gIdx1 = pFile->PresetBags[i].GenNdx;
953 int gIdx2 = pFile->PresetBags[i + 1].GenNdx;
954
955 if (gIdx1 < 0 || gIdx2 < 0 || gIdx1 > gIdx2 || gIdx2 >= pFile->PresetGenLists.size()) {
956 throw Exception("Broken SF2 file (invalid PresetGenNdx)");
957 }
958
959 Region* reg = CreateRegion();
960
961 for (int j = gIdx1; j < gIdx2; j++) {
962 reg->SetGenerator(pFile, pFile->PresetGenLists[j]);
963 }
964 if (reg->pInstrument == NULL) {
965 if (i == idx1 && idx2 - idx1 > 1) {
966 pGlobalRegion = reg; // global zone
967 } else {
968 std::cerr << "Ignoring preset's region without instrument" << std::endl;
969 delete reg;
970 }
971 } else {
972 regions.push_back(reg);
973 }
974 }
975 }
976
986 File::File(RIFF::File* pRIFF) {
987 if (!pRIFF) throw Exception("NULL pointer reference to RIFF::File object.");
988 this->pRIFF = pRIFF;
989
990 if (pRIFF->GetListType() != RIFF_TYPE_SF2) {
991 throw Exception("Not a SF2 file");
992 }
993
994 pInfo = new Info(pRIFF);
995 if (pInfo->pVer->Major != 2) {
996 throw Exception("Unsupported version: " + ToString(pInfo->pVer->Major));
997 }
998
999 RIFF::List* lstSDTA = pRIFF->GetSubList(LIST_TYPE_SDTA);
1000 if (lstSDTA == NULL) {
1001 throw Exception("Broken SF2 file (missing sdta)");
1002 }
1003
1004 RIFF::Chunk* pCkSmpl = lstSDTA->GetSubChunk(CHUNK_ID_SMPL);
1005 RIFF::Chunk* pCkSm24 = lstSDTA->GetSubChunk(CHUNK_ID_SM24);
1006 if (pCkSmpl != NULL && pCkSm24 != NULL) {
1007 long l = pCkSmpl->GetSize() / 2;
1008 if (l%2) l++;
1009 if (pCkSm24->GetSize() != l) {
1010 pCkSm24 = NULL; // ignoring sm24 due to invalid size
1011 }
1012 }
1013
1014 RIFF::List* lstPDTA = pRIFF->GetSubList(LIST_TYPE_PDTA);
1015 if (lstPDTA == NULL) {
1016 throw Exception("Broken SF2 file (missing pdta)");
1017 }
1018
1019 RIFF::Chunk* ck = lstPDTA->GetSubChunk(CHUNK_ID_PHDR);
1020 if (ck->GetSize() < 38) {
1021 throw Exception("Broken SF2 file (broken phdr)");
1022 }
1023
1024 int count = (int) ck->GetSize() / 38;
1025 for (int i = 0; i < count; i++) {
1026 Presets.push_back(new Preset(this, ck));
1027 }
1028
1029 ck = GetMandatoryChunk(lstPDTA, CHUNK_ID_PBAG);
1030 if (ck->GetSize() < 4 || (ck->GetSize() % 4)) {
1031 throw Exception("Broken SF2 file (broken pbag)");
1032 }
1033
1034 count = int(ck->GetSize() / 4);
1035 for (int i = 0; i < count; i++) {
1036 PresetBag pb;
1037 pb.GenNdx = ck->ReadInt16();
1038 pb.ModNdx = ck->ReadInt16();
1039 PresetBags.push_back(pb);
1040 }
1041 //std::cout << "Preset bags: " << PresetBags.size() << std::endl;
1042
1043 ck = GetMandatoryChunk(lstPDTA, CHUNK_ID_PMOD);
1044 if (ck->GetSize() % 10) {
1045 throw Exception("Broken SF2 file (broken pmod)");
1046 }
1047
1048 count = int(ck->GetSize() / 10);
1049 for (int i = 0; i < count; i++) {
1050 ModList ml;
1051 ml.ModSrcOper = ck->ReadInt16();
1052 ml.ModDestOper = ck->ReadInt16();
1053 ml.ModAmount = ck->ReadInt16();
1054 ml.ModAmtSrcOper = ck->ReadInt16();
1055 ml.ModTransOper = ck->ReadInt16();
1056 PresetModLists.push_back(ml);
1057 }
1058 //std::cout << "Preset mod lists: " << PresetModLists.size() << std::endl;
1059
1060 ck = GetMandatoryChunk(lstPDTA, CHUNK_ID_PGEN);
1061 if (ck->GetSize() < 4 || (ck->GetSize() % 4)) {
1062 throw Exception("Broken SF2 file (broken pgen)");
1063 }
1064
1065 count = int(ck->GetSize() / 4);
1066 for (int i = 0; i < count; i++) {
1067 GenList gl;
1068 gl.GenOper = ck->ReadInt16();
1069 gl.GenAmount.wAmount = ck->ReadInt16();
1070 PresetGenLists.push_back(gl);
1071 }
1072 //std::cout << "Preset gen lists: " << PresetGenLists.size() << std::endl;
1073
1074 ck = GetMandatoryChunk(lstPDTA, CHUNK_ID_INST);
1075 if (ck->GetSize() < (22 * 2) || (ck->GetSize() % 22)) {
1076 throw Exception("Broken SF2 file (broken inst)");
1077 }
1078 count = int(ck->GetSize() / 22);
1079 for (int i = 0; i < count; i++) {
1080 Instruments.push_back(new Instrument(this, ck));
1081 }
1082
1083 ck = GetMandatoryChunk(lstPDTA, CHUNK_ID_IBAG);
1084 if (ck->GetSize() < 4 || (ck->GetSize() % 4)) {
1085 throw Exception("Broken SF2 file (broken ibag)");
1086 }
1087
1088 count = int(ck->GetSize() / 4);
1089 for (int i = 0; i < count; i++) {
1090 InstBag ib;
1091 ib.InstGenNdx = ck->ReadInt16();
1092 ib.InstModNdx = ck->ReadInt16();
1093 InstBags.push_back(ib);
1094 }
1095 //std::cout << "Instrument bags: " << InstBags.size() << std::endl;
1096
1097 ck = GetMandatoryChunk(lstPDTA, CHUNK_ID_IMOD);
1098 if (ck->GetSize() % 10) {
1099 throw Exception("Broken SF2 file (broken imod)");
1100 }
1101
1102 count = int(ck->GetSize() / 10);
1103 for (int i = 0; i < count; i++) {
1104 ModList ml;
1105 ml.ModSrcOper = ck->ReadInt16();
1106 ml.ModDestOper = ck->ReadInt16();
1107 ml.ModAmount = ck->ReadInt16();
1108 ml.ModAmtSrcOper = ck->ReadInt16();
1109 ml.ModTransOper = ck->ReadInt16();
1110 InstModLists.push_back(ml);
1111 }
1112 //std::cout << "Instrument mod lists: " << InstModLists.size() << std::endl;
1113
1114 ck = GetMandatoryChunk(lstPDTA, CHUNK_ID_IGEN);
1115 if (ck->GetSize() < 4 || (ck->GetSize() % 4)) {
1116 throw Exception("Broken SF2 file (broken igen)");
1117 }
1118
1119 count = int(ck->GetSize() / 4);
1120 for (int i = 0; i < count; i++) {
1121 GenList gl;
1122 gl.GenOper = ck->ReadInt16();
1123 gl.GenAmount.wAmount = ck->ReadInt16();
1124 InstGenLists.push_back(gl);
1125 }
1126 //std::cout << "Instrument gen lists: " << InstGenLists.size() << std::endl;
1127
1128 ck = GetMandatoryChunk(lstPDTA, CHUNK_ID_SHDR);
1129 if ((ck->GetSize() % 46)) {
1130 throw Exception("Broken SF2 file (broken shdr)");
1131 }
1132 count = int(ck->GetSize() / 46);
1133 for (int i = 0; i < count; i++) {
1134 Samples.push_back(new Sample(this, ck, pCkSmpl, pCkSm24));
1135 }
1136
1137 // Loading instrument regions
1138 for (int i = 0; i < Instruments.size() - 1; i++) {
1139 Instrument* instr = Instruments[i];
1140 int x1 = instr->InstBagNdx;
1141 int x2 = Instruments[i + 1]->InstBagNdx;
1142 if (x1 < 0 || x2 < 0 || x1 > x2 || x2 >= InstBags.size()) {
1143 throw Exception("Broken SF2 file (invalid InstBagNdx)");
1144 }
1145
1146 instr->LoadRegions(x1, x2);
1147 }
1148
1149 // Loading preset regions
1150 for (int i = 0; i < Presets.size() - 1; i++) {
1151 Preset* preset = Presets[i];
1152 int x1 = preset->PresetBagNdx;
1153 int x2 = Presets[i + 1]->PresetBagNdx;
1154 if (x1 < 0 || x2 < 0 || x1 > x2 || x2 >= PresetBags.size()) {
1155 throw Exception("Broken SF2 file (invalid PresetBagNdx)");
1156 }
1157
1158 preset->LoadRegions(x1, x2);
1159 }
1160 }
1161
1162 File::~File() {
1163 delete pInfo;
1164 for (ssize_t i = Presets.size() - 1; i >= 0; i--) {
1165 if (Presets[i]) delete (Presets[i]);
1166 }
1167 for (ssize_t i = Instruments.size() - 1; i >= 0; i--) {
1168 if (Instruments[i]) delete (Instruments[i]);
1169 }
1170 for (ssize_t i = Samples.size() - 1; i >= 0; i--) {
1171 if (Samples[i]) delete (Samples[i]);
1172 }
1173 }
1174
1175 int File::GetPresetCount() {
1176 return (int) Presets.size() - 1; // exclude terminal preset (EOP)
1177 }
1178
1179 Preset* File::GetPreset(int idx) {
1180 if (idx < 0 || idx >= GetPresetCount()) {
1181 throw Exception("Preset index out of bounds");
1182 }
1183
1184 return Presets[idx];
1185 }
1186
1187 int File::GetInstrumentCount() {
1188 return (int) Instruments.size() - 1; // exclude terminal instrument (EOI)
1189 }
1190
1191 Instrument* File::GetInstrument(int idx) {
1192 if (idx < 0 || idx >= GetInstrumentCount()) {
1193 throw Exception("Instrument index out of bounds");
1194 }
1195
1196 return Instruments[idx];
1197 }
1198
1199 void File::DeleteInstrument(Instrument* pInstrument) {
1200 if (!pInstrument) return;
1201
1202 for (int i = 0; i < GetPresetCount(); i++) {
1203 Preset* p = GetPreset(i);
1204 if (p == NULL) continue;
1205 for (int j = p->GetRegionCount() - 1; j >= 0 ; j--) {
1206 if (p->GetRegion(j) && p->GetRegion(j)->pInstrument == pInstrument) {
1207 p->GetRegion(j)->pInstrument = NULL;
1208 }
1209 }
1210 }
1211
1212 for (int i = 0; i < GetInstrumentCount(); i++) {
1213 if (GetInstrument(i) == pInstrument) {
1214 Instruments[i] = NULL;
1215 delete pInstrument;
1216 // an instrument instance only exists once in the list, so stop
1217 // here (which also silences a clang sanatizer warning about
1218 // potential multiple memory releases of pInstrument above)
1219 return;
1220 }
1221 }
1222 }
1223
1224 int File::GetSampleCount() {
1225 return (int) Samples.size() - 1; // exclude terminal sample (EOS)
1226 }
1227
1228 Sample* File::GetSample(int idx) {
1229 if (idx < 0 || idx >= GetSampleCount()) {
1230 throw Exception("Sample index out of bounds");
1231 }
1232
1233 return Samples[idx];
1234 }
1235
1236 void File::DeleteSample(Sample* pSample) {
1237 // Sanity check
1238 for (int i = GetInstrumentCount() - 1; i >= 0; i--) {
1239 Instrument* pInstr = GetInstrument(i);
1240 if (pInstr == NULL) continue;
1241
1242 for (int j = pInstr->GetRegionCount() - 1; j >= 0 ; j--) {
1243 if (pInstr->GetRegion(j) && pInstr->GetRegion(j)->GetSample() == pSample) {
1244 std::cerr << "Deleting sample which is still in use" << std::endl;
1245 }
1246 }
1247 }
1249
1250 for (int i = 0; i < GetSampleCount(); i++) {
1251 if (Samples[i] == pSample) {
1252 delete pSample;
1253 Samples[i] = NULL;
1254 return;
1255 }
1256 }
1257
1258 throw Exception("Unknown sample: " + pSample->Name);
1259 }
1260
1261 bool File::HasSamples() {
1262 for (int i = 0; i < GetSampleCount(); i++) {
1263 if (Samples[i] != NULL) return true;
1264 }
1265
1266 return false;
1267 }
1268
1269 RIFF::File* File::GetRiffFile() {
1270 return pRIFF;
1271 }
1272
1282 Sample::buffer_t Sample::LoadSampleData() {
1283 return LoadSampleDataWithNullSamplesExtension(GetTotalFrameCount(), 0); // 0 amount of NullSamples
1284 }
1285
1304 Sample::buffer_t Sample::LoadSampleData(unsigned long SampleCount) {
1305 return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
1306 }
1307
1327 Sample::buffer_t Sample::LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount) {
1328 return LoadSampleDataWithNullSamplesExtension(GetTotalFrameCount(), NullSamplesCount);
1329 }
1330
1359 Sample::buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {
1360 if (SampleCount > GetTotalFrameCount()) SampleCount = GetTotalFrameCount();
1361 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1362 unsigned long allocationsize = (SampleCount + NullSamplesCount) * GetFrameSize();
1363 SetPos(0); // reset read position to begin of sample
1364 RAMCache.pStart = new int8_t[allocationsize];
1365 RAMCache.Size = Read(RAMCache.pStart, SampleCount) * GetFrameSize();
1366 RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
1367 // fill the remaining buffer space with silence samples
1368 memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
1369 return GetCache();
1370 }
1371
1382 Sample::buffer_t Sample::GetCache() {
1383 // return a copy of the buffer_t structure
1384 buffer_t result;
1385 result.Size = this->RAMCache.Size;
1386 result.pStart = this->RAMCache.pStart;
1387 result.NullExtensionSize = this->RAMCache.NullExtensionSize;
1388 return result;
1389 }
1390
1397 void Sample::ReleaseSampleData() {
1398 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1399 RAMCache.pStart = NULL;
1400 RAMCache.Size = 0;
1401 RAMCache.NullExtensionSize = 0;
1402 }
1403
1413 unsigned long Sample::SetPos(unsigned long SampleCount) {
1414 pCkSmpl->SetPos((Start * 2) + (SampleCount * 2), RIFF::stream_start);
1415 if(pCkSm24) pCkSm24->SetPos(Start + SampleCount, RIFF::stream_start);
1416 return SampleCount;
1417 }
1418
1422 unsigned long Sample::GetPos() {
1423 return (pCkSmpl->GetPos() - (Start * 2)) / 2;
1424 }
1425
1426 // Actual implementation of Sample::Read*() code. Wrapped into a template for a) runtime effeciency and b) code redundancy reasons.
1427 template<bool CLEAR>
1428 inline unsigned long ReadSample(Sample* pSample, void* pBuffer, unsigned long SampleCount, Sample::buffer_t* tempBuffer = NULL) {
1429 // TODO: startAddrsCoarseOffset, endAddrsCoarseOffset
1430 if (SampleCount == 0) return 0;
1431 long pos = pSample->GetPos();
1432 // prevent bogus/huge SampleCount value if pos >= sample end
1433 if (pos >= pSample->GetTotalFrameCount())
1434 return 0;
1435 if (pos + SampleCount > pSample->GetTotalFrameCount())
1436 SampleCount = pSample->GetTotalFrameCount() - pos;
1437 if (!CLEAR) {
1438 if (tempBuffer->Size < SampleCount * pSample->GetFrameSize()) {
1439 std::cerr << "sf2::Sample error: tempBuffer too small. This is a BUG!" << std::endl;
1440 return 0;
1441 }
1442 }
1443
1444 // this is less error-prone than checking all SampleType enums
1445 const bool bMono = (pSample->GetChannelCount() == 1);
1446
1447 if (pSample->GetFrameSize() / pSample->GetChannelCount() == 3 /* 24 bit */) {
1448 uint8_t* const pBuf = (uint8_t*) pBuffer;
1449 // read the raw (little-endian) sample data into the staging buffer
1450 // (16-bit to the front, followed by 8-bit at the end of buffer)
1451 uint8_t* const pStage = (CLEAR) ? pBuf : (uint8_t*) tempBuffer->pStart;
1452 pSample->pCkSmpl->Read(pStage, SampleCount * 2, 1);
1453 pSample->pCkSm24->Read(pStage + SampleCount * 2, SampleCount, 1);
1454
1455 if (CLEAR) {
1456 // in-place interleaving into one contiguous 24-bit stream
1457 // (for mono we are then already done here)
1458 interleave16_8to24(pStage, SampleCount);
1459 // For stereo we must still spread the 24-bit words into the
1460 // respective channel slots.
1461 if (!bMono) {
1462 // process from high to low to avoid self-overlap
1463 // (because staging and destination are alias here)
1464 if (pSample->SampleType == Sample::LEFT_SAMPLE || pSample->SampleType == Sample::ROM_LEFT_SAMPLE) {
1465 for (long i = SampleCount - 1; i >= 0; i--) {
1466 pBuf[i*6 + 2] = pStage[i*3 + 2];
1467 pBuf[i*6 + 1] = pStage[i*3 + 1];
1468 pBuf[i*6] = pStage[i*3];
1469 pBuf[i*6 + 3] = pBuf[i*6 + 4] = pBuf[i*6 + 5] = 0;
1470 }
1471 } else if (pSample->SampleType == Sample::RIGHT_SAMPLE || pSample->SampleType == Sample::ROM_RIGHT_SAMPLE) {
1472 for (long i = SampleCount - 1; i >= 0; i--) {
1473 pBuf[i*6 + 5] = pStage[i*3 + 2];
1474 pBuf[i*6 + 4] = pStage[i*3 + 1];
1475 pBuf[i*6 + 3] = pStage[i*3];
1476 pBuf[i*6] = pBuf[i*6 + 1] = pBuf[i*6 + 2] = 0;
1477 }
1478 }
1479 }
1480 } else {
1481 // We have a true separate staging buffer here (pBuf != pStage),
1482 // so we can use straigh-forward (and fast) direct copy without
1483 // fearing overlap.
1484 if (bMono) {
1485 for (unsigned long i = 0; i < SampleCount; i++) {
1486 pBuf[i*3] = pStage[SampleCount * 2 + i];
1487 pBuf[i*3 + 1] = pStage[i * 2];
1488 pBuf[i*3 + 2] = pStage[i * 2 + 1];
1489 }
1490 } else if (pSample->SampleType == Sample::LEFT_SAMPLE || pSample->SampleType == Sample::ROM_LEFT_SAMPLE) {
1491 for (unsigned long i = 0; i < SampleCount; i++) {
1492 pBuf[i*6] = pStage[SampleCount * 2 + i];
1493 pBuf[i*6 + 1] = pStage[i * 2];
1494 pBuf[i*6 + 2] = pStage[i * 2 + 1];
1495 }
1496 } else if (pSample->SampleType == Sample::RIGHT_SAMPLE || pSample->SampleType == Sample::ROM_RIGHT_SAMPLE) {
1497 for (unsigned long i = 0; i < SampleCount; i++) {
1498 pBuf[i*6 + 3] = pStage[SampleCount * 2 + i];
1499 pBuf[i*6 + 4] = pStage[i * 2];
1500 pBuf[i*6 + 5] = pStage[i * 2 + 1];
1501 }
1502 }
1503 }
1504 } else {
1505 if (bMono) {
1506 return pSample->pCkSmpl->Read(pBuffer, SampleCount, 2);
1507 }
1508
1509 int16_t* const pTmpBuf = (int16_t*) ((CLEAR) ? pBuffer : tempBuffer->pStart);
1510 int16_t* const pBuf = (int16_t*) pBuffer;
1511 if (pSample->SampleType == Sample::LEFT_SAMPLE || pSample->SampleType == Sample::ROM_LEFT_SAMPLE) {
1512 pSample->pCkSmpl->Read(pTmpBuf, SampleCount, 2);
1513 for (long i = SampleCount - 1; i >= 0; i--) {
1514 pBuf[i*2] = pTmpBuf[i];
1515 if (CLEAR)
1516 pBuf[i*2 + 1] = 0;
1517 }
1518 } else if (pSample->SampleType == Sample::RIGHT_SAMPLE || pSample->SampleType == Sample::ROM_RIGHT_SAMPLE) {
1519 pSample->pCkSmpl->Read(pTmpBuf, SampleCount, 2);
1520 for (long i = SampleCount - 1; i >= 0; i--) {
1521 // copy before zeroing: pTmpBuf == pBuf if CLEAR=true,
1522 // so zeroing pBuf[2*i] first would destroy pTmpBuf[i]
1523 // (causing loss of first sample at i == 0)
1524 pBuf[i*2 + 1] = pTmpBuf[i];
1525 if (CLEAR)
1526 pBuf[i*2] = 0;
1527 }
1528 }
1529 }
1530
1531 if (pSample->pCkSmpl->GetPos() > (pSample->End * 2)) {
1532 std::cerr << "Read after the sample end. This is a BUG!" << std::endl;
1533 std::cerr << "Current position: " << pSample->GetPos() << std::endl;
1534 std::cerr << "Total number of frames: " << pSample->GetTotalFrameCount() << std::endl << std::endl;
1535 }
1536 return SampleCount;
1537 }
1538
1562 unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {
1563 return ReadSample<true>(this, pBuffer, SampleCount);
1564 }
1565
1596 unsigned long Sample::ReadNoClear(void* pBuffer, unsigned long SampleCount, buffer_t& tempBuffer) {
1597 return ReadSample<false>(this, pBuffer, SampleCount, &tempBuffer);
1598 }
1599
1600
1601// *************** functions ***************
1602// *
1603
1607 String libraryName() {
1608 return PACKAGE;
1609 }
1610
1615 return VERSION;
1616 }
1617
1618} // namespace sf2
Ordinary RIFF Chunk.
Definition RIFF.h:186
file_offset_t ReadInt8(int8_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 8 Bit signed integer words and copies it into the buffer pointed by pData.
Definition RIFF.cpp:595
file_offset_t SetPos(file_offset_t Where, stream_whence_t Whence=stream_start)
Sets the position within the chunk body, thus within the data portion of the chunk (in bytes).
Definition RIFF.cpp:375
file_offset_t GetPos() const
Current read/write position within the chunk data body (starting with 0).
Definition RIFF.cpp:345
file_offset_t ReadUint16(uint16_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 16 Bit unsigned integer words and copies it into the buffer pointed by pDat...
Definition RIFF.cpp:712
file_offset_t ReadInt16(int16_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 16 Bit signed integer words and copies it into the buffer pointed by pData.
Definition RIFF.cpp:673
uint32_t GetChunkID() const
Chunk ID in unsigned integer representation.
Definition RIFF.h:190
file_offset_t ReadInt32(int32_t *pData, file_offset_t WordCount=1)
Reads WordCount number of 32 Bit signed integer words and copies it into the buffer pointed by pData.
Definition RIFF.cpp:751
file_offset_t GetSize() const
Chunk size in bytes (without header, thus the chunk data body).
Definition RIFF.h:193
RIFF File.
Definition RIFF.h:314
RIFF List Chunk.
Definition RIFF.h:262
Chunk * GetSubChunk(uint32_t ChunkID)
Returns subchunk with chunk ID ChunkID within this chunk list.
Definition RIFF.cpp:1251
List * GetSubList(uint32_t ListType)
Returns sublist chunk with list type ListType within this chunk list.
Definition RIFF.cpp:1292
uint32_t GetListType() const
Returns unsigned integer representation of the list's ID.
Definition RIFF.h:266
uint32_t Version
Version number data type.
SoundFont specific classes and definitions.
Definition SF.h:62
void VerifySize(RIFF::Chunk *ck, int size)
Throws an error if the chunk is NULL or the chunk data size is less than size (in bytes).
Definition SF.cpp:77
String libraryVersion()
Returns version of this C++ library.
Definition SF.cpp:1614
String libraryName()
Returns the name of this C++ library.
Definition SF.cpp:1607
file_offset_t Size
Size of the actual data in the buffer in bytes.
Definition gig.h:116