/[svn]/libgig/trunk/src/gig.cpp
ViewVC logotype

Contents of /libgig/trunk/src/gig.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 16 - (show annotations) (download)
Sat Nov 29 14:56:16 2003 UTC (20 years, 4 months ago) by schoenebeck
File size: 53935 byte(s)
* src/gig.cpp, src/gig.h: added method GetVelocityAttenuation() to class
  DimensionRegion which takes the MIDI key velocity value as an argument
  and returns the appropriate volume factor (0.0-1.0) for the sample to be
  be played back, the velocity curve transformation functions used for this
  are only an approximation so far

1 /***************************************************************************
2 * *
3 * libgig - C++ cross-platform Gigasampler format file loader library *
4 * *
5 * Copyright (C) 2003 by Christian Schoenebeck *
6 * <cuse@users.sourceforge.net> *
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 "gig.h"
25
26 namespace gig {
27
28 // *************** Sample ***************
29 // *
30
31 unsigned int Sample::Instances = 0;
32 void* Sample::pDecompressionBuffer = NULL;
33 unsigned long Sample::DecompressionBufferSize = 0;
34
35 Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
36 Instances++;
37
38 RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
39 if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");
40 SampleGroup = _3gix->ReadInt16();
41
42 RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
43 if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");
44 Manufacturer = smpl->ReadInt32();
45 Product = smpl->ReadInt32();
46 SamplePeriod = smpl->ReadInt32();
47 MIDIUnityNote = smpl->ReadInt32();
48 MIDIPitchFraction = smpl->ReadInt32();
49 smpl->Read(&SMPTEFormat, 1, 4);
50 SMPTEOffset = smpl->ReadInt32();
51 Loops = smpl->ReadInt32();
52 LoopID = smpl->ReadInt32();
53 smpl->Read(&LoopType, 1, 4);
54 LoopStart = smpl->ReadInt32();
55 LoopEnd = smpl->ReadInt32();
56 LoopFraction = smpl->ReadInt32();
57 LoopPlayCount = smpl->ReadInt32();
58
59 FrameTable = NULL;
60 SamplePos = 0;
61 RAMCache.Size = 0;
62 RAMCache.pStart = NULL;
63 RAMCache.NullExtensionSize = 0;
64
65 Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));
66 if (Compressed) {
67 ScanCompressedSample();
68 if (!pDecompressionBuffer) {
69 pDecompressionBuffer = new int8_t[INITIAL_SAMPLE_BUFFER_SIZE];
70 DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;
71 }
72 }
73 FrameOffset = 0; // just for streaming compressed samples
74 }
75
76 /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
77 void Sample::ScanCompressedSample() {
78 //TODO: we have to add some more scans here (e.g. determine compression rate)
79 this->SamplesTotal = 0;
80 std::list<unsigned long> frameOffsets;
81
82 // Scanning
83 pCkData->SetPos(0);
84 while (pCkData->GetState() == RIFF::stream_ready) {
85 frameOffsets.push_back(pCkData->GetPos());
86 int16_t compressionmode = pCkData->ReadInt16();
87 this->SamplesTotal += 2048;
88 switch (compressionmode) {
89 case 1: // left channel compressed
90 case 256: // right channel compressed
91 pCkData->SetPos(6148, RIFF::stream_curpos);
92 break;
93 case 257: // both channels compressed
94 pCkData->SetPos(4104, RIFF::stream_curpos);
95 break;
96 default: // both channels uncompressed
97 pCkData->SetPos(8192, RIFF::stream_curpos);
98 }
99 }
100 pCkData->SetPos(0);
101
102 //FIXME: only seen compressed samples with 16 bit stereo so far
103 this->FrameSize = 4;
104 this->BitDepth = 16;
105
106 // Build the frames table (which is used for fast resolving of a frame's chunk offset)
107 if (FrameTable) delete[] FrameTable;
108 FrameTable = new unsigned long[frameOffsets.size()];
109 std::list<unsigned long>::iterator end = frameOffsets.end();
110 std::list<unsigned long>::iterator iter = frameOffsets.begin();
111 for (int i = 0; iter != end; i++, iter++) {
112 FrameTable[i] = *iter;
113 }
114 }
115
116 /**
117 * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
118 * ReleaseSampleData() to free the memory if you don't need the cached
119 * sample data anymore.
120 *
121 * @returns buffer_t structure with start address and size of the buffer
122 * in bytes
123 * @see ReleaseSampleData(), Read(), SetPos()
124 */
125 buffer_t Sample::LoadSampleData() {
126 return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0); // 0 amount of NullSamples
127 }
128
129 /**
130 * Reads (uncompresses if needed) and caches the first \a SampleCount
131 * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
132 * memory space if you don't need the cached samples anymore. There is no
133 * guarantee that exactly \a SampleCount samples will be cached; this is
134 * not an error. The size will be eventually truncated e.g. to the
135 * beginning of a frame of a compressed sample. This is done for
136 * efficiency reasons while streaming the wave by your sampler engine
137 * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
138 * that will be returned to determine the actual cached samples, but note
139 * that the size is given in bytes! You get the number of actually cached
140 * samples by dividing it by the frame size of the sample:
141 *
142 * buffer_t buf = pSample->LoadSampleData(acquired_samples);
143 * long cachedsamples = buf.Size / pSample->FrameSize;
144 *
145 * @param SampleCount - number of sample points to load into RAM
146 * @returns buffer_t structure with start address and size of
147 * the cached sample data in bytes
148 * @see ReleaseSampleData(), Read(), SetPos()
149 */
150 buffer_t Sample::LoadSampleData(unsigned long SampleCount) {
151 return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
152 }
153
154 /**
155 * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
156 * ReleaseSampleData() to free the memory if you don't need the cached
157 * sample data anymore.
158 * The method will add \a NullSamplesCount silence samples past the
159 * official buffer end (this won't affect the 'Size' member of the
160 * buffer_t structure, that means 'Size' always reflects the size of the
161 * actual sample data, the buffer might be bigger though). Silence
162 * samples past the official buffer are needed for differential
163 * algorithms that always have to take subsequent samples into account
164 * (resampling/interpolation would be an important example) and avoids
165 * memory access faults in such cases.
166 *
167 * @param NullSamplesCount - number of silence samples the buffer should
168 * be extended past it's data end
169 * @returns buffer_t structure with start address and
170 * size of the buffer in bytes
171 * @see ReleaseSampleData(), Read(), SetPos()
172 */
173 buffer_t Sample::LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount) {
174 return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
175 }
176
177 /**
178 * Reads (uncompresses if needed) and caches the first \a SampleCount
179 * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
180 * memory space if you don't need the cached samples anymore. There is no
181 * guarantee that exactly \a SampleCount samples will be cached; this is
182 * not an error. The size will be eventually truncated e.g. to the
183 * beginning of a frame of a compressed sample. This is done for
184 * efficiency reasons while streaming the wave by your sampler engine
185 * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
186 * that will be returned to determine the actual cached samples, but note
187 * that the size is given in bytes! You get the number of actually cached
188 * samples by dividing it by the frame size of the sample:
189 *
190 * buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
191 * long cachedsamples = buf.Size / pSample->FrameSize;
192 *
193 * The method will add \a NullSamplesCount silence samples past the
194 * official buffer end (this won't affect the 'Size' member of the
195 * buffer_t structure, that means 'Size' always reflects the size of the
196 * actual sample data, the buffer might be bigger though). Silence
197 * samples past the official buffer are needed for differential
198 * algorithms that always have to take subsequent samples into account
199 * (resampling/interpolation would be an important example) and avoids
200 * memory access faults in such cases.
201 *
202 * @param SampleCount - number of sample points to load into RAM
203 * @param NullSamplesCount - number of silence samples the buffer should
204 * be extended past it's data end
205 * @returns buffer_t structure with start address and
206 * size of the cached sample data in bytes
207 * @see ReleaseSampleData(), Read(), SetPos()
208 */
209 buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {
210 if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
211 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
212 unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
213 RAMCache.pStart = new int8_t[allocationsize];
214 RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
215 RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
216 // fill the remaining buffer space with silence samples
217 memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
218 return GetCache();
219 }
220
221 /**
222 * Returns current cached sample points. A buffer_t structure will be
223 * returned which contains address pointer to the begin of the cache and
224 * the size of the cached sample data in bytes. Use
225 * <i>LoadSampleData()</i> to cache a specific amount of sample points in
226 * RAM.
227 *
228 * @returns buffer_t structure with current cached sample points
229 * @see LoadSampleData();
230 */
231 buffer_t Sample::GetCache() {
232 // return a copy of the buffer_t structure
233 buffer_t result;
234 result.Size = this->RAMCache.Size;
235 result.pStart = this->RAMCache.pStart;
236 result.NullExtensionSize = this->RAMCache.NullExtensionSize;
237 return result;
238 }
239
240 /**
241 * Frees the cached sample from RAM if loaded with
242 * <i>LoadSampleData()</i> previously.
243 *
244 * @see LoadSampleData();
245 */
246 void Sample::ReleaseSampleData() {
247 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
248 RAMCache.pStart = NULL;
249 RAMCache.Size = 0;
250 }
251
252 /**
253 * Sets the position within the sample (in sample points, not in
254 * bytes). Use this method and <i>Read()</i> if you don't want to load
255 * the sample into RAM, thus for disk streaming.
256 *
257 * Although the original Gigasampler engine doesn't allow positioning
258 * within compressed samples, I decided to implement it. Even though
259 * the Gigasampler format doesn't allow to define loops for compressed
260 * samples at the moment, positioning within compressed samples might be
261 * interesting for some sampler engines though. The only drawback about
262 * my decision is that it takes longer to load compressed gig Files on
263 * startup, because it's neccessary to scan the samples for some
264 * mandatory informations. But I think as it doesn't affect the runtime
265 * efficiency, nobody will have a problem with that.
266 *
267 * @param SampleCount number of sample points to jump
268 * @param Whence optional: to which relation \a SampleCount refers
269 * to, if omited <i>RIFF::stream_start</i> is assumed
270 * @returns the new sample position
271 * @see Read()
272 */
273 unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
274 if (Compressed) {
275 switch (Whence) {
276 case RIFF::stream_curpos:
277 this->SamplePos += SampleCount;
278 break;
279 case RIFF::stream_end:
280 this->SamplePos = this->SamplesTotal - 1 - SampleCount;
281 break;
282 case RIFF::stream_backward:
283 this->SamplePos -= SampleCount;
284 break;
285 case RIFF::stream_start: default:
286 this->SamplePos = SampleCount;
287 break;
288 }
289 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
290
291 unsigned long frame = this->SamplePos / 2048; // to which frame to jump
292 this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame
293 pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame
294 return this->SamplePos;
295 }
296 else { // not compressed
297 unsigned long orderedBytes = SampleCount * this->FrameSize;
298 unsigned long result = pCkData->SetPos(orderedBytes, Whence);
299 return (result == orderedBytes) ? SampleCount
300 : result / this->FrameSize;
301 }
302 }
303
304 /**
305 * Returns the current position in the sample (in sample points).
306 */
307 unsigned long Sample::GetPos() {
308 if (Compressed) return SamplePos;
309 else return pCkData->GetPos() / FrameSize;
310 }
311
312 /**
313 * Reads \a SampleCount number of sample points from the current
314 * position into the buffer pointed by \a pBuffer and increments the
315 * position within the sample. The sample wave stream will be
316 * decompressed on the fly if using a compressed sample. Use this method
317 * and <i>SetPos()</i> if you don't want to load the sample into RAM,
318 * thus for disk streaming.
319 *
320 * @param pBuffer destination buffer
321 * @param SampleCount number of sample points to read
322 * @returns number of successfully read sample points
323 * @see SetPos()
324 */
325 unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {
326 if (!Compressed) return pCkData->Read(pBuffer, SampleCount, FrameSize); //FIXME: channel inversion due to endian correction?
327 else { //FIXME: no support for mono compressed samples yet, are there any?
328 if (this->SamplePos >= this->SamplesTotal) return 0;
329 //TODO: efficiency: we simply assume here that all frames are compressed, maybe we should test for an average compression rate
330 // best case needed buffer size (all frames compressed)
331 unsigned long assumedsize = (SampleCount << 1) + // *2 (16 Bit, stereo, but assume all frames compressed)
332 (SampleCount >> 10) + // 10 bytes header per 2048 sample points
333 8194, // at least one worst case sample frame
334 remainingbytes = 0, // remaining bytes in the local buffer
335 remainingsamples = SampleCount,
336 copysamples;
337 int currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
338 this->FrameOffset = 0;
339
340 if (assumedsize > this->DecompressionBufferSize) {
341 // local buffer reallocation - hope this won't happen
342 if (this->pDecompressionBuffer) delete[] (int8_t*) this->pDecompressionBuffer;
343 this->pDecompressionBuffer = new int8_t[assumedsize << 1]; // double of current needed size
344 this->DecompressionBufferSize = assumedsize;
345 }
346
347 int16_t compressionmode, left, dleft, right, dright;
348 int8_t* pSrc = (int8_t*) this->pDecompressionBuffer;
349 int16_t* pDst = (int16_t*) pBuffer;
350 remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
351
352 while (remainingsamples) {
353
354 // reload from disk to local buffer if needed
355 if (remainingbytes < 8194) {
356 if (pCkData->GetState() != RIFF::stream_ready) {
357 this->SamplePos = this->SamplesTotal;
358 return (SampleCount - remainingsamples);
359 }
360 assumedsize = remainingsamples;
361 assumedsize = (assumedsize << 1) + // *2 (16 Bit, stereo, but assume all frames compressed)
362 (assumedsize >> 10) + // 10 bytes header per 2048 sample points
363 8194; // at least one worst case sample frame
364 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
365 if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
366 remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);
367 pSrc = (int8_t*) this->pDecompressionBuffer;
368 }
369
370 // determine how many samples in this frame to skip and read
371 if (remainingsamples >= 2048) {
372 copysamples = 2048 - currentframeoffset;
373 remainingsamples -= copysamples;
374 }
375 else {
376 copysamples = remainingsamples;
377 if (currentframeoffset + copysamples > 2048) {
378 copysamples = 2048 - currentframeoffset;
379 remainingsamples -= copysamples;
380 }
381 else {
382 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
383 remainingsamples = 0;
384 this->FrameOffset = currentframeoffset + copysamples;
385 }
386 }
387
388 // decompress and copy current frame from local buffer to destination buffer
389 compressionmode = *(int16_t*)pSrc; pSrc+=2;
390 switch (compressionmode) {
391 case 1: // left channel compressed
392 remainingbytes -= 6150; // (left 8 bit, right 16 bit, +6 byte header)
393 if (!remainingsamples && copysamples == 2048)
394 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
395
396 left = *(int16_t*)pSrc; pSrc+=2;
397 dleft = *(int16_t*)pSrc; pSrc+=2;
398 while (currentframeoffset) {
399 dleft -= *pSrc;
400 left -= dleft;
401 pSrc+=3; // 8 bit left channel, skip uncompressed right channel (16 bit)
402 currentframeoffset--;
403 }
404 while (copysamples) {
405 dleft -= *pSrc; pSrc++;
406 left -= dleft;
407 *pDst = left; pDst++;
408 *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;
409 copysamples--;
410 }
411 break;
412 case 256: // right channel compressed
413 remainingbytes -= 6150; // (left 16 bit, right 8 bit, +6 byte header)
414 if (!remainingsamples && copysamples == 2048)
415 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
416
417 right = *(int16_t*)pSrc; pSrc+=2;
418 dright = *(int16_t*)pSrc; pSrc+=2;
419 if (currentframeoffset) {
420 pSrc+=2; // skip uncompressed left channel, now we can increment by 3
421 while (currentframeoffset) {
422 dright -= *pSrc;
423 right -= dright;
424 pSrc+=3; // 8 bit right channel, skip uncompressed left channel (16 bit)
425 currentframeoffset--;
426 }
427 pSrc-=2; // back aligned to left channel
428 }
429 while (copysamples) {
430 *pDst = *(int16_t*)pSrc; pDst++; pSrc+=2;
431 dright -= *pSrc; pSrc++;
432 right -= dright;
433 *pDst = right; pDst++;
434 copysamples--;
435 }
436 break;
437 case 257: // both channels compressed
438 remainingbytes -= 4106; // (left 8 bit, right 8 bit, +10 byte header)
439 if (!remainingsamples && copysamples == 2048)
440 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
441
442 left = *(int16_t*)pSrc; pSrc+=2;
443 dleft = *(int16_t*)pSrc; pSrc+=2;
444 right = *(int16_t*)pSrc; pSrc+=2;
445 dright = *(int16_t*)pSrc; pSrc+=2;
446 while (currentframeoffset) {
447 dleft -= *pSrc; pSrc++;
448 left -= dleft;
449 dright -= *pSrc; pSrc++;
450 right -= dright;
451 currentframeoffset--;
452 }
453 while (copysamples) {
454 dleft -= *pSrc; pSrc++;
455 left -= dleft;
456 dright -= *pSrc; pSrc++;
457 right -= dright;
458 *pDst = left; pDst++;
459 *pDst = right; pDst++;
460 copysamples--;
461 }
462 break;
463 default: // both channels uncompressed
464 remainingbytes -= 8194; // (left 16 bit, right 16 bit, +2 byte header)
465 if (!remainingsamples && copysamples == 2048)
466 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
467
468 pSrc += currentframeoffset << 2;
469 currentframeoffset = 0;
470 memcpy(pDst, pSrc, copysamples << 2);
471 pDst += copysamples << 1;
472 pSrc += copysamples << 2;
473 break;
474 }
475 }
476 this->SamplePos += (SampleCount - remainingsamples);
477 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
478 return (SampleCount - remainingsamples);
479 }
480 }
481
482 Sample::~Sample() {
483 Instances--;
484 if (!Instances && pDecompressionBuffer) delete[] (int8_t*) pDecompressionBuffer;
485 if (FrameTable) delete[] FrameTable;
486 if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
487 }
488
489
490
491 // *************** DimensionRegion ***************
492 // *
493
494 uint DimensionRegion::Instances = 0;
495 DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
496
497 DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
498 Instances++;
499
500 memcpy(&Crossfade, &SamplerOptions, 4);
501 if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
502
503 RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
504 _3ewa->ReadInt32(); // unknown, allways 0x0000008C ?
505 LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
506 EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
507 _3ewa->ReadInt16(); // unknown
508 LFO1InternalDepth = _3ewa->ReadUint16();
509 _3ewa->ReadInt16(); // unknown
510 LFO3InternalDepth = _3ewa->ReadInt16();
511 _3ewa->ReadInt16(); // unknown
512 LFO1ControlDepth = _3ewa->ReadUint16();
513 _3ewa->ReadInt16(); // unknown
514 LFO3ControlDepth = _3ewa->ReadInt16();
515 EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
516 EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
517 _3ewa->ReadInt16(); // unknown
518 EG1Sustain = _3ewa->ReadUint16();
519 EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
520 EG1Controller = static_cast<eg1_ctrl_t>(_3ewa->ReadUint8());
521 uint8_t eg1ctrloptions = _3ewa->ReadUint8();
522 EG1ControllerInvert = eg1ctrloptions & 0x01;
523 EG1ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
524 EG1ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
525 EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
526 EG2Controller = static_cast<eg2_ctrl_t>(_3ewa->ReadUint8());
527 uint8_t eg2ctrloptions = _3ewa->ReadUint8();
528 EG2ControllerInvert = eg2ctrloptions & 0x01;
529 EG2ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
530 EG2ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
531 EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
532 LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
533 EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
534 EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
535 _3ewa->ReadInt16(); // unknown
536 EG2Sustain = _3ewa->ReadUint16();
537 EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
538 _3ewa->ReadInt16(); // unknown
539 LFO2ControlDepth = _3ewa->ReadUint16();
540 LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
541 _3ewa->ReadInt16(); // unknown
542 LFO2InternalDepth = _3ewa->ReadUint16();
543 int32_t eg1decay2 = _3ewa->ReadInt32();
544 EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
545 EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
546 _3ewa->ReadInt16(); // unknown
547 EG1PreAttack = _3ewa->ReadUint16();
548 int32_t eg2decay2 = _3ewa->ReadInt32();
549 EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
550 EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
551 _3ewa->ReadInt16(); // unknown
552 EG2PreAttack = _3ewa->ReadUint16();
553 uint8_t velocityresponse = _3ewa->ReadUint8();
554 if (velocityresponse < 5) {
555 VelocityResponseCurve = curve_type_nonlinear;
556 VelocityResponseDepth = velocityresponse;
557 }
558 else if (velocityresponse < 10) {
559 VelocityResponseCurve = curve_type_linear;
560 VelocityResponseDepth = velocityresponse - 5;
561 }
562 else if (velocityresponse < 15) {
563 VelocityResponseCurve = curve_type_special;
564 VelocityResponseDepth = velocityresponse - 10;
565 }
566 else {
567 VelocityResponseCurve = curve_type_unknown;
568 VelocityResponseDepth = 0;
569 }
570 uint8_t releasevelocityresponse = _3ewa->ReadUint8();
571 if (releasevelocityresponse < 5) {
572 ReleaseVelocityResponseCurve = curve_type_nonlinear;
573 ReleaseVelocityResponseDepth = releasevelocityresponse;
574 }
575 else if (releasevelocityresponse < 10) {
576 ReleaseVelocityResponseCurve = curve_type_linear;
577 ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
578 }
579 else if (releasevelocityresponse < 15) {
580 ReleaseVelocityResponseCurve = curve_type_special;
581 ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
582 }
583 else {
584 ReleaseVelocityResponseCurve = curve_type_unknown;
585 ReleaseVelocityResponseDepth = 0;
586 }
587 VelocityResponseCurveScaling = _3ewa->ReadUint8();
588 AttenuationControlTreshold = _3ewa->ReadInt8();
589 _3ewa->ReadInt32(); // unknown
590 SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
591 _3ewa->ReadInt16(); // unknown
592 uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
593 PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
594 if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
595 else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
596 else DimensionBypass = dim_bypass_ctrl_none;
597 uint8_t pan = _3ewa->ReadUint8();
598 Pan = (pan < 64) ? pan : (-1) * (int8_t)pan - 63;
599 SelfMask = _3ewa->ReadInt8() & 0x01;
600 _3ewa->ReadInt8(); // unknown
601 uint8_t lfo3ctrl = _3ewa->ReadUint8();
602 LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
603 LFO3Sync = lfo3ctrl & 0x20; // bit 5
604 InvertAttenuationControl = lfo3ctrl & 0x80; // bit 7
605 if (VCFType == vcf_type_lowpass) {
606 if (lfo3ctrl & 0x40) // bit 6
607 VCFType = vcf_type_lowpassturbo;
608 }
609 AttenuationControl = static_cast<attenuation_ctrl_t>(_3ewa->ReadUint8());
610 uint8_t lfo2ctrl = _3ewa->ReadUint8();
611 LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
612 LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
613 LFO2Sync = lfo2ctrl & 0x20; // bit 5
614 bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
615 uint8_t lfo1ctrl = _3ewa->ReadUint8();
616 LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
617 LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
618 LFO1Sync = lfo1ctrl & 0x40; // bit 6
619 VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
620 : vcf_res_ctrl_none;
621 uint16_t eg3depth = _3ewa->ReadUint16();
622 EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
623 : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
624 _3ewa->ReadInt16(); // unknown
625 ChannelOffset = _3ewa->ReadUint8() / 4;
626 uint8_t regoptions = _3ewa->ReadUint8();
627 MSDecode = regoptions & 0x01; // bit 0
628 SustainDefeat = regoptions & 0x02; // bit 1
629 _3ewa->ReadInt16(); // unknown
630 VelocityUpperLimit = _3ewa->ReadInt8();
631 _3ewa->ReadInt8(); // unknown
632 _3ewa->ReadInt16(); // unknown
633 ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
634 _3ewa->ReadInt8(); // unknown
635 _3ewa->ReadInt8(); // unknown
636 EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
637 uint8_t vcfcutoff = _3ewa->ReadUint8();
638 VCFEnabled = vcfcutoff & 0x80; // bit 7
639 VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
640 VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
641 VCFVelocityScale = _3ewa->ReadUint8();
642 _3ewa->ReadInt8(); // unknown
643 uint8_t vcfresonance = _3ewa->ReadUint8();
644 VCFResonance = vcfresonance & 0x7f; // lower 7 bits
645 VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
646 uint8_t vcfbreakpoint = _3ewa->ReadUint8();
647 VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
648 VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
649 uint8_t vcfvelocity = _3ewa->ReadUint8();
650 VCFVelocityDynamicRange = vcfvelocity % 5;
651 VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
652 VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
653
654 // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet
655 uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;
656 if (pVelocityTables->count(tableKey)) { // if key exists
657 pVelocityAttenuationTable = (*pVelocityTables)[tableKey];
658 }
659 else {
660 pVelocityAttenuationTable = new double[128];
661 switch (VelocityResponseCurve) { // calculate the new table
662 case curve_type_nonlinear:
663 for (int velocity = 0; velocity < 128; velocity++) {
664 pVelocityAttenuationTable[velocity] =
665 GIG_VELOCITY_TRANSFORM_NONLINEAR((double)(velocity+1),(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);
666 if (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;
667 else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;
668 }
669 break;
670 case curve_type_linear:
671 for (int velocity = 0; velocity < 128; velocity++) {
672 pVelocityAttenuationTable[velocity] =
673 GIG_VELOCITY_TRANSFORM_LINEAR((double)velocity,(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);
674 if (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;
675 else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;
676 }
677 break;
678 case curve_type_special:
679 for (int velocity = 0; velocity < 128; velocity++) {
680 pVelocityAttenuationTable[velocity] =
681 GIG_VELOCITY_TRANSFORM_SPECIAL((double)(velocity+1),(double)(VelocityResponseDepth+1),(double)VelocityResponseCurveScaling);
682 if (pVelocityAttenuationTable[velocity] > 1.0) pVelocityAttenuationTable[velocity] = 1.0;
683 else if (pVelocityAttenuationTable[velocity] < 0.0) pVelocityAttenuationTable[velocity] = 0.0;
684 }
685 break;
686 case curve_type_unknown:
687 default:
688 throw gig::Exception("Unknown transform curve type.");
689 }
690 (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map
691 }
692 }
693
694 DimensionRegion::~DimensionRegion() {
695 Instances--;
696 if (!Instances) {
697 // delete the velocity->volume tables
698 VelocityTableMap::iterator iter;
699 for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
700 double* pTable = iter->second;
701 if (pTable) delete[] pTable;
702 }
703 pVelocityTables->clear();
704 delete pVelocityTables;
705 pVelocityTables = NULL;
706 }
707 }
708
709 /**
710 * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
711 * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
712 * and VelocityResponseCurveScaling) involved are taken into account to
713 * calculate the amplitude factor. Use this method when a key was
714 * triggered to get the volume with which the sample should be played
715 * back.
716 *
717 * @param MIDI velocity value of the triggered key (between 0 and 127)
718 * @returns amplitude factor (between 0.0 and 1.0)
719 */
720 double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
721 return pVelocityAttenuationTable[MIDIKeyVelocity];
722 }
723
724
725
726 // *************** Region ***************
727 // *
728
729 Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
730 // Initialization
731 Dimensions = 0;
732 for (int i = 0; i < 32; i++) {
733 pDimensionRegions[i] = NULL;
734 }
735
736 // Actual Loading
737
738 LoadDimensionRegions(rgnList);
739
740 RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
741 if (_3lnk) {
742 DimensionRegions = _3lnk->ReadUint32();
743 for (int i = 0; i < 5; i++) {
744 dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
745 uint8_t bits = _3lnk->ReadUint8();
746 if (dimension == dimension_none) { // inactive dimension
747 pDimensionDefinitions[i].dimension = dimension_none;
748 pDimensionDefinitions[i].bits = 0;
749 pDimensionDefinitions[i].zones = 0;
750 pDimensionDefinitions[i].split_type = split_type_bit;
751 pDimensionDefinitions[i].ranges = NULL;
752 pDimensionDefinitions[i].zone_size = 0;
753 }
754 else { // active dimension
755 pDimensionDefinitions[i].dimension = dimension;
756 pDimensionDefinitions[i].bits = bits;
757 pDimensionDefinitions[i].zones = 0x01 << bits; // = pow(2,bits)
758 pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
759 dimension == dimension_samplechannel) ? split_type_bit
760 : split_type_normal;
761 pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point
762 pDimensionDefinitions[i].zone_size =
763 (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones
764 : 0;
765 Dimensions++;
766 }
767 _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition
768 }
769
770 // check velocity dimension (if there is one) for custom defined zone ranges
771 for (uint i = 0; i < Dimensions; i++) {
772 dimension_def_t* pDimDef = pDimensionDefinitions + i;
773 if (pDimDef->dimension == dimension_velocity) {
774 if (pDimensionRegions[0]->VelocityUpperLimit == 0) {
775 // no custom defined ranges
776 pDimDef->split_type = split_type_normal;
777 pDimDef->ranges = NULL;
778 }
779 else { // custom defined ranges
780 pDimDef->split_type = split_type_customvelocity;
781 pDimDef->ranges = new range_t[pDimDef->zones];
782 unsigned int bits[5] = {0,0,0,0,0};
783 int previousUpperLimit = -1;
784 for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {
785 bits[i] = velocityZone;
786 DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);
787
788 pDimDef->ranges[velocityZone].low = previousUpperLimit + 1;
789 pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;
790 previousUpperLimit = pDimDef->ranges[velocityZone].high;
791 // fill velocity table
792 for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {
793 VelocityTable[i] = velocityZone;
794 }
795 }
796 }
797 }
798 }
799
800 // load sample references
801 _3lnk->SetPos(44); // jump to start of the wave pool indices (if not already there)
802 for (uint i = 0; i < DimensionRegions; i++) {
803 uint32_t wavepoolindex = _3lnk->ReadUint32();
804 pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
805 }
806 }
807 else throw gig::Exception("Mandatory <3lnk> chunk not found.");
808 }
809
810 void Region::LoadDimensionRegions(RIFF::List* rgn) {
811 RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
812 if (_3prg) {
813 int dimensionRegionNr = 0;
814 RIFF::List* _3ewl = _3prg->GetFirstSubList();
815 while (_3ewl) {
816 if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
817 pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);
818 dimensionRegionNr++;
819 }
820 _3ewl = _3prg->GetNextSubList();
821 }
822 if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
823 }
824 }
825
826 Region::~Region() {
827 for (uint i = 0; i < Dimensions; i++) {
828 if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;
829 }
830 for (int i = 0; i < 32; i++) {
831 if (pDimensionRegions[i]) delete pDimensionRegions[i];
832 }
833 }
834
835 /**
836 * Use this method in your audio engine to get the appropriate dimension
837 * region with it's articulation data for the current situation. Just
838 * call the method with the current MIDI controller values and you'll get
839 * the DimensionRegion with the appropriate articulation data for the
840 * current situation (for this Region of course only). To do that you'll
841 * first have to look which dimensions with which controllers and in
842 * which order are defined for this Region when you load the .gig file.
843 * Special cases are e.g. layer or channel dimensions where you just put
844 * in the index numbers instead of a MIDI controller value (means 0 for
845 * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
846 * etc.).
847 *
848 * @param Dim4Val MIDI controller value (0-127) for dimension 4
849 * @param Dim3Val MIDI controller value (0-127) for dimension 3
850 * @param Dim2Val MIDI controller value (0-127) for dimension 2
851 * @param Dim1Val MIDI controller value (0-127) for dimension 1
852 * @param Dim0Val MIDI controller value (0-127) for dimension 0
853 * @returns adress to the DimensionRegion for the given situation
854 * @see pDimensionDefinitions
855 * @see Dimensions
856 */
857 DimensionRegion* Region::GetDimensionRegionByValue(uint Dim4Val, uint Dim3Val, uint Dim2Val, uint Dim1Val, uint Dim0Val) {
858 unsigned int bits[5] = {Dim0Val,Dim1Val,Dim2Val,Dim3Val,Dim4Val};
859 for (uint i = 0; i < Dimensions; i++) {
860 switch (pDimensionDefinitions[i].split_type) {
861 case split_type_normal:
862 bits[i] /= pDimensionDefinitions[i].zone_size;
863 break;
864 case split_type_customvelocity:
865 bits[i] = VelocityTable[bits[i]];
866 break;
867 // else the value is already the sought dimension bit number
868 }
869 }
870 return GetDimensionRegionByBit(bits[4],bits[3],bits[2],bits[1],bits[0]);
871 }
872
873 /**
874 * Returns the appropriate DimensionRegion for the given dimension bit
875 * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
876 * instead of calling this method directly!
877 *
878 * @param Dim4Bit Bit number for dimension 4
879 * @param Dim3Bit Bit number for dimension 3
880 * @param Dim2Bit Bit number for dimension 2
881 * @param Dim1Bit Bit number for dimension 1
882 * @param Dim0Bit Bit number for dimension 0
883 * @returns adress to the DimensionRegion for the given dimension
884 * bit numbers
885 * @see GetDimensionRegionByValue()
886 */
887 DimensionRegion* Region::GetDimensionRegionByBit(uint8_t Dim4Bit, uint8_t Dim3Bit, uint8_t Dim2Bit, uint8_t Dim1Bit, uint8_t Dim0Bit) {
888 return *(pDimensionRegions + ((((((((Dim4Bit << pDimensionDefinitions[3].bits) | Dim3Bit)
889 << pDimensionDefinitions[2].bits) | Dim2Bit)
890 << pDimensionDefinitions[1].bits) | Dim1Bit)
891 << pDimensionDefinitions[0].bits) | Dim0Bit) );
892 }
893
894 /**
895 * Returns pointer address to the Sample referenced with this region.
896 * This is the global Sample for the entire Region (not sure if this is
897 * actually used by the Gigasampler engine - I would only use the Sample
898 * referenced by the appropriate DimensionRegion instead of this sample).
899 *
900 * @returns address to Sample or NULL if there is no reference to a
901 * sample saved in the .gig file
902 */
903 Sample* Region::GetSample() {
904 if (pSample) return static_cast<gig::Sample*>(pSample);
905 else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
906 }
907
908 Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {
909 File* file = (File*) GetParent()->GetParent();
910 unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
911 Sample* sample = file->GetFirstSample();
912 while (sample) {
913 if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);
914 sample = file->GetNextSample();
915 }
916 return NULL;
917 }
918
919
920
921 // *************** Instrument ***************
922 // *
923
924 Instrument::Instrument(File* pFile, RIFF::List* insList) : DLS::Instrument((DLS::File*)pFile, insList) {
925 // Initialization
926 for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
927 RegionIndex = -1;
928
929 // Loading
930 RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
931 if (lart) {
932 RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
933 if (_3ewg) {
934 EffectSend = _3ewg->ReadUint16();
935 Attenuation = _3ewg->ReadInt32();
936 FineTune = _3ewg->ReadInt16();
937 PitchbendRange = _3ewg->ReadInt16();
938 uint8_t dimkeystart = _3ewg->ReadUint8();
939 PianoReleaseMode = dimkeystart & 0x01;
940 DimensionKeyRange.low = dimkeystart >> 1;
941 DimensionKeyRange.high = _3ewg->ReadUint8();
942 }
943 else throw gig::Exception("Mandatory <3ewg> chunk not found.");
944 }
945 else throw gig::Exception("Mandatory <lart> list chunk not found.");
946
947 RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
948 if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");
949 pRegions = new Region*[Regions];
950 RIFF::List* rgn = lrgn->GetFirstSubList();
951 unsigned int iRegion = 0;
952 while (rgn) {
953 if (rgn->GetListType() == LIST_TYPE_RGN) {
954 pRegions[iRegion] = new Region(this, rgn);
955 iRegion++;
956 }
957 rgn = lrgn->GetNextSubList();
958 }
959
960 // Creating Region Key Table for fast lookup
961 for (uint iReg = 0; iReg < Regions; iReg++) {
962 for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {
963 RegionKeyTable[iKey] = pRegions[iReg];
964 }
965 }
966 }
967
968 Instrument::~Instrument() {
969 for (uint i = 0; i < Regions; i++) {
970 if (pRegions) {
971 if (pRegions[i]) delete (pRegions[i]);
972 }
973 delete[] pRegions;
974 }
975 }
976
977 /**
978 * Returns the appropriate Region for a triggered note.
979 *
980 * @param Key MIDI Key number of triggered note / key (0 - 127)
981 * @returns pointer adress to the appropriate Region or NULL if there
982 * there is no Region defined for the given \a Key
983 */
984 Region* Instrument::GetRegion(unsigned int Key) {
985 if (!pRegions || Key > 127) return NULL;
986 return RegionKeyTable[Key];
987 /*for (int i = 0; i < Regions; i++) {
988 if (Key <= pRegions[i]->KeyRange.high &&
989 Key >= pRegions[i]->KeyRange.low) return pRegions[i];
990 }
991 return NULL;*/
992 }
993
994 /**
995 * Returns the first Region of the instrument. You have to call this
996 * method once before you use GetNextRegion().
997 *
998 * @returns pointer address to first region or NULL if there is none
999 * @see GetNextRegion()
1000 */
1001 Region* Instrument::GetFirstRegion() {
1002 if (!Regions) return NULL;
1003 RegionIndex = 1;
1004 return pRegions[0];
1005 }
1006
1007 /**
1008 * Returns the next Region of the instrument. You have to call
1009 * GetFirstRegion() once before you can use this method. By calling this
1010 * method multiple times it iterates through the available Regions.
1011 *
1012 * @returns pointer address to the next region or NULL if end reached
1013 * @see GetFirstRegion()
1014 */
1015 Region* Instrument::GetNextRegion() {
1016 if (RegionIndex < 0 || RegionIndex >= Regions) return NULL;
1017 return pRegions[RegionIndex++];
1018 }
1019
1020
1021
1022 // *************** File ***************
1023 // *
1024
1025 File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
1026 pSamples = NULL;
1027 pInstruments = NULL;
1028 }
1029
1030 Sample* File::GetFirstSample() {
1031 if (!pSamples) LoadSamples();
1032 if (!pSamples) return NULL;
1033 SamplesIterator = pSamples->begin();
1034 return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1035 }
1036
1037 Sample* File::GetNextSample() {
1038 if (!pSamples) return NULL;
1039 SamplesIterator++;
1040 return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
1041 }
1042
1043 void File::LoadSamples() {
1044 RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1045 if (wvpl) {
1046 unsigned long wvplFileOffset = wvpl->GetFilePos();
1047 RIFF::List* wave = wvpl->GetFirstSubList();
1048 while (wave) {
1049 if (wave->GetListType() == LIST_TYPE_WAVE) {
1050 if (!pSamples) pSamples = new SampleList;
1051 unsigned long waveFileOffset = wave->GetFilePos();
1052 pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1053 }
1054 wave = wvpl->GetNextSubList();
1055 }
1056 }
1057 else throw gig::Exception("Mandatory <wvpl> chunk not found.");
1058 }
1059
1060 Instrument* File::GetFirstInstrument() {
1061 if (!pInstruments) LoadInstruments();
1062 if (!pInstruments) return NULL;
1063 InstrumentsIterator = pInstruments->begin();
1064 return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1065 }
1066
1067 Instrument* File::GetNextInstrument() {
1068 if (!pInstruments) return NULL;
1069 InstrumentsIterator++;
1070 return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1071 }
1072
1073 void File::LoadInstruments() {
1074 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1075 if (lstInstruments) {
1076 RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
1077 while (lstInstr) {
1078 if (lstInstr->GetListType() == LIST_TYPE_INS) {
1079 if (!pInstruments) pInstruments = new InstrumentList;
1080 pInstruments->push_back(new Instrument(this, lstInstr));
1081 }
1082 lstInstr = lstInstruments->GetNextSubList();
1083 }
1084 }
1085 else throw gig::Exception("Mandatory <lins> list chunk not found.");
1086 }
1087
1088
1089
1090 // *************** Exception ***************
1091 // *
1092
1093 Exception::Exception(String Message) : DLS::Exception(Message) {
1094 }
1095
1096 void Exception::PrintMessage() {
1097 std::cout << "gig::Exception: " << Message << std::endl;
1098 }
1099
1100 } // namespace gig

  ViewVC Help
Powered by ViewVC