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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 823 - (hide annotations) (download)
Fri Dec 23 01:38:50 2005 UTC (18 years, 3 months ago) by schoenebeck
File size: 133195 byte(s)
* recommited bugfixes regarding .gig write support
(that commit batch got lost due to the recent CVS server defect)

1 schoenebeck 2 /***************************************************************************
2     * *
3     * libgig - C++ cross-platform Gigasampler format file loader library *
4     * *
5 schoenebeck 384 * Copyright (C) 2003-2005 by Christian Schoenebeck *
6     * <cuse@users.sourceforge.net> *
7 schoenebeck 2 * *
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 schoenebeck 809 #include "helper.h"
27    
28     #include <math.h>
29 schoenebeck 384 #include <iostream>
30    
31 schoenebeck 809 /// Initial size of the sample buffer which is used for decompression of
32     /// compressed sample wave streams - this value should always be bigger than
33     /// the biggest sample piece expected to be read by the sampler engine,
34     /// otherwise the buffer size will be raised at runtime and thus the buffer
35     /// reallocated which is time consuming and unefficient.
36     #define INITIAL_SAMPLE_BUFFER_SIZE 512000 // 512 kB
37    
38     /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
39     #define GIG_EXP_DECODE(x) (pow(1.000000008813822, x))
40     #define GIG_EXP_ENCODE(x) (log(x) / log(1.000000008813822))
41     #define GIG_PITCH_TRACK_EXTRACT(x) (!(x & 0x01))
42     #define GIG_PITCH_TRACK_ENCODE(x) ((x) ? 0x00 : 0x01)
43     #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x) ((x >> 4) & 0x03)
44     #define GIG_VCF_RESONANCE_CTRL_ENCODE(x) ((x & 0x03) << 4)
45     #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x) ((x >> 1) & 0x03)
46     #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x) ((x >> 3) & 0x03)
47     #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
48     #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x) ((x & 0x03) << 1)
49     #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x) ((x & 0x03) << 3)
50     #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x) ((x & 0x03) << 5)
51    
52 schoenebeck 515 namespace gig {
53 schoenebeck 2
54 schoenebeck 809 // *************** dimension_def_t ***************
55     // *
56    
57     dimension_def_t& dimension_def_t::operator=(const dimension_def_t& arg) {
58     dimension = arg.dimension;
59     bits = arg.bits;
60     zones = arg.zones;
61     split_type = arg.split_type;
62     ranges = arg.ranges;
63     zone_size = arg.zone_size;
64     if (ranges) {
65     ranges = new range_t[zones];
66     for (int i = 0; i < zones; i++)
67     ranges[i] = arg.ranges[i];
68     }
69     return *this;
70     }
71    
72    
73    
74 schoenebeck 515 // *************** progress_t ***************
75     // *
76    
77     progress_t::progress_t() {
78     callback = NULL;
79 schoenebeck 516 custom = NULL;
80 schoenebeck 515 __range_min = 0.0f;
81     __range_max = 1.0f;
82     }
83    
84     // private helper function to convert progress of a subprocess into the global progress
85     static void __notify_progress(progress_t* pProgress, float subprogress) {
86     if (pProgress && pProgress->callback) {
87     const float totalrange = pProgress->__range_max - pProgress->__range_min;
88     const float totalprogress = pProgress->__range_min + subprogress * totalrange;
89 schoenebeck 516 pProgress->factor = totalprogress;
90     pProgress->callback(pProgress); // now actually notify about the progress
91 schoenebeck 515 }
92     }
93    
94     // private helper function to divide a progress into subprogresses
95     static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
96     if (pParentProgress && pParentProgress->callback) {
97     const float totalrange = pParentProgress->__range_max - pParentProgress->__range_min;
98     pSubProgress->callback = pParentProgress->callback;
99 schoenebeck 516 pSubProgress->custom = pParentProgress->custom;
100 schoenebeck 515 pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
101     pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
102     }
103     }
104    
105    
106 schoenebeck 809 // *************** Internal functions for sample decompression ***************
107 persson 365 // *
108    
109 schoenebeck 515 namespace {
110    
111 persson 365 inline int get12lo(const unsigned char* pSrc)
112     {
113     const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
114     return x & 0x800 ? x - 0x1000 : x;
115     }
116    
117     inline int get12hi(const unsigned char* pSrc)
118     {
119     const int x = pSrc[1] >> 4 | pSrc[2] << 4;
120     return x & 0x800 ? x - 0x1000 : x;
121     }
122    
123     inline int16_t get16(const unsigned char* pSrc)
124     {
125     return int16_t(pSrc[0] | pSrc[1] << 8);
126     }
127    
128     inline int get24(const unsigned char* pSrc)
129     {
130     const int x = pSrc[0] | pSrc[1] << 8 | pSrc[2] << 16;
131     return x & 0x800000 ? x - 0x1000000 : x;
132     }
133    
134     void Decompress16(int compressionmode, const unsigned char* params,
135 persson 372 int srcStep, int dstStep,
136     const unsigned char* pSrc, int16_t* pDst,
137 persson 365 unsigned long currentframeoffset,
138     unsigned long copysamples)
139     {
140     switch (compressionmode) {
141     case 0: // 16 bit uncompressed
142     pSrc += currentframeoffset * srcStep;
143     while (copysamples) {
144     *pDst = get16(pSrc);
145 persson 372 pDst += dstStep;
146 persson 365 pSrc += srcStep;
147     copysamples--;
148     }
149     break;
150    
151     case 1: // 16 bit compressed to 8 bit
152     int y = get16(params);
153     int dy = get16(params + 2);
154     while (currentframeoffset) {
155     dy -= int8_t(*pSrc);
156     y -= dy;
157     pSrc += srcStep;
158     currentframeoffset--;
159     }
160     while (copysamples) {
161     dy -= int8_t(*pSrc);
162     y -= dy;
163     *pDst = y;
164 persson 372 pDst += dstStep;
165 persson 365 pSrc += srcStep;
166     copysamples--;
167     }
168     break;
169     }
170     }
171    
172     void Decompress24(int compressionmode, const unsigned char* params,
173 persson 372 int dstStep, const unsigned char* pSrc, int16_t* pDst,
174 persson 365 unsigned long currentframeoffset,
175 persson 437 unsigned long copysamples, int truncatedBits)
176 persson 365 {
177     // Note: The 24 bits are truncated to 16 bits for now.
178    
179 persson 695 int y, dy, ddy, dddy;
180 persson 437 const int shift = 8 - truncatedBits;
181    
182 persson 695 #define GET_PARAMS(params) \
183     y = get24(params); \
184     dy = y - get24((params) + 3); \
185     ddy = get24((params) + 6); \
186     dddy = get24((params) + 9)
187 persson 365
188     #define SKIP_ONE(x) \
189 persson 695 dddy -= (x); \
190     ddy -= dddy; \
191     dy = -dy - ddy; \
192     y += dy
193 persson 365
194     #define COPY_ONE(x) \
195     SKIP_ONE(x); \
196 persson 695 *pDst = y >> shift; \
197 persson 372 pDst += dstStep
198 persson 365
199     switch (compressionmode) {
200     case 2: // 24 bit uncompressed
201     pSrc += currentframeoffset * 3;
202     while (copysamples) {
203 persson 437 *pDst = get24(pSrc) >> shift;
204 persson 372 pDst += dstStep;
205 persson 365 pSrc += 3;
206     copysamples--;
207     }
208     break;
209    
210     case 3: // 24 bit compressed to 16 bit
211     GET_PARAMS(params);
212     while (currentframeoffset) {
213     SKIP_ONE(get16(pSrc));
214     pSrc += 2;
215     currentframeoffset--;
216     }
217     while (copysamples) {
218     COPY_ONE(get16(pSrc));
219     pSrc += 2;
220     copysamples--;
221     }
222     break;
223    
224     case 4: // 24 bit compressed to 12 bit
225     GET_PARAMS(params);
226     while (currentframeoffset > 1) {
227     SKIP_ONE(get12lo(pSrc));
228     SKIP_ONE(get12hi(pSrc));
229     pSrc += 3;
230     currentframeoffset -= 2;
231     }
232     if (currentframeoffset) {
233     SKIP_ONE(get12lo(pSrc));
234     currentframeoffset--;
235     if (copysamples) {
236     COPY_ONE(get12hi(pSrc));
237     pSrc += 3;
238     copysamples--;
239     }
240     }
241     while (copysamples > 1) {
242     COPY_ONE(get12lo(pSrc));
243     COPY_ONE(get12hi(pSrc));
244     pSrc += 3;
245     copysamples -= 2;
246     }
247     if (copysamples) {
248     COPY_ONE(get12lo(pSrc));
249     }
250     break;
251    
252     case 5: // 24 bit compressed to 8 bit
253     GET_PARAMS(params);
254     while (currentframeoffset) {
255     SKIP_ONE(int8_t(*pSrc++));
256     currentframeoffset--;
257     }
258     while (copysamples) {
259     COPY_ONE(int8_t(*pSrc++));
260     copysamples--;
261     }
262     break;
263     }
264     }
265    
266     const int bytesPerFrame[] = { 4096, 2052, 768, 524, 396, 268 };
267     const int bytesPerFrameNoHdr[] = { 4096, 2048, 768, 512, 384, 256 };
268     const int headerSize[] = { 0, 4, 0, 12, 12, 12 };
269     const int bitsPerSample[] = { 16, 8, 24, 16, 12, 8 };
270     }
271    
272    
273 schoenebeck 2 // *************** Sample ***************
274     // *
275    
276 schoenebeck 384 unsigned int Sample::Instances = 0;
277     buffer_t Sample::InternalDecompressionBuffer;
278 schoenebeck 2
279 schoenebeck 809 /** @brief Constructor.
280     *
281     * Load an existing sample or create a new one. A 'wave' list chunk must
282     * be given to this constructor. In case the given 'wave' list chunk
283     * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
284     * format and sample data will be loaded from there, otherwise default
285     * values will be used and those chunks will be created when
286     * File::Save() will be called later on.
287     *
288     * @param pFile - pointer to gig::File where this sample is
289     * located (or will be located)
290     * @param waveList - pointer to 'wave' list chunk which is (or
291     * will be) associated with this sample
292     * @param WavePoolOffset - offset of this sample data from wave pool
293     * ('wvpl') list chunk
294     * @param fileNo - number of an extension file where this sample
295     * is located, 0 otherwise
296     */
297 persson 666 Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
298 schoenebeck 2 Instances++;
299 persson 666 FileNo = fileNo;
300 schoenebeck 2
301 schoenebeck 809 pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
302     if (pCk3gix) {
303     SampleGroup = pCk3gix->ReadInt16();
304     } else { // '3gix' chunk missing
305     // use default value(s)
306     SampleGroup = 0;
307     }
308 schoenebeck 2
309 schoenebeck 809 pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
310     if (pCkSmpl) {
311     Manufacturer = pCkSmpl->ReadInt32();
312     Product = pCkSmpl->ReadInt32();
313     SamplePeriod = pCkSmpl->ReadInt32();
314     MIDIUnityNote = pCkSmpl->ReadInt32();
315     FineTune = pCkSmpl->ReadInt32();
316     pCkSmpl->Read(&SMPTEFormat, 1, 4);
317     SMPTEOffset = pCkSmpl->ReadInt32();
318     Loops = pCkSmpl->ReadInt32();
319     pCkSmpl->ReadInt32(); // manufByt
320     LoopID = pCkSmpl->ReadInt32();
321     pCkSmpl->Read(&LoopType, 1, 4);
322     LoopStart = pCkSmpl->ReadInt32();
323     LoopEnd = pCkSmpl->ReadInt32();
324     LoopFraction = pCkSmpl->ReadInt32();
325     LoopPlayCount = pCkSmpl->ReadInt32();
326     } else { // 'smpl' chunk missing
327     // use default values
328     Manufacturer = 0;
329     Product = 0;
330     SamplePeriod = 1 / SamplesPerSecond;
331     MIDIUnityNote = 64;
332     FineTune = 0;
333     SMPTEOffset = 0;
334     Loops = 0;
335     LoopID = 0;
336     LoopStart = 0;
337     LoopEnd = 0;
338     LoopFraction = 0;
339     LoopPlayCount = 0;
340     }
341 schoenebeck 2
342     FrameTable = NULL;
343     SamplePos = 0;
344     RAMCache.Size = 0;
345     RAMCache.pStart = NULL;
346     RAMCache.NullExtensionSize = 0;
347    
348 persson 365 if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
349    
350 persson 437 RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
351     Compressed = ewav;
352     Dithered = false;
353     TruncatedBits = 0;
354 schoenebeck 2 if (Compressed) {
355 persson 437 uint32_t version = ewav->ReadInt32();
356     if (version == 3 && BitDepth == 24) {
357     Dithered = ewav->ReadInt32();
358     ewav->SetPos(Channels == 2 ? 84 : 64);
359     TruncatedBits = ewav->ReadInt32();
360     }
361 schoenebeck 2 ScanCompressedSample();
362     }
363 schoenebeck 317
364     // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
365 schoenebeck 384 if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
366     InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
367     InternalDecompressionBuffer.Size = INITIAL_SAMPLE_BUFFER_SIZE;
368 schoenebeck 317 }
369 persson 437 FrameOffset = 0; // just for streaming compressed samples
370 schoenebeck 21
371 schoenebeck 27 LoopSize = LoopEnd - LoopStart;
372 schoenebeck 2 }
373    
374 schoenebeck 809 /**
375     * Apply sample and its settings to the respective RIFF chunks. You have
376     * to call File::Save() to make changes persistent.
377     *
378     * Usually there is absolutely no need to call this method explicitly.
379     * It will be called automatically when File::Save() was called.
380     *
381     * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data
382     * was provided yet
383     * @throws gig::Exception if there is any invalid sample setting
384     */
385     void Sample::UpdateChunks() {
386     // first update base class's chunks
387     DLS::Sample::UpdateChunks();
388    
389     // make sure 'smpl' chunk exists
390     pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
391     if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
392     // update 'smpl' chunk
393     uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
394     SamplePeriod = 1 / SamplesPerSecond;
395     memcpy(&pData[0], &Manufacturer, 4);
396     memcpy(&pData[4], &Product, 4);
397     memcpy(&pData[8], &SamplePeriod, 4);
398     memcpy(&pData[12], &MIDIUnityNote, 4);
399     memcpy(&pData[16], &FineTune, 4);
400     memcpy(&pData[20], &SMPTEFormat, 4);
401     memcpy(&pData[24], &SMPTEOffset, 4);
402     memcpy(&pData[28], &Loops, 4);
403    
404     // we skip 'manufByt' for now (4 bytes)
405    
406     memcpy(&pData[36], &LoopID, 4);
407     memcpy(&pData[40], &LoopType, 4);
408     memcpy(&pData[44], &LoopStart, 4);
409     memcpy(&pData[48], &LoopEnd, 4);
410     memcpy(&pData[52], &LoopFraction, 4);
411     memcpy(&pData[56], &LoopPlayCount, 4);
412    
413     // make sure '3gix' chunk exists
414     pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
415     if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
416     // update '3gix' chunk
417     pData = (uint8_t*) pCk3gix->LoadChunkData();
418     memcpy(&pData[0], &SampleGroup, 2);
419     }
420    
421 schoenebeck 2 /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
422     void Sample::ScanCompressedSample() {
423     //TODO: we have to add some more scans here (e.g. determine compression rate)
424     this->SamplesTotal = 0;
425     std::list<unsigned long> frameOffsets;
426    
427 persson 365 SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
428 schoenebeck 384 WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
429 persson 365
430 schoenebeck 2 // Scanning
431     pCkData->SetPos(0);
432 persson 365 if (Channels == 2) { // Stereo
433     for (int i = 0 ; ; i++) {
434     // for 24 bit samples every 8:th frame offset is
435     // stored, to save some memory
436     if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
437    
438     const int mode_l = pCkData->ReadUint8();
439     const int mode_r = pCkData->ReadUint8();
440     if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
441     const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
442    
443     if (pCkData->RemainingBytes() <= frameSize) {
444     SamplesInLastFrame =
445     ((pCkData->RemainingBytes() - headerSize[mode_l] - headerSize[mode_r]) << 3) /
446     (bitsPerSample[mode_l] + bitsPerSample[mode_r]);
447     SamplesTotal += SamplesInLastFrame;
448 schoenebeck 2 break;
449 persson 365 }
450     SamplesTotal += SamplesPerFrame;
451     pCkData->SetPos(frameSize, RIFF::stream_curpos);
452     }
453     }
454     else { // Mono
455     for (int i = 0 ; ; i++) {
456     if (BitDepth != 24 || (i & 7) == 0) frameOffsets.push_back(pCkData->GetPos());
457    
458     const int mode = pCkData->ReadUint8();
459     if (mode > 5) throw gig::Exception("Unknown compression mode");
460     const unsigned long frameSize = bytesPerFrame[mode];
461    
462     if (pCkData->RemainingBytes() <= frameSize) {
463     SamplesInLastFrame =
464     ((pCkData->RemainingBytes() - headerSize[mode]) << 3) / bitsPerSample[mode];
465     SamplesTotal += SamplesInLastFrame;
466 schoenebeck 2 break;
467 persson 365 }
468     SamplesTotal += SamplesPerFrame;
469     pCkData->SetPos(frameSize, RIFF::stream_curpos);
470 schoenebeck 2 }
471     }
472     pCkData->SetPos(0);
473    
474     // Build the frames table (which is used for fast resolving of a frame's chunk offset)
475     if (FrameTable) delete[] FrameTable;
476     FrameTable = new unsigned long[frameOffsets.size()];
477     std::list<unsigned long>::iterator end = frameOffsets.end();
478     std::list<unsigned long>::iterator iter = frameOffsets.begin();
479     for (int i = 0; iter != end; i++, iter++) {
480     FrameTable[i] = *iter;
481     }
482     }
483    
484     /**
485     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
486     * ReleaseSampleData() to free the memory if you don't need the cached
487     * sample data anymore.
488     *
489     * @returns buffer_t structure with start address and size of the buffer
490     * in bytes
491     * @see ReleaseSampleData(), Read(), SetPos()
492     */
493     buffer_t Sample::LoadSampleData() {
494     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, 0); // 0 amount of NullSamples
495     }
496    
497     /**
498     * Reads (uncompresses if needed) and caches the first \a SampleCount
499     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
500     * memory space if you don't need the cached samples anymore. There is no
501     * guarantee that exactly \a SampleCount samples will be cached; this is
502     * not an error. The size will be eventually truncated e.g. to the
503     * beginning of a frame of a compressed sample. This is done for
504     * efficiency reasons while streaming the wave by your sampler engine
505     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
506     * that will be returned to determine the actual cached samples, but note
507     * that the size is given in bytes! You get the number of actually cached
508     * samples by dividing it by the frame size of the sample:
509 schoenebeck 384 * @code
510 schoenebeck 2 * buffer_t buf = pSample->LoadSampleData(acquired_samples);
511     * long cachedsamples = buf.Size / pSample->FrameSize;
512 schoenebeck 384 * @endcode
513 schoenebeck 2 *
514     * @param SampleCount - number of sample points to load into RAM
515     * @returns buffer_t structure with start address and size of
516     * the cached sample data in bytes
517     * @see ReleaseSampleData(), Read(), SetPos()
518     */
519     buffer_t Sample::LoadSampleData(unsigned long SampleCount) {
520     return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
521     }
522    
523     /**
524     * Loads (and uncompresses if needed) the whole sample wave into RAM. Use
525     * ReleaseSampleData() to free the memory if you don't need the cached
526     * sample data anymore.
527     * The method will add \a NullSamplesCount silence samples past the
528     * official buffer end (this won't affect the 'Size' member of the
529     * buffer_t structure, that means 'Size' always reflects the size of the
530     * actual sample data, the buffer might be bigger though). Silence
531     * samples past the official buffer are needed for differential
532     * algorithms that always have to take subsequent samples into account
533     * (resampling/interpolation would be an important example) and avoids
534     * memory access faults in such cases.
535     *
536     * @param NullSamplesCount - number of silence samples the buffer should
537     * be extended past it's data end
538     * @returns buffer_t structure with start address and
539     * size of the buffer in bytes
540     * @see ReleaseSampleData(), Read(), SetPos()
541     */
542     buffer_t Sample::LoadSampleDataWithNullSamplesExtension(uint NullSamplesCount) {
543     return LoadSampleDataWithNullSamplesExtension(this->SamplesTotal, NullSamplesCount);
544     }
545    
546     /**
547     * Reads (uncompresses if needed) and caches the first \a SampleCount
548     * numbers of SamplePoints in RAM. Use ReleaseSampleData() to free the
549     * memory space if you don't need the cached samples anymore. There is no
550     * guarantee that exactly \a SampleCount samples will be cached; this is
551     * not an error. The size will be eventually truncated e.g. to the
552     * beginning of a frame of a compressed sample. This is done for
553     * efficiency reasons while streaming the wave by your sampler engine
554     * later. Read the <i>Size</i> member of the <i>buffer_t</i> structure
555     * that will be returned to determine the actual cached samples, but note
556     * that the size is given in bytes! You get the number of actually cached
557     * samples by dividing it by the frame size of the sample:
558 schoenebeck 384 * @code
559 schoenebeck 2 * buffer_t buf = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
560     * long cachedsamples = buf.Size / pSample->FrameSize;
561 schoenebeck 384 * @endcode
562 schoenebeck 2 * The method will add \a NullSamplesCount silence samples past the
563     * official buffer end (this won't affect the 'Size' member of the
564     * buffer_t structure, that means 'Size' always reflects the size of the
565     * actual sample data, the buffer might be bigger though). Silence
566     * samples past the official buffer are needed for differential
567     * algorithms that always have to take subsequent samples into account
568     * (resampling/interpolation would be an important example) and avoids
569     * memory access faults in such cases.
570     *
571     * @param SampleCount - number of sample points to load into RAM
572     * @param NullSamplesCount - number of silence samples the buffer should
573     * be extended past it's data end
574     * @returns buffer_t structure with start address and
575     * size of the cached sample data in bytes
576     * @see ReleaseSampleData(), Read(), SetPos()
577     */
578     buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {
579     if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
580     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
581     unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
582     RAMCache.pStart = new int8_t[allocationsize];
583     RAMCache.Size = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
584     RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
585     // fill the remaining buffer space with silence samples
586     memset((int8_t*)RAMCache.pStart + RAMCache.Size, 0, RAMCache.NullExtensionSize);
587     return GetCache();
588     }
589    
590     /**
591     * Returns current cached sample points. A buffer_t structure will be
592     * returned which contains address pointer to the begin of the cache and
593     * the size of the cached sample data in bytes. Use
594     * <i>LoadSampleData()</i> to cache a specific amount of sample points in
595     * RAM.
596     *
597     * @returns buffer_t structure with current cached sample points
598     * @see LoadSampleData();
599     */
600     buffer_t Sample::GetCache() {
601     // return a copy of the buffer_t structure
602     buffer_t result;
603     result.Size = this->RAMCache.Size;
604     result.pStart = this->RAMCache.pStart;
605     result.NullExtensionSize = this->RAMCache.NullExtensionSize;
606     return result;
607     }
608    
609     /**
610     * Frees the cached sample from RAM if loaded with
611     * <i>LoadSampleData()</i> previously.
612     *
613     * @see LoadSampleData();
614     */
615     void Sample::ReleaseSampleData() {
616     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
617     RAMCache.pStart = NULL;
618     RAMCache.Size = 0;
619     }
620    
621 schoenebeck 809 /** @brief Resize sample.
622     *
623     * Resizes the sample's wave form data, that is the actual size of
624     * sample wave data possible to be written for this sample. This call
625     * will return immediately and just schedule the resize operation. You
626     * should call File::Save() to actually perform the resize operation(s)
627     * "physically" to the file. As this can take a while on large files, it
628     * is recommended to call Resize() first on all samples which have to be
629     * resized and finally to call File::Save() to perform all those resize
630     * operations in one rush.
631     *
632     * The actual size (in bytes) is dependant to the current FrameSize
633     * value. You may want to set FrameSize before calling Resize().
634     *
635     * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
636     * enlarged samples before calling File::Save() as this might exceed the
637     * current sample's boundary!
638     *
639     * Also note: only WAVE_FORMAT_PCM is currently supported, that is
640     * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with
641     * other formats will fail!
642     *
643     * @param iNewSize - new sample wave data size in sample points (must be
644     * greater than zero)
645     * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM
646     * or if \a iNewSize is less than 1
647     * @throws gig::Exception if existing sample is compressed
648     * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
649     * DLS::Sample::FormatTag, File::Save()
650     */
651     void Sample::Resize(int iNewSize) {
652     if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
653     DLS::Sample::Resize(iNewSize);
654     }
655    
656 schoenebeck 2 /**
657     * Sets the position within the sample (in sample points, not in
658     * bytes). Use this method and <i>Read()</i> if you don't want to load
659     * the sample into RAM, thus for disk streaming.
660     *
661     * Although the original Gigasampler engine doesn't allow positioning
662     * within compressed samples, I decided to implement it. Even though
663     * the Gigasampler format doesn't allow to define loops for compressed
664     * samples at the moment, positioning within compressed samples might be
665     * interesting for some sampler engines though. The only drawback about
666     * my decision is that it takes longer to load compressed gig Files on
667     * startup, because it's neccessary to scan the samples for some
668     * mandatory informations. But I think as it doesn't affect the runtime
669     * efficiency, nobody will have a problem with that.
670     *
671     * @param SampleCount number of sample points to jump
672     * @param Whence optional: to which relation \a SampleCount refers
673     * to, if omited <i>RIFF::stream_start</i> is assumed
674     * @returns the new sample position
675     * @see Read()
676     */
677     unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {
678     if (Compressed) {
679     switch (Whence) {
680     case RIFF::stream_curpos:
681     this->SamplePos += SampleCount;
682     break;
683     case RIFF::stream_end:
684     this->SamplePos = this->SamplesTotal - 1 - SampleCount;
685     break;
686     case RIFF::stream_backward:
687     this->SamplePos -= SampleCount;
688     break;
689     case RIFF::stream_start: default:
690     this->SamplePos = SampleCount;
691     break;
692     }
693     if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
694    
695     unsigned long frame = this->SamplePos / 2048; // to which frame to jump
696     this->FrameOffset = this->SamplePos % 2048; // offset (in sample points) within that frame
697     pCkData->SetPos(FrameTable[frame]); // set chunk pointer to the start of sought frame
698     return this->SamplePos;
699     }
700     else { // not compressed
701     unsigned long orderedBytes = SampleCount * this->FrameSize;
702     unsigned long result = pCkData->SetPos(orderedBytes, Whence);
703     return (result == orderedBytes) ? SampleCount
704     : result / this->FrameSize;
705     }
706     }
707    
708     /**
709     * Returns the current position in the sample (in sample points).
710     */
711     unsigned long Sample::GetPos() {
712     if (Compressed) return SamplePos;
713     else return pCkData->GetPos() / FrameSize;
714     }
715    
716     /**
717 schoenebeck 24 * Reads \a SampleCount number of sample points from the position stored
718     * in \a pPlaybackState into the buffer pointed by \a pBuffer and moves
719     * the position within the sample respectively, this method honors the
720     * looping informations of the sample (if any). The sample wave stream
721     * will be decompressed on the fly if using a compressed sample. Use this
722     * method if you don't want to load the sample into RAM, thus for disk
723     * streaming. All this methods needs to know to proceed with streaming
724     * for the next time you call this method is stored in \a pPlaybackState.
725     * You have to allocate and initialize the playback_state_t structure by
726     * yourself before you use it to stream a sample:
727 schoenebeck 384 * @code
728     * gig::playback_state_t playbackstate;
729     * playbackstate.position = 0;
730     * playbackstate.reverse = false;
731     * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
732     * @endcode
733 schoenebeck 24 * You don't have to take care of things like if there is actually a loop
734     * defined or if the current read position is located within a loop area.
735     * The method already handles such cases by itself.
736     *
737 schoenebeck 384 * <b>Caution:</b> If you are using more than one streaming thread, you
738     * have to use an external decompression buffer for <b>EACH</b>
739     * streaming thread to avoid race conditions and crashes!
740     *
741 schoenebeck 24 * @param pBuffer destination buffer
742     * @param SampleCount number of sample points to read
743     * @param pPlaybackState will be used to store and reload the playback
744     * state for the next ReadAndLoop() call
745 schoenebeck 384 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
746 schoenebeck 24 * @returns number of successfully read sample points
747 schoenebeck 384 * @see CreateDecompressionBuffer()
748 schoenebeck 24 */
749 schoenebeck 384 unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, buffer_t* pExternalDecompressionBuffer) {
750 schoenebeck 24 unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
751     uint8_t* pDst = (uint8_t*) pBuffer;
752    
753     SetPos(pPlaybackState->position); // recover position from the last time
754    
755     if (this->Loops && GetPos() <= this->LoopEnd) { // honor looping if there are loop points defined
756    
757     switch (this->LoopType) {
758    
759     case loop_type_bidirectional: { //TODO: not tested yet!
760     do {
761     // if not endless loop check if max. number of loop cycles have been passed
762     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
763    
764     if (!pPlaybackState->reverse) { // forward playback
765     do {
766     samplestoloopend = this->LoopEnd - GetPos();
767 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
768 schoenebeck 24 samplestoread -= readsamples;
769     totalreadsamples += readsamples;
770     if (readsamples == samplestoloopend) {
771     pPlaybackState->reverse = true;
772     break;
773     }
774     } while (samplestoread && readsamples);
775     }
776     else { // backward playback
777    
778     // as we can only read forward from disk, we have to
779     // determine the end position within the loop first,
780     // read forward from that 'end' and finally after
781     // reading, swap all sample frames so it reflects
782     // backward playback
783    
784     unsigned long swapareastart = totalreadsamples;
785     unsigned long loopoffset = GetPos() - this->LoopStart;
786     unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
787     unsigned long reverseplaybackend = GetPos() - samplestoreadinloop;
788    
789     SetPos(reverseplaybackend);
790    
791     // read samples for backward playback
792     do {
793 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
794 schoenebeck 24 samplestoreadinloop -= readsamples;
795     samplestoread -= readsamples;
796     totalreadsamples += readsamples;
797     } while (samplestoreadinloop && readsamples);
798    
799     SetPos(reverseplaybackend); // pretend we really read backwards
800    
801     if (reverseplaybackend == this->LoopStart) {
802     pPlaybackState->loop_cycles_left--;
803     pPlaybackState->reverse = false;
804     }
805    
806     // reverse the sample frames for backward playback
807     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
808     }
809     } while (samplestoread && readsamples);
810     break;
811     }
812    
813     case loop_type_backward: { // TODO: not tested yet!
814     // forward playback (not entered the loop yet)
815     if (!pPlaybackState->reverse) do {
816     samplestoloopend = this->LoopEnd - GetPos();
817 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
818 schoenebeck 24 samplestoread -= readsamples;
819     totalreadsamples += readsamples;
820     if (readsamples == samplestoloopend) {
821     pPlaybackState->reverse = true;
822     break;
823     }
824     } while (samplestoread && readsamples);
825    
826     if (!samplestoread) break;
827    
828     // as we can only read forward from disk, we have to
829     // determine the end position within the loop first,
830     // read forward from that 'end' and finally after
831     // reading, swap all sample frames so it reflects
832     // backward playback
833    
834     unsigned long swapareastart = totalreadsamples;
835     unsigned long loopoffset = GetPos() - this->LoopStart;
836     unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset)
837     : samplestoread;
838     unsigned long reverseplaybackend = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);
839    
840     SetPos(reverseplaybackend);
841    
842     // read samples for backward playback
843     do {
844     // if not endless loop check if max. number of loop cycles have been passed
845     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
846     samplestoloopend = this->LoopEnd - GetPos();
847 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
848 schoenebeck 24 samplestoreadinloop -= readsamples;
849     samplestoread -= readsamples;
850     totalreadsamples += readsamples;
851     if (readsamples == samplestoloopend) {
852     pPlaybackState->loop_cycles_left--;
853     SetPos(this->LoopStart);
854     }
855     } while (samplestoreadinloop && readsamples);
856    
857     SetPos(reverseplaybackend); // pretend we really read backwards
858    
859     // reverse the sample frames for backward playback
860     SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
861     break;
862     }
863    
864     default: case loop_type_normal: {
865     do {
866     // if not endless loop check if max. number of loop cycles have been passed
867     if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
868     samplestoloopend = this->LoopEnd - GetPos();
869 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
870 schoenebeck 24 samplestoread -= readsamples;
871     totalreadsamples += readsamples;
872     if (readsamples == samplestoloopend) {
873     pPlaybackState->loop_cycles_left--;
874     SetPos(this->LoopStart);
875     }
876     } while (samplestoread && readsamples);
877     break;
878     }
879     }
880     }
881    
882     // read on without looping
883     if (samplestoread) do {
884 schoenebeck 384 readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
885 schoenebeck 24 samplestoread -= readsamples;
886     totalreadsamples += readsamples;
887     } while (readsamples && samplestoread);
888    
889     // store current position
890     pPlaybackState->position = GetPos();
891    
892     return totalreadsamples;
893     }
894    
895     /**
896 schoenebeck 2 * Reads \a SampleCount number of sample points from the current
897     * position into the buffer pointed by \a pBuffer and increments the
898     * position within the sample. The sample wave stream will be
899     * decompressed on the fly if using a compressed sample. Use this method
900     * and <i>SetPos()</i> if you don't want to load the sample into RAM,
901     * thus for disk streaming.
902     *
903 schoenebeck 384 * <b>Caution:</b> If you are using more than one streaming thread, you
904     * have to use an external decompression buffer for <b>EACH</b>
905     * streaming thread to avoid race conditions and crashes!
906     *
907 schoenebeck 2 * @param pBuffer destination buffer
908     * @param SampleCount number of sample points to read
909 schoenebeck 384 * @param pExternalDecompressionBuffer (optional) external buffer to use for decompression
910 schoenebeck 2 * @returns number of successfully read sample points
911 schoenebeck 384 * @see SetPos(), CreateDecompressionBuffer()
912 schoenebeck 2 */
913 schoenebeck 384 unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
914 schoenebeck 21 if (SampleCount == 0) return 0;
915 schoenebeck 317 if (!Compressed) {
916     if (BitDepth == 24) {
917     // 24 bit sample. For now just truncate to 16 bit.
918 schoenebeck 384 unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);
919 persson 365 int16_t* pDst = static_cast<int16_t*>(pBuffer);
920     if (Channels == 2) { // Stereo
921     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
922 schoenebeck 317 pSrc++;
923 persson 365 for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
924     *pDst++ = get16(pSrc);
925     pSrc += 3;
926     }
927     return (pDst - static_cast<int16_t*>(pBuffer)) >> 1;
928 schoenebeck 317 }
929 persson 365 else { // Mono
930     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1);
931     pSrc++;
932     for (unsigned long i = readBytes ; i > 0 ; i -= 3) {
933     *pDst++ = get16(pSrc);
934     pSrc += 3;
935     }
936     return pDst - static_cast<int16_t*>(pBuffer);
937     }
938 schoenebeck 317 }
939 persson 365 else { // 16 bit
940     // (pCkData->Read does endian correction)
941     return Channels == 2 ? pCkData->Read(pBuffer, SampleCount << 1, 2) >> 1
942     : pCkData->Read(pBuffer, SampleCount, 2);
943     }
944 schoenebeck 317 }
945 persson 365 else {
946 schoenebeck 11 if (this->SamplePos >= this->SamplesTotal) return 0;
947 persson 365 //TODO: efficiency: maybe we should test for an average compression rate
948     unsigned long assumedsize = GuessSize(SampleCount),
949 schoenebeck 2 remainingbytes = 0, // remaining bytes in the local buffer
950     remainingsamples = SampleCount,
951 persson 365 copysamples, skipsamples,
952     currentframeoffset = this->FrameOffset; // offset in current sample frame since last Read()
953 schoenebeck 2 this->FrameOffset = 0;
954    
955 schoenebeck 384 buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
956    
957     // if decompression buffer too small, then reduce amount of samples to read
958     if (pDecompressionBuffer->Size < assumedsize) {
959     std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
960     SampleCount = WorstCaseMaxSamples(pDecompressionBuffer);
961     remainingsamples = SampleCount;
962     assumedsize = GuessSize(SampleCount);
963 schoenebeck 2 }
964    
965 schoenebeck 384 unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
966 persson 365 int16_t* pDst = static_cast<int16_t*>(pBuffer);
967 schoenebeck 2 remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
968    
969 persson 365 while (remainingsamples && remainingbytes) {
970     unsigned long framesamples = SamplesPerFrame;
971     unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;
972 schoenebeck 2
973 persson 365 int mode_l = *pSrc++, mode_r = 0;
974    
975     if (Channels == 2) {
976     mode_r = *pSrc++;
977     framebytes = bytesPerFrame[mode_l] + bytesPerFrame[mode_r] + 2;
978     rightChannelOffset = bytesPerFrameNoHdr[mode_l];
979     nextFrameOffset = rightChannelOffset + bytesPerFrameNoHdr[mode_r];
980     if (remainingbytes < framebytes) { // last frame in sample
981     framesamples = SamplesInLastFrame;
982     if (mode_l == 4 && (framesamples & 1)) {
983     rightChannelOffset = ((framesamples + 1) * bitsPerSample[mode_l]) >> 3;
984     }
985     else {
986     rightChannelOffset = (framesamples * bitsPerSample[mode_l]) >> 3;
987     }
988 schoenebeck 2 }
989     }
990 persson 365 else {
991     framebytes = bytesPerFrame[mode_l] + 1;
992     nextFrameOffset = bytesPerFrameNoHdr[mode_l];
993     if (remainingbytes < framebytes) {
994     framesamples = SamplesInLastFrame;
995     }
996     }
997 schoenebeck 2
998     // determine how many samples in this frame to skip and read
999 persson 365 if (currentframeoffset + remainingsamples >= framesamples) {
1000     if (currentframeoffset <= framesamples) {
1001     copysamples = framesamples - currentframeoffset;
1002     skipsamples = currentframeoffset;
1003     }
1004     else {
1005     copysamples = 0;
1006     skipsamples = framesamples;
1007     }
1008 schoenebeck 2 }
1009     else {
1010 persson 365 // This frame has enough data for pBuffer, but not
1011     // all of the frame is needed. Set file position
1012     // to start of this frame for next call to Read.
1013 schoenebeck 2 copysamples = remainingsamples;
1014 persson 365 skipsamples = currentframeoffset;
1015     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1016     this->FrameOffset = currentframeoffset + copysamples;
1017     }
1018     remainingsamples -= copysamples;
1019    
1020     if (remainingbytes > framebytes) {
1021     remainingbytes -= framebytes;
1022     if (remainingsamples == 0 &&
1023     currentframeoffset + copysamples == framesamples) {
1024     // This frame has enough data for pBuffer, and
1025     // all of the frame is needed. Set file
1026     // position to start of next frame for next
1027     // call to Read. FrameOffset is 0.
1028 schoenebeck 2 pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1029     }
1030     }
1031 persson 365 else remainingbytes = 0;
1032 schoenebeck 2
1033 persson 365 currentframeoffset -= skipsamples;
1034 schoenebeck 2
1035 persson 365 if (copysamples == 0) {
1036     // skip this frame
1037     pSrc += framebytes - Channels;
1038     }
1039     else {
1040     const unsigned char* const param_l = pSrc;
1041     if (BitDepth == 24) {
1042     if (mode_l != 2) pSrc += 12;
1043 schoenebeck 2
1044 persson 365 if (Channels == 2) { // Stereo
1045     const unsigned char* const param_r = pSrc;
1046     if (mode_r != 2) pSrc += 12;
1047    
1048 persson 437 Decompress24(mode_l, param_l, 2, pSrc, pDst,
1049     skipsamples, copysamples, TruncatedBits);
1050 persson 372 Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
1051 persson 437 skipsamples, copysamples, TruncatedBits);
1052 persson 365 pDst += copysamples << 1;
1053 schoenebeck 2 }
1054 persson 365 else { // Mono
1055 persson 437 Decompress24(mode_l, param_l, 1, pSrc, pDst,
1056     skipsamples, copysamples, TruncatedBits);
1057 persson 365 pDst += copysamples;
1058 schoenebeck 2 }
1059 persson 365 }
1060     else { // 16 bit
1061     if (mode_l) pSrc += 4;
1062 schoenebeck 2
1063 persson 365 int step;
1064     if (Channels == 2) { // Stereo
1065     const unsigned char* const param_r = pSrc;
1066     if (mode_r) pSrc += 4;
1067    
1068     step = (2 - mode_l) + (2 - mode_r);
1069 persson 372 Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1070     Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1071 persson 365 skipsamples, copysamples);
1072     pDst += copysamples << 1;
1073 schoenebeck 2 }
1074 persson 365 else { // Mono
1075     step = 2 - mode_l;
1076 persson 372 Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1077 persson 365 pDst += copysamples;
1078 schoenebeck 2 }
1079 persson 365 }
1080     pSrc += nextFrameOffset;
1081     }
1082 schoenebeck 2
1083 persson 365 // reload from disk to local buffer if needed
1084     if (remainingsamples && remainingbytes < WorstCaseFrameSize && pCkData->GetState() == RIFF::stream_ready) {
1085     assumedsize = GuessSize(remainingsamples);
1086     pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1087     if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1088 schoenebeck 384 remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1089     pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1090 schoenebeck 2 }
1091 persson 365 } // while
1092    
1093 schoenebeck 2 this->SamplePos += (SampleCount - remainingsamples);
1094 schoenebeck 11 if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
1095 schoenebeck 2 return (SampleCount - remainingsamples);
1096     }
1097     }
1098    
1099 schoenebeck 809 /** @brief Write sample wave data.
1100     *
1101     * Writes \a SampleCount number of sample points from the buffer pointed
1102     * by \a pBuffer and increments the position within the sample. Use this
1103     * method to directly write the sample data to disk, i.e. if you don't
1104     * want or cannot load the whole sample data into RAM.
1105     *
1106     * You have to Resize() the sample to the desired size and call
1107     * File::Save() <b>before</b> using Write().
1108     *
1109     * Note: there is currently no support for writing compressed samples.
1110     *
1111     * @param pBuffer - source buffer
1112     * @param SampleCount - number of sample points to write
1113     * @throws DLS::Exception if current sample size is too small
1114     * @throws gig::Exception if sample is compressed
1115     * @see DLS::LoadSampleData()
1116     */
1117     unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1118     if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1119     return DLS::Sample::Write(pBuffer, SampleCount);
1120     }
1121    
1122 schoenebeck 384 /**
1123     * Allocates a decompression buffer for streaming (compressed) samples
1124     * with Sample::Read(). If you are using more than one streaming thread
1125     * in your application you <b>HAVE</b> to create a decompression buffer
1126     * for <b>EACH</b> of your streaming threads and provide it with the
1127     * Sample::Read() call in order to avoid race conditions and crashes.
1128     *
1129     * You should free the memory occupied by the allocated buffer(s) once
1130     * you don't need one of your streaming threads anymore by calling
1131     * DestroyDecompressionBuffer().
1132     *
1133     * @param MaxReadSize - the maximum size (in sample points) you ever
1134     * expect to read with one Read() call
1135     * @returns allocated decompression buffer
1136     * @see DestroyDecompressionBuffer()
1137     */
1138     buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1139     buffer_t result;
1140     const double worstCaseHeaderOverhead =
1141     (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1142     result.Size = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1143     result.pStart = new int8_t[result.Size];
1144     result.NullExtensionSize = 0;
1145     return result;
1146     }
1147    
1148     /**
1149     * Free decompression buffer, previously created with
1150     * CreateDecompressionBuffer().
1151     *
1152     * @param DecompressionBuffer - previously allocated decompression
1153     * buffer to free
1154     */
1155     void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1156     if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1157     delete[] (int8_t*) DecompressionBuffer.pStart;
1158     DecompressionBuffer.pStart = NULL;
1159     DecompressionBuffer.Size = 0;
1160     DecompressionBuffer.NullExtensionSize = 0;
1161     }
1162     }
1163    
1164 schoenebeck 2 Sample::~Sample() {
1165     Instances--;
1166 schoenebeck 384 if (!Instances && InternalDecompressionBuffer.Size) {
1167     delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1168     InternalDecompressionBuffer.pStart = NULL;
1169     InternalDecompressionBuffer.Size = 0;
1170 schoenebeck 355 }
1171 schoenebeck 2 if (FrameTable) delete[] FrameTable;
1172     if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
1173     }
1174    
1175    
1176    
1177     // *************** DimensionRegion ***************
1178     // *
1179    
1180 schoenebeck 16 uint DimensionRegion::Instances = 0;
1181     DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1182    
1183 schoenebeck 2 DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1184 schoenebeck 16 Instances++;
1185    
1186 schoenebeck 823 pSample = NULL;
1187    
1188 schoenebeck 2 memcpy(&Crossfade, &SamplerOptions, 4);
1189 schoenebeck 16 if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1190 schoenebeck 2
1191     RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1192 schoenebeck 809 if (_3ewa) { // if '3ewa' chunk exists
1193     _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
1194     LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1195     EG3Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1196     _3ewa->ReadInt16(); // unknown
1197     LFO1InternalDepth = _3ewa->ReadUint16();
1198     _3ewa->ReadInt16(); // unknown
1199     LFO3InternalDepth = _3ewa->ReadInt16();
1200     _3ewa->ReadInt16(); // unknown
1201     LFO1ControlDepth = _3ewa->ReadUint16();
1202     _3ewa->ReadInt16(); // unknown
1203     LFO3ControlDepth = _3ewa->ReadInt16();
1204     EG1Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1205     EG1Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1206     _3ewa->ReadInt16(); // unknown
1207     EG1Sustain = _3ewa->ReadUint16();
1208     EG1Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1209     EG1Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1210     uint8_t eg1ctrloptions = _3ewa->ReadUint8();
1211     EG1ControllerInvert = eg1ctrloptions & 0x01;
1212     EG1ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1213     EG1ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1214     EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1215     EG2Controller = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1216     uint8_t eg2ctrloptions = _3ewa->ReadUint8();
1217     EG2ControllerInvert = eg2ctrloptions & 0x01;
1218     EG2ControllerAttackInfluence = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1219     EG2ControllerDecayInfluence = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1220     EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1221     LFO1Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1222     EG2Attack = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1223     EG2Decay1 = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1224     _3ewa->ReadInt16(); // unknown
1225     EG2Sustain = _3ewa->ReadUint16();
1226     EG2Release = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1227     _3ewa->ReadInt16(); // unknown
1228     LFO2ControlDepth = _3ewa->ReadUint16();
1229     LFO2Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1230     _3ewa->ReadInt16(); // unknown
1231     LFO2InternalDepth = _3ewa->ReadUint16();
1232     int32_t eg1decay2 = _3ewa->ReadInt32();
1233     EG1Decay2 = (double) GIG_EXP_DECODE(eg1decay2);
1234     EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1235     _3ewa->ReadInt16(); // unknown
1236     EG1PreAttack = _3ewa->ReadUint16();
1237     int32_t eg2decay2 = _3ewa->ReadInt32();
1238     EG2Decay2 = (double) GIG_EXP_DECODE(eg2decay2);
1239     EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1240     _3ewa->ReadInt16(); // unknown
1241     EG2PreAttack = _3ewa->ReadUint16();
1242     uint8_t velocityresponse = _3ewa->ReadUint8();
1243     if (velocityresponse < 5) {
1244     VelocityResponseCurve = curve_type_nonlinear;
1245     VelocityResponseDepth = velocityresponse;
1246     } else if (velocityresponse < 10) {
1247     VelocityResponseCurve = curve_type_linear;
1248     VelocityResponseDepth = velocityresponse - 5;
1249     } else if (velocityresponse < 15) {
1250     VelocityResponseCurve = curve_type_special;
1251     VelocityResponseDepth = velocityresponse - 10;
1252     } else {
1253     VelocityResponseCurve = curve_type_unknown;
1254     VelocityResponseDepth = 0;
1255     }
1256     uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1257     if (releasevelocityresponse < 5) {
1258     ReleaseVelocityResponseCurve = curve_type_nonlinear;
1259     ReleaseVelocityResponseDepth = releasevelocityresponse;
1260     } else if (releasevelocityresponse < 10) {
1261     ReleaseVelocityResponseCurve = curve_type_linear;
1262     ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1263     } else if (releasevelocityresponse < 15) {
1264     ReleaseVelocityResponseCurve = curve_type_special;
1265     ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1266     } else {
1267     ReleaseVelocityResponseCurve = curve_type_unknown;
1268     ReleaseVelocityResponseDepth = 0;
1269     }
1270     VelocityResponseCurveScaling = _3ewa->ReadUint8();
1271     AttenuationControllerThreshold = _3ewa->ReadInt8();
1272     _3ewa->ReadInt32(); // unknown
1273     SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1274     _3ewa->ReadInt16(); // unknown
1275     uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1276     PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1277     if (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1278     else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1279     else DimensionBypass = dim_bypass_ctrl_none;
1280     uint8_t pan = _3ewa->ReadUint8();
1281     Pan = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1282     SelfMask = _3ewa->ReadInt8() & 0x01;
1283     _3ewa->ReadInt8(); // unknown
1284     uint8_t lfo3ctrl = _3ewa->ReadUint8();
1285     LFO3Controller = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1286     LFO3Sync = lfo3ctrl & 0x20; // bit 5
1287     InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1288     AttenuationController = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1289     uint8_t lfo2ctrl = _3ewa->ReadUint8();
1290     LFO2Controller = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1291     LFO2FlipPhase = lfo2ctrl & 0x80; // bit 7
1292     LFO2Sync = lfo2ctrl & 0x20; // bit 5
1293     bool extResonanceCtrl = lfo2ctrl & 0x40; // bit 6
1294     uint8_t lfo1ctrl = _3ewa->ReadUint8();
1295     LFO1Controller = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1296     LFO1FlipPhase = lfo1ctrl & 0x80; // bit 7
1297     LFO1Sync = lfo1ctrl & 0x40; // bit 6
1298     VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1299     : vcf_res_ctrl_none;
1300     uint16_t eg3depth = _3ewa->ReadUint16();
1301     EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1302     : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1303     _3ewa->ReadInt16(); // unknown
1304     ChannelOffset = _3ewa->ReadUint8() / 4;
1305     uint8_t regoptions = _3ewa->ReadUint8();
1306     MSDecode = regoptions & 0x01; // bit 0
1307     SustainDefeat = regoptions & 0x02; // bit 1
1308     _3ewa->ReadInt16(); // unknown
1309     VelocityUpperLimit = _3ewa->ReadInt8();
1310     _3ewa->ReadInt8(); // unknown
1311     _3ewa->ReadInt16(); // unknown
1312     ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1313     _3ewa->ReadInt8(); // unknown
1314     _3ewa->ReadInt8(); // unknown
1315     EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1316     uint8_t vcfcutoff = _3ewa->ReadUint8();
1317     VCFEnabled = vcfcutoff & 0x80; // bit 7
1318     VCFCutoff = vcfcutoff & 0x7f; // lower 7 bits
1319     VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1320     uint8_t vcfvelscale = _3ewa->ReadUint8();
1321     VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1322     VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1323     _3ewa->ReadInt8(); // unknown
1324     uint8_t vcfresonance = _3ewa->ReadUint8();
1325     VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1326     VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1327     uint8_t vcfbreakpoint = _3ewa->ReadUint8();
1328     VCFKeyboardTracking = vcfbreakpoint & 0x80; // bit 7
1329     VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1330     uint8_t vcfvelocity = _3ewa->ReadUint8();
1331     VCFVelocityDynamicRange = vcfvelocity % 5;
1332     VCFVelocityCurve = static_cast<curve_type_t>(vcfvelocity / 5);
1333     VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1334     if (VCFType == vcf_type_lowpass) {
1335     if (lfo3ctrl & 0x40) // bit 6
1336     VCFType = vcf_type_lowpassturbo;
1337     }
1338     } else { // '3ewa' chunk does not exist yet
1339     // use default values
1340     LFO3Frequency = 1.0;
1341     EG3Attack = 0.0;
1342     LFO1InternalDepth = 0;
1343     LFO3InternalDepth = 0;
1344     LFO1ControlDepth = 0;
1345     LFO3ControlDepth = 0;
1346     EG1Attack = 0.0;
1347     EG1Decay1 = 0.0;
1348     EG1Sustain = 0;
1349     EG1Release = 0.0;
1350     EG1Controller.type = eg1_ctrl_t::type_none;
1351     EG1Controller.controller_number = 0;
1352     EG1ControllerInvert = false;
1353     EG1ControllerAttackInfluence = 0;
1354     EG1ControllerDecayInfluence = 0;
1355     EG1ControllerReleaseInfluence = 0;
1356     EG2Controller.type = eg2_ctrl_t::type_none;
1357     EG2Controller.controller_number = 0;
1358     EG2ControllerInvert = false;
1359     EG2ControllerAttackInfluence = 0;
1360     EG2ControllerDecayInfluence = 0;
1361     EG2ControllerReleaseInfluence = 0;
1362     LFO1Frequency = 1.0;
1363     EG2Attack = 0.0;
1364     EG2Decay1 = 0.0;
1365     EG2Sustain = 0;
1366     EG2Release = 0.0;
1367     LFO2ControlDepth = 0;
1368     LFO2Frequency = 1.0;
1369     LFO2InternalDepth = 0;
1370     EG1Decay2 = 0.0;
1371     EG1InfiniteSustain = false;
1372     EG1PreAttack = 1000;
1373     EG2Decay2 = 0.0;
1374     EG2InfiniteSustain = false;
1375     EG2PreAttack = 1000;
1376     VelocityResponseCurve = curve_type_nonlinear;
1377     VelocityResponseDepth = 3;
1378     ReleaseVelocityResponseCurve = curve_type_nonlinear;
1379     ReleaseVelocityResponseDepth = 3;
1380     VelocityResponseCurveScaling = 32;
1381     AttenuationControllerThreshold = 0;
1382     SampleStartOffset = 0;
1383     PitchTrack = true;
1384     DimensionBypass = dim_bypass_ctrl_none;
1385     Pan = 0;
1386     SelfMask = true;
1387     LFO3Controller = lfo3_ctrl_modwheel;
1388     LFO3Sync = false;
1389     InvertAttenuationController = false;
1390     AttenuationController.type = attenuation_ctrl_t::type_none;
1391     AttenuationController.controller_number = 0;
1392     LFO2Controller = lfo2_ctrl_internal;
1393     LFO2FlipPhase = false;
1394     LFO2Sync = false;
1395     LFO1Controller = lfo1_ctrl_internal;
1396     LFO1FlipPhase = false;
1397     LFO1Sync = false;
1398     VCFResonanceController = vcf_res_ctrl_none;
1399     EG3Depth = 0;
1400     ChannelOffset = 0;
1401     MSDecode = false;
1402     SustainDefeat = false;
1403     VelocityUpperLimit = 0;
1404     ReleaseTriggerDecay = 0;
1405     EG1Hold = false;
1406     VCFEnabled = false;
1407     VCFCutoff = 0;
1408     VCFCutoffController = vcf_cutoff_ctrl_none;
1409     VCFCutoffControllerInvert = false;
1410     VCFVelocityScale = 0;
1411     VCFResonance = 0;
1412     VCFResonanceDynamic = false;
1413     VCFKeyboardTracking = false;
1414     VCFKeyboardTrackingBreakpoint = 0;
1415     VCFVelocityDynamicRange = 0x04;
1416     VCFVelocityCurve = curve_type_linear;
1417     VCFType = vcf_type_lowpass;
1418 schoenebeck 2 }
1419 schoenebeck 16
1420 persson 613 pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1421     VelocityResponseDepth,
1422     VelocityResponseCurveScaling);
1423    
1424     curve_type_t curveType = ReleaseVelocityResponseCurve;
1425     uint8_t depth = ReleaseVelocityResponseDepth;
1426    
1427     // this models a strange behaviour or bug in GSt: two of the
1428     // velocity response curves for release time are not used even
1429     // if specified, instead another curve is chosen.
1430     if ((curveType == curve_type_nonlinear && depth == 0) ||
1431     (curveType == curve_type_special && depth == 4)) {
1432     curveType = curve_type_nonlinear;
1433     depth = 3;
1434     }
1435     pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1436    
1437 persson 728 curveType = VCFVelocityCurve;
1438     depth = VCFVelocityDynamicRange;
1439    
1440     // even stranger GSt: two of the velocity response curves for
1441     // filter cutoff are not used, instead another special curve
1442     // is chosen. This curve is not used anywhere else.
1443     if ((curveType == curve_type_nonlinear && depth == 0) ||
1444     (curveType == curve_type_special && depth == 4)) {
1445     curveType = curve_type_special;
1446     depth = 5;
1447     }
1448     pVelocityCutoffTable = GetVelocityTable(curveType, depth,
1449 persson 773 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1450 persson 728
1451 persson 613 SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1452     }
1453    
1454 schoenebeck 809 /**
1455     * Apply dimension region settings to the respective RIFF chunks. You
1456     * have to call File::Save() to make changes persistent.
1457     *
1458     * Usually there is absolutely no need to call this method explicitly.
1459     * It will be called automatically when File::Save() was called.
1460     */
1461     void DimensionRegion::UpdateChunks() {
1462     // first update base class's chunk
1463     DLS::Sampler::UpdateChunks();
1464    
1465     // make sure '3ewa' chunk exists
1466     RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1467     if (!_3ewa) _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);
1468     uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();
1469    
1470     // update '3ewa' chunk with DimensionRegion's current settings
1471    
1472     const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?
1473     memcpy(&pData[0], &unknown, 4);
1474    
1475     const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1476     memcpy(&pData[4], &lfo3freq, 4);
1477    
1478     const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1479     memcpy(&pData[4], &eg3attack, 4);
1480    
1481     // next 2 bytes unknown
1482    
1483     memcpy(&pData[10], &LFO1InternalDepth, 2);
1484    
1485     // next 2 bytes unknown
1486    
1487     memcpy(&pData[14], &LFO3InternalDepth, 2);
1488    
1489     // next 2 bytes unknown
1490    
1491     memcpy(&pData[18], &LFO1ControlDepth, 2);
1492    
1493     // next 2 bytes unknown
1494    
1495     memcpy(&pData[22], &LFO3ControlDepth, 2);
1496    
1497     const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1498     memcpy(&pData[24], &eg1attack, 4);
1499    
1500     const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1501     memcpy(&pData[28], &eg1decay1, 4);
1502    
1503     // next 2 bytes unknown
1504    
1505     memcpy(&pData[34], &EG1Sustain, 2);
1506    
1507     const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1508     memcpy(&pData[36], &eg1release, 4);
1509    
1510     const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1511     memcpy(&pData[40], &eg1ctl, 1);
1512    
1513     const uint8_t eg1ctrloptions =
1514     (EG1ControllerInvert) ? 0x01 : 0x00 |
1515     GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1516     GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1517     GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1518     memcpy(&pData[41], &eg1ctrloptions, 1);
1519    
1520     const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1521     memcpy(&pData[42], &eg2ctl, 1);
1522    
1523     const uint8_t eg2ctrloptions =
1524     (EG2ControllerInvert) ? 0x01 : 0x00 |
1525     GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1526     GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1527     GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1528     memcpy(&pData[43], &eg2ctrloptions, 1);
1529    
1530     const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1531     memcpy(&pData[44], &lfo1freq, 4);
1532    
1533     const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1534     memcpy(&pData[48], &eg2attack, 4);
1535    
1536     const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1537     memcpy(&pData[52], &eg2decay1, 4);
1538    
1539     // next 2 bytes unknown
1540    
1541     memcpy(&pData[58], &EG2Sustain, 2);
1542    
1543     const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1544     memcpy(&pData[60], &eg2release, 4);
1545    
1546     // next 2 bytes unknown
1547    
1548     memcpy(&pData[66], &LFO2ControlDepth, 2);
1549    
1550     const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1551     memcpy(&pData[68], &lfo2freq, 4);
1552    
1553     // next 2 bytes unknown
1554    
1555     memcpy(&pData[72], &LFO2InternalDepth, 2);
1556    
1557     const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1558     memcpy(&pData[74], &eg1decay2, 4);
1559    
1560     // next 2 bytes unknown
1561    
1562     memcpy(&pData[80], &EG1PreAttack, 2);
1563    
1564     const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1565     memcpy(&pData[82], &eg2decay2, 4);
1566    
1567     // next 2 bytes unknown
1568    
1569     memcpy(&pData[88], &EG2PreAttack, 2);
1570    
1571     {
1572     if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1573     uint8_t velocityresponse = VelocityResponseDepth;
1574     switch (VelocityResponseCurve) {
1575     case curve_type_nonlinear:
1576     break;
1577     case curve_type_linear:
1578     velocityresponse += 5;
1579     break;
1580     case curve_type_special:
1581     velocityresponse += 10;
1582     break;
1583     case curve_type_unknown:
1584     default:
1585     throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1586     }
1587     memcpy(&pData[90], &velocityresponse, 1);
1588     }
1589    
1590     {
1591     if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1592     uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1593     switch (ReleaseVelocityResponseCurve) {
1594     case curve_type_nonlinear:
1595     break;
1596     case curve_type_linear:
1597     releasevelocityresponse += 5;
1598     break;
1599     case curve_type_special:
1600     releasevelocityresponse += 10;
1601     break;
1602     case curve_type_unknown:
1603     default:
1604     throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1605     }
1606     memcpy(&pData[91], &releasevelocityresponse, 1);
1607     }
1608    
1609     memcpy(&pData[92], &VelocityResponseCurveScaling, 1);
1610    
1611     memcpy(&pData[93], &AttenuationControllerThreshold, 1);
1612    
1613     // next 4 bytes unknown
1614    
1615     memcpy(&pData[98], &SampleStartOffset, 2);
1616    
1617     // next 2 bytes unknown
1618    
1619     {
1620     uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1621     switch (DimensionBypass) {
1622     case dim_bypass_ctrl_94:
1623     pitchTrackDimensionBypass |= 0x10;
1624     break;
1625     case dim_bypass_ctrl_95:
1626     pitchTrackDimensionBypass |= 0x20;
1627     break;
1628     case dim_bypass_ctrl_none:
1629     //FIXME: should we set anything here?
1630     break;
1631     default:
1632     throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1633     }
1634     memcpy(&pData[102], &pitchTrackDimensionBypass, 1);
1635     }
1636    
1637     const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1638     memcpy(&pData[103], &pan, 1);
1639    
1640     const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1641     memcpy(&pData[104], &selfmask, 1);
1642    
1643     // next byte unknown
1644    
1645     {
1646     uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1647     if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1648     if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1649     if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1650     memcpy(&pData[106], &lfo3ctrl, 1);
1651     }
1652    
1653     const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1654     memcpy(&pData[107], &attenctl, 1);
1655    
1656     {
1657     uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1658     if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1659     if (LFO2Sync) lfo2ctrl |= 0x20; // bit 5
1660     if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1661     memcpy(&pData[108], &lfo2ctrl, 1);
1662     }
1663    
1664     {
1665     uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1666     if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1667     if (LFO1Sync) lfo1ctrl |= 0x40; // bit 6
1668     if (VCFResonanceController != vcf_res_ctrl_none)
1669     lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1670     memcpy(&pData[109], &lfo1ctrl, 1);
1671     }
1672    
1673     const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1674     : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1675     memcpy(&pData[110], &eg3depth, 1);
1676    
1677     // next 2 bytes unknown
1678    
1679     const uint8_t channeloffset = ChannelOffset * 4;
1680     memcpy(&pData[113], &channeloffset, 1);
1681    
1682     {
1683     uint8_t regoptions = 0;
1684     if (MSDecode) regoptions |= 0x01; // bit 0
1685     if (SustainDefeat) regoptions |= 0x02; // bit 1
1686     memcpy(&pData[114], &regoptions, 1);
1687     }
1688    
1689     // next 2 bytes unknown
1690    
1691     memcpy(&pData[117], &VelocityUpperLimit, 1);
1692    
1693     // next 3 bytes unknown
1694    
1695     memcpy(&pData[121], &ReleaseTriggerDecay, 1);
1696    
1697     // next 2 bytes unknown
1698    
1699     const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1700     memcpy(&pData[124], &eg1hold, 1);
1701    
1702     const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 | /* bit 7 */
1703     (VCFCutoff) ? 0x7f : 0x00; /* lower 7 bits */
1704     memcpy(&pData[125], &vcfcutoff, 1);
1705    
1706     memcpy(&pData[126], &VCFCutoffController, 1);
1707    
1708     const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1709     (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */
1710     memcpy(&pData[127], &vcfvelscale, 1);
1711    
1712     // next byte unknown
1713    
1714     const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1715     (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */
1716     memcpy(&pData[129], &vcfresonance, 1);
1717    
1718     const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1719     (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */
1720     memcpy(&pData[130], &vcfbreakpoint, 1);
1721    
1722     const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1723     VCFVelocityCurve * 5;
1724     memcpy(&pData[131], &vcfvelocity, 1);
1725    
1726     const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1727     memcpy(&pData[132], &vcftype, 1);
1728     }
1729    
1730 persson 613 // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1731     double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1732     {
1733     double* table;
1734     uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1735 schoenebeck 16 if (pVelocityTables->count(tableKey)) { // if key exists
1736 persson 613 table = (*pVelocityTables)[tableKey];
1737 schoenebeck 16 }
1738     else {
1739 persson 613 table = CreateVelocityTable(curveType, depth, scaling);
1740     (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
1741 schoenebeck 16 }
1742 persson 613 return table;
1743 schoenebeck 2 }
1744 schoenebeck 55
1745 schoenebeck 36 leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
1746     leverage_ctrl_t decodedcontroller;
1747     switch (EncodedController) {
1748     // special controller
1749     case _lev_ctrl_none:
1750     decodedcontroller.type = leverage_ctrl_t::type_none;
1751     decodedcontroller.controller_number = 0;
1752     break;
1753     case _lev_ctrl_velocity:
1754     decodedcontroller.type = leverage_ctrl_t::type_velocity;
1755     decodedcontroller.controller_number = 0;
1756     break;
1757     case _lev_ctrl_channelaftertouch:
1758     decodedcontroller.type = leverage_ctrl_t::type_channelaftertouch;
1759     decodedcontroller.controller_number = 0;
1760     break;
1761 schoenebeck 55
1762 schoenebeck 36 // ordinary MIDI control change controller
1763     case _lev_ctrl_modwheel:
1764     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1765     decodedcontroller.controller_number = 1;
1766     break;
1767     case _lev_ctrl_breath:
1768     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1769     decodedcontroller.controller_number = 2;
1770     break;
1771     case _lev_ctrl_foot:
1772     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1773     decodedcontroller.controller_number = 4;
1774     break;
1775     case _lev_ctrl_effect1:
1776     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1777     decodedcontroller.controller_number = 12;
1778     break;
1779     case _lev_ctrl_effect2:
1780     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1781     decodedcontroller.controller_number = 13;
1782     break;
1783     case _lev_ctrl_genpurpose1:
1784     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1785     decodedcontroller.controller_number = 16;
1786     break;
1787     case _lev_ctrl_genpurpose2:
1788     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1789     decodedcontroller.controller_number = 17;
1790     break;
1791     case _lev_ctrl_genpurpose3:
1792     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1793     decodedcontroller.controller_number = 18;
1794     break;
1795     case _lev_ctrl_genpurpose4:
1796     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1797     decodedcontroller.controller_number = 19;
1798     break;
1799     case _lev_ctrl_portamentotime:
1800     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1801     decodedcontroller.controller_number = 5;
1802     break;
1803     case _lev_ctrl_sustainpedal:
1804     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1805     decodedcontroller.controller_number = 64;
1806     break;
1807     case _lev_ctrl_portamento:
1808     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1809     decodedcontroller.controller_number = 65;
1810     break;
1811     case _lev_ctrl_sostenutopedal:
1812     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1813     decodedcontroller.controller_number = 66;
1814     break;
1815     case _lev_ctrl_softpedal:
1816     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1817     decodedcontroller.controller_number = 67;
1818     break;
1819     case _lev_ctrl_genpurpose5:
1820     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1821     decodedcontroller.controller_number = 80;
1822     break;
1823     case _lev_ctrl_genpurpose6:
1824     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1825     decodedcontroller.controller_number = 81;
1826     break;
1827     case _lev_ctrl_genpurpose7:
1828     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1829     decodedcontroller.controller_number = 82;
1830     break;
1831     case _lev_ctrl_genpurpose8:
1832     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1833     decodedcontroller.controller_number = 83;
1834     break;
1835     case _lev_ctrl_effect1depth:
1836     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1837     decodedcontroller.controller_number = 91;
1838     break;
1839     case _lev_ctrl_effect2depth:
1840     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1841     decodedcontroller.controller_number = 92;
1842     break;
1843     case _lev_ctrl_effect3depth:
1844     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1845     decodedcontroller.controller_number = 93;
1846     break;
1847     case _lev_ctrl_effect4depth:
1848     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1849     decodedcontroller.controller_number = 94;
1850     break;
1851     case _lev_ctrl_effect5depth:
1852     decodedcontroller.type = leverage_ctrl_t::type_controlchange;
1853     decodedcontroller.controller_number = 95;
1854     break;
1855 schoenebeck 55
1856 schoenebeck 36 // unknown controller type
1857     default:
1858     throw gig::Exception("Unknown leverage controller type.");
1859     }
1860     return decodedcontroller;
1861     }
1862 schoenebeck 2
1863 schoenebeck 809 DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
1864     _lev_ctrl_t encodedcontroller;
1865     switch (DecodedController.type) {
1866     // special controller
1867     case leverage_ctrl_t::type_none:
1868     encodedcontroller = _lev_ctrl_none;
1869     break;
1870     case leverage_ctrl_t::type_velocity:
1871     encodedcontroller = _lev_ctrl_velocity;
1872     break;
1873     case leverage_ctrl_t::type_channelaftertouch:
1874     encodedcontroller = _lev_ctrl_channelaftertouch;
1875     break;
1876    
1877     // ordinary MIDI control change controller
1878     case leverage_ctrl_t::type_controlchange:
1879     switch (DecodedController.controller_number) {
1880     case 1:
1881     encodedcontroller = _lev_ctrl_modwheel;
1882     break;
1883     case 2:
1884     encodedcontroller = _lev_ctrl_breath;
1885     break;
1886     case 4:
1887     encodedcontroller = _lev_ctrl_foot;
1888     break;
1889     case 12:
1890     encodedcontroller = _lev_ctrl_effect1;
1891     break;
1892     case 13:
1893     encodedcontroller = _lev_ctrl_effect2;
1894     break;
1895     case 16:
1896     encodedcontroller = _lev_ctrl_genpurpose1;
1897     break;
1898     case 17:
1899     encodedcontroller = _lev_ctrl_genpurpose2;
1900     break;
1901     case 18:
1902     encodedcontroller = _lev_ctrl_genpurpose3;
1903     break;
1904     case 19:
1905     encodedcontroller = _lev_ctrl_genpurpose4;
1906     break;
1907     case 5:
1908     encodedcontroller = _lev_ctrl_portamentotime;
1909     break;
1910     case 64:
1911     encodedcontroller = _lev_ctrl_sustainpedal;
1912     break;
1913     case 65:
1914     encodedcontroller = _lev_ctrl_portamento;
1915     break;
1916     case 66:
1917     encodedcontroller = _lev_ctrl_sostenutopedal;
1918     break;
1919     case 67:
1920     encodedcontroller = _lev_ctrl_softpedal;
1921     break;
1922     case 80:
1923     encodedcontroller = _lev_ctrl_genpurpose5;
1924     break;
1925     case 81:
1926     encodedcontroller = _lev_ctrl_genpurpose6;
1927     break;
1928     case 82:
1929     encodedcontroller = _lev_ctrl_genpurpose7;
1930     break;
1931     case 83:
1932     encodedcontroller = _lev_ctrl_genpurpose8;
1933     break;
1934     case 91:
1935     encodedcontroller = _lev_ctrl_effect1depth;
1936     break;
1937     case 92:
1938     encodedcontroller = _lev_ctrl_effect2depth;
1939     break;
1940     case 93:
1941     encodedcontroller = _lev_ctrl_effect3depth;
1942     break;
1943     case 94:
1944     encodedcontroller = _lev_ctrl_effect4depth;
1945     break;
1946     case 95:
1947     encodedcontroller = _lev_ctrl_effect5depth;
1948     break;
1949     default:
1950     throw gig::Exception("leverage controller number is not supported by the gig format");
1951     }
1952     default:
1953     throw gig::Exception("Unknown leverage controller type.");
1954     }
1955     return encodedcontroller;
1956     }
1957    
1958 schoenebeck 16 DimensionRegion::~DimensionRegion() {
1959     Instances--;
1960     if (!Instances) {
1961     // delete the velocity->volume tables
1962     VelocityTableMap::iterator iter;
1963     for (iter = pVelocityTables->begin(); iter != pVelocityTables->end(); iter++) {
1964     double* pTable = iter->second;
1965     if (pTable) delete[] pTable;
1966     }
1967     pVelocityTables->clear();
1968     delete pVelocityTables;
1969     pVelocityTables = NULL;
1970     }
1971     }
1972 schoenebeck 2
1973 schoenebeck 16 /**
1974     * Returns the correct amplitude factor for the given \a MIDIKeyVelocity.
1975     * All involved parameters (VelocityResponseCurve, VelocityResponseDepth
1976     * and VelocityResponseCurveScaling) involved are taken into account to
1977     * calculate the amplitude factor. Use this method when a key was
1978     * triggered to get the volume with which the sample should be played
1979     * back.
1980     *
1981 schoenebeck 36 * @param MIDIKeyVelocity MIDI velocity value of the triggered key (between 0 and 127)
1982     * @returns amplitude factor (between 0.0 and 1.0)
1983 schoenebeck 16 */
1984     double DimensionRegion::GetVelocityAttenuation(uint8_t MIDIKeyVelocity) {
1985     return pVelocityAttenuationTable[MIDIKeyVelocity];
1986     }
1987 schoenebeck 2
1988 persson 613 double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
1989     return pVelocityReleaseTable[MIDIKeyVelocity];
1990     }
1991    
1992 persson 728 double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
1993     return pVelocityCutoffTable[MIDIKeyVelocity];
1994     }
1995    
1996 schoenebeck 308 double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
1997 schoenebeck 317
1998 schoenebeck 308 // line-segment approximations of the 15 velocity curves
1999 schoenebeck 16
2000 schoenebeck 308 // linear
2001     const int lin0[] = { 1, 1, 127, 127 };
2002     const int lin1[] = { 1, 21, 127, 127 };
2003     const int lin2[] = { 1, 45, 127, 127 };
2004     const int lin3[] = { 1, 74, 127, 127 };
2005     const int lin4[] = { 1, 127, 127, 127 };
2006 schoenebeck 16
2007 schoenebeck 308 // non-linear
2008     const int non0[] = { 1, 4, 24, 5, 57, 17, 92, 57, 122, 127, 127, 127 };
2009 schoenebeck 317 const int non1[] = { 1, 4, 46, 9, 93, 56, 118, 106, 123, 127,
2010 schoenebeck 308 127, 127 };
2011     const int non2[] = { 1, 4, 46, 9, 57, 20, 102, 107, 107, 127,
2012     127, 127 };
2013     const int non3[] = { 1, 15, 10, 19, 67, 73, 80, 80, 90, 98, 98, 127,
2014     127, 127 };
2015     const int non4[] = { 1, 25, 33, 57, 82, 81, 92, 127, 127, 127 };
2016 schoenebeck 317
2017 schoenebeck 308 // special
2018 schoenebeck 317 const int spe0[] = { 1, 2, 76, 10, 90, 15, 95, 20, 99, 28, 103, 44,
2019 schoenebeck 308 113, 127, 127, 127 };
2020     const int spe1[] = { 1, 2, 27, 5, 67, 18, 89, 29, 95, 35, 107, 67,
2021     118, 127, 127, 127 };
2022 schoenebeck 317 const int spe2[] = { 1, 1, 33, 1, 53, 5, 61, 13, 69, 32, 79, 74,
2023 schoenebeck 308 85, 90, 91, 127, 127, 127 };
2024 schoenebeck 317 const int spe3[] = { 1, 32, 28, 35, 66, 48, 89, 59, 95, 65, 99, 73,
2025 schoenebeck 308 117, 127, 127, 127 };
2026 schoenebeck 317 const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2027 schoenebeck 308 127, 127 };
2028 schoenebeck 317
2029 persson 728 // this is only used by the VCF velocity curve
2030     const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2031     91, 127, 127, 127 };
2032    
2033 schoenebeck 308 const int* const curves[] = { non0, non1, non2, non3, non4,
2034 schoenebeck 317 lin0, lin1, lin2, lin3, lin4,
2035 persson 728 spe0, spe1, spe2, spe3, spe4, spe5 };
2036 schoenebeck 317
2037 schoenebeck 308 double* const table = new double[128];
2038    
2039     const int* curve = curves[curveType * 5 + depth];
2040     const int s = scaling == 0 ? 20 : scaling; // 0 or 20 means no scaling
2041 schoenebeck 317
2042 schoenebeck 308 table[0] = 0;
2043     for (int x = 1 ; x < 128 ; x++) {
2044    
2045     if (x > curve[2]) curve += 2;
2046 schoenebeck 317 double y = curve[1] + (x - curve[0]) *
2047 schoenebeck 308 (double(curve[3] - curve[1]) / (curve[2] - curve[0]));
2048     y = y / 127;
2049    
2050     // Scale up for s > 20, down for s < 20. When
2051     // down-scaling, the curve still ends at 1.0.
2052     if (s < 20 && y >= 0.5)
2053     y = y / ((2 - 40.0 / s) * y + 40.0 / s - 1);
2054     else
2055     y = y * (s / 20.0);
2056     if (y > 1) y = 1;
2057    
2058     table[x] = y;
2059     }
2060     return table;
2061     }
2062    
2063    
2064 schoenebeck 2 // *************** Region ***************
2065     // *
2066    
2067     Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2068     // Initialization
2069     Dimensions = 0;
2070 schoenebeck 347 for (int i = 0; i < 256; i++) {
2071 schoenebeck 2 pDimensionRegions[i] = NULL;
2072     }
2073 schoenebeck 282 Layers = 1;
2074 schoenebeck 347 File* file = (File*) GetParent()->GetParent();
2075     int dimensionBits = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2076 schoenebeck 2
2077     // Actual Loading
2078    
2079     LoadDimensionRegions(rgnList);
2080    
2081     RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
2082     if (_3lnk) {
2083     DimensionRegions = _3lnk->ReadUint32();
2084 schoenebeck 347 for (int i = 0; i < dimensionBits; i++) {
2085 schoenebeck 2 dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2086     uint8_t bits = _3lnk->ReadUint8();
2087 persson 774 _3lnk->ReadUint8(); // probably the position of the dimension
2088     _3lnk->ReadUint8(); // unknown
2089     uint8_t zones = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2090 schoenebeck 2 if (dimension == dimension_none) { // inactive dimension
2091     pDimensionDefinitions[i].dimension = dimension_none;
2092     pDimensionDefinitions[i].bits = 0;
2093     pDimensionDefinitions[i].zones = 0;
2094     pDimensionDefinitions[i].split_type = split_type_bit;
2095     pDimensionDefinitions[i].ranges = NULL;
2096     pDimensionDefinitions[i].zone_size = 0;
2097     }
2098     else { // active dimension
2099     pDimensionDefinitions[i].dimension = dimension;
2100     pDimensionDefinitions[i].bits = bits;
2101 persson 774 pDimensionDefinitions[i].zones = zones ? zones : 0x01 << bits; // = pow(2,bits)
2102 schoenebeck 2 pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
2103 schoenebeck 241 dimension == dimension_samplechannel ||
2104 persson 437 dimension == dimension_releasetrigger ||
2105     dimension == dimension_roundrobin ||
2106     dimension == dimension_random) ? split_type_bit
2107     : split_type_normal;
2108 schoenebeck 2 pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point
2109     pDimensionDefinitions[i].zone_size =
2110 persson 774 (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones
2111 schoenebeck 2 : 0;
2112     Dimensions++;
2113 schoenebeck 282
2114     // if this is a layer dimension, remember the amount of layers
2115     if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2116 schoenebeck 2 }
2117 persson 774 _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2118 schoenebeck 2 }
2119    
2120     // check velocity dimension (if there is one) for custom defined zone ranges
2121     for (uint i = 0; i < Dimensions; i++) {
2122     dimension_def_t* pDimDef = pDimensionDefinitions + i;
2123     if (pDimDef->dimension == dimension_velocity) {
2124     if (pDimensionRegions[0]->VelocityUpperLimit == 0) {
2125     // no custom defined ranges
2126     pDimDef->split_type = split_type_normal;
2127     pDimDef->ranges = NULL;
2128     }
2129     else { // custom defined ranges
2130     pDimDef->split_type = split_type_customvelocity;
2131     pDimDef->ranges = new range_t[pDimDef->zones];
2132 schoenebeck 809 UpdateVelocityTable(pDimDef);
2133 schoenebeck 2 }
2134     }
2135     }
2136    
2137 schoenebeck 317 // jump to start of the wave pool indices (if not already there)
2138     File* file = (File*) GetParent()->GetParent();
2139     if (file->pVersion && file->pVersion->major == 3)
2140     _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2141     else
2142     _3lnk->SetPos(44);
2143    
2144 schoenebeck 2 // load sample references
2145     for (uint i = 0; i < DimensionRegions; i++) {
2146     uint32_t wavepoolindex = _3lnk->ReadUint32();
2147     pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2148     }
2149     }
2150 schoenebeck 823
2151     // make sure there is at least one dimension region
2152     if (!DimensionRegions) {
2153     RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2154     if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2155     RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2156     pDimensionRegions[0] = new DimensionRegion(_3ewl);
2157     DimensionRegions = 1;
2158     }
2159 schoenebeck 2 }
2160    
2161 schoenebeck 809 /**
2162     * Apply Region settings and all its DimensionRegions to the respective
2163     * RIFF chunks. You have to call File::Save() to make changes persistent.
2164     *
2165     * Usually there is absolutely no need to call this method explicitly.
2166     * It will be called automatically when File::Save() was called.
2167     *
2168     * @throws gig::Exception if samples cannot be dereferenced
2169     */
2170     void Region::UpdateChunks() {
2171     // first update base class's chunks
2172     DLS::Region::UpdateChunks();
2173    
2174     // update dimension region's chunks
2175 schoenebeck 823 for (int i = 0; i < DimensionRegions; i++) {
2176 schoenebeck 809 pDimensionRegions[i]->UpdateChunks();
2177 schoenebeck 823 }
2178 schoenebeck 809
2179     File* pFile = (File*) GetParent()->GetParent();
2180     const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
2181     const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;
2182    
2183     // make sure '3lnk' chunk exists
2184     RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2185     if (!_3lnk) {
2186     const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;
2187     _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2188     }
2189    
2190     // update dimension definitions in '3lnk' chunk
2191     uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2192     for (int i = 0; i < iMaxDimensions; i++) {
2193     pData[i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2194     pData[i * 8 + 1] = pDimensionDefinitions[i].bits;
2195     // next 2 bytes unknown
2196     pData[i * 8 + 4] = pDimensionDefinitions[i].zones;
2197     // next 3 bytes unknown
2198     }
2199    
2200     // update wave pool table in '3lnk' chunk
2201     const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;
2202     for (uint i = 0; i < iMaxDimensionRegions; i++) {
2203     int iWaveIndex = -1;
2204     if (i < DimensionRegions) {
2205 schoenebeck 823 if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2206     File::SampleList::iterator iter = pFile->pSamples->begin();
2207     File::SampleList::iterator end = pFile->pSamples->end();
2208 schoenebeck 809 for (int index = 0; iter != end; ++iter, ++index) {
2209 schoenebeck 823 if (*iter == pDimensionRegions[i]->pSample) {
2210     iWaveIndex = index;
2211     break;
2212     }
2213 schoenebeck 809 }
2214     if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2215     }
2216     memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);
2217     }
2218     }
2219    
2220 schoenebeck 2 void Region::LoadDimensionRegions(RIFF::List* rgn) {
2221     RIFF::List* _3prg = rgn->GetSubList(LIST_TYPE_3PRG);
2222     if (_3prg) {
2223     int dimensionRegionNr = 0;
2224     RIFF::List* _3ewl = _3prg->GetFirstSubList();
2225     while (_3ewl) {
2226     if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2227     pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);
2228     dimensionRegionNr++;
2229     }
2230     _3ewl = _3prg->GetNextSubList();
2231     }
2232     if (dimensionRegionNr == 0) throw gig::Exception("No dimension region found.");
2233     }
2234     }
2235    
2236 schoenebeck 809 void Region::UpdateVelocityTable(dimension_def_t* pDimDef) {
2237     // get dimension's index
2238     int iDimensionNr = -1;
2239     for (int i = 0; i < Dimensions; i++) {
2240     if (&pDimensionDefinitions[i] == pDimDef) {
2241     iDimensionNr = i;
2242     break;
2243     }
2244     }
2245     if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2246    
2247     uint8_t bits[8] = { 0 };
2248     int previousUpperLimit = -1;
2249     for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {
2250     bits[iDimensionNr] = velocityZone;
2251     DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);
2252    
2253     pDimDef->ranges[velocityZone].low = previousUpperLimit + 1;
2254     pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;
2255     previousUpperLimit = pDimDef->ranges[velocityZone].high;
2256     // fill velocity table
2257     for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {
2258     VelocityTable[i] = velocityZone;
2259     }
2260     }
2261     }
2262    
2263     /** @brief Einstein would have dreamed of it - create a new dimension.
2264     *
2265     * Creates a new dimension with the dimension definition given by
2266     * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2267     * There is a hard limit of dimensions and total amount of "bits" all
2268     * dimensions can have. This limit is dependant to what gig file format
2269     * version this file refers to. The gig v2 (and lower) format has a
2270     * dimension limit and total amount of bits limit of 5, whereas the gig v3
2271     * format has a limit of 8.
2272     *
2273     * @param pDimDef - defintion of the new dimension
2274     * @throws gig::Exception if dimension of the same type exists already
2275     * @throws gig::Exception if amount of dimensions or total amount of
2276     * dimension bits limit is violated
2277     */
2278     void Region::AddDimension(dimension_def_t* pDimDef) {
2279     // check if max. amount of dimensions reached
2280     File* file = (File*) GetParent()->GetParent();
2281     const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2282     if (Dimensions >= iMaxDimensions)
2283     throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2284     // check if max. amount of dimension bits reached
2285     int iCurrentBits = 0;
2286     for (int i = 0; i < Dimensions; i++)
2287     iCurrentBits += pDimensionDefinitions[i].bits;
2288     if (iCurrentBits >= iMaxDimensions)
2289     throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2290     const int iNewBits = iCurrentBits + pDimDef->bits;
2291     if (iNewBits > iMaxDimensions)
2292     throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2293     // check if there's already a dimensions of the same type
2294     for (int i = 0; i < Dimensions; i++)
2295     if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2296     throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2297    
2298     // assign definition of new dimension
2299     pDimensionDefinitions[Dimensions] = *pDimDef;
2300    
2301     // create new dimension region(s) for this new dimension
2302     for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2303     //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values
2304     RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);
2305     pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);
2306     DimensionRegions++;
2307     }
2308    
2309     Dimensions++;
2310    
2311     // if this is a layer dimension, update 'Layers' attribute
2312     if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2313    
2314     // if this is velocity dimension and got custom defined ranges, update velocity table
2315     if (pDimDef->dimension == dimension_velocity &&
2316     pDimDef->split_type == split_type_customvelocity) {
2317     UpdateVelocityTable(pDimDef);
2318     }
2319     }
2320    
2321     /** @brief Delete an existing dimension.
2322     *
2323     * Deletes the dimension given by \a pDimDef and deletes all respective
2324     * dimension regions, that is all dimension regions where the dimension's
2325     * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2326     * for example this would delete all dimension regions for the case(s)
2327     * where the sustain pedal is pressed down.
2328     *
2329     * @param pDimDef - dimension to delete
2330     * @throws gig::Exception if given dimension cannot be found
2331     */
2332     void Region::DeleteDimension(dimension_def_t* pDimDef) {
2333     // get dimension's index
2334     int iDimensionNr = -1;
2335     for (int i = 0; i < Dimensions; i++) {
2336     if (&pDimensionDefinitions[i] == pDimDef) {
2337     iDimensionNr = i;
2338     break;
2339     }
2340     }
2341     if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2342    
2343     // get amount of bits below the dimension to delete
2344     int iLowerBits = 0;
2345     for (int i = 0; i < iDimensionNr; i++)
2346     iLowerBits += pDimensionDefinitions[i].bits;
2347    
2348     // get amount ot bits above the dimension to delete
2349     int iUpperBits = 0;
2350     for (int i = iDimensionNr + 1; i < Dimensions; i++)
2351     iUpperBits += pDimensionDefinitions[i].bits;
2352    
2353     // delete dimension regions which belong to the given dimension
2354     // (that is where the dimension's bit > 0)
2355     for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2356     for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2357     for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2358     int iToDelete = iUpperBit << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2359     iObsoleteBit << iLowerBits |
2360     iLowerBit;
2361     delete pDimensionRegions[iToDelete];
2362     pDimensionRegions[iToDelete] = NULL;
2363     DimensionRegions--;
2364     }
2365     }
2366     }
2367    
2368     // defrag pDimensionRegions array
2369     // (that is remove the NULL spaces within the pDimensionRegions array)
2370     for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2371     if (!pDimensionRegions[iTo]) {
2372     if (iFrom <= iTo) iFrom = iTo + 1;
2373     while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2374     if (iFrom < 256 && pDimensionRegions[iFrom]) {
2375     pDimensionRegions[iTo] = pDimensionRegions[iFrom];
2376     pDimensionRegions[iFrom] = NULL;
2377     }
2378     }
2379     }
2380    
2381     // 'remove' dimension definition
2382     for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2383     pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2384     }
2385     pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2386     pDimensionDefinitions[Dimensions - 1].bits = 0;
2387     pDimensionDefinitions[Dimensions - 1].zones = 0;
2388     if (pDimensionDefinitions[Dimensions - 1].ranges) {
2389     delete[] pDimensionDefinitions[Dimensions - 1].ranges;
2390     pDimensionDefinitions[Dimensions - 1].ranges = NULL;
2391     }
2392    
2393     Dimensions--;
2394    
2395     // if this was a layer dimension, update 'Layers' attribute
2396     if (pDimDef->dimension == dimension_layer) Layers = 1;
2397     }
2398    
2399 schoenebeck 2 Region::~Region() {
2400     for (uint i = 0; i < Dimensions; i++) {
2401     if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;
2402     }
2403 schoenebeck 350 for (int i = 0; i < 256; i++) {
2404 schoenebeck 2 if (pDimensionRegions[i]) delete pDimensionRegions[i];
2405     }
2406     }
2407    
2408     /**
2409     * Use this method in your audio engine to get the appropriate dimension
2410     * region with it's articulation data for the current situation. Just
2411     * call the method with the current MIDI controller values and you'll get
2412     * the DimensionRegion with the appropriate articulation data for the
2413     * current situation (for this Region of course only). To do that you'll
2414     * first have to look which dimensions with which controllers and in
2415     * which order are defined for this Region when you load the .gig file.
2416     * Special cases are e.g. layer or channel dimensions where you just put
2417     * in the index numbers instead of a MIDI controller value (means 0 for
2418     * left channel, 1 for right channel or 0 for layer 0, 1 for layer 1,
2419     * etc.).
2420     *
2421 schoenebeck 347 * @param DimValues MIDI controller values (0-127) for dimension 0 to 7
2422 schoenebeck 2 * @returns adress to the DimensionRegion for the given situation
2423     * @see pDimensionDefinitions
2424     * @see Dimensions
2425     */
2426 schoenebeck 347 DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2427     uint8_t bits[8] = { 0 };
2428 schoenebeck 2 for (uint i = 0; i < Dimensions; i++) {
2429 schoenebeck 347 bits[i] = DimValues[i];
2430 schoenebeck 2 switch (pDimensionDefinitions[i].split_type) {
2431     case split_type_normal:
2432 persson 774 bits[i] = uint8_t(bits[i] / pDimensionDefinitions[i].zone_size);
2433 schoenebeck 2 break;
2434     case split_type_customvelocity:
2435     bits[i] = VelocityTable[bits[i]];
2436     break;
2437 schoenebeck 241 case split_type_bit: // the value is already the sought dimension bit number
2438     const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2439     bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed
2440     break;
2441 schoenebeck 2 }
2442     }
2443 schoenebeck 347 return GetDimensionRegionByBit(bits);
2444 schoenebeck 2 }
2445    
2446     /**
2447     * Returns the appropriate DimensionRegion for the given dimension bit
2448     * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
2449     * instead of calling this method directly!
2450     *
2451 schoenebeck 347 * @param DimBits Bit numbers for dimension 0 to 7
2452 schoenebeck 2 * @returns adress to the DimensionRegion for the given dimension
2453     * bit numbers
2454     * @see GetDimensionRegionByValue()
2455     */
2456 schoenebeck 347 DimensionRegion* Region::GetDimensionRegionByBit(const uint8_t DimBits[8]) {
2457     return pDimensionRegions[((((((DimBits[7] << pDimensionDefinitions[6].bits | DimBits[6])
2458     << pDimensionDefinitions[5].bits | DimBits[5])
2459     << pDimensionDefinitions[4].bits | DimBits[4])
2460     << pDimensionDefinitions[3].bits | DimBits[3])
2461     << pDimensionDefinitions[2].bits | DimBits[2])
2462     << pDimensionDefinitions[1].bits | DimBits[1])
2463     << pDimensionDefinitions[0].bits | DimBits[0]];
2464 schoenebeck 2 }
2465    
2466     /**
2467     * Returns pointer address to the Sample referenced with this region.
2468     * This is the global Sample for the entire Region (not sure if this is
2469     * actually used by the Gigasampler engine - I would only use the Sample
2470     * referenced by the appropriate DimensionRegion instead of this sample).
2471     *
2472     * @returns address to Sample or NULL if there is no reference to a
2473     * sample saved in the .gig file
2474     */
2475     Sample* Region::GetSample() {
2476     if (pSample) return static_cast<gig::Sample*>(pSample);
2477     else return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
2478     }
2479    
2480 schoenebeck 515 Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2481 schoenebeck 352 if ((int32_t)WavePoolTableIndex == -1) return NULL;
2482 schoenebeck 2 File* file = (File*) GetParent()->GetParent();
2483     unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2484 persson 666 unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2485 schoenebeck 515 Sample* sample = file->GetFirstSample(pProgress);
2486 schoenebeck 2 while (sample) {
2487 persson 666 if (sample->ulWavePoolOffset == soughtoffset &&
2488     sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);
2489 schoenebeck 2 sample = file->GetNextSample();
2490     }
2491     return NULL;
2492     }
2493    
2494    
2495    
2496     // *************** Instrument ***************
2497     // *
2498    
2499 schoenebeck 515 Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
2500 schoenebeck 2 // Initialization
2501     for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
2502    
2503     // Loading
2504     RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
2505     if (lart) {
2506     RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2507     if (_3ewg) {
2508     EffectSend = _3ewg->ReadUint16();
2509     Attenuation = _3ewg->ReadInt32();
2510     FineTune = _3ewg->ReadInt16();
2511     PitchbendRange = _3ewg->ReadInt16();
2512     uint8_t dimkeystart = _3ewg->ReadUint8();
2513     PianoReleaseMode = dimkeystart & 0x01;
2514     DimensionKeyRange.low = dimkeystart >> 1;
2515     DimensionKeyRange.high = _3ewg->ReadUint8();
2516     }
2517     }
2518    
2519 schoenebeck 823 if (!pRegions) pRegions = new RegionList;
2520 schoenebeck 2 RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2521 schoenebeck 809 if (lrgn) {
2522     RIFF::List* rgn = lrgn->GetFirstSubList();
2523     while (rgn) {
2524     if (rgn->GetListType() == LIST_TYPE_RGN) {
2525 schoenebeck 823 __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2526     pRegions->push_back(new Region(this, rgn));
2527 schoenebeck 809 }
2528     rgn = lrgn->GetNextSubList();
2529 schoenebeck 2 }
2530 schoenebeck 809 // Creating Region Key Table for fast lookup
2531     UpdateRegionKeyTable();
2532 schoenebeck 2 }
2533    
2534 schoenebeck 809 __notify_progress(pProgress, 1.0f); // notify done
2535     }
2536    
2537     void Instrument::UpdateRegionKeyTable() {
2538 schoenebeck 823 RegionList::iterator iter = pRegions->begin();
2539     RegionList::iterator end = pRegions->end();
2540     for (; iter != end; ++iter) {
2541     gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2542     for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2543     RegionKeyTable[iKey] = pRegion;
2544 schoenebeck 2 }
2545     }
2546     }
2547    
2548     Instrument::~Instrument() {
2549     }
2550    
2551     /**
2552 schoenebeck 809 * Apply Instrument with all its Regions to the respective RIFF chunks.
2553     * You have to call File::Save() to make changes persistent.
2554     *
2555     * Usually there is absolutely no need to call this method explicitly.
2556     * It will be called automatically when File::Save() was called.
2557     *
2558     * @throws gig::Exception if samples cannot be dereferenced
2559     */
2560     void Instrument::UpdateChunks() {
2561     // first update base classes' chunks
2562     DLS::Instrument::UpdateChunks();
2563    
2564     // update Regions' chunks
2565 schoenebeck 823 {
2566     RegionList::iterator iter = pRegions->begin();
2567     RegionList::iterator end = pRegions->end();
2568     for (; iter != end; ++iter)
2569     (*iter)->UpdateChunks();
2570     }
2571 schoenebeck 809
2572     // make sure 'lart' RIFF list chunk exists
2573     RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
2574     if (!lart) lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
2575     // make sure '3ewg' RIFF chunk exists
2576     RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2577     if (!_3ewg) _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2578     // update '3ewg' RIFF chunk
2579     uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2580     memcpy(&pData[0], &EffectSend, 2);
2581     memcpy(&pData[2], &Attenuation, 4);
2582     memcpy(&pData[6], &FineTune, 2);
2583     memcpy(&pData[8], &PitchbendRange, 2);
2584     const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2585     DimensionKeyRange.low << 1;
2586     memcpy(&pData[10], &dimkeystart, 1);
2587     memcpy(&pData[11], &DimensionKeyRange.high, 1);
2588     }
2589    
2590     /**
2591 schoenebeck 2 * Returns the appropriate Region for a triggered note.
2592     *
2593     * @param Key MIDI Key number of triggered note / key (0 - 127)
2594     * @returns pointer adress to the appropriate Region or NULL if there
2595     * there is no Region defined for the given \a Key
2596     */
2597     Region* Instrument::GetRegion(unsigned int Key) {
2598 schoenebeck 823 if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2599 schoenebeck 2 return RegionKeyTable[Key];
2600 schoenebeck 823
2601 schoenebeck 2 /*for (int i = 0; i < Regions; i++) {
2602     if (Key <= pRegions[i]->KeyRange.high &&
2603     Key >= pRegions[i]->KeyRange.low) return pRegions[i];
2604     }
2605     return NULL;*/
2606     }
2607    
2608     /**
2609     * Returns the first Region of the instrument. You have to call this
2610     * method once before you use GetNextRegion().
2611     *
2612     * @returns pointer address to first region or NULL if there is none
2613     * @see GetNextRegion()
2614     */
2615     Region* Instrument::GetFirstRegion() {
2616 schoenebeck 823 if (!pRegions) return NULL;
2617     RegionsIterator = pRegions->begin();
2618     return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2619 schoenebeck 2 }
2620    
2621     /**
2622     * Returns the next Region of the instrument. You have to call
2623     * GetFirstRegion() once before you can use this method. By calling this
2624     * method multiple times it iterates through the available Regions.
2625     *
2626     * @returns pointer address to the next region or NULL if end reached
2627     * @see GetFirstRegion()
2628     */
2629     Region* Instrument::GetNextRegion() {
2630 schoenebeck 823 if (!pRegions) return NULL;
2631     RegionsIterator++;
2632     return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2633 schoenebeck 2 }
2634    
2635 schoenebeck 809 Region* Instrument::AddRegion() {
2636     // create new Region object (and its RIFF chunks)
2637     RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
2638     if (!lrgn) lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2639     RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2640     Region* pNewRegion = new Region(this, rgn);
2641 schoenebeck 823 pRegions->push_back(pNewRegion);
2642     Regions = pRegions->size();
2643 schoenebeck 809 // update Region key table for fast lookup
2644     UpdateRegionKeyTable();
2645     // done
2646     return pNewRegion;
2647     }
2648 schoenebeck 2
2649 schoenebeck 809 void Instrument::DeleteRegion(Region* pRegion) {
2650     if (!pRegions) return;
2651 schoenebeck 823 DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
2652 schoenebeck 809 // update Region key table for fast lookup
2653     UpdateRegionKeyTable();
2654     }
2655 schoenebeck 2
2656 schoenebeck 809
2657    
2658 schoenebeck 2 // *************** File ***************
2659     // *
2660    
2661 schoenebeck 809 File::File() : DLS::File() {
2662     }
2663    
2664 schoenebeck 2 File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
2665     }
2666    
2667 schoenebeck 350 File::~File() {
2668 persson 666 // free extension files
2669     for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)
2670     delete *i;
2671 schoenebeck 350 }
2672    
2673 schoenebeck 515 Sample* File::GetFirstSample(progress_t* pProgress) {
2674     if (!pSamples) LoadSamples(pProgress);
2675 schoenebeck 2 if (!pSamples) return NULL;
2676     SamplesIterator = pSamples->begin();
2677     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2678     }
2679    
2680     Sample* File::GetNextSample() {
2681     if (!pSamples) return NULL;
2682     SamplesIterator++;
2683     return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2684     }
2685    
2686 schoenebeck 809 /** @brief Add a new sample.
2687     *
2688     * This will create a new Sample object for the gig file. You have to
2689     * call Save() to make this persistent to the file.
2690     *
2691     * @returns pointer to new Sample object
2692     */
2693     Sample* File::AddSample() {
2694     if (!pSamples) LoadSamples();
2695     __ensureMandatoryChunksExist();
2696     RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2697     // create new Sample object and its respective 'wave' list chunk
2698     RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2699     Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2700     pSamples->push_back(pSample);
2701     return pSample;
2702     }
2703    
2704     /** @brief Delete a sample.
2705     *
2706     * This will delete the given Sample object from the gig file. You have
2707     * to call Save() to make this persistent to the file.
2708     *
2709     * @param pSample - sample to delete
2710     * @throws gig::Exception if given sample could not be found
2711     */
2712     void File::DeleteSample(Sample* pSample) {
2713 schoenebeck 823 if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2714     SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2715 schoenebeck 809 if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2716     pSamples->erase(iter);
2717     delete pSample;
2718     }
2719    
2720 schoenebeck 823 void File::LoadSamples() {
2721     LoadSamples(NULL);
2722     }
2723    
2724 schoenebeck 515 void File::LoadSamples(progress_t* pProgress) {
2725 schoenebeck 823 if (!pSamples) pSamples = new SampleList;
2726    
2727 persson 666 RIFF::File* file = pRIFF;
2728 schoenebeck 515
2729 persson 666 // just for progress calculation
2730     int iSampleIndex = 0;
2731     int iTotalSamples = WavePoolCount;
2732 schoenebeck 515
2733 persson 666 // check if samples should be loaded from extension files
2734     int lastFileNo = 0;
2735     for (int i = 0 ; i < WavePoolCount ; i++) {
2736     if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
2737     }
2738 schoenebeck 780 String name(pRIFF->GetFileName());
2739     int nameLen = name.length();
2740 persson 666 char suffix[6];
2741 schoenebeck 780 if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
2742 schoenebeck 515
2743 persson 666 for (int fileNo = 0 ; ; ) {
2744     RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
2745     if (wvpl) {
2746     unsigned long wvplFileOffset = wvpl->GetFilePos();
2747     RIFF::List* wave = wvpl->GetFirstSubList();
2748     while (wave) {
2749     if (wave->GetListType() == LIST_TYPE_WAVE) {
2750     // notify current progress
2751     const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2752     __notify_progress(pProgress, subprogress);
2753    
2754     unsigned long waveFileOffset = wave->GetFilePos();
2755     pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
2756    
2757     iSampleIndex++;
2758     }
2759     wave = wvpl->GetNextSubList();
2760 schoenebeck 2 }
2761 persson 666
2762     if (fileNo == lastFileNo) break;
2763    
2764     // open extension file (*.gx01, *.gx02, ...)
2765     fileNo++;
2766     sprintf(suffix, ".gx%02d", fileNo);
2767     name.replace(nameLen, 5, suffix);
2768     file = new RIFF::File(name);
2769     ExtensionFiles.push_back(file);
2770 schoenebeck 823 } else break;
2771 schoenebeck 2 }
2772 persson 666
2773     __notify_progress(pProgress, 1.0); // notify done
2774 schoenebeck 2 }
2775    
2776     Instrument* File::GetFirstInstrument() {
2777     if (!pInstruments) LoadInstruments();
2778     if (!pInstruments) return NULL;
2779     InstrumentsIterator = pInstruments->begin();
2780 schoenebeck 823 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2781 schoenebeck 2 }
2782    
2783     Instrument* File::GetNextInstrument() {
2784     if (!pInstruments) return NULL;
2785     InstrumentsIterator++;
2786 schoenebeck 823 return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2787 schoenebeck 2 }
2788    
2789 schoenebeck 21 /**
2790     * Returns the instrument with the given index.
2791     *
2792 schoenebeck 515 * @param index - number of the sought instrument (0..n)
2793     * @param pProgress - optional: callback function for progress notification
2794 schoenebeck 21 * @returns sought instrument or NULL if there's no such instrument
2795     */
2796 schoenebeck 515 Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
2797     if (!pInstruments) {
2798     // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
2799    
2800     // sample loading subtask
2801     progress_t subprogress;
2802     __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
2803     __notify_progress(&subprogress, 0.0f);
2804     GetFirstSample(&subprogress); // now force all samples to be loaded
2805     __notify_progress(&subprogress, 1.0f);
2806    
2807     // instrument loading subtask
2808     if (pProgress && pProgress->callback) {
2809     subprogress.__range_min = subprogress.__range_max;
2810     subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
2811     }
2812     __notify_progress(&subprogress, 0.0f);
2813     LoadInstruments(&subprogress);
2814     __notify_progress(&subprogress, 1.0f);
2815     }
2816 schoenebeck 21 if (!pInstruments) return NULL;
2817     InstrumentsIterator = pInstruments->begin();
2818     for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
2819 schoenebeck 823 if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
2820 schoenebeck 21 InstrumentsIterator++;
2821     }
2822     return NULL;
2823     }
2824    
2825 schoenebeck 809 /** @brief Add a new instrument definition.
2826     *
2827     * This will create a new Instrument object for the gig file. You have
2828     * to call Save() to make this persistent to the file.
2829     *
2830     * @returns pointer to new Instrument object
2831     */
2832     Instrument* File::AddInstrument() {
2833     if (!pInstruments) LoadInstruments();
2834     __ensureMandatoryChunksExist();
2835     RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2836     RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
2837     Instrument* pInstrument = new Instrument(this, lstInstr);
2838     pInstruments->push_back(pInstrument);
2839     return pInstrument;
2840     }
2841    
2842     /** @brief Delete an instrument.
2843     *
2844     * This will delete the given Instrument object from the gig file. You
2845     * have to call Save() to make this persistent to the file.
2846     *
2847     * @param pInstrument - instrument to delete
2848     * @throws gig::Excption if given instrument could not be found
2849     */
2850     void File::DeleteInstrument(Instrument* pInstrument) {
2851     if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
2852 schoenebeck 823 InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
2853 schoenebeck 809 if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
2854     pInstruments->erase(iter);
2855     delete pInstrument;
2856     }
2857    
2858 schoenebeck 823 void File::LoadInstruments() {
2859     LoadInstruments(NULL);
2860     }
2861    
2862 schoenebeck 515 void File::LoadInstruments(progress_t* pProgress) {
2863 schoenebeck 823 if (!pInstruments) pInstruments = new InstrumentList;
2864 schoenebeck 2 RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2865     if (lstInstruments) {
2866 schoenebeck 515 int iInstrumentIndex = 0;
2867 schoenebeck 2 RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
2868     while (lstInstr) {
2869     if (lstInstr->GetListType() == LIST_TYPE_INS) {
2870 schoenebeck 515 // notify current progress
2871     const float localProgress = (float) iInstrumentIndex / (float) Instruments;
2872     __notify_progress(pProgress, localProgress);
2873    
2874     // divide local progress into subprogress for loading current Instrument
2875     progress_t subprogress;
2876     __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
2877    
2878     pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
2879    
2880     iInstrumentIndex++;
2881 schoenebeck 2 }
2882     lstInstr = lstInstruments->GetNextSubList();
2883     }
2884 schoenebeck 515 __notify_progress(pProgress, 1.0); // notify done
2885 schoenebeck 2 }
2886     }
2887    
2888    
2889    
2890     // *************** Exception ***************
2891     // *
2892    
2893     Exception::Exception(String Message) : DLS::Exception(Message) {
2894     }
2895    
2896     void Exception::PrintMessage() {
2897     std::cout << "gig::Exception: " << Message << std::endl;
2898     }
2899    
2900 schoenebeck 518
2901     // *************** functions ***************
2902     // *
2903    
2904     /**
2905     * Returns the name of this C++ library. This is usually "libgig" of
2906     * course. This call is equivalent to RIFF::libraryName() and
2907     * DLS::libraryName().
2908     */
2909     String libraryName() {
2910     return PACKAGE;
2911     }
2912    
2913     /**
2914     * Returns version of this C++ library. This call is equivalent to
2915     * RIFF::libraryVersion() and DLS::libraryVersion().
2916     */
2917     String libraryVersion() {
2918     return VERSION;
2919     }
2920    
2921 schoenebeck 2 } // namespace gig

  ViewVC Help
Powered by ViewVC