/[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 2599 by schoenebeck, Sat Jun 7 00:00:10 2014 UTC revision 2912 by schoenebeck, Tue May 17 14:30:10 2016 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2014 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2016 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 53  Line 57 
57    
58  namespace gig {  namespace gig {
59    
 // *************** progress_t ***************  
 // *  
   
     progress_t::progress_t() {  
         callback    = NULL;  
         custom      = NULL;  
         __range_min = 0.0f;  
         __range_max = 1.0f;  
     }  
   
     // private helper function to convert progress of a subprocess into the global progress  
     static void __notify_progress(progress_t* pProgress, float subprogress) {  
         if (pProgress && pProgress->callback) {  
             const float totalrange    = pProgress->__range_max - pProgress->__range_min;  
             const float totalprogress = pProgress->__range_min + subprogress * totalrange;  
             pProgress->factor         = totalprogress;  
             pProgress->callback(pProgress); // now actually notify about the progress  
         }  
     }  
   
     // private helper function to divide a progress into subprogresses  
     static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {  
         if (pParentProgress && pParentProgress->callback) {  
             const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;  
             pSubProgress->callback    = pParentProgress->callback;  
             pSubProgress->custom      = pParentProgress->custom;  
             pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;  
             pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;  
         }  
     }  
   
   
60  // *************** Internal functions for sample decompression ***************  // *************** Internal functions for sample decompression ***************
61  // *  // *
62    
# Line 123  namespace { Line 95  namespace {
95      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
96                        int srcStep, int dstStep,                        int srcStep, int dstStep,
97                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
98                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
99                        unsigned long copysamples)                        file_offset_t copysamples)
100      {      {
101          switch (compressionmode) {          switch (compressionmode) {
102              case 0: // 16 bit uncompressed              case 0: // 16 bit uncompressed
# Line 160  namespace { Line 132  namespace {
132    
133      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
134                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
135                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
136                        unsigned long copysamples, int truncatedBits)                        file_offset_t copysamples, int truncatedBits)
137      {      {
138          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
139    
# Line 367  namespace { Line 339  namespace {
339       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
340       *                         is located, 0 otherwise       *                         is located, 0 otherwise
341       */       */
342      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) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
343          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
344              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
345              { 0, 0 }              { 0, 0 }
# Line 509  namespace { Line 481  namespace {
481          const int iReadAtOnce = 32*1024;          const int iReadAtOnce = 32*1024;
482          char* buf = new char[iReadAtOnce * orig->FrameSize];          char* buf = new char[iReadAtOnce * orig->FrameSize];
483          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
484          unsigned long restorePos = pOrig->GetPos();          file_offset_t restorePos = pOrig->GetPos();
485          pOrig->SetPos(0);          pOrig->SetPos(0);
486          SetPos(0);          SetPos(0);
487          for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;          for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
488                             n = pOrig->Read(buf, iReadAtOnce))                             n = pOrig->Read(buf, iReadAtOnce))
489          {          {
490              Write(buf, n);              Write(buf, n);
# Line 528  namespace { Line 500  namespace {
500       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
501       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
502       *       *
503         * @param pProgress - callback function for progress notification
504       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
505       *                        was provided yet       *                        was provided yet
506       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
507       */       */
508      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
509          // first update base class's chunks          // first update base class's chunks
510          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
511    
512          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
513          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 596  namespace { Line 569  namespace {
569      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
570          //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)
571          this->SamplesTotal = 0;          this->SamplesTotal = 0;
572          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
573    
574          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
575          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 612  namespace { Line 585  namespace {
585                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
586                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
587                  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");
588                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
589    
590                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
591                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 631  namespace { Line 604  namespace {
604    
605                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
606                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
607                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
608    
609                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
610                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 647  namespace { Line 620  namespace {
620    
621          // 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)
622          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
623          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
624          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
625          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
626          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
627              FrameTable[i] = *iter;              FrameTable[i] = *iter;
628          }          }
# Line 690  namespace { Line 663  namespace {
663       *                      the cached sample data in bytes       *                      the cached sample data in bytes
664       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
665       */       */
666      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
667          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
668      }      }
669    
# Line 749  namespace { Line 722  namespace {
722       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
723       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
724       */       */
725      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
726          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
727          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
728          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
729          SetPos(0); // reset read position to begin of sample          SetPos(0); // reset read position to begin of sample
730          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
731          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
# Line 850  namespace { Line 823  namespace {
823       * @returns            the new sample position       * @returns            the new sample position
824       * @see                Read()       * @see                Read()
825       */       */
826      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) {
827          if (Compressed) {          if (Compressed) {
828              switch (Whence) {              switch (Whence) {
829                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 868  namespace { Line 841  namespace {
841              }              }
842              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
843    
844              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
845              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
846              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
847              return this->SamplePos;              return this->SamplePos;
848          }          }
849          else { // not compressed          else { // not compressed
850              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
851              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
852              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
853                                              : result / this->FrameSize;                                              : result / this->FrameSize;
854          }          }
# Line 884  namespace { Line 857  namespace {
857      /**      /**
858       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
859       */       */
860      unsigned long Sample::GetPos() const {      file_offset_t Sample::GetPos() const {
861          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
862          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
863      }      }
# Line 923  namespace { Line 896  namespace {
896       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
897       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
898       */       */
899      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,
900                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
901          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
902          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
903    
904          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 963  namespace { Line 936  namespace {
936                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
937                                  // backward playback                                  // backward playback
938    
939                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
940                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
941                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
942                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
943    
944                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
945    
# Line 1014  namespace { Line 987  namespace {
987                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
988                          // backward playback                          // backward playback
989    
990                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
991                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
992                          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)
993                                                                                    : samplestoread;                                                                                    : samplestoread;
994                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
995    
996                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
997    
# Line 1098  namespace { Line 1071  namespace {
1071       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1072       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1073       */       */
1074      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) {
1075          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1076          if (!Compressed) {          if (!Compressed) {
1077              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 1113  namespace { Line 1086  namespace {
1086          else {          else {
1087              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1088              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1089              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1090                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1091                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1092                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1136  namespace { Line 1109  namespace {
1109              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1110    
1111              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1112                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1113                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1114    
1115                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1116    
# Line 1287  namespace { Line 1260  namespace {
1260       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1261       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1262       */       */
1263      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1264          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)");
1265    
1266          // if this is the first write in this sample, reset the          // if this is the first write in this sample, reset the
# Line 1296  namespace { Line 1269  namespace {
1269              __resetCRC(crc);              __resetCRC(crc);
1270          }          }
1271          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");
1272          unsigned long res;          file_offset_t res;
1273          if (BitDepth == 24) {          if (BitDepth == 24) {
1274              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1275          } else { // 16 bit          } else { // 16 bit
# Line 1330  namespace { Line 1303  namespace {
1303       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1304       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1305       */       */
1306      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1307          buffer_t result;          buffer_t result;
1308          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1309                  (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;
1310          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);
1311          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1312          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1313          return result;          return result;
# Line 1752  namespace { Line 1725  namespace {
1725       *       *
1726       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1727       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1728         *
1729         * @param pProgress - callback function for progress notification
1730       */       */
1731      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1732          // first update base class's chunk          // first update base class's chunk
1733          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1734    
1735          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1736          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
# Line 3026  namespace { Line 3001  namespace {
3001       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3002       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3003       *       *
3004         * @param pProgress - callback function for progress notification
3005       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3006       */       */
3007      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3008          // in the gig format we don't care about the Region's sample reference          // in the gig format we don't care about the Region's sample reference
3009          // but we still have to provide some existing one to not corrupt the          // but we still have to provide some existing one to not corrupt the
3010          // file, so to avoid the latter we simply always assign the sample of          // file, so to avoid the latter we simply always assign the sample of
# Line 3036  namespace { Line 3012  namespace {
3012          pSample = pDimensionRegions[0]->pSample;          pSample = pDimensionRegions[0]->pSample;
3013    
3014          // first update base class's chunks          // first update base class's chunks
3015          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3016    
3017          // update dimension region's chunks          // update dimension region's chunks
3018          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3019              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3020          }          }
3021    
3022          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
# Line 3652  namespace { Line 3628  namespace {
3628          UpdateVelocityTable();          UpdateVelocityTable();
3629      }      }
3630    
3631        /** @brief Change type of an existing dimension.
3632         *
3633         * Alters the dimension type of a dimension already existing on this
3634         * region. If there is currently no dimension on this Region with type
3635         * @a oldType, then this call with throw an Exception. Likewise there are
3636         * cases where the requested dimension type cannot be performed. For example
3637         * if the new dimension type shall be gig::dimension_samplechannel, and the
3638         * current dimension has more than 2 zones. In such cases an Exception is
3639         * thrown as well.
3640         *
3641         * @param oldType - identifies the existing dimension to be changed
3642         * @param newType - to which dimension type it should be changed to
3643         * @throws gig::Exception if requested change cannot be performed
3644         */
3645        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3646            if (oldType == newType) return;
3647            dimension_def_t* def = GetDimensionDefinition(oldType);
3648            if (!def)
3649                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3650            if (newType == dimension_samplechannel && def->zones != 2)
3651                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3652            if (GetDimensionDefinition(newType))
3653                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3654            def->dimension  = newType;
3655            def->split_type = __resolveSplitType(newType);
3656        }
3657    
3658      DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {      DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3659          uint8_t bits[8] = {};          uint8_t bits[8] = {};
3660          for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();          for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
# Line 3847  namespace { Line 3850  namespace {
3850          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3851          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3852          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
3853          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          if (file->HasMonolithicLargeFilePolicy()) {
3854          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];              uint64_t soughtoffset =
3855          Sample* sample = file->GetFirstSample(pProgress);                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
3856          while (sample) {                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
3857              if (sample->ulWavePoolOffset == soughtoffset &&              Sample* sample = file->GetFirstSample(pProgress);
3858                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);              while (sample) {
3859              sample = file->GetNextSample();                  if (sample->ullWavePoolOffset == soughtoffset)
3860                        return static_cast<gig::Sample*>(sample);
3861                    sample = file->GetNextSample();
3862                }
3863            } else {
3864                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3865                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3866                Sample* sample = file->GetFirstSample(pProgress);
3867                while (sample) {
3868                    if (sample->ullWavePoolOffset == soughtoffset &&
3869                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3870                    sample = file->GetNextSample();
3871                }
3872          }          }
3873          return NULL;          return NULL;
3874      }      }
# Line 4094  namespace { Line 4109  namespace {
4109              for (int i = 0; i < nameSize; ++i)              for (int i = 0; i < nameSize; ++i)
4110                  Name[i] = ckScri->ReadUint8();                  Name[i] = ckScri->ReadUint8();
4111              // to handle potential future extensions of the header              // to handle potential future extensions of the header
4112              ckScri->SetPos(headerSize - 6*sizeof(int32_t) + nameSize, RIFF::stream_curpos);              ckScri->SetPos(sizeof(int32_t) + headerSize);
4113              // read actual script data              // read actual script data
4114              uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();              uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4115              data.resize(scriptSize);              data.resize(scriptSize);
# Line 4134  namespace { Line 4149  namespace {
4149          memcpy(&data[0], &text[0], text.size());          memcpy(&data[0], &text[0], text.size());
4150      }      }
4151    
4152      void Script::UpdateChunks() {      /**
4153         * Apply this script to the respective RIFF chunks. You have to call
4154         * File::Save() to make changes persistent.
4155         *
4156         * Usually there is absolutely no need to call this method explicitly.
4157         * It will be called automatically when File::Save() was called.
4158         *
4159         * @param pProgress - callback function for progress notification
4160         */
4161        void Script::UpdateChunks(progress_t* pProgress) {
4162          // recalculate CRC32 check sum          // recalculate CRC32 check sum
4163          __resetCRC(crc);          __resetCRC(crc);
4164          __calculateCRC(&data[0], data.size(), crc);          __calculateCRC(&data[0], data.size(), crc);
# Line 4173  namespace { Line 4197  namespace {
4197       * @param pGroup - script's new group       * @param pGroup - script's new group
4198       */       */
4199      void Script::SetGroup(ScriptGroup* pGroup) {      void Script::SetGroup(ScriptGroup* pGroup) {
4200          if (this->pGroup = pGroup) return;          if (this->pGroup == pGroup) return;
4201          if (pChunk)          if (pChunk)
4202              pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);              pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4203          this->pGroup = pGroup;          this->pGroup = pGroup;
4204      }      }
4205    
4206        /**
4207         * Returns the script group this script currently belongs to. Each script
4208         * is a member of exactly one ScriptGroup.
4209         *
4210         * @returns current script group
4211         */
4212        ScriptGroup* Script::GetGroup() const {
4213            return pGroup;
4214        }
4215    
4216      void Script::RemoveAllScriptReferences() {      void Script::RemoveAllScriptReferences() {
4217          File* pFile = pGroup->pFile;          File* pFile = pGroup->pFile;
4218          for (int i = 0; pFile->GetInstrument(i); ++i) {          for (int i = 0; pFile->GetInstrument(i); ++i) {
# Line 4214  namespace { Line 4248  namespace {
4248          }          }
4249      }      }
4250    
4251      void ScriptGroup::UpdateChunks() {      /**
4252         * Apply this script group to the respective RIFF chunks. You have to call
4253         * File::Save() to make changes persistent.
4254         *
4255         * Usually there is absolutely no need to call this method explicitly.
4256         * It will be called automatically when File::Save() was called.
4257         *
4258         * @param pProgress - callback function for progress notification
4259         */
4260        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4261          if (pScripts) {          if (pScripts) {
4262              if (!pList)              if (!pList)
4263                  pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);                  pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
# Line 4225  namespace { Line 4268  namespace {
4268              for (std::list<Script*>::iterator it = pScripts->begin();              for (std::list<Script*>::iterator it = pScripts->begin();
4269                   it != pScripts->end(); ++it)                   it != pScripts->end(); ++it)
4270              {              {
4271                  (*it)->UpdateChunks();                  (*it)->UpdateChunks(pProgress);
4272              }              }
4273          }          }
4274      }      }
# Line 4388  namespace { Line 4431  namespace {
4431          if (lst3LS) {          if (lst3LS) {
4432              RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);              RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4433              if (ckSCSL) {              if (ckSCSL) {
4434                  int slotCount = ckSCSL->ReadUint32();                  int headerSize = ckSCSL->ReadUint32();
4435                  int slotSize  = ckSCSL->ReadUint32();                  int slotCount  = ckSCSL->ReadUint32();
4436                  int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future extensions                  if (slotCount) {
4437                  for (int i = 0; i < slotCount; ++i) {                      int slotSize  = ckSCSL->ReadUint32();
4438                      _ScriptPooolEntry e;                      ckSCSL->SetPos(headerSize); // in case of future header extensions
4439                      e.fileOffset = ckSCSL->ReadUint32();                      int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4440                      e.bypass     = ckSCSL->ReadUint32() & 1;                      for (int i = 0; i < slotCount; ++i) {
4441                      if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions                          _ScriptPooolEntry e;
4442                      scriptPoolFileOffsets.push_back(e);                          e.fileOffset = ckSCSL->ReadUint32();
4443                            e.bypass     = ckSCSL->ReadUint32() & 1;
4444                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4445                            scriptPoolFileOffsets.push_back(e);
4446                        }
4447                  }                  }
4448              }              }
4449          }          }
# Line 4431  namespace { Line 4478  namespace {
4478       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4479       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4480       *       *
4481         * @param pProgress - callback function for progress notification
4482       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4483       */       */
4484      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4485          // first update base classes' chunks          // first update base classes' chunks
4486          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4487    
4488          // update Regions' chunks          // update Regions' chunks
4489          {          {
4490              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4491              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4492              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4493                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4494          }          }
4495    
4496          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 4479  namespace { Line 4527  namespace {
4527          }          }
4528    
4529          // own gig format extensions          // own gig format extensions
4530         if (pScriptRefs) {         if (ScriptSlotCount()) {
4531               // make sure we have converted the original loaded script file
4532               // offsets into valid Script object pointers
4533               LoadScripts();
4534    
4535             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4536             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4537             const int totalSize = pScriptRefs->size() * 2*sizeof(uint32_t);             const int slotCount = pScriptRefs->size();
4538               const int headerSize = 3 * sizeof(uint32_t);
4539               const int slotSize  = 2 * sizeof(uint32_t);
4540               const int totalChunkSize = headerSize + slotCount * slotSize;
4541             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4542             if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalSize);             if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4543             else ckSCSL->Resize(totalSize);             else ckSCSL->Resize(totalChunkSize);
4544             uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();             uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4545             for (int i = 0, pos = 0; i < pScriptRefs->size(); ++i) {             int pos = 0;
4546                 int fileOffset =             store32(&pData[pos], headerSize);
4547                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -             pos += sizeof(uint32_t);
4548                      (*pScriptRefs)[i].script->pChunk->GetPos() -             store32(&pData[pos], slotCount);
4549                      CHUNK_HEADER_SIZE;             pos += sizeof(uint32_t);
4550                 store32(&pData[pos], fileOffset);             store32(&pData[pos], slotSize);
4551               pos += sizeof(uint32_t);
4552               for (int i = 0; i < slotCount; ++i) {
4553                   // arbitrary value, the actual file offset will be updated in
4554                   // UpdateScriptFileOffsets() after the file has been resized
4555                   int bogusFileOffset = 0;
4556                   store32(&pData[pos], bogusFileOffset);
4557                 pos += sizeof(uint32_t);                 pos += sizeof(uint32_t);
4558                 store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);                 store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4559                 pos += sizeof(uint32_t);                 pos += sizeof(uint32_t);
4560             }             }
4561           } else {
4562               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4563               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4564               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4565         }         }
4566      }      }
4567    
4568        void Instrument::UpdateScriptFileOffsets() {
4569           // own gig format extensions
4570           if (pScriptRefs && pScriptRefs->size() > 0) {
4571               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4572               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4573               const int slotCount = pScriptRefs->size();
4574               const int headerSize = 3 * sizeof(uint32_t);
4575               ckSCSL->SetPos(headerSize);
4576               for (int i = 0; i < slotCount; ++i) {
4577                   uint32_t fileOffset =
4578                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4579                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4580                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize());
4581                   ckSCSL->WriteUint32(&fileOffset);
4582                   // jump over flags entry (containing the bypass flag)
4583                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4584               }
4585           }        
4586        }
4587    
4588      /**      /**
4589       * Returns the appropriate Region for a triggered note.       * Returns the appropriate Region for a triggered note.
4590       *       *
# Line 4567  namespace { Line 4652  namespace {
4652      }      }
4653    
4654      /**      /**
4655         * Move this instrument at the position before @arg dst.
4656         *
4657         * This method can be used to reorder the sequence of instruments in a
4658         * .gig file. This might be helpful especially on large .gig files which
4659         * contain a large number of instruments within the same .gig file. So
4660         * grouping such instruments to similar ones, can help to keep track of them
4661         * when working with such complex .gig files.
4662         *
4663         * When calling this method, this instrument will be removed from in its
4664         * current position in the instruments list and moved to the requested
4665         * target position provided by @param dst. You may also pass NULL as
4666         * argument to this method, in that case this intrument will be moved to the
4667         * very end of the .gig file's instrument list.
4668         *
4669         * You have to call Save() to make the order change persistent to the .gig
4670         * file.
4671         *
4672         * Currently this method is limited to moving the instrument within the same
4673         * .gig file. Trying to move it to another .gig file by calling this method
4674         * will throw an exception.
4675         *
4676         * @param dst - destination instrument at which this instrument will be
4677         *              moved to, or pass NULL for moving to end of list
4678         * @throw gig::Exception if this instrument and target instrument are not
4679         *                       part of the same file
4680         */
4681        void Instrument::MoveTo(Instrument* dst) {
4682            if (dst && GetParent() != dst->GetParent())
4683                throw Exception(
4684                    "gig::Instrument::MoveTo() can only be used for moving within "
4685                    "the same gig file."
4686                );
4687    
4688            File* pFile = (File*) GetParent();
4689    
4690            // move this instrument within the instrument list
4691            {
4692                File::InstrumentList& list = *pFile->pInstruments;
4693    
4694                File::InstrumentList::iterator itFrom =
4695                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4696    
4697                File::InstrumentList::iterator itTo =
4698                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4699    
4700                list.splice(itTo, list, itFrom);
4701            }
4702    
4703            // move the instrument's actual list RIFF chunk appropriately
4704            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4705            lstCkInstruments->MoveSubChunk(
4706                this->pCkInstrument,
4707                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4708            );
4709        }
4710    
4711        /**
4712       * Returns a MIDI rule of the instrument.       * Returns a MIDI rule of the instrument.
4713       *       *
4714       * The list of MIDI rules, at least in gig v3, always contains at       * The list of MIDI rules, at least in gig v3, always contains at
# Line 4635  namespace { Line 4777  namespace {
4777          if (scriptPoolFileOffsets.empty()) return;          if (scriptPoolFileOffsets.empty()) return;
4778          File* pFile = (File*) GetParent();          File* pFile = (File*) GetParent();
4779          for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {          for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4780              uint32_t offset = scriptPoolFileOffsets[k].fileOffset;              uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4781              for (uint i = 0; pFile->GetScriptGroup(i); ++i) {              for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4782                  ScriptGroup* group = pFile->GetScriptGroup(i);                  ScriptGroup* group = pFile->GetScriptGroup(i);
4783                  for (uint s = 0; group->GetScript(s); ++s) {                  for (uint s = 0; group->GetScript(s); ++s) {
4784                      Script* script = group->GetScript(s);                      Script* script = group->GetScript(s);
4785                      if (script->pChunk) {                      if (script->pChunk) {
4786                          script->pChunk->SetPos(0);                          uint32_t offset = script->pChunk->GetFilePos() -
4787                          if (script->pChunk->GetFilePos() -                                            script->pChunk->GetPos() -
4788                              script->pChunk->GetPos() -                                            CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize());
4789                              CHUNK_HEADER_SIZE == offset)                          if (offset == soughtOffset)
4790                          {                          {
4791                              _ScriptPooolRef ref;                              _ScriptPooolRef ref;
4792                              ref.script = script;                              ref.script = script;
# Line 4926  namespace { Line 5068  namespace {
5068       *       *
5069       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5070       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5071         *
5072         * @param pProgress - callback function for progress notification
5073       */       */
5074      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5075          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5076          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5077          if (!_3gri) {          if (!_3gri) {
# Line 5205  namespace { Line 5349  namespace {
5349    
5350          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5351          int lastFileNo = 0;          int lastFileNo = 0;
5352          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!HasMonolithicLargeFilePolicy()) {
5353              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5354                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5355                }
5356          }          }
5357          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5358          int nameLen = name.length();          int nameLen = name.length();
# Line 5216  namespace { Line 5362  namespace {
5362          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5363              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5364              if (wvpl) {              if (wvpl) {
5365                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5366                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5367                  while (wave) {                  while (wave) {
5368                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 5224  namespace { Line 5370  namespace {
5370                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5371                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5372    
5373                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5374                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
5375    
5376                          iSampleIndex++;                          iSampleIndex++;
# Line 5695  namespace { Line 5841  namespace {
5841          }          }
5842      }      }
5843    
5844        /** @brief Returns the version number of libgig's Giga file format extension.
5845         *
5846         * libgig added several new features which were not available with the
5847         * original GigaStudio software. For those purposes libgig's own custom RIFF
5848         * chunks were added to the Giga file format.
5849         *
5850         * This method returns the version number of the Giga file format extension
5851         * used in this Giga file. Currently there are 3 possible values that might
5852         * be returned by this method:
5853         *
5854         * - @c 0: This gig file is not using any libgig specific file format
5855         *         extension at all.
5856         * - @c 1: This gig file uses the RT instrument script format extension.
5857         * - @c 2: This gig file additionally provides support for monolithic
5858         *         large gig files (larger than 2 GB).
5859         *
5860         * @note This method is currently protected and shall not be used as public
5861         * API method, since its method signature might change in future.
5862         */
5863        uint File::GetFormatExtensionVersion() const {
5864            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
5865            if (!lst3LS) return 0; // is not using custom Giga format extensions at all
5866            RIFF::Chunk* ckFFmt = lst3LS->GetSubChunk(CHUNK_ID_FFMT);
5867            if (!ckFFmt) return 1; // uses custom Giga format extension(s) but had no format version saved
5868            uint8_t* pData = (uint8_t*) ckFFmt->LoadChunkData();
5869            return load32(pData);
5870        }
5871    
5872        /** @brief Returns true in case this file is stored as one, single monolithic gig file.
5873         *
5874         * To avoid issues with operating systems which did not support large files
5875         * (larger than 2 GB) the original Giga file format avoided to ever save gig
5876         * files larger than 2 GB, instead such large Giga files were splitted into
5877         * several files, each one not being larger than 2 GB. It used a predefined
5878         * file name scheme for them like this:
5879         * @code
5880         * foo.gig
5881         * foo.gx01
5882         * foo.gx02
5883         * foo.gx03
5884         * ...
5885         * @endcode
5886         * So when like in this example foo.gig was loaded, all other files
5887         * (foo.gx01, ...) were automatically loaded as well to make up the overall
5888         * large gig file (provided they were located at the same directory). Such
5889         * additional .gxYY files were called "extension files".
5890         *
5891         * Since nowadays all modern systems support large files, libgig always
5892         * saves large gig files as one single monolithic gig file instead, that
5893         * is libgig won't split such a large gig file into separate files like the
5894         * original GigaStudio software did. It uses a custom Giga file format
5895         * extension for this feature.
5896         *
5897         * For still being able though to load old splitted gig files and the new
5898         * large monolithic ones, this method is used to determine which loading
5899         * policy must be used for this gig file.
5900         *
5901         * @note This method is currently protected and shall not be used as public
5902         * API method, since its method signature might change in future and since
5903         * this method should not be directly relevant for applications based on
5904         * libgig.
5905         */
5906        bool File::HasMonolithicLargeFilePolicy() const {
5907            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
5908            if (!lst3LS) return false;
5909            RIFF::Chunk* ckFFmt = lst3LS->GetSubChunk(CHUNK_ID_FFMT);
5910            if (!ckFFmt) return false;
5911            uint8_t* pData = (uint8_t*) ckFFmt->LoadChunkData();
5912            uint32_t formatBitField = load32(&pData[4]);
5913            return formatBitField & 1;
5914        }
5915    
5916      /**      /**
5917       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
5918       * to the respective RIFF chunks. You have to call Save() to make changes       * to the respective RIFF chunks. You have to call Save() to make changes
# Line 5703  namespace { Line 5921  namespace {
5921       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5922       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5923       *       *
5924         * @param pProgress - callback function for progress notification
5925       * @throws Exception - on errors       * @throws Exception - on errors
5926       */       */
5927      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
5928          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
5929    
5930          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
5931    
5932          // update own gig format extension chunks          // update own gig format extension chunks
5933          // (not part of the GigaStudio 4 format)          // (not part of the GigaStudio 4 format)
5934            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
5935            if (!lst3LS) {
5936                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
5937            }
5938            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
5939            // location of <3LS > is irrelevant, however it MUST BE located BEFORE
5940            // the actual wave data, otherwise the <3LS > chunk becomes
5941            // inaccessible on gig files larger than 4GB !
5942            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
5943            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
5944    
5945            // Update <FFmt> chunk with informations about our file format
5946            // extensions. Currently this <FFmt> chunk has the following
5947            // layout:
5948          //          //
5949            // <uint32> -> (libgig's) File Format Extension version
5950            // <uint32> -> Format bit field:
5951            //             bit 0: If flag is not set use separate .gx01
5952            //                    extension files if file is larger than 2 GB
5953            //                    like with the original Giga format, if flag
5954            //                    is set use 64 bit sample references and keep
5955            //                    everything as one single monolithic gig file.
5956            RIFF::Chunk* ckFFmt = lst3LS->GetSubChunk(CHUNK_ID_FFMT);
5957            if (!ckFFmt) {
5958                const int iChunkSize = 2 * sizeof(uint32_t);
5959                ckFFmt = lst3LS->AddSubChunk(CHUNK_ID_FFMT, iChunkSize);
5960            }
5961            {
5962                uint8_t* pData = (uint8_t*) ckFFmt->LoadChunkData();
5963                store32(&pData[0], GIG_FILE_EXT_VERSION);
5964                // for now we always save gig files larger than 2 GB as one
5965                // single monolithic file (saving those with extension files is
5966                // currently not supported and probably also not desired anymore
5967                // nowadays).
5968                uint32_t formatBitfield = 1;
5969                store32(&pData[4], formatBitfield);
5970            }
5971          // This must be performed before writing the chunks for instruments,          // This must be performed before writing the chunks for instruments,
5972          // because the instruments' script slots will write the file offsets          // because the instruments' script slots will write the file offsets
5973          // of the respective instrument script chunk as reference.          // of the respective instrument script chunk as reference.
5974          if (pScriptGroups) {          if (pScriptGroups) {
5975              RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);              // Update instrument script (group) chunks.
5976              if (pScriptGroups->empty()) {              for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5977                  if (lst3LS) pRIFF->DeleteSubChunk(lst3LS);                   it != pScriptGroups->end(); ++it)
5978              } else {              {
5979                  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();  
                 }  
5980              }              }
5981          }          }
5982    
5983          // first update base class's chunks          // first update base class's chunks
5984          DLS::File::UpdateChunks();          DLS::File::UpdateChunks(pProgress);
5985    
5986          if (newFile) {          if (newFile) {
5987              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
# Line 5771  namespace { Line 6018  namespace {
6018              std::list<Group*>::iterator iter = pGroups->begin();              std::list<Group*>::iterator iter = pGroups->begin();
6019              std::list<Group*>::iterator end  = pGroups->end();              std::list<Group*>::iterator end  = pGroups->end();
6020              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
6021                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
6022              }              }
6023          }          }
6024    
# Line 5903  namespace { Line 6150  namespace {
6150              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6151          }          }
6152      }      }
6153        
6154        void File::UpdateFileOffsets() {
6155            DLS::File::UpdateFileOffsets();
6156    
6157            for (Instrument* instrument = GetFirstInstrument(); instrument;
6158                 instrument = GetNextInstrument())
6159            {
6160                instrument->UpdateScriptFileOffsets();
6161            }
6162        }
6163    
6164      /**      /**
6165       * Enable / disable automatic loading. By default this properyt is       * Enable / disable automatic loading. By default this properyt is

Legend:
Removed from v.2599  
changed lines
  Added in v.2912

  ViewVC Help
Powered by ViewVC