/[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 2985 by schoenebeck, Tue Sep 20 22:13:37 2016 UTC revision 3140 by schoenebeck, Wed May 3 16:19:53 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-2016 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2017 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 24  Line 24 
24  #include "gig.h"  #include "gig.h"
25    
26  #include "helper.h"  #include "helper.h"
27    #include "Serialization.h"
28    
29  #include <algorithm>  #include <algorithm>
30  #include <math.h>  #include <math.h>
# Line 55  Line 56 
56  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
57  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
58    
59    #define SRLZ(member) \
60        archive->serializeMember(*this, member, #member);
61    
62  namespace gig {  namespace gig {
63    
64  // *************** Internal functions for sample decompression ***************  // *************** Internal functions for sample decompression ***************
# Line 269  namespace { Line 273  namespace {
273       * steps.       * steps.
274       *       *
275       * Once the whole data was processed by __calculateCRC(), one should       * Once the whole data was processed by __calculateCRC(), one should
276       * call __encodeCRC() to get the final CRC result.       * call __finalizeCRC() to get the final CRC result.
277       *       *
278       * @param buf     - pointer to data the CRC shall be calculated of       * @param buf     - pointer to data the CRC shall be calculated of
279       * @param bufSize - size of the data to be processed       * @param bufSize - size of the data to be processed
280       * @param crc     - variable the CRC sum shall be stored to       * @param crc     - variable the CRC sum shall be stored to
281       */       */
282      static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {      static void __calculateCRC(unsigned char* buf, size_t bufSize, uint32_t& crc) {
283          for (int i = 0 ; i < bufSize ; i++) {          for (size_t i = 0 ; i < bufSize ; i++) {
284              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
285          }          }
286      }      }
# Line 286  namespace { Line 290  namespace {
290       *       *
291       * @param crc - variable previously passed to __calculateCRC()       * @param crc - variable previously passed to __calculateCRC()
292       */       */
293      inline static uint32_t __encodeCRC(const uint32_t& crc) {      inline static void __finalizeCRC(uint32_t& crc) {
294          return crc ^ 0xffffffff;          crc ^= 0xffffffff;
295      }      }
296    
297    
# Line 315  namespace { Line 319  namespace {
319    
320    
321    
322    // *************** leverage_ctrl_t ***************
323    // *
324    
325        void leverage_ctrl_t::serialize(Serialization::Archive* archive) {
326            SRLZ(type);
327            SRLZ(controller_number);
328        }
329    
330    
331    
332    // *************** crossfade_t ***************
333    // *
334    
335        void crossfade_t::serialize(Serialization::Archive* archive) {
336            SRLZ(in_start);
337            SRLZ(in_end);
338            SRLZ(out_start);
339            SRLZ(out_end);
340        }
341    
342    
343    
344  // *************** Sample ***************  // *************** Sample ***************
345  // *  // *
346    
# Line 338  namespace { Line 364  namespace {
364       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
365       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
366       *                         is located, 0 otherwise       *                         is located, 0 otherwise
367         * @param index          - wave pool index of sample (may be -1 on new sample)
368       */       */
369      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo, int index)
370            : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
371        {
372          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
373              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
374              { 0, 0 }              { 0, 0 }
# Line 349  namespace { Line 378  namespace {
378          FileNo = fileNo;          FileNo = fileNo;
379    
380          __resetCRC(crc);          __resetCRC(crc);
381            // if this is not a new sample, try to get the sample's already existing
382            // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
383            // checksum of the time when the sample was consciously modified by the
384            // user for the last time (by calling Sample::Write() that is).
385            if (index >= 0) { // not a new file ...
386                try {
387                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
388                    this->crc = crc;
389                } catch (...) {}
390            }
391    
392          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
393          if (pCk3gix) {          if (pCk3gix) {
# Line 1281  namespace { Line 1320  namespace {
1320          // if this is the last write, update the checksum chunk in the          // if this is the last write, update the checksum chunk in the
1321          // file          // file
1322          if (pCkData->GetPos() == pCkData->GetSize()) {          if (pCkData->GetPos() == pCkData->GetSize()) {
1323                __finalizeCRC(crc);
1324              File* pFile = static_cast<File*>(GetParent());              File* pFile = static_cast<File*>(GetParent());
1325              pFile->SetSampleChecksum(this, __encodeCRC(crc));              pFile->SetSampleChecksum(this, crc);
1326          }          }
1327          return res;          return res;
1328      }      }
# Line 1342  namespace { Line 1382  namespace {
1382      }      }
1383    
1384      /**      /**
1385         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1386         * time when this sample's wave form data was modified for the last time
1387         * by calling Write(). This checksum only covers the raw wave form data,
1388         * not any meta informations like i.e. bit depth or loop points. Since
1389         * this method just returns the checksum stored for this sample i.e. when
1390         * the gig file was loaded, this method returns immediately. So it does no
1391         * recalcuation of the checksum with the currently available sample wave
1392         * form data.
1393         *
1394         * @see VerifyWaveData()
1395         */
1396        uint32_t Sample::GetWaveDataCRC32Checksum() {
1397            return crc;
1398        }
1399    
1400        /**
1401       * Checks the integrity of this sample's raw audio wave data. Whenever a       * Checks the integrity of this sample's raw audio wave data. Whenever a
1402       * Sample's raw wave data is intentionally modified (i.e. by calling       * Sample's raw wave data is intentionally modified (i.e. by calling
1403       * Write() and supplying the new raw audio wave form data) a CRC32 checksum       * Write() and supplying the new raw audio wave form data) a CRC32 checksum
# Line 1357  namespace { Line 1413  namespace {
1413       * default whenever a gig file is loaded. So this method must be called       * default whenever a gig file is loaded. So this method must be called
1414       * explicitly to fulfill this task.       * explicitly to fulfill this task.
1415       *       *
1416         * @param pActually - (optional) if provided, will be set to the actually
1417         *                    calculated checksum of the current raw wave form data,
1418         *                    you can get the expected checksum instead by calling
1419         *                    GetWaveDataCRC32Checksum()
1420       * @returns true if sample is OK or false if the sample is damaged       * @returns true if sample is OK or false if the sample is damaged
1421       * @throws Exception if no checksum had been stored to disk for this       * @throws Exception if no checksum had been stored to disk for this
1422       *         sample yet, or on I/O issues       *         sample yet, or on I/O issues
1423         * @see GetWaveDataCRC32Checksum()
1424       */       */
1425      bool Sample::VerifyWaveData() {      bool Sample::VerifyWaveData(uint32_t* pActually) {
1426          File* pFile = static_cast<File*>(GetParent());          //File* pFile = static_cast<File*>(GetParent());
         const uint32_t referenceCRC = pFile->GetSampleChecksum(this);  
1427          uint32_t crc = CalculateWaveDataChecksum();          uint32_t crc = CalculateWaveDataChecksum();
1428          return crc == referenceCRC;          if (pActually) *pActually = crc;
1429            return crc == this->crc;
1430      }      }
1431    
1432      uint32_t Sample::CalculateWaveDataChecksum() {      uint32_t Sample::CalculateWaveDataChecksum() {
# Line 1382  namespace { Line 1443  namespace {
1443              if (nRead <= 0) break;              if (nRead <= 0) break;
1444              __calculateCRC(&buffer[0], nRead * FrameSize, crc);              __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1445          }          }
1446          __encodeCRC(crc);          __finalizeCRC(crc);
1447          return crc;          return crc;
1448      }      }
1449    
# Line 1596  namespace { Line 1657  namespace {
1657              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1658              EG2Decay1                       = 0.005;              EG2Decay1                       = 0.005;
1659              EG2Sustain                      = 1000;              EG2Sustain                      = 1000;
1660              EG2Release                      = 0.3;              EG2Release                      = 60;
1661              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1662              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1663              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
# Line 1755  namespace { Line 1816  namespace {
1816          }          }
1817      }      }
1818    
1819        void DimensionRegion::serialize(Serialization::Archive* archive) {
1820            SRLZ(VelocityUpperLimit);
1821            SRLZ(EG1PreAttack);
1822            SRLZ(EG1Attack);
1823            SRLZ(EG1Decay1);
1824            SRLZ(EG1Decay2);
1825            SRLZ(EG1InfiniteSustain);
1826            SRLZ(EG1Sustain);
1827            SRLZ(EG1Release);
1828            SRLZ(EG1Hold);
1829            SRLZ(EG1Controller);
1830            SRLZ(EG1ControllerInvert);
1831            SRLZ(EG1ControllerAttackInfluence);
1832            SRLZ(EG1ControllerDecayInfluence);
1833            SRLZ(EG1ControllerReleaseInfluence);
1834            SRLZ(LFO1Frequency);
1835            SRLZ(LFO1InternalDepth);
1836            SRLZ(LFO1ControlDepth);
1837            SRLZ(LFO1Controller);
1838            SRLZ(LFO1FlipPhase);
1839            SRLZ(LFO1Sync);
1840            SRLZ(EG2PreAttack);
1841            SRLZ(EG2Attack);
1842            SRLZ(EG2Decay1);
1843            SRLZ(EG2Decay2);
1844            SRLZ(EG2InfiniteSustain);
1845            SRLZ(EG2Sustain);
1846            SRLZ(EG2Release);
1847            SRLZ(EG2Controller);
1848            SRLZ(EG2ControllerInvert);
1849            SRLZ(EG2ControllerAttackInfluence);
1850            SRLZ(EG2ControllerDecayInfluence);
1851            SRLZ(EG2ControllerReleaseInfluence);
1852            SRLZ(LFO2Frequency);
1853            SRLZ(LFO2InternalDepth);
1854            SRLZ(LFO2ControlDepth);
1855            SRLZ(LFO2Controller);
1856            SRLZ(LFO2FlipPhase);
1857            SRLZ(LFO2Sync);
1858            SRLZ(EG3Attack);
1859            SRLZ(EG3Depth);
1860            SRLZ(LFO3Frequency);
1861            SRLZ(LFO3InternalDepth);
1862            SRLZ(LFO3ControlDepth);
1863            SRLZ(LFO3Controller);
1864            SRLZ(LFO3Sync);
1865            SRLZ(VCFEnabled);
1866            SRLZ(VCFType);
1867            SRLZ(VCFCutoffController);
1868            SRLZ(VCFCutoffControllerInvert);
1869            SRLZ(VCFCutoff);
1870            SRLZ(VCFVelocityCurve);
1871            SRLZ(VCFVelocityScale);
1872            SRLZ(VCFVelocityDynamicRange);
1873            SRLZ(VCFResonance);
1874            SRLZ(VCFResonanceDynamic);
1875            SRLZ(VCFResonanceController);
1876            SRLZ(VCFKeyboardTracking);
1877            SRLZ(VCFKeyboardTrackingBreakpoint);
1878            SRLZ(VelocityResponseCurve);
1879            SRLZ(VelocityResponseDepth);
1880            SRLZ(VelocityResponseCurveScaling);
1881            SRLZ(ReleaseVelocityResponseCurve);
1882            SRLZ(ReleaseVelocityResponseDepth);
1883            SRLZ(ReleaseTriggerDecay);
1884            SRLZ(Crossfade);
1885            SRLZ(PitchTrack);
1886            SRLZ(DimensionBypass);
1887            SRLZ(Pan);
1888            SRLZ(SelfMask);
1889            SRLZ(AttenuationController);
1890            SRLZ(InvertAttenuationController);
1891            SRLZ(AttenuationControllerThreshold);
1892            SRLZ(ChannelOffset);
1893            SRLZ(SustainDefeat);
1894            SRLZ(MSDecode);
1895            //SRLZ(SampleStartOffset);
1896            SRLZ(SampleAttenuation);
1897    
1898            // derived attributes from DLS::Sampler
1899            SRLZ(FineTune);
1900            SRLZ(Gain);
1901        }
1902    
1903      /**      /**
1904       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
1905       * which depends on this value.       * which depends on this value.
# Line 1795  namespace { Line 1940  namespace {
1940    
1941          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1942    
1943          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1944          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1945    
1946          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 3763  namespace { Line 3908  namespace {
3908      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3909          uint8_t bits;          uint8_t bits;
3910          int veldim = -1;          int veldim = -1;
3911          int velbitpos;          int velbitpos = 0;
3912          int bitpos = 0;          int bitpos = 0;
3913          int dimregidx = 0;          int dimregidx = 0;
3914          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 3812  namespace { Line 3957  namespace {
3957      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3958          uint8_t bits;          uint8_t bits;
3959          int veldim = -1;          int veldim = -1;
3960          int velbitpos;          int velbitpos = 0;
3961          int bitpos = 0;          int bitpos = 0;
3962          int dimregidx = 0;          int dimregidx = 0;
3963          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 4161  namespace { Line 4306  namespace {
4306              // to handle potential future extensions of the header              // to handle potential future extensions of the header
4307              ckScri->SetPos(sizeof(int32_t) + headerSize);              ckScri->SetPos(sizeof(int32_t) + headerSize);
4308              // read actual script data              // read actual script data
4309              uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();              uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4310              data.resize(scriptSize);              data.resize(scriptSize);
4311              for (int i = 0; i < scriptSize; ++i)              for (int i = 0; i < scriptSize; ++i)
4312                  data[i] = ckScri->ReadUint8();                  data[i] = ckScri->ReadUint8();
# Line 4212  namespace { Line 4357  namespace {
4357          // recalculate CRC32 check sum          // recalculate CRC32 check sum
4358          __resetCRC(crc);          __resetCRC(crc);
4359          __calculateCRC(&data[0], data.size(), crc);          __calculateCRC(&data[0], data.size(), crc);
4360          __encodeCRC(crc);          __finalizeCRC(crc);
4361          // make sure chunk exists and has the required size          // make sure chunk exists and has the required size
4362          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();
4363          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4364          else pChunk->Resize(chunkSize);          else pChunk->Resize(chunkSize);
4365          // fill the chunk data to be written to disk          // fill the chunk data to be written to disk
4366          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4367          int pos = 0;          int pos = 0;
4368          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
4369          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4370          store32(&pData[pos], Compression);          store32(&pData[pos], Compression);
4371          pos += sizeof(int32_t);          pos += sizeof(int32_t);
# Line 4232  namespace { Line 4377  namespace {
4377          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4378          store32(&pData[pos], crc);          store32(&pData[pos], crc);
4379          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4380          store32(&pData[pos], Name.size());          store32(&pData[pos], (uint32_t) Name.size());
4381          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4382          for (int i = 0; i < Name.size(); ++i, ++pos)          for (int i = 0; i < Name.size(); ++i, ++pos)
4383              pData[pos] = Name[i];              pData[pos] = Name[i];
# Line 4263  namespace { Line 4408  namespace {
4408          return pGroup;          return pGroup;
4409      }      }
4410    
4411        /**
4412         * Make a (semi) deep copy of the Script object given by @a orig
4413         * and assign it to this object. Note: the ScriptGroup this Script
4414         * object belongs to remains untouched by this call.
4415         *
4416         * @param orig - original Script object to be copied from
4417         */
4418        void Script::CopyAssign(const Script* orig) {
4419            Name        = orig->Name;
4420            Compression = orig->Compression;
4421            Encoding    = orig->Encoding;
4422            Language    = orig->Language;
4423            Bypass      = orig->Bypass;
4424            data        = orig->data;
4425        }
4426    
4427      void Script::RemoveAllScriptReferences() {      void Script::RemoveAllScriptReferences() {
4428          File* pFile = pGroup->pFile;          File* pFile = pGroup->pFile;
4429          for (int i = 0; pFile->GetInstrument(i); ++i) {          for (int i = 0; pFile->GetInstrument(i); ++i) {
# Line 4409  namespace { Line 4570  namespace {
4570          EffectSend = 0;          EffectSend = 0;
4571          Attenuation = 0;          Attenuation = 0;
4572          FineTune = 0;          FineTune = 0;
4573          PitchbendRange = 0;          PitchbendRange = 2;
4574          PianoReleaseMode = false;          PianoReleaseMode = false;
4575          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4576          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
# Line 4584  namespace { Line 4745  namespace {
4745    
4746             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4747             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4748             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4749             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4750             const int slotSize  = 2 * sizeof(uint32_t);             const int slotSize  = 2 * sizeof(uint32_t);
4751             const int totalChunkSize = headerSize + slotCount * slotSize;             const int totalChunkSize = headerSize + slotCount * slotSize;
# Line 4620  namespace { Line 4781  namespace {
4781         if (pScriptRefs && pScriptRefs->size() > 0) {         if (pScriptRefs && pScriptRefs->size() > 0) {
4782             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4783             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4784             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4785             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4786             ckSCSL->SetPos(headerSize);             ckSCSL->SetPos(headerSize);
4787             for (int i = 0; i < slotCount; ++i) {             for (int i = 0; i < slotCount; ++i) {
4788                 uint32_t fileOffset =                 uint32_t fileOffset = uint32_t(
4789                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4790                      (*pScriptRefs)[i].script->pChunk->GetPos() -                      (*pScriptRefs)[i].script->pChunk->GetPos() -
4791                      CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize());                      CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4792                   );
4793                 ckSCSL->WriteUint32(&fileOffset);                 ckSCSL->WriteUint32(&fileOffset);
4794                 // jump over flags entry (containing the bypass flag)                 // jump over flags entry (containing the bypass flag)
4795                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
# Line 4687  namespace { Line 4849  namespace {
4849          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4850          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4851          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4852          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4853          // update Region key table for fast lookup          // update Region key table for fast lookup
4854          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4855          // done          // done
# Line 4833  namespace { Line 4995  namespace {
4995                  for (uint s = 0; group->GetScript(s); ++s) {                  for (uint s = 0; group->GetScript(s); ++s) {
4996                      Script* script = group->GetScript(s);                      Script* script = group->GetScript(s);
4997                      if (script->pChunk) {                      if (script->pChunk) {
4998                          uint32_t offset = script->pChunk->GetFilePos() -                          uint32_t offset = uint32_t(
4999                                            script->pChunk->GetPos() -                              script->pChunk->GetFilePos() -
5000                                            CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize());                              script->pChunk->GetPos() -
5001                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
5002                            );
5003                          if (offset == soughtOffset)                          if (offset == soughtOffset)
5004                          {                          {
5005                              _ScriptPooolRef ref;                              _ScriptPooolRef ref;
# Line 4960  namespace { Line 5124  namespace {
5124       */       */
5125      void Instrument::RemoveScript(Script* pScript) {      void Instrument::RemoveScript(Script* pScript) {
5126          LoadScripts();          LoadScripts();
5127          for (int i = pScriptRefs->size() - 1; i >= 0; --i) {          for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5128              if ((*pScriptRefs)[i].script == pScript) {              if ((*pScriptRefs)[i].script == pScript) {
5129                  pScriptRefs->erase( pScriptRefs->begin() + i );                  pScriptRefs->erase( pScriptRefs->begin() + i );
5130              }              }
# Line 4982  namespace { Line 5146  namespace {
5146       * gigedit.       * gigedit.
5147       */       */
5148      uint Instrument::ScriptSlotCount() const {      uint Instrument::ScriptSlotCount() const {
5149          return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();          return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5150      }      }
5151    
5152      /** @brief Whether script execution shall be skipped.      /** @brief Whether script execution shall be skipped.
# Line 5406  namespace { Line 5570  namespace {
5570              }              }
5571          }          }
5572          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5573          int nameLen = name.length();          int nameLen = (int) name.length();
5574          char suffix[6];          char suffix[6];
5575          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5576    
# Line 5422  namespace { Line 5586  namespace {
5586                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5587    
5588                          file_offset_t waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5589                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5590    
5591                          iSampleIndex++;                          iSampleIndex++;
5592                      }                      }
# Line 5575  namespace { Line 5739  namespace {
5739              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5740              mSamples[pFile->GetSample(i)] = s;              mSamples[pFile->GetSample(i)] = s;
5741          }          }
5742            
5743            // clone script groups and their scripts
5744            for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
5745                ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
5746                ScriptGroup* dg = AddScriptGroup();
5747                dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
5748                for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
5749                    Script* ss = sg->GetScript(iScript);
5750                    Script* ds = dg->AddScript();
5751                    ds->CopyAssign(ss);
5752                }
5753            }
5754    
5755          //BUG: For some reason this method only works with this additional          //BUG: For some reason this method only works with this additional
5756          //     Save() call in between here.          //     Save() call in between here.
5757          //          //
# Line 5668  namespace { Line 5844  namespace {
5844          uint32_t one = 1;          uint32_t one = 1;
5845          _3crc->WriteUint32(&one); // always 1          _3crc->WriteUint32(&one); // always 1
5846          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
   
         // reload CRC table to RAM to keep it persistent over several subsequent save operations  
         _3crc->ReleaseChunkData();  
         _3crc->LoadChunkData();  
5847      }      }
5848    
5849      uint32_t File::GetSampleChecksum(Sample* pSample) {      uint32_t File::GetSampleChecksum(Sample* pSample) {
5850            // get the index of the sample
5851            int iWaveIndex = GetWaveTableIndexOf(pSample);
5852            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5853    
5854            return GetSampleChecksumByIndex(iWaveIndex);
5855        }
5856    
5857        uint32_t File::GetSampleChecksumByIndex(int index) {
5858            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5859    
5860          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5861          if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");          if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5862          uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();          uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5863          if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");          if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5864    
         // get the index of the sample  
         int iWaveIndex = GetWaveTableIndexOf(pSample);  
         if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");  
   
5865          // read the CRC-32 checksum directly from disk          // read the CRC-32 checksum directly from disk
5866          size_t pos = iWaveIndex * 8;          size_t pos = index * 8;
5867          if (pos + 8 > _3crc->GetNewSize())          if (pos + 8 > _3crc->GetNewSize())
5868              throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");              throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5869    
5870          uint32_t one = load32(&pData[pos]); // always 1          uint32_t one = load32(&pData[pos]); // always 1
5871          if (one != 1)          if (one != 1)
5872              throw gig::Exception("Could not verify sample, because reference checksum table is damaged");              throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5873    
5874          return load32(&pData[pos+4]);          return load32(&pData[pos+4]);
5875      }      }
5876        
5877      int File::GetWaveTableIndexOf(gig::Sample* pSample) {      int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5878          if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned          if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5879          File::SampleList::iterator iter = pSamples->begin();          File::SampleList::iterator iter = pSamples->begin();
# Line 5720  namespace { Line 5898  namespace {
5898          if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned          if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5899          if (_3crc->GetNewSize() != pSamples->size() * 8) return false;          if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5900    
5901          const int n = _3crc->GetNewSize() / 8;          const file_offset_t n = _3crc->GetNewSize() / 8;
5902    
5903          uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();          uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5904          if (!pData) return false;          if (!pData) return false;
5905    
5906          for (int i = 0; i < n; ++i) {          for (file_offset_t i = 0; i < n; ++i) {
5907              uint32_t one = pData[i*2];              uint32_t one = pData[i*2];
5908              if (one != 1) return false;              if (one != 1) return false;
5909          }          }
# Line 5759  namespace { Line 5937  namespace {
5937          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5938          if (!_3crc) {          if (!_3crc) {
5939              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5940                // the order of einf and 3crc is not the same in v2 and v3
5941                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5942                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5943              bRequiresSave = true;              bRequiresSave = true;
5944          } else if (_3crc->GetNewSize() != pSamples->size() * 8) {          } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5945              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
# Line 5788  namespace { Line 5969  namespace {
5969                      gig::Sample* pSample = (gig::Sample*) *iter;                      gig::Sample* pSample = (gig::Sample*) *iter;
5970                      int index = GetWaveTableIndexOf(pSample);                      int index = GetWaveTableIndexOf(pSample);
5971                      if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");                      if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5972                      uint32_t crc = pSample->CalculateWaveDataChecksum();                      pSample->crc  = pSample->CalculateWaveDataChecksum();
5973                      SetSampleChecksum(pSample, crc);                      SetSampleChecksum(pSample, pSample->crc);
5974                  }                  }
5975              }              }
5976          }          }
# Line 6056  namespace { Line 6237  namespace {
6237              lst3LS = NULL;              lst3LS = NULL;
6238          }          }
6239    
         // if there is a 3CRC chunk, make sure it is loaded into RAM, otherwise  
         // its data might get lost or damaged on file structure changes  
         RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);  
         if (_3crc) _3crc->LoadChunkData();  
   
6240          // first update base class's chunks          // first update base class's chunks
6241          DLS::File::UpdateChunks(pProgress);          DLS::File::UpdateChunks(pProgress);
6242    
# Line 6119  namespace { Line 6295  namespace {
6295          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6296          // are set to zero.          // are set to zero.
6297    
6298          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6299          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6300    
6301          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 6192  namespace { Line 6368  namespace {
6368                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6369                  // next 8 bytes unknown                  // next 8 bytes unknown
6370                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6371                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6372                  // next 4 bytes unknown                  // next 4 bytes unknown
6373    
6374                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 6210  namespace { Line 6386  namespace {
6386              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6387              // next 8 bytes unknown              // next 8 bytes unknown
6388              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6389              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6390              // next 4 bytes unknown              // next 4 bytes unknown
6391          }          }
6392    
6393          // update 3crc chunk          // update 3crc chunk
6394    
6395          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6396          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6397          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6398            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6399            // member variable). This step is required, because samples might have
6400            // been deleted by the user since the file was opened, which in turn
6401            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6402            // If a sample was conciously modified by the user (that is if
6403            // Sample::Write() was called later on) then Sample::Write() will just
6404            // update the respective individual checksum(s) directly on disk and
6405            // leaves all other sample checksums untouched.
6406    
6407            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6408          if (_3crc) {          if (_3crc) {
6409              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6410          } else if (newFile) {          } else /*if (newFile)*/ {
6411              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6412              // 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
6413              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6414          }          }
6415            { // must be performed in RAM here ...
6416                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6417                if (pData) {
6418                    File::SampleList::iterator iter = pSamples->begin();
6419                    File::SampleList::iterator end  = pSamples->end();
6420                    for (int index = 0; iter != end; ++iter, ++index) {
6421                        gig::Sample* pSample = (gig::Sample*) *iter;
6422                        pData[index*2]   = 1; // always 1
6423                        pData[index*2+1] = pSample->crc;
6424                    }
6425                }
6426            }
6427      }      }
6428            
6429      void File::UpdateFileOffsets() {      void File::UpdateFileOffsets() {

Legend:
Removed from v.2985  
changed lines
  Added in v.3140

  ViewVC Help
Powered by ViewVC