/[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 2836 by persson, Sun Aug 23 05:57:18 2015 UTC revision 3323 by schoenebeck, Thu Jul 20 22:09:54 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-2015 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    // *************** eg_opt_t ***************
345    // *
346    
347        eg_opt_t::eg_opt_t() {
348            AttackCancel     = true;
349            AttackHoldCancel = true;
350            DecayCancel      = true;
351            ReleaseCancel    = true;
352        }
353    
354        void eg_opt_t::serialize(Serialization::Archive* archive) {
355            SRLZ(AttackCancel);
356            SRLZ(AttackHoldCancel);
357            SRLZ(DecayCancel);
358            SRLZ(ReleaseCancel);
359        }
360    
361    
362    
363  // *************** Sample ***************  // *************** Sample ***************
364  // *  // *
365    
366      unsigned int Sample::Instances = 0;      size_t       Sample::Instances = 0;
367      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
368    
369      /** @brief Constructor.      /** @brief Constructor.
# Line 334  namespace { Line 383  namespace {
383       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
384       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
385       *                         is located, 0 otherwise       *                         is located, 0 otherwise
386         * @param index          - wave pool index of sample (may be -1 on new sample)
387       */       */
388      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)
389            : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
390        {
391          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
392              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
393              { 0, 0 }              { 0, 0 }
# Line 345  namespace { Line 397  namespace {
397          FileNo = fileNo;          FileNo = fileNo;
398    
399          __resetCRC(crc);          __resetCRC(crc);
400            // if this is not a new sample, try to get the sample's already existing
401            // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
402            // checksum of the time when the sample was consciously modified by the
403            // user for the last time (by calling Sample::Write() that is).
404            if (index >= 0) { // not a new file ...
405                try {
406                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
407                    this->crc = crc;
408                } catch (...) {}
409            }
410    
411          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
412          if (pCk3gix) {          if (pCk3gix) {
# Line 477  namespace { Line 539  namespace {
539          const int iReadAtOnce = 32*1024;          const int iReadAtOnce = 32*1024;
540          char* buf = new char[iReadAtOnce * orig->FrameSize];          char* buf = new char[iReadAtOnce * orig->FrameSize];
541          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
542          unsigned long restorePos = pOrig->GetPos();          file_offset_t restorePos = pOrig->GetPos();
543          pOrig->SetPos(0);          pOrig->SetPos(0);
544          SetPos(0);          SetPos(0);
545          for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;          for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
546                             n = pOrig->Read(buf, iReadAtOnce))                             n = pOrig->Read(buf, iReadAtOnce))
547          {          {
548              Write(buf, n);              Write(buf, n);
# Line 565  namespace { Line 627  namespace {
627      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
628          //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)
629          this->SamplesTotal = 0;          this->SamplesTotal = 0;
630          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
631    
632          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
633          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 581  namespace { Line 643  namespace {
643                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
644                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
645                  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");
646                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
647    
648                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
649                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 600  namespace { Line 662  namespace {
662    
663                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
664                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
665                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
666    
667                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
668                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 616  namespace { Line 678  namespace {
678    
679          // 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)
680          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
681          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
682          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
683          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
684          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
685              FrameTable[i] = *iter;              FrameTable[i] = *iter;
686          }          }
# Line 659  namespace { Line 721  namespace {
721       *                      the cached sample data in bytes       *                      the cached sample data in bytes
722       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
723       */       */
724      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
725          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
726      }      }
727    
# Line 718  namespace { Line 780  namespace {
780       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
781       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
782       */       */
783      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
784          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
785          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
786          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
787          SetPos(0); // reset read position to begin of sample          SetPos(0); // reset read position to begin of sample
788          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
789          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
# Line 785  namespace { Line 847  namespace {
847       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
848       * other formats will fail!       * other formats will fail!
849       *       *
850       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
851       *                   greater than zero)       *                  greater than zero)
852       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
853       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
854       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
855       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
856       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
857       */       */
858      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
859          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)");
860          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
861      }      }
862    
863      /**      /**
# Line 819  namespace { Line 881  namespace {
881       * @returns            the new sample position       * @returns            the new sample position
882       * @see                Read()       * @see                Read()
883       */       */
884      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) {
885          if (Compressed) {          if (Compressed) {
886              switch (Whence) {              switch (Whence) {
887                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 837  namespace { Line 899  namespace {
899              }              }
900              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
901    
902              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
903              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
904              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
905              return this->SamplePos;              return this->SamplePos;
906          }          }
907          else { // not compressed          else { // not compressed
908              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
909              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
910              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
911                                              : result / this->FrameSize;                                              : result / this->FrameSize;
912          }          }
# Line 853  namespace { Line 915  namespace {
915      /**      /**
916       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
917       */       */
918      unsigned long Sample::GetPos() const {      file_offset_t Sample::GetPos() const {
919          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
920          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
921      }      }
# Line 892  namespace { Line 954  namespace {
954       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
955       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
956       */       */
957      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,
958                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
959          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
960          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
961    
962          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 932  namespace { Line 994  namespace {
994                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
995                                  // backward playback                                  // backward playback
996    
997                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
998                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
999                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
1000                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
1001    
1002                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
1003    
# Line 983  namespace { Line 1045  namespace {
1045                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1046                          // backward playback                          // backward playback
1047    
1048                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
1049                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
1050                          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)
1051                                                                                    : samplestoread;                                                                                    : samplestoread;
1052                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1053    
1054                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1055    
# Line 1067  namespace { Line 1129  namespace {
1129       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1130       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1131       */       */
1132      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) {
1133          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1134          if (!Compressed) {          if (!Compressed) {
1135              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 1082  namespace { Line 1144  namespace {
1144          else {          else {
1145              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1146              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1147              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1148                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1149                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1150                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1105  namespace { Line 1167  namespace {
1167              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1168    
1169              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1170                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1171                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1172    
1173                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1174    
# Line 1256  namespace { Line 1318  namespace {
1318       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1319       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1320       */       */
1321      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1322          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)");
1323    
1324          // 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 1327  namespace {
1327              __resetCRC(crc);              __resetCRC(crc);
1328          }          }
1329          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");
1330          unsigned long res;          file_offset_t res;
1331          if (BitDepth == 24) {          if (BitDepth == 24) {
1332              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1333          } else { // 16 bit          } else { // 16 bit
# Line 1277  namespace { Line 1339  namespace {
1339          // if this is the last write, update the checksum chunk in the          // if this is the last write, update the checksum chunk in the
1340          // file          // file
1341          if (pCkData->GetPos() == pCkData->GetSize()) {          if (pCkData->GetPos() == pCkData->GetSize()) {
1342                __finalizeCRC(crc);
1343              File* pFile = static_cast<File*>(GetParent());              File* pFile = static_cast<File*>(GetParent());
1344              pFile->SetSampleChecksum(this, __encodeCRC(crc));              pFile->SetSampleChecksum(this, crc);
1345          }          }
1346          return res;          return res;
1347      }      }
# Line 1299  namespace { Line 1362  namespace {
1362       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1363       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1364       */       */
1365      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1366          buffer_t result;          buffer_t result;
1367          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1368                  (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;
1369          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);
1370          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1371          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1372          return result;          return result;
# Line 1337  namespace { Line 1400  namespace {
1400          return pGroup;          return pGroup;
1401      }      }
1402    
1403        /**
1404         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1405         * time when this sample's wave form data was modified for the last time
1406         * by calling Write(). This checksum only covers the raw wave form data,
1407         * not any meta informations like i.e. bit depth or loop points. Since
1408         * this method just returns the checksum stored for this sample i.e. when
1409         * the gig file was loaded, this method returns immediately. So it does no
1410         * recalcuation of the checksum with the currently available sample wave
1411         * form data.
1412         *
1413         * @see VerifyWaveData()
1414         */
1415        uint32_t Sample::GetWaveDataCRC32Checksum() {
1416            return crc;
1417        }
1418    
1419        /**
1420         * Checks the integrity of this sample's raw audio wave data. Whenever a
1421         * Sample's raw wave data is intentionally modified (i.e. by calling
1422         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1423         * is calculated and stored/updated for this sample, along to the sample's
1424         * meta informations.
1425         *
1426         * Now by calling this method the current raw audio wave data is checked
1427         * against the already stored CRC32 check sum in order to check whether the
1428         * sample data had been damaged unintentionally for some reason. Since by
1429         * calling this method always the entire raw audio wave data has to be
1430         * read, verifying all samples this way may take a long time accordingly.
1431         * And that's also the reason why the sample integrity is not checked by
1432         * default whenever a gig file is loaded. So this method must be called
1433         * explicitly to fulfill this task.
1434         *
1435         * @param pActually - (optional) if provided, will be set to the actually
1436         *                    calculated checksum of the current raw wave form data,
1437         *                    you can get the expected checksum instead by calling
1438         *                    GetWaveDataCRC32Checksum()
1439         * @returns true if sample is OK or false if the sample is damaged
1440         * @throws Exception if no checksum had been stored to disk for this
1441         *         sample yet, or on I/O issues
1442         * @see GetWaveDataCRC32Checksum()
1443         */
1444        bool Sample::VerifyWaveData(uint32_t* pActually) {
1445            //File* pFile = static_cast<File*>(GetParent());
1446            uint32_t crc = CalculateWaveDataChecksum();
1447            if (pActually) *pActually = crc;
1448            return crc == this->crc;
1449        }
1450    
1451        uint32_t Sample::CalculateWaveDataChecksum() {
1452            const size_t sz = 20*1024; // 20kB buffer size
1453            std::vector<uint8_t> buffer(sz);
1454            buffer.resize(sz);
1455    
1456            const size_t n = sz / FrameSize;
1457            SetPos(0);
1458            uint32_t crc = 0;
1459            __resetCRC(crc);
1460            while (true) {
1461                file_offset_t nRead = Read(&buffer[0], n);
1462                if (nRead <= 0) break;
1463                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1464            }
1465            __finalizeCRC(crc);
1466            return crc;
1467        }
1468    
1469      Sample::~Sample() {      Sample::~Sample() {
1470          Instances--;          Instances--;
1471          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1353  namespace { Line 1482  namespace {
1482  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1483  // *  // *
1484    
1485      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1486      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1487    
1488      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1547  namespace { Line 1676  namespace {
1676              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1677              EG2Decay1                       = 0.005;              EG2Decay1                       = 0.005;
1678              EG2Sustain                      = 1000;              EG2Sustain                      = 1000;
1679              EG2Release                      = 0.3;              EG2Release                      = 60;
1680              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1681              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1682              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
# Line 1601  namespace { Line 1730  namespace {
1730              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1731              memset(DimensionUpperLimits, 127, 8);              memset(DimensionUpperLimits, 127, 8);
1732          }          }
1733            // format extension for EG behavior options, these will *NOT* work with
1734            // Gigasampler/GigaStudio !
1735            RIFF::Chunk* lsde = _3ewl->GetSubChunk(CHUNK_ID_LSDE);
1736            if (lsde) {
1737                unsigned char byte = lsde->ReadUint8();
1738                EGOptions.AttackCancel     = byte & 1;
1739                EGOptions.AttackHoldCancel = byte & (1 << 1);
1740                EGOptions.DecayCancel      = byte & (1 << 2);
1741                EGOptions.ReleaseCancel    = byte & (1 << 3);
1742            }
1743    
1744          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1745                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
# Line 1706  namespace { Line 1845  namespace {
1845          }          }
1846      }      }
1847    
1848        void DimensionRegion::serialize(Serialization::Archive* archive) {
1849            // in case this class will become backward incompatible one day,
1850            // then set a version and minimum version for this class like:
1851            //archive->setVersion(*this, 2);
1852            //archive->setMinVersion(*this, 1);
1853    
1854            SRLZ(VelocityUpperLimit);
1855            SRLZ(EG1PreAttack);
1856            SRLZ(EG1Attack);
1857            SRLZ(EG1Decay1);
1858            SRLZ(EG1Decay2);
1859            SRLZ(EG1InfiniteSustain);
1860            SRLZ(EG1Sustain);
1861            SRLZ(EG1Release);
1862            SRLZ(EG1Hold);
1863            SRLZ(EG1Controller);
1864            SRLZ(EG1ControllerInvert);
1865            SRLZ(EG1ControllerAttackInfluence);
1866            SRLZ(EG1ControllerDecayInfluence);
1867            SRLZ(EG1ControllerReleaseInfluence);
1868            SRLZ(LFO1Frequency);
1869            SRLZ(LFO1InternalDepth);
1870            SRLZ(LFO1ControlDepth);
1871            SRLZ(LFO1Controller);
1872            SRLZ(LFO1FlipPhase);
1873            SRLZ(LFO1Sync);
1874            SRLZ(EG2PreAttack);
1875            SRLZ(EG2Attack);
1876            SRLZ(EG2Decay1);
1877            SRLZ(EG2Decay2);
1878            SRLZ(EG2InfiniteSustain);
1879            SRLZ(EG2Sustain);
1880            SRLZ(EG2Release);
1881            SRLZ(EG2Controller);
1882            SRLZ(EG2ControllerInvert);
1883            SRLZ(EG2ControllerAttackInfluence);
1884            SRLZ(EG2ControllerDecayInfluence);
1885            SRLZ(EG2ControllerReleaseInfluence);
1886            SRLZ(LFO2Frequency);
1887            SRLZ(LFO2InternalDepth);
1888            SRLZ(LFO2ControlDepth);
1889            SRLZ(LFO2Controller);
1890            SRLZ(LFO2FlipPhase);
1891            SRLZ(LFO2Sync);
1892            SRLZ(EG3Attack);
1893            SRLZ(EG3Depth);
1894            SRLZ(LFO3Frequency);
1895            SRLZ(LFO3InternalDepth);
1896            SRLZ(LFO3ControlDepth);
1897            SRLZ(LFO3Controller);
1898            SRLZ(LFO3Sync);
1899            SRLZ(VCFEnabled);
1900            SRLZ(VCFType);
1901            SRLZ(VCFCutoffController);
1902            SRLZ(VCFCutoffControllerInvert);
1903            SRLZ(VCFCutoff);
1904            SRLZ(VCFVelocityCurve);
1905            SRLZ(VCFVelocityScale);
1906            SRLZ(VCFVelocityDynamicRange);
1907            SRLZ(VCFResonance);
1908            SRLZ(VCFResonanceDynamic);
1909            SRLZ(VCFResonanceController);
1910            SRLZ(VCFKeyboardTracking);
1911            SRLZ(VCFKeyboardTrackingBreakpoint);
1912            SRLZ(VelocityResponseCurve);
1913            SRLZ(VelocityResponseDepth);
1914            SRLZ(VelocityResponseCurveScaling);
1915            SRLZ(ReleaseVelocityResponseCurve);
1916            SRLZ(ReleaseVelocityResponseDepth);
1917            SRLZ(ReleaseTriggerDecay);
1918            SRLZ(Crossfade);
1919            SRLZ(PitchTrack);
1920            SRLZ(DimensionBypass);
1921            SRLZ(Pan);
1922            SRLZ(SelfMask);
1923            SRLZ(AttenuationController);
1924            SRLZ(InvertAttenuationController);
1925            SRLZ(AttenuationControllerThreshold);
1926            SRLZ(ChannelOffset);
1927            SRLZ(SustainDefeat);
1928            SRLZ(MSDecode);
1929            //SRLZ(SampleStartOffset);
1930            SRLZ(SampleAttenuation);
1931            SRLZ(EGOptions);
1932    
1933            // derived attributes from DLS::Sampler
1934            SRLZ(FineTune);
1935            SRLZ(Gain);
1936        }
1937    
1938      /**      /**
1939       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
1940       * which depends on this value.       * which depends on this value.
# Line 1746  namespace { Line 1975  namespace {
1975    
1976          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1977    
1978          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1979          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1980    
1981          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 2006  namespace { Line 2235  namespace {
2235          if (chunksize >= 148) {          if (chunksize >= 148) {
2236              memcpy(&pData[140], DimensionUpperLimits, 8);              memcpy(&pData[140], DimensionUpperLimits, 8);
2237          }          }
2238    
2239            // format extension for EG behavior options, these will *NOT* work with
2240            // Gigasampler/GigaStudio !
2241            RIFF::Chunk* lsde = pParentList->GetSubChunk(CHUNK_ID_LSDE);
2242            if (!lsde) {
2243                // only add this "LSDE" chunk if the EG options do not match the
2244                // default EG behavior
2245                eg_opt_t defaultOpt;
2246                if (memcmp(&EGOptions, &defaultOpt, sizeof(eg_opt_t))) {
2247                    lsde = pParentList->AddSubChunk(CHUNK_ID_LSDE, 1);
2248                    // move LSDE chunk to the end of parent list
2249                    pParentList->MoveSubChunk(lsde, (RIFF::Chunk*)NULL);
2250                }
2251            }
2252            if (lsde) {
2253                unsigned char* pByte = (unsigned char*) lsde->LoadChunkData();
2254                *pByte =
2255                    (EGOptions.AttackCancel     ? 1 : 0) |
2256                    (EGOptions.AttackHoldCancel ? (1<<1) : 0) |
2257                    (EGOptions.DecayCancel      ? (1<<2) : 0) |
2258                    (EGOptions.ReleaseCancel    ? (1<<3) : 0);
2259            }
2260      }      }
2261    
2262      double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {      double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
# Line 2420  namespace { Line 2671  namespace {
2671    
2672              // unknown controller type              // unknown controller type
2673              default:              default:
2674                  throw gig::Exception("Unknown leverage controller type.");                  decodedcontroller.type = leverage_ctrl_t::type_none;
2675                    decodedcontroller.controller_number = 0;
2676                    printf("Warning: Unknown leverage controller type (0x%x).\n", EncodedController);
2677                    break;
2678          }          }
2679          return decodedcontroller;          return decodedcontroller;
2680      }      }
# Line 3102  namespace { Line 3356  namespace {
3356          int step = 1;          int step = 1;
3357          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3358          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3359    
3360          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3361          int dim[8] = { 0 };          int dim[8] = { 0 };
3362          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3363                const int end = i + step * pDimensionDefinitions[veldim].zones;
3364    
3365                // create a velocity table for all cases where the velocity zone is zero
3366              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3367                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3368                  // create the velocity table                  // create the velocity table
# Line 3138  namespace { Line 3393  namespace {
3393                  }                  }
3394              }              }
3395    
3396                // jump to the next case where the velocity zone is zero
3397              int j;              int j;
3398              int shift = 0;              int shift = 0;
3399              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 3712  namespace { Line 3968  namespace {
3968      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3969          uint8_t bits;          uint8_t bits;
3970          int veldim = -1;          int veldim = -1;
3971          int velbitpos;          int velbitpos = 0;
3972          int bitpos = 0;          int bitpos = 0;
3973          int dimregidx = 0;          int dimregidx = 0;
3974          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 3761  namespace { Line 4017  namespace {
4017      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
4018          uint8_t bits;          uint8_t bits;
4019          int veldim = -1;          int veldim = -1;
4020          int velbitpos;          int velbitpos = 0;
4021          int bitpos = 0;          int bitpos = 0;
4022          int dimregidx = 0;          int dimregidx = 0;
4023          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 3846  namespace { Line 4102  namespace {
4102          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
4103          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
4104          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
4105          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
4106          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
4107          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
4108          while (sample) {              uint64_t soughtoffset =
4109              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
4110                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
4111              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
4112                while (sample) {
4113                    if (sample->ullWavePoolOffset == soughtoffset)
4114                        return static_cast<gig::Sample*>(sample);
4115                    sample = file->GetNextSample();
4116                }
4117            } else {
4118                // use extension files and 32 bit wave pool offsets
4119                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
4120                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
4121                Sample* sample = file->GetFirstSample(pProgress);
4122                while (sample) {
4123                    if (sample->ullWavePoolOffset == soughtoffset &&
4124                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
4125                    sample = file->GetNextSample();
4126                }
4127          }          }
4128          return NULL;          return NULL;
4129      }      }
# Line 4095  namespace { Line 4366  namespace {
4366              // to handle potential future extensions of the header              // to handle potential future extensions of the header
4367              ckScri->SetPos(sizeof(int32_t) + headerSize);              ckScri->SetPos(sizeof(int32_t) + headerSize);
4368              // read actual script data              // read actual script data
4369              uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();              uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4370              data.resize(scriptSize);              data.resize(scriptSize);
4371              for (int i = 0; i < scriptSize; ++i)              for (int i = 0; i < scriptSize; ++i)
4372                  data[i] = ckScri->ReadUint8();                  data[i] = ckScri->ReadUint8();
# Line 4146  namespace { Line 4417  namespace {
4417          // recalculate CRC32 check sum          // recalculate CRC32 check sum
4418          __resetCRC(crc);          __resetCRC(crc);
4419          __calculateCRC(&data[0], data.size(), crc);          __calculateCRC(&data[0], data.size(), crc);
4420          __encodeCRC(crc);          __finalizeCRC(crc);
4421          // make sure chunk exists and has the required size          // make sure chunk exists and has the required size
4422          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();
4423          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4424          else pChunk->Resize(chunkSize);          else pChunk->Resize(chunkSize);
4425          // fill the chunk data to be written to disk          // fill the chunk data to be written to disk
4426          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4427          int pos = 0;          int pos = 0;
4428          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
4429          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4430          store32(&pData[pos], Compression);          store32(&pData[pos], Compression);
4431          pos += sizeof(int32_t);          pos += sizeof(int32_t);
# Line 4166  namespace { Line 4437  namespace {
4437          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4438          store32(&pData[pos], crc);          store32(&pData[pos], crc);
4439          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4440          store32(&pData[pos], Name.size());          store32(&pData[pos], (uint32_t) Name.size());
4441          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4442          for (int i = 0; i < Name.size(); ++i, ++pos)          for (int i = 0; i < Name.size(); ++i, ++pos)
4443              pData[pos] = Name[i];              pData[pos] = Name[i];
# Line 4197  namespace { Line 4468  namespace {
4468          return pGroup;          return pGroup;
4469      }      }
4470    
4471        /**
4472         * Make a (semi) deep copy of the Script object given by @a orig
4473         * and assign it to this object. Note: the ScriptGroup this Script
4474         * object belongs to remains untouched by this call.
4475         *
4476         * @param orig - original Script object to be copied from
4477         */
4478        void Script::CopyAssign(const Script* orig) {
4479            Name        = orig->Name;
4480            Compression = orig->Compression;
4481            Encoding    = orig->Encoding;
4482            Language    = orig->Language;
4483            Bypass      = orig->Bypass;
4484            data        = orig->data;
4485        }
4486    
4487      void Script::RemoveAllScriptReferences() {      void Script::RemoveAllScriptReferences() {
4488          File* pFile = pGroup->pFile;          File* pFile = pGroup->pFile;
4489          for (int i = 0; pFile->GetInstrument(i); ++i) {          for (int i = 0; pFile->GetInstrument(i); ++i) {
# Line 4343  namespace { Line 4630  namespace {
4630          EffectSend = 0;          EffectSend = 0;
4631          Attenuation = 0;          Attenuation = 0;
4632          FineTune = 0;          FineTune = 0;
4633          PitchbendRange = 0;          PitchbendRange = 2;
4634          PianoReleaseMode = false;          PianoReleaseMode = false;
4635          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4636          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
# Line 4518  namespace { Line 4805  namespace {
4805    
4806             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4807             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4808             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4809             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4810             const int slotSize  = 2 * sizeof(uint32_t);             const int slotSize  = 2 * sizeof(uint32_t);
4811             const int totalChunkSize = headerSize + slotCount * slotSize;             const int totalChunkSize = headerSize + slotCount * slotSize;
# Line 4554  namespace { Line 4841  namespace {
4841         if (pScriptRefs && pScriptRefs->size() > 0) {         if (pScriptRefs && pScriptRefs->size() > 0) {
4842             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4843             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4844             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4845             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4846             ckSCSL->SetPos(headerSize);             ckSCSL->SetPos(headerSize);
4847             for (int i = 0; i < slotCount; ++i) {             for (int i = 0; i < slotCount; ++i) {
4848                 uint32_t fileOffset =                 uint32_t fileOffset = uint32_t(
4849                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4850                      (*pScriptRefs)[i].script->pChunk->GetPos() -                      (*pScriptRefs)[i].script->pChunk->GetPos() -
4851                      CHUNK_HEADER_SIZE;                      CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4852                   );
4853                 ckSCSL->WriteUint32(&fileOffset);                 ckSCSL->WriteUint32(&fileOffset);
4854                 // jump over flags entry (containing the bypass flag)                 // jump over flags entry (containing the bypass flag)
4855                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
# Line 4621  namespace { Line 4909  namespace {
4909          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4910          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4911          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4912          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4913          // update Region key table for fast lookup          // update Region key table for fast lookup
4914          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4915          // done          // done
# Line 4767  namespace { Line 5055  namespace {
5055                  for (uint s = 0; group->GetScript(s); ++s) {                  for (uint s = 0; group->GetScript(s); ++s) {
5056                      Script* script = group->GetScript(s);                      Script* script = group->GetScript(s);
5057                      if (script->pChunk) {                      if (script->pChunk) {
5058                          uint32_t offset = script->pChunk->GetFilePos() -                          uint32_t offset = uint32_t(
5059                                            script->pChunk->GetPos() -                              script->pChunk->GetFilePos() -
5060                                            CHUNK_HEADER_SIZE;                              script->pChunk->GetPos() -
5061                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
5062                            );
5063                          if (offset == soughtOffset)                          if (offset == soughtOffset)
5064                          {                          {
5065                              _ScriptPooolRef ref;                              _ScriptPooolRef ref;
# Line 4894  namespace { Line 5184  namespace {
5184       */       */
5185      void Instrument::RemoveScript(Script* pScript) {      void Instrument::RemoveScript(Script* pScript) {
5186          LoadScripts();          LoadScripts();
5187          for (int i = pScriptRefs->size() - 1; i >= 0; --i) {          for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5188              if ((*pScriptRefs)[i].script == pScript) {              if ((*pScriptRefs)[i].script == pScript) {
5189                  pScriptRefs->erase( pScriptRefs->begin() + i );                  pScriptRefs->erase( pScriptRefs->begin() + i );
5190              }              }
# Line 4916  namespace { Line 5206  namespace {
5206       * gigedit.       * gigedit.
5207       */       */
5208      uint Instrument::ScriptSlotCount() const {      uint Instrument::ScriptSlotCount() const {
5209          return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();          return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5210      }      }
5211    
5212      /** @brief Whether script execution shall be skipped.      /** @brief Whether script execution shall be skipped.
# Line 5332  namespace { Line 5622  namespace {
5622          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5623    
5624          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5625            // (only for old gig files < 2 GB)
5626          int lastFileNo = 0;          int lastFileNo = 0;
5627          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5628              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5629                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5630                }
5631          }          }
5632          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5633          int nameLen = name.length();          int nameLen = (int) name.length();
5634          char suffix[6];          char suffix[6];
5635          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5636    
5637          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5638              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5639              if (wvpl) {              if (wvpl) {
5640                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5641                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5642                  while (wave) {                  while (wave) {
5643                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 5352  namespace { Line 5645  namespace {
5645                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5646                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5647    
5648                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5649                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5650    
5651                          iSampleIndex++;                          iSampleIndex++;
5652                      }                      }
# Line 5506  namespace { Line 5799  namespace {
5799              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5800              mSamples[pFile->GetSample(i)] = s;              mSamples[pFile->GetSample(i)] = s;
5801          }          }
5802            
5803            // clone script groups and their scripts
5804            for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
5805                ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
5806                ScriptGroup* dg = AddScriptGroup();
5807                dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
5808                for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
5809                    Script* ss = sg->GetScript(iScript);
5810                    Script* ds = dg->AddScript();
5811                    ds->CopyAssign(ss);
5812                }
5813            }
5814    
5815          //BUG: For some reason this method only works with this additional          //BUG: For some reason this method only works with this additional
5816          //     Save() call in between here.          //     Save() call in between here.
5817          //          //
# Line 5591  namespace { Line 5896  namespace {
5896          if (!_3crc) return;          if (!_3crc) return;
5897    
5898          // get the index of the sample          // get the index of the sample
5899          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;  
             }  
         }  
5900          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");
5901    
5902          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5903          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5904          uint32_t tmp = 1;          uint32_t one = 1;
5905          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5906          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5907      }      }
5908    
5909        uint32_t File::GetSampleChecksum(Sample* pSample) {
5910            // get the index of the sample
5911            int iWaveIndex = GetWaveTableIndexOf(pSample);
5912            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5913    
5914            return GetSampleChecksumByIndex(iWaveIndex);
5915        }
5916    
5917        uint32_t File::GetSampleChecksumByIndex(int index) {
5918            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5919    
5920            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5921            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5922            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5923            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5924    
5925            // read the CRC-32 checksum directly from disk
5926            size_t pos = index * 8;
5927            if (pos + 8 > _3crc->GetNewSize())
5928                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5929    
5930            uint32_t one = load32(&pData[pos]); // always 1
5931            if (one != 1)
5932                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5933    
5934            return load32(&pData[pos+4]);
5935        }
5936    
5937        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5938            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5939            File::SampleList::iterator iter = pSamples->begin();
5940            File::SampleList::iterator end  = pSamples->end();
5941            for (int index = 0; iter != end; ++iter, ++index)
5942                if (*iter == pSample)
5943                    return index;
5944            return -1;
5945        }
5946    
5947        /**
5948         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5949         * the CRC32 check sums of all samples' raw wave data.
5950         *
5951         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5952         */
5953        bool File::VerifySampleChecksumTable() {
5954            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5955            if (!_3crc) return false;
5956            if (_3crc->GetNewSize() <= 0) return false;
5957            if (_3crc->GetNewSize() % 8) return false;
5958            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5959            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5960    
5961            const file_offset_t n = _3crc->GetNewSize() / 8;
5962    
5963            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5964            if (!pData) return false;
5965    
5966            for (file_offset_t i = 0; i < n; ++i) {
5967                uint32_t one = pData[i*2];
5968                if (one != 1) return false;
5969            }
5970    
5971            return true;
5972        }
5973    
5974        /**
5975         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5976         * file's checksum table with those new checksums. This might usually
5977         * just be necessary if the checksum table was damaged.
5978         *
5979         * @e IMPORTANT: The current implementation of this method only works
5980         * with files that have not been modified since it was loaded, because
5981         * it expects that no externally caused file structure changes are
5982         * required!
5983         *
5984         * Due to the expectation above, this method is currently protected
5985         * and actually only used by the command line tool "gigdump" yet.
5986         *
5987         * @returns true if Save() is required to be called after this call,
5988         *          false if no further action is required
5989         */
5990        bool File::RebuildSampleChecksumTable() {
5991            // make sure sample chunks were scanned
5992            if (!pSamples) GetFirstSample();
5993    
5994            bool bRequiresSave = false;
5995    
5996            // make sure "3CRC" chunk exists with required size
5997            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5998            if (!_3crc) {
5999                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6000                // the order of einf and 3crc is not the same in v2 and v3
6001                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
6002                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6003                bRequiresSave = true;
6004            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
6005                _3crc->Resize(pSamples->size() * 8);
6006                bRequiresSave = true;
6007            }
6008    
6009            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
6010                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6011                {
6012                    File::SampleList::iterator iter = pSamples->begin();
6013                    File::SampleList::iterator end  = pSamples->end();
6014                    for (; iter != end; ++iter) {
6015                        gig::Sample* pSample = (gig::Sample*) *iter;
6016                        int index = GetWaveTableIndexOf(pSample);
6017                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
6018                        pData[index*2]   = 1; // always 1
6019                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
6020                    }
6021                }
6022            } else { // no file structure changes necessary, so directly write to disk and we are done ...
6023                // make sure file is in write mode
6024                pRIFF->SetMode(RIFF::stream_mode_read_write);
6025                {
6026                    File::SampleList::iterator iter = pSamples->begin();
6027                    File::SampleList::iterator end  = pSamples->end();
6028                    for (; iter != end; ++iter) {
6029                        gig::Sample* pSample = (gig::Sample*) *iter;
6030                        int index = GetWaveTableIndexOf(pSample);
6031                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
6032                        pSample->crc  = pSample->CalculateWaveDataChecksum();
6033                        SetSampleChecksum(pSample, pSample->crc);
6034                    }
6035                }
6036            }
6037    
6038            return bRequiresSave;
6039        }
6040    
6041      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
6042          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
6043          // there must always be at least one group          // there must always be at least one group
# Line 5837  namespace { Line 6266  namespace {
6266      void File::UpdateChunks(progress_t* pProgress) {      void File::UpdateChunks(progress_t* pProgress) {
6267          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6268    
         b64BitWavePoolOffsets = pVersion && pVersion->major == 3;  
   
6269          // update own gig format extension chunks          // update own gig format extension chunks
6270          // (not part of the GigaStudio 4 format)          // (not part of the GigaStudio 4 format)
6271          //          RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6272            if (!lst3LS) {
6273                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6274            }
6275            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6276            // location of <3LS > is irrelevant, however it should be located
6277            // before  the actual wave data
6278            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6279            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6280    
6281          // This must be performed before writing the chunks for instruments,          // This must be performed before writing the chunks for instruments,
6282          // because the instruments' script slots will write the file offsets          // because the instruments' script slots will write the file offsets
6283          // of the respective instrument script chunk as reference.          // of the respective instrument script chunk as reference.
6284          if (pScriptGroups) {          if (pScriptGroups) {
6285              RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);              // Update instrument script (group) chunks.
6286              if (pScriptGroups->empty()) {              for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6287                  if (lst3LS) pRIFF->DeleteSubChunk(lst3LS);                   it != pScriptGroups->end(); ++it)
6288              } else {              {
6289                  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);  
                 }  
6290              }              }
6291          }          }
6292    
6293            // in case no libgig custom format data was added, then remove the
6294            // custom "3LS " chunk again
6295            if (!lst3LS->CountSubChunks()) {
6296                pRIFF->DeleteSubChunk(lst3LS);
6297                lst3LS = NULL;
6298            }
6299    
6300          // first update base class's chunks          // first update base class's chunks
6301          DLS::File::UpdateChunks(pProgress);          DLS::File::UpdateChunks(pProgress);
6302    
# Line 5920  namespace { Line 6355  namespace {
6355          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6356          // are set to zero.          // are set to zero.
6357    
6358          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6359          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6360    
6361          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 5993  namespace { Line 6428  namespace {
6428                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6429                  // next 8 bytes unknown                  // next 8 bytes unknown
6430                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6431                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6432                  // next 4 bytes unknown                  // next 4 bytes unknown
6433    
6434                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 6011  namespace { Line 6446  namespace {
6446              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6447              // next 8 bytes unknown              // next 8 bytes unknown
6448              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6449              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6450              // next 4 bytes unknown              // next 4 bytes unknown
6451          }          }
6452    
6453          // update 3crc chunk          // update 3crc chunk
6454    
6455          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6456          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6457          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6458            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6459            // member variable). This step is required, because samples might have
6460            // been deleted by the user since the file was opened, which in turn
6461            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6462            // If a sample was conciously modified by the user (that is if
6463            // Sample::Write() was called later on) then Sample::Write() will just
6464            // update the respective individual checksum(s) directly on disk and
6465            // leaves all other sample checksums untouched.
6466    
6467          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6468          if (_3crc) {          if (_3crc) {
6469              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6470          } else if (newFile) {          } else /*if (newFile)*/ {
6471              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6472              // 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
6473              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6474          }          }
6475            { // must be performed in RAM here ...
6476                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6477                if (pData) {
6478                    File::SampleList::iterator iter = pSamples->begin();
6479                    File::SampleList::iterator end  = pSamples->end();
6480                    for (int index = 0; iter != end; ++iter, ++index) {
6481                        gig::Sample* pSample = (gig::Sample*) *iter;
6482                        pData[index*2]   = 1; // always 1
6483                        pData[index*2+1] = pSample->crc;
6484                    }
6485                }
6486            }
6487      }      }
6488            
6489      void File::UpdateFileOffsets() {      void File::UpdateFileOffsets() {
# Line 6075  namespace { Line 6528  namespace {
6528  // *************** Exception ***************  // *************** Exception ***************
6529  // *  // *
6530    
6531      Exception::Exception(String Message) : DLS::Exception(Message) {      Exception::Exception() : DLS::Exception() {
6532        }
6533    
6534        Exception::Exception(String format, ...) : DLS::Exception() {
6535            va_list arg;
6536            va_start(arg, format);
6537            Message = assemble(format, arg);
6538            va_end(arg);
6539        }
6540    
6541        Exception::Exception(String format, va_list arg) : DLS::Exception() {
6542            Message = assemble(format, arg);
6543      }      }
6544    
6545      void Exception::PrintMessage() {      void Exception::PrintMessage() {

Legend:
Removed from v.2836  
changed lines
  Added in v.3323

  ViewVC Help
Powered by ViewVC