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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2682 by schoenebeck, Mon Dec 29 16:25:51 2014 UTC revision 3203 by schoenebeck, Tue May 23 14:51:01 2017 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2014 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2017 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 24  Line 24 
24  #include "gig.h"  #include "gig.h"
25    
26  #include "helper.h"  #include "helper.h"
27    #include "Serialization.h"
28    
29  #include <algorithm>  #include <algorithm>
30  #include <math.h>  #include <math.h>
31  #include <iostream>  #include <iostream>
32  #include <assert.h>  #include <assert.h>
33    
34    /// libgig's current file format version (for extending the original Giga file
35    /// format with libgig's own custom data / custom features).
36    #define GIG_FILE_EXT_VERSION    2
37    
38  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
39  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
40  /// the biggest sample piece expected to be read by the sampler engine,  /// the biggest sample piece expected to be read by the sampler engine,
# Line 51  Line 56 
56  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
57  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
58    
59    #define SRLZ(member) \
60        archive->serializeMember(*this, member, #member);
61    
62  namespace gig {  namespace gig {
63    
64  // *************** Internal functions for sample decompression ***************  // *************** Internal functions for sample decompression ***************
# Line 91  namespace { Line 99  namespace {
99      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
100                        int srcStep, int dstStep,                        int srcStep, int dstStep,
101                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
102                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
103                        unsigned long copysamples)                        file_offset_t copysamples)
104      {      {
105          switch (compressionmode) {          switch (compressionmode) {
106              case 0: // 16 bit uncompressed              case 0: // 16 bit uncompressed
# Line 128  namespace { Line 136  namespace {
136    
137      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
138                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
139                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
140                        unsigned long copysamples, int truncatedBits)                        file_offset_t copysamples, int truncatedBits)
141      {      {
142          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
143    
# Line 265  namespace { Line 273  namespace {
273       * steps.       * steps.
274       *       *
275       * Once the whole data was processed by __calculateCRC(), one should       * Once the whole data was processed by __calculateCRC(), one should
276       * call __encodeCRC() to get the final CRC result.       * call __finalizeCRC() to get the final CRC result.
277       *       *
278       * @param buf     - pointer to data the CRC shall be calculated of       * @param buf     - pointer to data the CRC shall be calculated of
279       * @param bufSize - size of the data to be processed       * @param bufSize - size of the data to be processed
280       * @param crc     - variable the CRC sum shall be stored to       * @param crc     - variable the CRC sum shall be stored to
281       */       */
282      static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {      static void __calculateCRC(unsigned char* buf, size_t bufSize, uint32_t& crc) {
283          for (int i = 0 ; i < bufSize ; i++) {          for (size_t i = 0 ; i < bufSize ; i++) {
284              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
285          }          }
286      }      }
# Line 282  namespace { Line 290  namespace {
290       *       *
291       * @param crc - variable previously passed to __calculateCRC()       * @param crc - variable previously passed to __calculateCRC()
292       */       */
293      inline static uint32_t __encodeCRC(const uint32_t& crc) {      inline static void __finalizeCRC(uint32_t& crc) {
294          return crc ^ 0xffffffff;          crc ^= 0xffffffff;
295      }      }
296    
297    
# Line 311  namespace { Line 319  namespace {
319    
320    
321    
322    // *************** leverage_ctrl_t ***************
323    // *
324    
325        void leverage_ctrl_t::serialize(Serialization::Archive* archive) {
326            SRLZ(type);
327            SRLZ(controller_number);
328        }
329    
330    
331    
332    // *************** crossfade_t ***************
333    // *
334    
335        void crossfade_t::serialize(Serialization::Archive* archive) {
336            SRLZ(in_start);
337            SRLZ(in_end);
338            SRLZ(out_start);
339            SRLZ(out_end);
340        }
341    
342    
343    
344  // *************** Sample ***************  // *************** Sample ***************
345  // *  // *
346    
347      unsigned int Sample::Instances = 0;      size_t       Sample::Instances = 0;
348      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
349    
350      /** @brief Constructor.      /** @brief Constructor.
# Line 334  namespace { Line 364  namespace {
364       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
365       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
366       *                         is located, 0 otherwise       *                         is located, 0 otherwise
367         * @param index          - wave pool index of sample (may be -1 on new sample)
368       */       */
369      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo, int index)
370            : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
371        {
372          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
373              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
374              { 0, 0 }              { 0, 0 }
# Line 345  namespace { Line 378  namespace {
378          FileNo = fileNo;          FileNo = fileNo;
379    
380          __resetCRC(crc);          __resetCRC(crc);
381            // if this is not a new sample, try to get the sample's already existing
382            // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
383            // checksum of the time when the sample was consciously modified by the
384            // user for the last time (by calling Sample::Write() that is).
385            if (index >= 0) { // not a new file ...
386                try {
387                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
388                    this->crc = crc;
389                } catch (...) {}
390            }
391    
392          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
393          if (pCk3gix) {          if (pCk3gix) {
# Line 477  namespace { Line 520  namespace {
520          const int iReadAtOnce = 32*1024;          const int iReadAtOnce = 32*1024;
521          char* buf = new char[iReadAtOnce * orig->FrameSize];          char* buf = new char[iReadAtOnce * orig->FrameSize];
522          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
523          unsigned long restorePos = pOrig->GetPos();          file_offset_t restorePos = pOrig->GetPos();
524          pOrig->SetPos(0);          pOrig->SetPos(0);
525          SetPos(0);          SetPos(0);
526          for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;          for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
527                             n = pOrig->Read(buf, iReadAtOnce))                             n = pOrig->Read(buf, iReadAtOnce))
528          {          {
529              Write(buf, n);              Write(buf, n);
# Line 565  namespace { Line 608  namespace {
608      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
609          //TODO: we have to add some more scans here (e.g. determine compression rate)          //TODO: we have to add some more scans here (e.g. determine compression rate)
610          this->SamplesTotal = 0;          this->SamplesTotal = 0;
611          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
612    
613          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
614          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 581  namespace { Line 624  namespace {
624                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
625                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
626                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
627                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
628    
629                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
630                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 600  namespace { Line 643  namespace {
643    
644                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
645                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
646                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
647    
648                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
649                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 616  namespace { Line 659  namespace {
659    
660          // Build the frames table (which is used for fast resolving of a frame's chunk offset)          // Build the frames table (which is used for fast resolving of a frame's chunk offset)
661          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
662          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
663          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
664          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
665          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
666              FrameTable[i] = *iter;              FrameTable[i] = *iter;
667          }          }
# Line 659  namespace { Line 702  namespace {
702       *                      the cached sample data in bytes       *                      the cached sample data in bytes
703       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
704       */       */
705      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
706          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
707      }      }
708    
# Line 718  namespace { Line 761  namespace {
761       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
762       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
763       */       */
764      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
765          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
766          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
767          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
768          SetPos(0); // reset read position to begin of sample          SetPos(0); // reset read position to begin of sample
769          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
770          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
# Line 785  namespace { Line 828  namespace {
828       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
829       * other formats will fail!       * other formats will fail!
830       *       *
831       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
832       *                   greater than zero)       *                  greater than zero)
833       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
834       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
835       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
836       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
837       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
838       */       */
839      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
840          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
841          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
842      }      }
843    
844      /**      /**
# Line 819  namespace { Line 862  namespace {
862       * @returns            the new sample position       * @returns            the new sample position
863       * @see                Read()       * @see                Read()
864       */       */
865      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
866          if (Compressed) {          if (Compressed) {
867              switch (Whence) {              switch (Whence) {
868                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 837  namespace { Line 880  namespace {
880              }              }
881              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
882    
883              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
884              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
885              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame
886              return this->SamplePos;              return this->SamplePos;
887          }          }
888          else { // not compressed          else { // not compressed
889              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
890              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
891              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
892                                              : result / this->FrameSize;                                              : result / this->FrameSize;
893          }          }
# Line 853  namespace { Line 896  namespace {
896      /**      /**
897       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
898       */       */
899      unsigned long Sample::GetPos() const {      file_offset_t Sample::GetPos() const {
900          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
901          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
902      }      }
# Line 892  namespace { Line 935  namespace {
935       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
936       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
937       */       */
938      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,      file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
939                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
940          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
941          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
942    
943          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 932  namespace { Line 975  namespace {
975                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
976                                  // backward playback                                  // backward playback
977    
978                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
979                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
980                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
981                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
982    
983                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
984    
# Line 983  namespace { Line 1026  namespace {
1026                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1027                          // backward playback                          // backward playback
1028    
1029                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
1030                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
1031                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)                          file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
1032                                                                                    : samplestoread;                                                                                    : samplestoread;
1033                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1034    
1035                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1036    
# Line 1067  namespace { Line 1110  namespace {
1110       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1111       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1112       */       */
1113      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1114          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1115          if (!Compressed) {          if (!Compressed) {
1116              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 1082  namespace { Line 1125  namespace {
1125          else {          else {
1126              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1127              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1128              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1129                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1130                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1131                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1105  namespace { Line 1148  namespace {
1148              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1149    
1150              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1151                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1152                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1153    
1154                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1155    
# Line 1256  namespace { Line 1299  namespace {
1299       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1300       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1301       */       */
1302      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1303          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1304    
1305          // if this is the first write in this sample, reset the          // if this is the first write in this sample, reset the
# Line 1265  namespace { Line 1308  namespace {
1308              __resetCRC(crc);              __resetCRC(crc);
1309          }          }
1310          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1311          unsigned long res;          file_offset_t res;
1312          if (BitDepth == 24) {          if (BitDepth == 24) {
1313              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1314          } else { // 16 bit          } else { // 16 bit
# Line 1277  namespace { Line 1320  namespace {
1320          // if this is the last write, update the checksum chunk in the          // if this is the last write, update the checksum chunk in the
1321          // file          // file
1322          if (pCkData->GetPos() == pCkData->GetSize()) {          if (pCkData->GetPos() == pCkData->GetSize()) {
1323                __finalizeCRC(crc);
1324              File* pFile = static_cast<File*>(GetParent());              File* pFile = static_cast<File*>(GetParent());
1325              pFile->SetSampleChecksum(this, __encodeCRC(crc));              pFile->SetSampleChecksum(this, crc);
1326          }          }
1327          return res;          return res;
1328      }      }
# Line 1299  namespace { Line 1343  namespace {
1343       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1344       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1345       */       */
1346      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1347          buffer_t result;          buffer_t result;
1348          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1349                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1350          result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);          result.Size              = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1351          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1352          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1353          return result;          return result;
# Line 1337  namespace { Line 1381  namespace {
1381          return pGroup;          return pGroup;
1382      }      }
1383    
1384        /**
1385         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1386         * time when this sample's wave form data was modified for the last time
1387         * by calling Write(). This checksum only covers the raw wave form data,
1388         * not any meta informations like i.e. bit depth or loop points. Since
1389         * this method just returns the checksum stored for this sample i.e. when
1390         * the gig file was loaded, this method returns immediately. So it does no
1391         * recalcuation of the checksum with the currently available sample wave
1392         * form data.
1393         *
1394         * @see VerifyWaveData()
1395         */
1396        uint32_t Sample::GetWaveDataCRC32Checksum() {
1397            return crc;
1398        }
1399    
1400        /**
1401         * Checks the integrity of this sample's raw audio wave data. Whenever a
1402         * Sample's raw wave data is intentionally modified (i.e. by calling
1403         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1404         * is calculated and stored/updated for this sample, along to the sample's
1405         * meta informations.
1406         *
1407         * Now by calling this method the current raw audio wave data is checked
1408         * against the already stored CRC32 check sum in order to check whether the
1409         * sample data had been damaged unintentionally for some reason. Since by
1410         * calling this method always the entire raw audio wave data has to be
1411         * read, verifying all samples this way may take a long time accordingly.
1412         * And that's also the reason why the sample integrity is not checked by
1413         * default whenever a gig file is loaded. So this method must be called
1414         * explicitly to fulfill this task.
1415         *
1416         * @param pActually - (optional) if provided, will be set to the actually
1417         *                    calculated checksum of the current raw wave form data,
1418         *                    you can get the expected checksum instead by calling
1419         *                    GetWaveDataCRC32Checksum()
1420         * @returns true if sample is OK or false if the sample is damaged
1421         * @throws Exception if no checksum had been stored to disk for this
1422         *         sample yet, or on I/O issues
1423         * @see GetWaveDataCRC32Checksum()
1424         */
1425        bool Sample::VerifyWaveData(uint32_t* pActually) {
1426            //File* pFile = static_cast<File*>(GetParent());
1427            uint32_t crc = CalculateWaveDataChecksum();
1428            if (pActually) *pActually = crc;
1429            return crc == this->crc;
1430        }
1431    
1432        uint32_t Sample::CalculateWaveDataChecksum() {
1433            const size_t sz = 20*1024; // 20kB buffer size
1434            std::vector<uint8_t> buffer(sz);
1435            buffer.resize(sz);
1436    
1437            const size_t n = sz / FrameSize;
1438            SetPos(0);
1439            uint32_t crc = 0;
1440            __resetCRC(crc);
1441            while (true) {
1442                file_offset_t nRead = Read(&buffer[0], n);
1443                if (nRead <= 0) break;
1444                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1445            }
1446            __finalizeCRC(crc);
1447            return crc;
1448        }
1449    
1450      Sample::~Sample() {      Sample::~Sample() {
1451          Instances--;          Instances--;
1452          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1353  namespace { Line 1463  namespace {
1463  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1464  // *  // *
1465    
1466      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1467      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1468    
1469      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1547  namespace { Line 1657  namespace {
1657              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1658              EG2Decay1                       = 0.005;              EG2Decay1                       = 0.005;
1659              EG2Sustain                      = 1000;              EG2Sustain                      = 1000;
1660              EG2Release                      = 0.3;              EG2Release                      = 60;
1661              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1662              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1663              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
# Line 1706  namespace { Line 1816  namespace {
1816          }          }
1817      }      }
1818    
1819        void DimensionRegion::serialize(Serialization::Archive* archive) {
1820            // in case this class will become backward incompatible one day,
1821            // then set a version and minimum version for this class like:
1822            //archive->setVersion(*this, 2);
1823            //archive->setMinVersion(*this, 1);
1824    
1825            SRLZ(VelocityUpperLimit);
1826            SRLZ(EG1PreAttack);
1827            SRLZ(EG1Attack);
1828            SRLZ(EG1Decay1);
1829            SRLZ(EG1Decay2);
1830            SRLZ(EG1InfiniteSustain);
1831            SRLZ(EG1Sustain);
1832            SRLZ(EG1Release);
1833            SRLZ(EG1Hold);
1834            SRLZ(EG1Controller);
1835            SRLZ(EG1ControllerInvert);
1836            SRLZ(EG1ControllerAttackInfluence);
1837            SRLZ(EG1ControllerDecayInfluence);
1838            SRLZ(EG1ControllerReleaseInfluence);
1839            SRLZ(LFO1Frequency);
1840            SRLZ(LFO1InternalDepth);
1841            SRLZ(LFO1ControlDepth);
1842            SRLZ(LFO1Controller);
1843            SRLZ(LFO1FlipPhase);
1844            SRLZ(LFO1Sync);
1845            SRLZ(EG2PreAttack);
1846            SRLZ(EG2Attack);
1847            SRLZ(EG2Decay1);
1848            SRLZ(EG2Decay2);
1849            SRLZ(EG2InfiniteSustain);
1850            SRLZ(EG2Sustain);
1851            SRLZ(EG2Release);
1852            SRLZ(EG2Controller);
1853            SRLZ(EG2ControllerInvert);
1854            SRLZ(EG2ControllerAttackInfluence);
1855            SRLZ(EG2ControllerDecayInfluence);
1856            SRLZ(EG2ControllerReleaseInfluence);
1857            SRLZ(LFO2Frequency);
1858            SRLZ(LFO2InternalDepth);
1859            SRLZ(LFO2ControlDepth);
1860            SRLZ(LFO2Controller);
1861            SRLZ(LFO2FlipPhase);
1862            SRLZ(LFO2Sync);
1863            SRLZ(EG3Attack);
1864            SRLZ(EG3Depth);
1865            SRLZ(LFO3Frequency);
1866            SRLZ(LFO3InternalDepth);
1867            SRLZ(LFO3ControlDepth);
1868            SRLZ(LFO3Controller);
1869            SRLZ(LFO3Sync);
1870            SRLZ(VCFEnabled);
1871            SRLZ(VCFType);
1872            SRLZ(VCFCutoffController);
1873            SRLZ(VCFCutoffControllerInvert);
1874            SRLZ(VCFCutoff);
1875            SRLZ(VCFVelocityCurve);
1876            SRLZ(VCFVelocityScale);
1877            SRLZ(VCFVelocityDynamicRange);
1878            SRLZ(VCFResonance);
1879            SRLZ(VCFResonanceDynamic);
1880            SRLZ(VCFResonanceController);
1881            SRLZ(VCFKeyboardTracking);
1882            SRLZ(VCFKeyboardTrackingBreakpoint);
1883            SRLZ(VelocityResponseCurve);
1884            SRLZ(VelocityResponseDepth);
1885            SRLZ(VelocityResponseCurveScaling);
1886            SRLZ(ReleaseVelocityResponseCurve);
1887            SRLZ(ReleaseVelocityResponseDepth);
1888            SRLZ(ReleaseTriggerDecay);
1889            SRLZ(Crossfade);
1890            SRLZ(PitchTrack);
1891            SRLZ(DimensionBypass);
1892            SRLZ(Pan);
1893            SRLZ(SelfMask);
1894            SRLZ(AttenuationController);
1895            SRLZ(InvertAttenuationController);
1896            SRLZ(AttenuationControllerThreshold);
1897            SRLZ(ChannelOffset);
1898            SRLZ(SustainDefeat);
1899            SRLZ(MSDecode);
1900            //SRLZ(SampleStartOffset);
1901            SRLZ(SampleAttenuation);
1902    
1903            // derived attributes from DLS::Sampler
1904            SRLZ(FineTune);
1905            SRLZ(Gain);
1906        }
1907    
1908      /**      /**
1909       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
1910       * which depends on this value.       * which depends on this value.
# Line 1746  namespace { Line 1945  namespace {
1945    
1946          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1947    
1948          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1949          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1950    
1951          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 2420  namespace { Line 2619  namespace {
2619    
2620              // unknown controller type              // unknown controller type
2621              default:              default:
2622                  throw gig::Exception("Unknown leverage controller type.");                  decodedcontroller.type = leverage_ctrl_t::type_none;
2623                    decodedcontroller.controller_number = 0;
2624                    printf("Warning: Unknown leverage controller type (0x%x).\n", EncodedController);
2625                    break;
2626          }          }
2627          return decodedcontroller;          return decodedcontroller;
2628      }      }
# Line 3102  namespace { Line 3304  namespace {
3304          int step = 1;          int step = 1;
3305          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3306          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3307    
3308          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3309          int dim[8] = { 0 };          int dim[8] = { 0 };
3310          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3311                const int end = i + step * pDimensionDefinitions[veldim].zones;
3312    
3313                // create a velocity table for all cases where the velocity zone is zero
3314              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3315                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3316                  // create the velocity table                  // create the velocity table
# Line 3138  namespace { Line 3341  namespace {
3341                  }                  }
3342              }              }
3343    
3344                // jump to the next case where the velocity zone is zero
3345              int j;              int j;
3346              int shift = 0;              int shift = 0;
3347              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 3712  namespace { Line 3916  namespace {
3916      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3917          uint8_t bits;          uint8_t bits;
3918          int veldim = -1;          int veldim = -1;
3919          int velbitpos;          int velbitpos = 0;
3920          int bitpos = 0;          int bitpos = 0;
3921          int dimregidx = 0;          int dimregidx = 0;
3922          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 3761  namespace { Line 3965  namespace {
3965      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3966          uint8_t bits;          uint8_t bits;
3967          int veldim = -1;          int veldim = -1;
3968          int velbitpos;          int velbitpos = 0;
3969          int bitpos = 0;          int bitpos = 0;
3970          int dimregidx = 0;          int dimregidx = 0;
3971          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 3846  namespace { Line 4050  namespace {
4050          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
4051          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
4052          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
4053          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
4054          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
4055          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
4056          while (sample) {              uint64_t soughtoffset =
4057              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
4058                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
4059              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
4060                while (sample) {
4061                    if (sample->ullWavePoolOffset == soughtoffset)
4062                        return static_cast<gig::Sample*>(sample);
4063                    sample = file->GetNextSample();
4064                }
4065            } else {
4066                // use extension files and 32 bit wave pool offsets
4067                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
4068                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
4069                Sample* sample = file->GetFirstSample(pProgress);
4070                while (sample) {
4071                    if (sample->ullWavePoolOffset == soughtoffset &&
4072                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
4073                    sample = file->GetNextSample();
4074                }
4075          }          }
4076          return NULL;          return NULL;
4077      }      }
# Line 4095  namespace { Line 4314  namespace {
4314              // to handle potential future extensions of the header              // to handle potential future extensions of the header
4315              ckScri->SetPos(sizeof(int32_t) + headerSize);              ckScri->SetPos(sizeof(int32_t) + headerSize);
4316              // read actual script data              // read actual script data
4317              uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();              uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4318              data.resize(scriptSize);              data.resize(scriptSize);
4319              for (int i = 0; i < scriptSize; ++i)              for (int i = 0; i < scriptSize; ++i)
4320                  data[i] = ckScri->ReadUint8();                  data[i] = ckScri->ReadUint8();
# Line 4146  namespace { Line 4365  namespace {
4365          // recalculate CRC32 check sum          // recalculate CRC32 check sum
4366          __resetCRC(crc);          __resetCRC(crc);
4367          __calculateCRC(&data[0], data.size(), crc);          __calculateCRC(&data[0], data.size(), crc);
4368          __encodeCRC(crc);          __finalizeCRC(crc);
4369          // make sure chunk exists and has the required size          // make sure chunk exists and has the required size
4370          const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();          const file_offset_t chunkSize = (file_offset_t) 7*sizeof(int32_t) + Name.size() + data.size();
4371          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4372          else pChunk->Resize(chunkSize);          else pChunk->Resize(chunkSize);
4373          // fill the chunk data to be written to disk          // fill the chunk data to be written to disk
4374          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4375          int pos = 0;          int pos = 0;
4376          store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size          store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size())); // total header size
4377          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4378          store32(&pData[pos], Compression);          store32(&pData[pos], Compression);
4379          pos += sizeof(int32_t);          pos += sizeof(int32_t);
# Line 4166  namespace { Line 4385  namespace {
4385          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4386          store32(&pData[pos], crc);          store32(&pData[pos], crc);
4387          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4388          store32(&pData[pos], Name.size());          store32(&pData[pos], (uint32_t) Name.size());
4389          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4390          for (int i = 0; i < Name.size(); ++i, ++pos)          for (int i = 0; i < Name.size(); ++i, ++pos)
4391              pData[pos] = Name[i];              pData[pos] = Name[i];
# Line 4181  namespace { Line 4400  namespace {
4400       * @param pGroup - script's new group       * @param pGroup - script's new group
4401       */       */
4402      void Script::SetGroup(ScriptGroup* pGroup) {      void Script::SetGroup(ScriptGroup* pGroup) {
4403          if (this->pGroup = pGroup) return;          if (this->pGroup == pGroup) return;
4404          if (pChunk)          if (pChunk)
4405              pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);              pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4406          this->pGroup = pGroup;          this->pGroup = pGroup;
# Line 4197  namespace { Line 4416  namespace {
4416          return pGroup;          return pGroup;
4417      }      }
4418    
4419        /**
4420         * Make a (semi) deep copy of the Script object given by @a orig
4421         * and assign it to this object. Note: the ScriptGroup this Script
4422         * object belongs to remains untouched by this call.
4423         *
4424         * @param orig - original Script object to be copied from
4425         */
4426        void Script::CopyAssign(const Script* orig) {
4427            Name        = orig->Name;
4428            Compression = orig->Compression;
4429            Encoding    = orig->Encoding;
4430            Language    = orig->Language;
4431            Bypass      = orig->Bypass;
4432            data        = orig->data;
4433        }
4434    
4435      void Script::RemoveAllScriptReferences() {      void Script::RemoveAllScriptReferences() {
4436          File* pFile = pGroup->pFile;          File* pFile = pGroup->pFile;
4437          for (int i = 0; pFile->GetInstrument(i); ++i) {          for (int i = 0; pFile->GetInstrument(i); ++i) {
# Line 4343  namespace { Line 4578  namespace {
4578          EffectSend = 0;          EffectSend = 0;
4579          Attenuation = 0;          Attenuation = 0;
4580          FineTune = 0;          FineTune = 0;
4581          PitchbendRange = 0;          PitchbendRange = 2;
4582          PianoReleaseMode = false;          PianoReleaseMode = false;
4583          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4584          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
# Line 4518  namespace { Line 4753  namespace {
4753    
4754             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4755             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4756             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4757             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4758             const int slotSize  = 2 * sizeof(uint32_t);             const int slotSize  = 2 * sizeof(uint32_t);
4759             const int totalChunkSize = headerSize + slotCount * slotSize;             const int totalChunkSize = headerSize + slotCount * slotSize;
# Line 4554  namespace { Line 4789  namespace {
4789         if (pScriptRefs && pScriptRefs->size() > 0) {         if (pScriptRefs && pScriptRefs->size() > 0) {
4790             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4791             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4792             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4793             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4794             ckSCSL->SetPos(headerSize);             ckSCSL->SetPos(headerSize);
4795             for (int i = 0; i < slotCount; ++i) {             for (int i = 0; i < slotCount; ++i) {
4796                 uint32_t fileOffset =                 uint32_t fileOffset = uint32_t(
4797                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4798                      (*pScriptRefs)[i].script->pChunk->GetPos() -                      (*pScriptRefs)[i].script->pChunk->GetPos() -
4799                      CHUNK_HEADER_SIZE;                      CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4800                   );
4801                 ckSCSL->WriteUint32(&fileOffset);                 ckSCSL->WriteUint32(&fileOffset);
4802                 // jump over flags entry (containing the bypass flag)                 // jump over flags entry (containing the bypass flag)
4803                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
# Line 4621  namespace { Line 4857  namespace {
4857          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4858          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4859          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4860          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4861          // update Region key table for fast lookup          // update Region key table for fast lookup
4862          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4863          // done          // done
# Line 4636  namespace { Line 4872  namespace {
4872      }      }
4873    
4874      /**      /**
4875         * Move this instrument at the position before @arg dst.
4876         *
4877         * This method can be used to reorder the sequence of instruments in a
4878         * .gig file. This might be helpful especially on large .gig files which
4879         * contain a large number of instruments within the same .gig file. So
4880         * grouping such instruments to similar ones, can help to keep track of them
4881         * when working with such complex .gig files.
4882         *
4883         * When calling this method, this instrument will be removed from in its
4884         * current position in the instruments list and moved to the requested
4885         * target position provided by @param dst. You may also pass NULL as
4886         * argument to this method, in that case this intrument will be moved to the
4887         * very end of the .gig file's instrument list.
4888         *
4889         * You have to call Save() to make the order change persistent to the .gig
4890         * file.
4891         *
4892         * Currently this method is limited to moving the instrument within the same
4893         * .gig file. Trying to move it to another .gig file by calling this method
4894         * will throw an exception.
4895         *
4896         * @param dst - destination instrument at which this instrument will be
4897         *              moved to, or pass NULL for moving to end of list
4898         * @throw gig::Exception if this instrument and target instrument are not
4899         *                       part of the same file
4900         */
4901        void Instrument::MoveTo(Instrument* dst) {
4902            if (dst && GetParent() != dst->GetParent())
4903                throw Exception(
4904                    "gig::Instrument::MoveTo() can only be used for moving within "
4905                    "the same gig file."
4906                );
4907    
4908            File* pFile = (File*) GetParent();
4909    
4910            // move this instrument within the instrument list
4911            {
4912                File::InstrumentList& list = *pFile->pInstruments;
4913    
4914                File::InstrumentList::iterator itFrom =
4915                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4916    
4917                File::InstrumentList::iterator itTo =
4918                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4919    
4920                list.splice(itTo, list, itFrom);
4921            }
4922    
4923            // move the instrument's actual list RIFF chunk appropriately
4924            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4925            lstCkInstruments->MoveSubChunk(
4926                this->pCkInstrument,
4927                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4928            );
4929        }
4930    
4931        /**
4932       * Returns a MIDI rule of the instrument.       * Returns a MIDI rule of the instrument.
4933       *       *
4934       * The list of MIDI rules, at least in gig v3, always contains at       * The list of MIDI rules, at least in gig v3, always contains at
# Line 4710  namespace { Line 5003  namespace {
5003                  for (uint s = 0; group->GetScript(s); ++s) {                  for (uint s = 0; group->GetScript(s); ++s) {
5004                      Script* script = group->GetScript(s);                      Script* script = group->GetScript(s);
5005                      if (script->pChunk) {                      if (script->pChunk) {
5006                          uint32_t offset = script->pChunk->GetFilePos() -                          uint32_t offset = uint32_t(
5007                                            script->pChunk->GetPos() -                              script->pChunk->GetFilePos() -
5008                                            CHUNK_HEADER_SIZE;                              script->pChunk->GetPos() -
5009                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
5010                            );
5011                          if (offset == soughtOffset)                          if (offset == soughtOffset)
5012                          {                          {
5013                              _ScriptPooolRef ref;                              _ScriptPooolRef ref;
# Line 4837  namespace { Line 5132  namespace {
5132       */       */
5133      void Instrument::RemoveScript(Script* pScript) {      void Instrument::RemoveScript(Script* pScript) {
5134          LoadScripts();          LoadScripts();
5135          for (int i = pScriptRefs->size() - 1; i >= 0; --i) {          for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5136              if ((*pScriptRefs)[i].script == pScript) {              if ((*pScriptRefs)[i].script == pScript) {
5137                  pScriptRefs->erase( pScriptRefs->begin() + i );                  pScriptRefs->erase( pScriptRefs->begin() + i );
5138              }              }
# Line 4859  namespace { Line 5154  namespace {
5154       * gigedit.       * gigedit.
5155       */       */
5156      uint Instrument::ScriptSlotCount() const {      uint Instrument::ScriptSlotCount() const {
5157          return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();          return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5158      }      }
5159    
5160      /** @brief Whether script execution shall be skipped.      /** @brief Whether script execution shall be skipped.
# Line 5275  namespace { Line 5570  namespace {
5570          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5571    
5572          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5573            // (only for old gig files < 2 GB)
5574          int lastFileNo = 0;          int lastFileNo = 0;
5575          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5576              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5577                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5578                }
5579          }          }
5580          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5581          int nameLen = name.length();          int nameLen = (int) name.length();
5582          char suffix[6];          char suffix[6];
5583          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5584    
5585          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5586              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5587              if (wvpl) {              if (wvpl) {
5588                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5589                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5590                  while (wave) {                  while (wave) {
5591                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 5295  namespace { Line 5593  namespace {
5593                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5594                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5595    
5596                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5597                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5598    
5599                          iSampleIndex++;                          iSampleIndex++;
5600                      }                      }
# Line 5449  namespace { Line 5747  namespace {
5747              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5748              mSamples[pFile->GetSample(i)] = s;              mSamples[pFile->GetSample(i)] = s;
5749          }          }
5750            
5751            // clone script groups and their scripts
5752            for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
5753                ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
5754                ScriptGroup* dg = AddScriptGroup();
5755                dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
5756                for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
5757                    Script* ss = sg->GetScript(iScript);
5758                    Script* ds = dg->AddScript();
5759                    ds->CopyAssign(ss);
5760                }
5761            }
5762    
5763          //BUG: For some reason this method only works with this additional          //BUG: For some reason this method only works with this additional
5764          //     Save() call in between here.          //     Save() call in between here.
5765          //          //
# Line 5534  namespace { Line 5844  namespace {
5844          if (!_3crc) return;          if (!_3crc) return;
5845    
5846          // get the index of the sample          // get the index of the sample
5847          int iWaveIndex = -1;          int iWaveIndex = GetWaveTableIndexOf(pSample);
         File::SampleList::iterator iter = pSamples->begin();  
         File::SampleList::iterator end  = pSamples->end();  
         for (int index = 0; iter != end; ++iter, ++index) {  
             if (*iter == pSample) {  
                 iWaveIndex = index;  
                 break;  
             }  
         }  
5848          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5849    
5850          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5851          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5852          uint32_t tmp = 1;          uint32_t one = 1;
5853          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5854          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5855      }      }
5856    
5857        uint32_t File::GetSampleChecksum(Sample* pSample) {
5858            // get the index of the sample
5859            int iWaveIndex = GetWaveTableIndexOf(pSample);
5860            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5861    
5862            return GetSampleChecksumByIndex(iWaveIndex);
5863        }
5864    
5865        uint32_t File::GetSampleChecksumByIndex(int index) {
5866            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5867    
5868            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5869            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5870            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5871            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5872    
5873            // read the CRC-32 checksum directly from disk
5874            size_t pos = index * 8;
5875            if (pos + 8 > _3crc->GetNewSize())
5876                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5877    
5878            uint32_t one = load32(&pData[pos]); // always 1
5879            if (one != 1)
5880                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5881    
5882            return load32(&pData[pos+4]);
5883        }
5884    
5885        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5886            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5887            File::SampleList::iterator iter = pSamples->begin();
5888            File::SampleList::iterator end  = pSamples->end();
5889            for (int index = 0; iter != end; ++iter, ++index)
5890                if (*iter == pSample)
5891                    return index;
5892            return -1;
5893        }
5894    
5895        /**
5896         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5897         * the CRC32 check sums of all samples' raw wave data.
5898         *
5899         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5900         */
5901        bool File::VerifySampleChecksumTable() {
5902            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5903            if (!_3crc) return false;
5904            if (_3crc->GetNewSize() <= 0) return false;
5905            if (_3crc->GetNewSize() % 8) return false;
5906            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5907            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5908    
5909            const file_offset_t n = _3crc->GetNewSize() / 8;
5910    
5911            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5912            if (!pData) return false;
5913    
5914            for (file_offset_t i = 0; i < n; ++i) {
5915                uint32_t one = pData[i*2];
5916                if (one != 1) return false;
5917            }
5918    
5919            return true;
5920        }
5921    
5922        /**
5923         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5924         * file's checksum table with those new checksums. This might usually
5925         * just be necessary if the checksum table was damaged.
5926         *
5927         * @e IMPORTANT: The current implementation of this method only works
5928         * with files that have not been modified since it was loaded, because
5929         * it expects that no externally caused file structure changes are
5930         * required!
5931         *
5932         * Due to the expectation above, this method is currently protected
5933         * and actually only used by the command line tool "gigdump" yet.
5934         *
5935         * @returns true if Save() is required to be called after this call,
5936         *          false if no further action is required
5937         */
5938        bool File::RebuildSampleChecksumTable() {
5939            // make sure sample chunks were scanned
5940            if (!pSamples) GetFirstSample();
5941    
5942            bool bRequiresSave = false;
5943    
5944            // make sure "3CRC" chunk exists with required size
5945            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5946            if (!_3crc) {
5947                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5948                // the order of einf and 3crc is not the same in v2 and v3
5949                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5950                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5951                bRequiresSave = true;
5952            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5953                _3crc->Resize(pSamples->size() * 8);
5954                bRequiresSave = true;
5955            }
5956    
5957            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5958                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5959                {
5960                    File::SampleList::iterator iter = pSamples->begin();
5961                    File::SampleList::iterator end  = pSamples->end();
5962                    for (; iter != end; ++iter) {
5963                        gig::Sample* pSample = (gig::Sample*) *iter;
5964                        int index = GetWaveTableIndexOf(pSample);
5965                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5966                        pData[index*2]   = 1; // always 1
5967                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5968                    }
5969                }
5970            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5971                // make sure file is in write mode
5972                pRIFF->SetMode(RIFF::stream_mode_read_write);
5973                {
5974                    File::SampleList::iterator iter = pSamples->begin();
5975                    File::SampleList::iterator end  = pSamples->end();
5976                    for (; iter != end; ++iter) {
5977                        gig::Sample* pSample = (gig::Sample*) *iter;
5978                        int index = GetWaveTableIndexOf(pSample);
5979                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5980                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5981                        SetSampleChecksum(pSample, pSample->crc);
5982                    }
5983                }
5984            }
5985    
5986            return bRequiresSave;
5987        }
5988    
5989      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5990          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5991          // there must always be at least one group          // there must always be at least one group
# Line 5780  namespace { Line 6214  namespace {
6214      void File::UpdateChunks(progress_t* pProgress) {      void File::UpdateChunks(progress_t* pProgress) {
6215          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6216    
         b64BitWavePoolOffsets = pVersion && pVersion->major == 3;  
   
6217          // update own gig format extension chunks          // update own gig format extension chunks
6218          // (not part of the GigaStudio 4 format)          // (not part of the GigaStudio 4 format)
6219          //          RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6220            if (!lst3LS) {
6221                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6222            }
6223            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6224            // location of <3LS > is irrelevant, however it should be located
6225            // before  the actual wave data
6226            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6227            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6228    
6229          // This must be performed before writing the chunks for instruments,          // This must be performed before writing the chunks for instruments,
6230          // because the instruments' script slots will write the file offsets          // because the instruments' script slots will write the file offsets
6231          // of the respective instrument script chunk as reference.          // of the respective instrument script chunk as reference.
6232          if (pScriptGroups) {          if (pScriptGroups) {
6233              RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);              // Update instrument script (group) chunks.
6234              if (pScriptGroups->empty()) {              for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6235                  if (lst3LS) pRIFF->DeleteSubChunk(lst3LS);                   it != pScriptGroups->end(); ++it)
6236              } else {              {
6237                  if (!lst3LS) lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);                  (*it)->UpdateChunks(pProgress);
   
                 // Update instrument script (group) chunks.  
   
                 for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();  
                      it != pScriptGroups->end(); ++it)  
                 {  
                     (*it)->UpdateChunks(pProgress);  
                 }  
6238              }              }
6239          }          }
6240    
6241            // in case no libgig custom format data was added, then remove the
6242            // custom "3LS " chunk again
6243            if (!lst3LS->CountSubChunks()) {
6244                pRIFF->DeleteSubChunk(lst3LS);
6245                lst3LS = NULL;
6246            }
6247    
6248          // first update base class's chunks          // first update base class's chunks
6249          DLS::File::UpdateChunks(pProgress);          DLS::File::UpdateChunks(pProgress);
6250    
# Line 5863  namespace { Line 6303  namespace {
6303          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6304          // are set to zero.          // are set to zero.
6305    
6306          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6307          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6308    
6309          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 5936  namespace { Line 6376  namespace {
6376                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6377                  // next 8 bytes unknown                  // next 8 bytes unknown
6378                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6379                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6380                  // next 4 bytes unknown                  // next 4 bytes unknown
6381    
6382                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 5954  namespace { Line 6394  namespace {
6394              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6395              // next 8 bytes unknown              // next 8 bytes unknown
6396              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6397              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6398              // next 4 bytes unknown              // next 4 bytes unknown
6399          }          }
6400    
6401          // update 3crc chunk          // update 3crc chunk
6402    
6403          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6404          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6405          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6406            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6407            // member variable). This step is required, because samples might have
6408            // been deleted by the user since the file was opened, which in turn
6409            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6410            // If a sample was conciously modified by the user (that is if
6411            // Sample::Write() was called later on) then Sample::Write() will just
6412            // update the respective individual checksum(s) directly on disk and
6413            // leaves all other sample checksums untouched.
6414    
6415          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6416          if (_3crc) {          if (_3crc) {
6417              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6418          } else if (newFile) {          } else /*if (newFile)*/ {
6419              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6420              // the order of einf and 3crc is not the same in v2 and v3              // the order of einf and 3crc is not the same in v2 and v3
6421              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6422          }          }
6423            { // must be performed in RAM here ...
6424                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6425                if (pData) {
6426                    File::SampleList::iterator iter = pSamples->begin();
6427                    File::SampleList::iterator end  = pSamples->end();
6428                    for (int index = 0; iter != end; ++iter, ++index) {
6429                        gig::Sample* pSample = (gig::Sample*) *iter;
6430                        pData[index*2]   = 1; // always 1
6431                        pData[index*2+1] = pSample->crc;
6432                    }
6433                }
6434            }
6435      }      }
6436            
6437      void File::UpdateFileOffsets() {      void File::UpdateFileOffsets() {
# Line 6018  namespace { Line 6476  namespace {
6476  // *************** Exception ***************  // *************** Exception ***************
6477  // *  // *
6478    
6479      Exception::Exception(String Message) : DLS::Exception(Message) {      Exception::Exception() : DLS::Exception() {
6480        }
6481    
6482        Exception::Exception(String format, ...) : DLS::Exception() {
6483            va_list arg;
6484            va_start(arg, format);
6485            Message = assemble(format, arg);
6486            va_end(arg);
6487        }
6488    
6489        Exception::Exception(String format, va_list arg) : DLS::Exception() {
6490            Message = assemble(format, arg);
6491      }      }
6492    
6493      void Exception::PrintMessage() {      void Exception::PrintMessage() {

Legend:
Removed from v.2682  
changed lines
  Added in v.3203

  ViewVC Help
Powered by ViewVC