/[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 2922 by schoenebeck, Wed May 18 18:04:49 2016 UTC revision 3112 by schoenebeck, Wed Feb 15 13:21:31 2017 UTC
# Line 275  namespace { Line 275  namespace {
275       * @param bufSize - size of the data to be processed       * @param bufSize - size of the data to be processed
276       * @param crc     - variable the CRC sum shall be stored to       * @param crc     - variable the CRC sum shall be stored to
277       */       */
278      static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {      static void __calculateCRC(unsigned char* buf, size_t bufSize, uint32_t& crc) {
279          for (int i = 0 ; i < bufSize ; i++) {          for (size_t i = 0 ; i < bufSize ; i++) {
280              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
281          }          }
282      }      }
# Line 338  namespace { Line 338  namespace {
338       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
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         * @param index          - wave pool index of sample (may be -1 on new sample)
342       */       */
343      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)
344            : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
345        {
346          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
347              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
348              { 0, 0 }              { 0, 0 }
# Line 349  namespace { Line 352  namespace {
352          FileNo = fileNo;          FileNo = fileNo;
353    
354          __resetCRC(crc);          __resetCRC(crc);
355            // if this is not a new sample, try to get the sample's already existing
356            // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
357            // checksum of the time when the sample was consciously modified by the
358            // user for the last time (by calling Sample::Write() that is).
359            if (index >= 0) { // not a new file ...
360                try {
361                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
362                    this->crc = crc;
363                } catch (...) {}
364            }
365    
366          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
367          if (pCk3gix) {          if (pCk3gix) {
# Line 1341  namespace { Line 1354  namespace {
1354          return pGroup;          return pGroup;
1355      }      }
1356    
1357        /**
1358         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1359         * time when this sample's wave form data was modified for the last time
1360         * by calling Write(). This checksum only covers the raw wave form data,
1361         * not any meta informations like i.e. bit depth or loop points. Since
1362         * this method just returns the checksum stored for this sample i.e. when
1363         * the gig file was loaded, this method returns immediately. So it does no
1364         * recalcuation of the checksum with the currently available sample wave
1365         * form data.
1366         *
1367         * @see VerifyWaveData()
1368         */
1369        uint32_t Sample::GetWaveDataCRC32Checksum() {
1370            return crc;
1371        }
1372    
1373        /**
1374         * Checks the integrity of this sample's raw audio wave data. Whenever a
1375         * Sample's raw wave data is intentionally modified (i.e. by calling
1376         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1377         * is calculated and stored/updated for this sample, along to the sample's
1378         * meta informations.
1379         *
1380         * Now by calling this method the current raw audio wave data is checked
1381         * against the already stored CRC32 check sum in order to check whether the
1382         * sample data had been damaged unintentionally for some reason. Since by
1383         * calling this method always the entire raw audio wave data has to be
1384         * read, verifying all samples this way may take a long time accordingly.
1385         * And that's also the reason why the sample integrity is not checked by
1386         * default whenever a gig file is loaded. So this method must be called
1387         * explicitly to fulfill this task.
1388         *
1389         * @param pActually - (optional) if provided, will be set to the actually
1390         *                    calculated checksum of the current raw wave form data,
1391         *                    you can get the expected checksum instead by calling
1392         *                    GetWaveDataCRC32Checksum()
1393         * @returns true if sample is OK or false if the sample is damaged
1394         * @throws Exception if no checksum had been stored to disk for this
1395         *         sample yet, or on I/O issues
1396         * @see GetWaveDataCRC32Checksum()
1397         */
1398        bool Sample::VerifyWaveData(uint32_t* pActually) {
1399            //File* pFile = static_cast<File*>(GetParent());
1400            uint32_t crc = CalculateWaveDataChecksum();
1401            if (pActually) *pActually = crc;
1402            return crc == this->crc;
1403        }
1404    
1405        uint32_t Sample::CalculateWaveDataChecksum() {
1406            const size_t sz = 20*1024; // 20kB buffer size
1407            std::vector<uint8_t> buffer(sz);
1408            buffer.resize(sz);
1409    
1410            const size_t n = sz / FrameSize;
1411            SetPos(0);
1412            uint32_t crc = 0;
1413            __resetCRC(crc);
1414            while (true) {
1415                file_offset_t nRead = Read(&buffer[0], n);
1416                if (nRead <= 0) break;
1417                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1418            }
1419            __encodeCRC(crc);
1420            return crc;
1421        }
1422    
1423      Sample::~Sample() {      Sample::~Sample() {
1424          Instances--;          Instances--;
1425          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1551  namespace { Line 1630  namespace {
1630              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1631              EG2Decay1                       = 0.005;              EG2Decay1                       = 0.005;
1632              EG2Sustain                      = 1000;              EG2Sustain                      = 1000;
1633              EG2Release                      = 0.3;              EG2Release                      = 60;
1634              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1635              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1636              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
# Line 1750  namespace { Line 1829  namespace {
1829    
1830          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1831    
1832          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1833          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1834    
1835          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 3106  namespace { Line 3185  namespace {
3185          int step = 1;          int step = 1;
3186          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3187          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3188    
3189          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3190          int dim[8] = { 0 };          int dim[8] = { 0 };
3191          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3192                const int end = i + step * pDimensionDefinitions[veldim].zones;
3193    
3194                // create a velocity table for all cases where the velocity zone is zero
3195              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3196                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3197                  // create the velocity table                  // create the velocity table
# Line 3142  namespace { Line 3222  namespace {
3222                  }                  }
3223              }              }
3224    
3225                // jump to the next case where the velocity zone is zero
3226              int j;              int j;
3227              int shift = 0;              int shift = 0;
3228              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 3716  namespace { Line 3797  namespace {
3797      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3798          uint8_t bits;          uint8_t bits;
3799          int veldim = -1;          int veldim = -1;
3800          int velbitpos;          int velbitpos = 0;
3801          int bitpos = 0;          int bitpos = 0;
3802          int dimregidx = 0;          int dimregidx = 0;
3803          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 3765  namespace { Line 3846  namespace {
3846      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3847          uint8_t bits;          uint8_t bits;
3848          int veldim = -1;          int veldim = -1;
3849          int velbitpos;          int velbitpos = 0;
3850          int bitpos = 0;          int bitpos = 0;
3851          int dimregidx = 0;          int dimregidx = 0;
3852          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 4114  namespace { Line 4195  namespace {
4195              // to handle potential future extensions of the header              // to handle potential future extensions of the header
4196              ckScri->SetPos(sizeof(int32_t) + headerSize);              ckScri->SetPos(sizeof(int32_t) + headerSize);
4197              // read actual script data              // read actual script data
4198              uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();              uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4199              data.resize(scriptSize);              data.resize(scriptSize);
4200              for (int i = 0; i < scriptSize; ++i)              for (int i = 0; i < scriptSize; ++i)
4201                  data[i] = ckScri->ReadUint8();                  data[i] = ckScri->ReadUint8();
# Line 4167  namespace { Line 4248  namespace {
4248          __calculateCRC(&data[0], data.size(), crc);          __calculateCRC(&data[0], data.size(), crc);
4249          __encodeCRC(crc);          __encodeCRC(crc);
4250          // make sure chunk exists and has the required size          // make sure chunk exists and has the required size
4251          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();
4252          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4253          else pChunk->Resize(chunkSize);          else pChunk->Resize(chunkSize);
4254          // fill the chunk data to be written to disk          // fill the chunk data to be written to disk
4255          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4256          int pos = 0;          int pos = 0;
4257          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
4258          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4259          store32(&pData[pos], Compression);          store32(&pData[pos], Compression);
4260          pos += sizeof(int32_t);          pos += sizeof(int32_t);
# Line 4185  namespace { Line 4266  namespace {
4266          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4267          store32(&pData[pos], crc);          store32(&pData[pos], crc);
4268          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4269          store32(&pData[pos], Name.size());          store32(&pData[pos], (uint32_t) Name.size());
4270          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4271          for (int i = 0; i < Name.size(); ++i, ++pos)          for (int i = 0; i < Name.size(); ++i, ++pos)
4272              pData[pos] = Name[i];              pData[pos] = Name[i];
# Line 4362  namespace { Line 4443  namespace {
4443          EffectSend = 0;          EffectSend = 0;
4444          Attenuation = 0;          Attenuation = 0;
4445          FineTune = 0;          FineTune = 0;
4446          PitchbendRange = 0;          PitchbendRange = 2;
4447          PianoReleaseMode = false;          PianoReleaseMode = false;
4448          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4449          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
# Line 4537  namespace { Line 4618  namespace {
4618    
4619             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4620             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4621             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4622             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4623             const int slotSize  = 2 * sizeof(uint32_t);             const int slotSize  = 2 * sizeof(uint32_t);
4624             const int totalChunkSize = headerSize + slotCount * slotSize;             const int totalChunkSize = headerSize + slotCount * slotSize;
# Line 4573  namespace { Line 4654  namespace {
4654         if (pScriptRefs && pScriptRefs->size() > 0) {         if (pScriptRefs && pScriptRefs->size() > 0) {
4655             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4656             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4657             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4658             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4659             ckSCSL->SetPos(headerSize);             ckSCSL->SetPos(headerSize);
4660             for (int i = 0; i < slotCount; ++i) {             for (int i = 0; i < slotCount; ++i) {
4661                 uint32_t fileOffset =                 uint32_t fileOffset = uint32_t(
4662                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4663                      (*pScriptRefs)[i].script->pChunk->GetPos() -                      (*pScriptRefs)[i].script->pChunk->GetPos() -
4664                      CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize());                      CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4665                   );
4666                 ckSCSL->WriteUint32(&fileOffset);                 ckSCSL->WriteUint32(&fileOffset);
4667                 // jump over flags entry (containing the bypass flag)                 // jump over flags entry (containing the bypass flag)
4668                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
# Line 4640  namespace { Line 4722  namespace {
4722          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4723          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4724          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4725          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4726          // update Region key table for fast lookup          // update Region key table for fast lookup
4727          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4728          // done          // done
# Line 4786  namespace { Line 4868  namespace {
4868                  for (uint s = 0; group->GetScript(s); ++s) {                  for (uint s = 0; group->GetScript(s); ++s) {
4869                      Script* script = group->GetScript(s);                      Script* script = group->GetScript(s);
4870                      if (script->pChunk) {                      if (script->pChunk) {
4871                          uint32_t offset = script->pChunk->GetFilePos() -                          uint32_t offset = uint32_t(
4872                                            script->pChunk->GetPos() -                              script->pChunk->GetFilePos() -
4873                                            CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize());                              script->pChunk->GetPos() -
4874                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
4875                            );
4876                          if (offset == soughtOffset)                          if (offset == soughtOffset)
4877                          {                          {
4878                              _ScriptPooolRef ref;                              _ScriptPooolRef ref;
# Line 4913  namespace { Line 4997  namespace {
4997       */       */
4998      void Instrument::RemoveScript(Script* pScript) {      void Instrument::RemoveScript(Script* pScript) {
4999          LoadScripts();          LoadScripts();
5000          for (int i = pScriptRefs->size() - 1; i >= 0; --i) {          for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5001              if ((*pScriptRefs)[i].script == pScript) {              if ((*pScriptRefs)[i].script == pScript) {
5002                  pScriptRefs->erase( pScriptRefs->begin() + i );                  pScriptRefs->erase( pScriptRefs->begin() + i );
5003              }              }
# Line 4935  namespace { Line 5019  namespace {
5019       * gigedit.       * gigedit.
5020       */       */
5021      uint Instrument::ScriptSlotCount() const {      uint Instrument::ScriptSlotCount() const {
5022          return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();          return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5023      }      }
5024    
5025      /** @brief Whether script execution shall be skipped.      /** @brief Whether script execution shall be skipped.
# Line 5359  namespace { Line 5443  namespace {
5443              }              }
5444          }          }
5445          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5446          int nameLen = name.length();          int nameLen = (int) name.length();
5447          char suffix[6];          char suffix[6];
5448          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5449    
# Line 5375  namespace { Line 5459  namespace {
5459                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5460    
5461                          file_offset_t waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5462                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5463    
5464                          iSampleIndex++;                          iSampleIndex++;
5465                      }                      }
# Line 5613  namespace { Line 5697  namespace {
5697          if (!_3crc) return;          if (!_3crc) return;
5698    
5699          // get the index of the sample          // get the index of the sample
5700          int iWaveIndex = -1;          int iWaveIndex = GetWaveTableIndexOf(pSample);
         File::SampleList::iterator iter = pSamples->begin();  
         File::SampleList::iterator end  = pSamples->end();  
         for (int index = 0; iter != end; ++iter, ++index) {  
             if (*iter == pSample) {  
                 iWaveIndex = index;  
                 break;  
             }  
         }  
5701          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5702    
5703          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5704          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5705          uint32_t tmp = 1;          uint32_t one = 1;
5706          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5707          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5708      }      }
5709    
5710        uint32_t File::GetSampleChecksum(Sample* pSample) {
5711            // get the index of the sample
5712            int iWaveIndex = GetWaveTableIndexOf(pSample);
5713            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5714    
5715            return GetSampleChecksumByIndex(iWaveIndex);
5716        }
5717    
5718        uint32_t File::GetSampleChecksumByIndex(int index) {
5719            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5720    
5721            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5722            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5723            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5724            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5725    
5726            // read the CRC-32 checksum directly from disk
5727            size_t pos = index * 8;
5728            if (pos + 8 > _3crc->GetNewSize())
5729                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5730    
5731            uint32_t one = load32(&pData[pos]); // always 1
5732            if (one != 1)
5733                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5734    
5735            return load32(&pData[pos+4]);
5736        }
5737    
5738        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5739            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5740            File::SampleList::iterator iter = pSamples->begin();
5741            File::SampleList::iterator end  = pSamples->end();
5742            for (int index = 0; iter != end; ++iter, ++index)
5743                if (*iter == pSample)
5744                    return index;
5745            return -1;
5746        }
5747    
5748        /**
5749         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5750         * the CRC32 check sums of all samples' raw wave data.
5751         *
5752         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5753         */
5754        bool File::VerifySampleChecksumTable() {
5755            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5756            if (!_3crc) return false;
5757            if (_3crc->GetNewSize() <= 0) return false;
5758            if (_3crc->GetNewSize() % 8) return false;
5759            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5760            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5761    
5762            const file_offset_t n = _3crc->GetNewSize() / 8;
5763    
5764            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5765            if (!pData) return false;
5766    
5767            for (file_offset_t i = 0; i < n; ++i) {
5768                uint32_t one = pData[i*2];
5769                if (one != 1) return false;
5770            }
5771    
5772            return true;
5773        }
5774    
5775        /**
5776         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5777         * file's checksum table with those new checksums. This might usually
5778         * just be necessary if the checksum table was damaged.
5779         *
5780         * @e IMPORTANT: The current implementation of this method only works
5781         * with files that have not been modified since it was loaded, because
5782         * it expects that no externally caused file structure changes are
5783         * required!
5784         *
5785         * Due to the expectation above, this method is currently protected
5786         * and actually only used by the command line tool "gigdump" yet.
5787         *
5788         * @returns true if Save() is required to be called after this call,
5789         *          false if no further action is required
5790         */
5791        bool File::RebuildSampleChecksumTable() {
5792            // make sure sample chunks were scanned
5793            if (!pSamples) GetFirstSample();
5794    
5795            bool bRequiresSave = false;
5796    
5797            // make sure "3CRC" chunk exists with required size
5798            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5799            if (!_3crc) {
5800                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5801                // the order of einf and 3crc is not the same in v2 and v3
5802                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5803                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5804                bRequiresSave = true;
5805            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5806                _3crc->Resize(pSamples->size() * 8);
5807                bRequiresSave = true;
5808            }
5809    
5810            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5811                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5812                {
5813                    File::SampleList::iterator iter = pSamples->begin();
5814                    File::SampleList::iterator end  = pSamples->end();
5815                    for (; iter != end; ++iter) {
5816                        gig::Sample* pSample = (gig::Sample*) *iter;
5817                        int index = GetWaveTableIndexOf(pSample);
5818                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5819                        pData[index*2]   = 1; // always 1
5820                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5821                    }
5822                }
5823            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5824                // make sure file is in write mode
5825                pRIFF->SetMode(RIFF::stream_mode_read_write);
5826                {
5827                    File::SampleList::iterator iter = pSamples->begin();
5828                    File::SampleList::iterator end  = pSamples->end();
5829                    for (; iter != end; ++iter) {
5830                        gig::Sample* pSample = (gig::Sample*) *iter;
5831                        int index = GetWaveTableIndexOf(pSample);
5832                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5833                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5834                        SetSampleChecksum(pSample, pSample->crc);
5835                    }
5836                }
5837            }
5838    
5839            return bRequiresSave;
5840        }
5841    
5842      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5843          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5844          // there must always be at least one group          // there must always be at least one group
# Line 5948  namespace { Line 6156  namespace {
6156          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6157          // are set to zero.          // are set to zero.
6158    
6159          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6160          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6161    
6162          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 6021  namespace { Line 6229  namespace {
6229                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6230                  // next 8 bytes unknown                  // next 8 bytes unknown
6231                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6232                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6233                  // next 4 bytes unknown                  // next 4 bytes unknown
6234    
6235                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 6039  namespace { Line 6247  namespace {
6247              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6248              // next 8 bytes unknown              // next 8 bytes unknown
6249              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6250              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6251              // next 4 bytes unknown              // next 4 bytes unknown
6252          }          }
6253    
6254          // update 3crc chunk          // update 3crc chunk
6255    
6256          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6257          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6258          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6259            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6260            // member variable). This step is required, because samples might have
6261            // been deleted by the user since the file was opened, which in turn
6262            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6263            // If a sample was conciously modified by the user (that is if
6264            // Sample::Write() was called later on) then Sample::Write() will just
6265            // update the respective individual checksum(s) directly on disk and
6266            // leaves all other sample checksums untouched.
6267    
6268          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6269          if (_3crc) {          if (_3crc) {
6270              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6271          } else if (newFile) {          } else /*if (newFile)*/ {
6272              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6273              // 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
6274              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6275          }          }
6276            { // must be performed in RAM here ...
6277                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6278                if (pData) {
6279                    File::SampleList::iterator iter = pSamples->begin();
6280                    File::SampleList::iterator end  = pSamples->end();
6281                    for (int index = 0; iter != end; ++iter, ++index) {
6282                        gig::Sample* pSample = (gig::Sample*) *iter;
6283                        pData[index*2]   = 1; // always 1
6284                        pData[index*2+1] = pSample->crc;
6285                    }
6286                }
6287            }
6288      }      }
6289            
6290      void File::UpdateFileOffsets() {      void File::UpdateFileOffsets() {

Legend:
Removed from v.2922  
changed lines
  Added in v.3112

  ViewVC Help
Powered by ViewVC