/[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 3138 by schoenebeck, Wed May 3 14:41:58 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 30  Line 30 
30  #include <iostream>  #include <iostream>
31  #include <assert.h>  #include <assert.h>
32    
33    /// libgig's current file format version (for extending the original Giga file
34    /// format with libgig's own custom data / custom features).
35    #define GIG_FILE_EXT_VERSION    2
36    
37  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
38  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
39  /// 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 55 
55  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
56  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
57    
58    #define SRLZ(member) \
59        archive->serializeMember(*this, member, #member);
60    
61  namespace gig {  namespace gig {
62    
63  // *************** Internal functions for sample decompression ***************  // *************** Internal functions for sample decompression ***************
# Line 91  namespace { Line 98  namespace {
98      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
99                        int srcStep, int dstStep,                        int srcStep, int dstStep,
100                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
101                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
102                        unsigned long copysamples)                        file_offset_t copysamples)
103      {      {
104          switch (compressionmode) {          switch (compressionmode) {
105              case 0: // 16 bit uncompressed              case 0: // 16 bit uncompressed
# Line 128  namespace { Line 135  namespace {
135    
136      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
137                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
138                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
139                        unsigned long copysamples, int truncatedBits)                        file_offset_t copysamples, int truncatedBits)
140      {      {
141          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
142    
# Line 265  namespace { Line 272  namespace {
272       * steps.       * steps.
273       *       *
274       * Once the whole data was processed by __calculateCRC(), one should       * Once the whole data was processed by __calculateCRC(), one should
275       * call __encodeCRC() to get the final CRC result.       * call __finalizeCRC() to get the final CRC result.
276       *       *
277       * @param buf     - pointer to data the CRC shall be calculated of       * @param buf     - pointer to data the CRC shall be calculated of
278       * @param bufSize - size of the data to be processed       * @param bufSize - size of the data to be processed
279       * @param crc     - variable the CRC sum shall be stored to       * @param crc     - variable the CRC sum shall be stored to
280       */       */
281      static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {      static void __calculateCRC(unsigned char* buf, size_t bufSize, uint32_t& crc) {
282          for (int i = 0 ; i < bufSize ; i++) {          for (size_t i = 0 ; i < bufSize ; i++) {
283              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
284          }          }
285      }      }
# Line 282  namespace { Line 289  namespace {
289       *       *
290       * @param crc - variable previously passed to __calculateCRC()       * @param crc - variable previously passed to __calculateCRC()
291       */       */
292      inline static uint32_t __encodeCRC(const uint32_t& crc) {      inline static void __finalizeCRC(uint32_t& crc) {
293          return crc ^ 0xffffffff;          crc ^= 0xffffffff;
294      }      }
295    
296    
# Line 311  namespace { Line 318  namespace {
318    
319    
320    
321    // *************** leverage_ctrl_t ***************
322    // *
323    
324        void leverage_ctrl_t::serialize(Serialization::Archive* archive) {
325            SRLZ(type);
326            SRLZ(controller_number);
327        }
328    
329    
330    
331    // *************** crossfade_t ***************
332    // *
333    
334        void crossfade_t::serialize(Serialization::Archive* archive) {
335            SRLZ(in_start);
336            SRLZ(in_end);
337            SRLZ(out_start);
338            SRLZ(out_end);
339        }
340    
341    
342    
343  // *************** Sample ***************  // *************** Sample ***************
344  // *  // *
345    
346      unsigned int Sample::Instances = 0;      size_t       Sample::Instances = 0;
347      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
348    
349      /** @brief Constructor.      /** @brief Constructor.
# Line 334  namespace { Line 363  namespace {
363       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
364       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
365       *                         is located, 0 otherwise       *                         is located, 0 otherwise
366         * @param index          - wave pool index of sample (may be -1 on new sample)
367       */       */
368      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)
369            : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
370        {
371          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
372              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
373              { 0, 0 }              { 0, 0 }
# Line 345  namespace { Line 377  namespace {
377          FileNo = fileNo;          FileNo = fileNo;
378    
379          __resetCRC(crc);          __resetCRC(crc);
380            // if this is not a new sample, try to get the sample's already existing
381            // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
382            // checksum of the time when the sample was consciously modified by the
383            // user for the last time (by calling Sample::Write() that is).
384            if (index >= 0) { // not a new file ...
385                try {
386                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
387                    this->crc = crc;
388                } catch (...) {}
389            }
390    
391          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
392          if (pCk3gix) {          if (pCk3gix) {
# Line 477  namespace { Line 519  namespace {
519          const int iReadAtOnce = 32*1024;          const int iReadAtOnce = 32*1024;
520          char* buf = new char[iReadAtOnce * orig->FrameSize];          char* buf = new char[iReadAtOnce * orig->FrameSize];
521          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
522          unsigned long restorePos = pOrig->GetPos();          file_offset_t restorePos = pOrig->GetPos();
523          pOrig->SetPos(0);          pOrig->SetPos(0);
524          SetPos(0);          SetPos(0);
525          for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;          for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
526                             n = pOrig->Read(buf, iReadAtOnce))                             n = pOrig->Read(buf, iReadAtOnce))
527          {          {
528              Write(buf, n);              Write(buf, n);
# Line 565  namespace { Line 607  namespace {
607      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
608          //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)
609          this->SamplesTotal = 0;          this->SamplesTotal = 0;
610          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
611    
612          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
613          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 581  namespace { Line 623  namespace {
623                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
624                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
625                  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");
626                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
627    
628                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
629                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 600  namespace { Line 642  namespace {
642    
643                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
644                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
645                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
646    
647                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
648                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 616  namespace { Line 658  namespace {
658    
659          // 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)
660          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
661          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
662          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
663          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
664          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
665              FrameTable[i] = *iter;              FrameTable[i] = *iter;
666          }          }
# Line 659  namespace { Line 701  namespace {
701       *                      the cached sample data in bytes       *                      the cached sample data in bytes
702       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
703       */       */
704      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
705          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
706      }      }
707    
# Line 718  namespace { Line 760  namespace {
760       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
761       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
762       */       */
763      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
764          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
765          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
766          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
767          SetPos(0); // reset read position to begin of sample          SetPos(0); // reset read position to begin of sample
768          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
769          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
# Line 785  namespace { Line 827  namespace {
827       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
828       * other formats will fail!       * other formats will fail!
829       *       *
830       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
831       *                   greater than zero)       *                  greater than zero)
832       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
833       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
834       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
835       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
836       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
837       */       */
838      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
839          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)");
840          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
841      }      }
842    
843      /**      /**
# Line 819  namespace { Line 861  namespace {
861       * @returns            the new sample position       * @returns            the new sample position
862       * @see                Read()       * @see                Read()
863       */       */
864      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) {
865          if (Compressed) {          if (Compressed) {
866              switch (Whence) {              switch (Whence) {
867                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 837  namespace { Line 879  namespace {
879              }              }
880              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
881    
882              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
883              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
884              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
885              return this->SamplePos;              return this->SamplePos;
886          }          }
887          else { // not compressed          else { // not compressed
888              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
889              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
890              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
891                                              : result / this->FrameSize;                                              : result / this->FrameSize;
892          }          }
# Line 853  namespace { Line 895  namespace {
895      /**      /**
896       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
897       */       */
898      unsigned long Sample::GetPos() const {      file_offset_t Sample::GetPos() const {
899          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
900          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
901      }      }
# Line 892  namespace { Line 934  namespace {
934       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
935       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
936       */       */
937      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,
938                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
939          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
940          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
941    
942          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 932  namespace { Line 974  namespace {
974                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
975                                  // backward playback                                  // backward playback
976    
977                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
978                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
979                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
980                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
981    
982                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
983    
# Line 983  namespace { Line 1025  namespace {
1025                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1026                          // backward playback                          // backward playback
1027    
1028                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
1029                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
1030                          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)
1031                                                                                    : samplestoread;                                                                                    : samplestoread;
1032                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1033    
1034                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1035    
# Line 1067  namespace { Line 1109  namespace {
1109       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1110       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1111       */       */
1112      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) {
1113          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1114          if (!Compressed) {          if (!Compressed) {
1115              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 1082  namespace { Line 1124  namespace {
1124          else {          else {
1125              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1126              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1127              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1128                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1129                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1130                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1105  namespace { Line 1147  namespace {
1147              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1148    
1149              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1150                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1151                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1152    
1153                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1154    
# Line 1256  namespace { Line 1298  namespace {
1298       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1299       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1300       */       */
1301      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1302          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)");
1303    
1304          // 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 1307  namespace {
1307              __resetCRC(crc);              __resetCRC(crc);
1308          }          }
1309          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");
1310          unsigned long res;          file_offset_t res;
1311          if (BitDepth == 24) {          if (BitDepth == 24) {
1312              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1313          } else { // 16 bit          } else { // 16 bit
# Line 1277  namespace { Line 1319  namespace {
1319          // if this is the last write, update the checksum chunk in the          // if this is the last write, update the checksum chunk in the
1320          // file          // file
1321          if (pCkData->GetPos() == pCkData->GetSize()) {          if (pCkData->GetPos() == pCkData->GetSize()) {
1322                __finalizeCRC(crc);
1323              File* pFile = static_cast<File*>(GetParent());              File* pFile = static_cast<File*>(GetParent());
1324              pFile->SetSampleChecksum(this, __encodeCRC(crc));              pFile->SetSampleChecksum(this, crc);
1325          }          }
1326          return res;          return res;
1327      }      }
# Line 1299  namespace { Line 1342  namespace {
1342       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1343       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1344       */       */
1345      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1346          buffer_t result;          buffer_t result;
1347          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1348                  (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;
1349          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);
1350          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1351          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1352          return result;          return result;
# Line 1337  namespace { Line 1380  namespace {
1380          return pGroup;          return pGroup;
1381      }      }
1382    
1383        /**
1384         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1385         * time when this sample's wave form data was modified for the last time
1386         * by calling Write(). This checksum only covers the raw wave form data,
1387         * not any meta informations like i.e. bit depth or loop points. Since
1388         * this method just returns the checksum stored for this sample i.e. when
1389         * the gig file was loaded, this method returns immediately. So it does no
1390         * recalcuation of the checksum with the currently available sample wave
1391         * form data.
1392         *
1393         * @see VerifyWaveData()
1394         */
1395        uint32_t Sample::GetWaveDataCRC32Checksum() {
1396            return crc;
1397        }
1398    
1399        /**
1400         * Checks the integrity of this sample's raw audio wave data. Whenever a
1401         * Sample's raw wave data is intentionally modified (i.e. by calling
1402         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1403         * is calculated and stored/updated for this sample, along to the sample's
1404         * meta informations.
1405         *
1406         * Now by calling this method the current raw audio wave data is checked
1407         * against the already stored CRC32 check sum in order to check whether the
1408         * sample data had been damaged unintentionally for some reason. Since by
1409         * calling this method always the entire raw audio wave data has to be
1410         * read, verifying all samples this way may take a long time accordingly.
1411         * And that's also the reason why the sample integrity is not checked by
1412         * default whenever a gig file is loaded. So this method must be called
1413         * explicitly to fulfill this task.
1414         *
1415         * @param pActually - (optional) if provided, will be set to the actually
1416         *                    calculated checksum of the current raw wave form data,
1417         *                    you can get the expected checksum instead by calling
1418         *                    GetWaveDataCRC32Checksum()
1419         * @returns true if sample is OK or false if the sample is damaged
1420         * @throws Exception if no checksum had been stored to disk for this
1421         *         sample yet, or on I/O issues
1422         * @see GetWaveDataCRC32Checksum()
1423         */
1424        bool Sample::VerifyWaveData(uint32_t* pActually) {
1425            //File* pFile = static_cast<File*>(GetParent());
1426            uint32_t crc = CalculateWaveDataChecksum();
1427            if (pActually) *pActually = crc;
1428            return crc == this->crc;
1429        }
1430    
1431        uint32_t Sample::CalculateWaveDataChecksum() {
1432            const size_t sz = 20*1024; // 20kB buffer size
1433            std::vector<uint8_t> buffer(sz);
1434            buffer.resize(sz);
1435    
1436            const size_t n = sz / FrameSize;
1437            SetPos(0);
1438            uint32_t crc = 0;
1439            __resetCRC(crc);
1440            while (true) {
1441                file_offset_t nRead = Read(&buffer[0], n);
1442                if (nRead <= 0) break;
1443                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1444            }
1445            __finalizeCRC(crc);
1446            return crc;
1447        }
1448    
1449      Sample::~Sample() {      Sample::~Sample() {
1450          Instances--;          Instances--;
1451          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1353  namespace { Line 1462  namespace {
1462  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1463  // *  // *
1464    
1465      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1466      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1467    
1468      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1547  namespace { Line 1656  namespace {
1656              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1657              EG2Decay1                       = 0.005;              EG2Decay1                       = 0.005;
1658              EG2Sustain                      = 1000;              EG2Sustain                      = 1000;
1659              EG2Release                      = 0.3;              EG2Release                      = 60;
1660              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1661              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1662              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
# Line 1706  namespace { Line 1815  namespace {
1815          }          }
1816      }      }
1817    
1818        void DimensionRegion::serialize(Serialization::Archive* archive) {
1819            SRLZ(VelocityUpperLimit);
1820            SRLZ(EG1PreAttack);
1821            SRLZ(EG1Attack);
1822            SRLZ(EG1Decay1);
1823            SRLZ(EG1Decay2);
1824            SRLZ(EG1InfiniteSustain);
1825            SRLZ(EG1Sustain);
1826            SRLZ(EG1Release);
1827            SRLZ(EG1Hold);
1828            SRLZ(EG1Controller);
1829            SRLZ(EG1ControllerInvert);
1830            SRLZ(EG1ControllerAttackInfluence);
1831            SRLZ(EG1ControllerDecayInfluence);
1832            SRLZ(EG1ControllerReleaseInfluence);
1833            SRLZ(LFO1Frequency);
1834            SRLZ(LFO1InternalDepth);
1835            SRLZ(LFO1ControlDepth);
1836            SRLZ(LFO1Controller);
1837            SRLZ(LFO1FlipPhase);
1838            SRLZ(LFO1Sync);
1839            SRLZ(EG2PreAttack);
1840            SRLZ(EG2Attack);
1841            SRLZ(EG2Decay1);
1842            SRLZ(EG2Decay2);
1843            SRLZ(EG2InfiniteSustain);
1844            SRLZ(EG2Sustain);
1845            SRLZ(EG2Release);
1846            SRLZ(EG2Controller);
1847            SRLZ(EG2ControllerInvert);
1848            SRLZ(EG2ControllerAttackInfluence);
1849            SRLZ(EG2ControllerDecayInfluence);
1850            SRLZ(EG2ControllerReleaseInfluence);
1851            SRLZ(LFO2Frequency);
1852            SRLZ(LFO2InternalDepth);
1853            SRLZ(LFO2ControlDepth);
1854            SRLZ(LFO2Controller);
1855            SRLZ(LFO2FlipPhase);
1856            SRLZ(LFO2Sync);
1857            SRLZ(EG3Attack);
1858            SRLZ(EG3Depth);
1859            SRLZ(LFO3Frequency);
1860            SRLZ(LFO3InternalDepth);
1861            SRLZ(LFO3ControlDepth);
1862            SRLZ(LFO3Controller);
1863            SRLZ(LFO3Sync);
1864            SRLZ(VCFEnabled);
1865            SRLZ(VCFType);
1866            SRLZ(VCFCutoffController);
1867            SRLZ(VCFCutoffControllerInvert);
1868            SRLZ(VCFCutoff);
1869            SRLZ(VCFVelocityCurve);
1870            SRLZ(VCFVelocityScale);
1871            SRLZ(VCFVelocityDynamicRange);
1872            SRLZ(VCFResonance);
1873            SRLZ(VCFResonanceDynamic);
1874            SRLZ(VCFResonanceController);
1875            SRLZ(VCFKeyboardTracking);
1876            SRLZ(VCFKeyboardTrackingBreakpoint);
1877            SRLZ(VelocityResponseCurve);
1878            SRLZ(VelocityResponseDepth);
1879            SRLZ(VelocityResponseCurveScaling);
1880            SRLZ(ReleaseVelocityResponseCurve);
1881            SRLZ(ReleaseVelocityResponseDepth);
1882            SRLZ(ReleaseTriggerDecay);
1883            SRLZ(Crossfade);
1884            SRLZ(PitchTrack);
1885            SRLZ(DimensionBypass);
1886            SRLZ(Pan);
1887            SRLZ(SelfMask);
1888            SRLZ(AttenuationController);
1889            SRLZ(InvertAttenuationController);
1890            SRLZ(AttenuationControllerThreshold);
1891            SRLZ(ChannelOffset);
1892            SRLZ(SustainDefeat);
1893            SRLZ(MSDecode);
1894            //SRLZ(SampleStartOffset);
1895            SRLZ(SampleAttenuation);
1896    
1897            // derived attributes from DLS::Sampler
1898            SRLZ(FineTune);
1899            SRLZ(Gain);
1900        }
1901    
1902      /**      /**
1903       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
1904       * which depends on this value.       * which depends on this value.
# Line 1746  namespace { Line 1939  namespace {
1939    
1940          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1941    
1942          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1943          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1944    
1945          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 3102  namespace { Line 3295  namespace {
3295          int step = 1;          int step = 1;
3296          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3297          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3298    
3299          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3300          int dim[8] = { 0 };          int dim[8] = { 0 };
3301          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3302                const int end = i + step * pDimensionDefinitions[veldim].zones;
3303    
3304                // create a velocity table for all cases where the velocity zone is zero
3305              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3306                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3307                  // create the velocity table                  // create the velocity table
# Line 3138  namespace { Line 3332  namespace {
3332                  }                  }
3333              }              }
3334    
3335                // jump to the next case where the velocity zone is zero
3336              int j;              int j;
3337              int shift = 0;              int shift = 0;
3338              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 3712  namespace { Line 3907  namespace {
3907      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3908          uint8_t bits;          uint8_t bits;
3909          int veldim = -1;          int veldim = -1;
3910          int velbitpos;          int velbitpos = 0;
3911          int bitpos = 0;          int bitpos = 0;
3912          int dimregidx = 0;          int dimregidx = 0;
3913          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 3761  namespace { Line 3956  namespace {
3956      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3957          uint8_t bits;          uint8_t bits;
3958          int veldim = -1;          int veldim = -1;
3959          int velbitpos;          int velbitpos = 0;
3960          int bitpos = 0;          int bitpos = 0;
3961          int dimregidx = 0;          int dimregidx = 0;
3962          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 3846  namespace { Line 4041  namespace {
4041          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
4042          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
4043          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
4044          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
4045          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
4046          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
4047          while (sample) {              uint64_t soughtoffset =
4048              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
4049                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
4050              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
4051                while (sample) {
4052                    if (sample->ullWavePoolOffset == soughtoffset)
4053                        return static_cast<gig::Sample*>(sample);
4054                    sample = file->GetNextSample();
4055                }
4056            } else {
4057                // use extension files and 32 bit wave pool offsets
4058                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
4059                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
4060                Sample* sample = file->GetFirstSample(pProgress);
4061                while (sample) {
4062                    if (sample->ullWavePoolOffset == soughtoffset &&
4063                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
4064                    sample = file->GetNextSample();
4065                }
4066          }          }
4067          return NULL;          return NULL;
4068      }      }
# Line 4095  namespace { Line 4305  namespace {
4305              // to handle potential future extensions of the header              // to handle potential future extensions of the header
4306              ckScri->SetPos(sizeof(int32_t) + headerSize);              ckScri->SetPos(sizeof(int32_t) + headerSize);
4307              // read actual script data              // read actual script data
4308              uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();              uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4309              data.resize(scriptSize);              data.resize(scriptSize);
4310              for (int i = 0; i < scriptSize; ++i)              for (int i = 0; i < scriptSize; ++i)
4311                  data[i] = ckScri->ReadUint8();                  data[i] = ckScri->ReadUint8();
# Line 4146  namespace { Line 4356  namespace {
4356          // recalculate CRC32 check sum          // recalculate CRC32 check sum
4357          __resetCRC(crc);          __resetCRC(crc);
4358          __calculateCRC(&data[0], data.size(), crc);          __calculateCRC(&data[0], data.size(), crc);
4359          __encodeCRC(crc);          __finalizeCRC(crc);
4360          // make sure chunk exists and has the required size          // make sure chunk exists and has the required size
4361          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();
4362          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4363          else pChunk->Resize(chunkSize);          else pChunk->Resize(chunkSize);
4364          // fill the chunk data to be written to disk          // fill the chunk data to be written to disk
4365          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4366          int pos = 0;          int pos = 0;
4367          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
4368          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4369          store32(&pData[pos], Compression);          store32(&pData[pos], Compression);
4370          pos += sizeof(int32_t);          pos += sizeof(int32_t);
# Line 4166  namespace { Line 4376  namespace {
4376          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4377          store32(&pData[pos], crc);          store32(&pData[pos], crc);
4378          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4379          store32(&pData[pos], Name.size());          store32(&pData[pos], (uint32_t) Name.size());
4380          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4381          for (int i = 0; i < Name.size(); ++i, ++pos)          for (int i = 0; i < Name.size(); ++i, ++pos)
4382              pData[pos] = Name[i];              pData[pos] = Name[i];
# Line 4197  namespace { Line 4407  namespace {
4407          return pGroup;          return pGroup;
4408      }      }
4409    
4410        /**
4411         * Make a (semi) deep copy of the Script object given by @a orig
4412         * and assign it to this object. Note: the ScriptGroup this Script
4413         * object belongs to remains untouched by this call.
4414         *
4415         * @param orig - original Script object to be copied from
4416         */
4417        void Script::CopyAssign(const Script* orig) {
4418            Name        = orig->Name;
4419            Compression = orig->Compression;
4420            Encoding    = orig->Encoding;
4421            Language    = orig->Language;
4422            Bypass      = orig->Bypass;
4423            data        = orig->data;
4424        }
4425    
4426      void Script::RemoveAllScriptReferences() {      void Script::RemoveAllScriptReferences() {
4427          File* pFile = pGroup->pFile;          File* pFile = pGroup->pFile;
4428          for (int i = 0; pFile->GetInstrument(i); ++i) {          for (int i = 0; pFile->GetInstrument(i); ++i) {
# Line 4343  namespace { Line 4569  namespace {
4569          EffectSend = 0;          EffectSend = 0;
4570          Attenuation = 0;          Attenuation = 0;
4571          FineTune = 0;          FineTune = 0;
4572          PitchbendRange = 0;          PitchbendRange = 2;
4573          PianoReleaseMode = false;          PianoReleaseMode = false;
4574          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4575          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
# Line 4518  namespace { Line 4744  namespace {
4744    
4745             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4746             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4747             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4748             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4749             const int slotSize  = 2 * sizeof(uint32_t);             const int slotSize  = 2 * sizeof(uint32_t);
4750             const int totalChunkSize = headerSize + slotCount * slotSize;             const int totalChunkSize = headerSize + slotCount * slotSize;
# Line 4554  namespace { Line 4780  namespace {
4780         if (pScriptRefs && pScriptRefs->size() > 0) {         if (pScriptRefs && pScriptRefs->size() > 0) {
4781             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4782             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4783             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4784             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4785             ckSCSL->SetPos(headerSize);             ckSCSL->SetPos(headerSize);
4786             for (int i = 0; i < slotCount; ++i) {             for (int i = 0; i < slotCount; ++i) {
4787                 uint32_t fileOffset =                 uint32_t fileOffset = uint32_t(
4788                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4789                      (*pScriptRefs)[i].script->pChunk->GetPos() -                      (*pScriptRefs)[i].script->pChunk->GetPos() -
4790                      CHUNK_HEADER_SIZE;                      CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4791                   );
4792                 ckSCSL->WriteUint32(&fileOffset);                 ckSCSL->WriteUint32(&fileOffset);
4793                 // jump over flags entry (containing the bypass flag)                 // jump over flags entry (containing the bypass flag)
4794                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
# Line 4621  namespace { Line 4848  namespace {
4848          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4849          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4850          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4851          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4852          // update Region key table for fast lookup          // update Region key table for fast lookup
4853          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4854          // done          // done
# Line 4767  namespace { Line 4994  namespace {
4994                  for (uint s = 0; group->GetScript(s); ++s) {                  for (uint s = 0; group->GetScript(s); ++s) {
4995                      Script* script = group->GetScript(s);                      Script* script = group->GetScript(s);
4996                      if (script->pChunk) {                      if (script->pChunk) {
4997                          uint32_t offset = script->pChunk->GetFilePos() -                          uint32_t offset = uint32_t(
4998                                            script->pChunk->GetPos() -                              script->pChunk->GetFilePos() -
4999                                            CHUNK_HEADER_SIZE;                              script->pChunk->GetPos() -
5000                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
5001                            );
5002                          if (offset == soughtOffset)                          if (offset == soughtOffset)
5003                          {                          {
5004                              _ScriptPooolRef ref;                              _ScriptPooolRef ref;
# Line 4894  namespace { Line 5123  namespace {
5123       */       */
5124      void Instrument::RemoveScript(Script* pScript) {      void Instrument::RemoveScript(Script* pScript) {
5125          LoadScripts();          LoadScripts();
5126          for (int i = pScriptRefs->size() - 1; i >= 0; --i) {          for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5127              if ((*pScriptRefs)[i].script == pScript) {              if ((*pScriptRefs)[i].script == pScript) {
5128                  pScriptRefs->erase( pScriptRefs->begin() + i );                  pScriptRefs->erase( pScriptRefs->begin() + i );
5129              }              }
# Line 4916  namespace { Line 5145  namespace {
5145       * gigedit.       * gigedit.
5146       */       */
5147      uint Instrument::ScriptSlotCount() const {      uint Instrument::ScriptSlotCount() const {
5148          return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();          return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5149      }      }
5150    
5151      /** @brief Whether script execution shall be skipped.      /** @brief Whether script execution shall be skipped.
# Line 5332  namespace { Line 5561  namespace {
5561          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5562    
5563          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5564            // (only for old gig files < 2 GB)
5565          int lastFileNo = 0;          int lastFileNo = 0;
5566          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5567              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5568                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5569                }
5570          }          }
5571          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5572          int nameLen = name.length();          int nameLen = (int) name.length();
5573          char suffix[6];          char suffix[6];
5574          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5575    
5576          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5577              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5578              if (wvpl) {              if (wvpl) {
5579                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5580                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5581                  while (wave) {                  while (wave) {
5582                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 5352  namespace { Line 5584  namespace {
5584                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5585                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5586    
5587                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5588                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5589    
5590                          iSampleIndex++;                          iSampleIndex++;
5591                      }                      }
# Line 5506  namespace { Line 5738  namespace {
5738              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5739              mSamples[pFile->GetSample(i)] = s;              mSamples[pFile->GetSample(i)] = s;
5740          }          }
5741            
5742            // clone script groups and their scripts
5743            for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
5744                ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
5745                ScriptGroup* dg = AddScriptGroup();
5746                dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
5747                for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
5748                    Script* ss = sg->GetScript(iScript);
5749                    Script* ds = dg->AddScript();
5750                    ds->CopyAssign(ss);
5751                }
5752            }
5753    
5754          //BUG: For some reason this method only works with this additional          //BUG: For some reason this method only works with this additional
5755          //     Save() call in between here.          //     Save() call in between here.
5756          //          //
# Line 5591  namespace { Line 5835  namespace {
5835          if (!_3crc) return;          if (!_3crc) return;
5836    
5837          // get the index of the sample          // get the index of the sample
5838          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;  
             }  
         }  
5839          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");
5840    
5841          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5842          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5843          uint32_t tmp = 1;          uint32_t one = 1;
5844          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5845          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5846      }      }
5847    
5848        uint32_t File::GetSampleChecksum(Sample* pSample) {
5849            // get the index of the sample
5850            int iWaveIndex = GetWaveTableIndexOf(pSample);
5851            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5852    
5853            return GetSampleChecksumByIndex(iWaveIndex);
5854        }
5855    
5856        uint32_t File::GetSampleChecksumByIndex(int index) {
5857            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5858    
5859            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5860            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5861            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5862            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5863    
5864            // read the CRC-32 checksum directly from disk
5865            size_t pos = index * 8;
5866            if (pos + 8 > _3crc->GetNewSize())
5867                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5868    
5869            uint32_t one = load32(&pData[pos]); // always 1
5870            if (one != 1)
5871                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5872    
5873            return load32(&pData[pos+4]);
5874        }
5875    
5876        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5877            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5878            File::SampleList::iterator iter = pSamples->begin();
5879            File::SampleList::iterator end  = pSamples->end();
5880            for (int index = 0; iter != end; ++iter, ++index)
5881                if (*iter == pSample)
5882                    return index;
5883            return -1;
5884        }
5885    
5886        /**
5887         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5888         * the CRC32 check sums of all samples' raw wave data.
5889         *
5890         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5891         */
5892        bool File::VerifySampleChecksumTable() {
5893            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5894            if (!_3crc) return false;
5895            if (_3crc->GetNewSize() <= 0) return false;
5896            if (_3crc->GetNewSize() % 8) return false;
5897            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5898            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5899    
5900            const file_offset_t n = _3crc->GetNewSize() / 8;
5901    
5902            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5903            if (!pData) return false;
5904    
5905            for (file_offset_t i = 0; i < n; ++i) {
5906                uint32_t one = pData[i*2];
5907                if (one != 1) return false;
5908            }
5909    
5910            return true;
5911        }
5912    
5913        /**
5914         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5915         * file's checksum table with those new checksums. This might usually
5916         * just be necessary if the checksum table was damaged.
5917         *
5918         * @e IMPORTANT: The current implementation of this method only works
5919         * with files that have not been modified since it was loaded, because
5920         * it expects that no externally caused file structure changes are
5921         * required!
5922         *
5923         * Due to the expectation above, this method is currently protected
5924         * and actually only used by the command line tool "gigdump" yet.
5925         *
5926         * @returns true if Save() is required to be called after this call,
5927         *          false if no further action is required
5928         */
5929        bool File::RebuildSampleChecksumTable() {
5930            // make sure sample chunks were scanned
5931            if (!pSamples) GetFirstSample();
5932    
5933            bool bRequiresSave = false;
5934    
5935            // make sure "3CRC" chunk exists with required size
5936            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5937            if (!_3crc) {
5938                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5939                // the order of einf and 3crc is not the same in v2 and v3
5940                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5941                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5942                bRequiresSave = true;
5943            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5944                _3crc->Resize(pSamples->size() * 8);
5945                bRequiresSave = true;
5946            }
5947    
5948            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5949                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5950                {
5951                    File::SampleList::iterator iter = pSamples->begin();
5952                    File::SampleList::iterator end  = pSamples->end();
5953                    for (; iter != end; ++iter) {
5954                        gig::Sample* pSample = (gig::Sample*) *iter;
5955                        int index = GetWaveTableIndexOf(pSample);
5956                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5957                        pData[index*2]   = 1; // always 1
5958                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5959                    }
5960                }
5961            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5962                // make sure file is in write mode
5963                pRIFF->SetMode(RIFF::stream_mode_read_write);
5964                {
5965                    File::SampleList::iterator iter = pSamples->begin();
5966                    File::SampleList::iterator end  = pSamples->end();
5967                    for (; iter != end; ++iter) {
5968                        gig::Sample* pSample = (gig::Sample*) *iter;
5969                        int index = GetWaveTableIndexOf(pSample);
5970                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5971                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5972                        SetSampleChecksum(pSample, pSample->crc);
5973                    }
5974                }
5975            }
5976    
5977            return bRequiresSave;
5978        }
5979    
5980      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5981          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5982          // there must always be at least one group          // there must always be at least one group
# Line 5837  namespace { Line 6205  namespace {
6205      void File::UpdateChunks(progress_t* pProgress) {      void File::UpdateChunks(progress_t* pProgress) {
6206          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6207    
         b64BitWavePoolOffsets = pVersion && pVersion->major == 3;  
   
6208          // update own gig format extension chunks          // update own gig format extension chunks
6209          // (not part of the GigaStudio 4 format)          // (not part of the GigaStudio 4 format)
6210          //          RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6211            if (!lst3LS) {
6212                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6213            }
6214            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6215            // location of <3LS > is irrelevant, however it should be located
6216            // before  the actual wave data
6217            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6218            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6219    
6220          // This must be performed before writing the chunks for instruments,          // This must be performed before writing the chunks for instruments,
6221          // because the instruments' script slots will write the file offsets          // because the instruments' script slots will write the file offsets
6222          // of the respective instrument script chunk as reference.          // of the respective instrument script chunk as reference.
6223          if (pScriptGroups) {          if (pScriptGroups) {
6224              RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);              // Update instrument script (group) chunks.
6225              if (pScriptGroups->empty()) {              for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6226                  if (lst3LS) pRIFF->DeleteSubChunk(lst3LS);                   it != pScriptGroups->end(); ++it)
6227              } else {              {
6228                  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);  
                 }  
6229              }              }
6230          }          }
6231    
6232            // in case no libgig custom format data was added, then remove the
6233            // custom "3LS " chunk again
6234            if (!lst3LS->CountSubChunks()) {
6235                pRIFF->DeleteSubChunk(lst3LS);
6236                lst3LS = NULL;
6237            }
6238    
6239          // first update base class's chunks          // first update base class's chunks
6240          DLS::File::UpdateChunks(pProgress);          DLS::File::UpdateChunks(pProgress);
6241    
# Line 5920  namespace { Line 6294  namespace {
6294          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6295          // are set to zero.          // are set to zero.
6296    
6297          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6298          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6299    
6300          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 5993  namespace { Line 6367  namespace {
6367                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6368                  // next 8 bytes unknown                  // next 8 bytes unknown
6369                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6370                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6371                  // next 4 bytes unknown                  // next 4 bytes unknown
6372    
6373                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 6011  namespace { Line 6385  namespace {
6385              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6386              // next 8 bytes unknown              // next 8 bytes unknown
6387              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6388              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6389              // next 4 bytes unknown              // next 4 bytes unknown
6390          }          }
6391    
6392          // update 3crc chunk          // update 3crc chunk
6393    
6394          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6395          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6396          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6397            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6398            // member variable). This step is required, because samples might have
6399            // been deleted by the user since the file was opened, which in turn
6400            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6401            // If a sample was conciously modified by the user (that is if
6402            // Sample::Write() was called later on) then Sample::Write() will just
6403            // update the respective individual checksum(s) directly on disk and
6404            // leaves all other sample checksums untouched.
6405    
6406          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6407          if (_3crc) {          if (_3crc) {
6408              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6409          } else if (newFile) {          } else /*if (newFile)*/ {
6410              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6411              // 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
6412              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6413          }          }
6414            { // must be performed in RAM here ...
6415                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6416                if (pData) {
6417                    File::SampleList::iterator iter = pSamples->begin();
6418                    File::SampleList::iterator end  = pSamples->end();
6419                    for (int index = 0; iter != end; ++iter, ++index) {
6420                        gig::Sample* pSample = (gig::Sample*) *iter;
6421                        pData[index*2]   = 1; // always 1
6422                        pData[index*2+1] = pSample->crc;
6423                    }
6424                }
6425            }
6426      }      }
6427            
6428      void File::UpdateFileOffsets() {      void File::UpdateFileOffsets() {

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

  ViewVC Help
Powered by ViewVC