/[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 2913 by schoenebeck, Tue May 17 15:19:33 2016 UTC revision 3198 by schoenebeck, Sun May 21 12:46:05 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    
347      unsigned int Sample::Instances = 0;      size_t       Sample::Instances = 0;
348      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
349    
350      /** @brief Constructor.      /** @brief Constructor.
# 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 789  namespace { Line 828  namespace {
828       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
829       * other formats will fail!       * other formats will fail!
830       *       *
831       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
832       *                   greater than zero)       *                  greater than zero)
833       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
834       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
835       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
836       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
837       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
838       */       */
839      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
840          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
841          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
842      }      }
843    
844      /**      /**
# 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 1341  namespace { Line 1381  namespace {
1381          return pGroup;          return pGroup;
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
1402         * 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
1404         * is calculated and stored/updated for this sample, along to the sample's
1405         * meta informations.
1406         *
1407         * Now by calling this method the current raw audio wave data is checked
1408         * against the already stored CRC32 check sum in order to check whether the
1409         * sample data had been damaged unintentionally for some reason. Since by
1410         * calling this method always the entire raw audio wave data has to be
1411         * read, verifying all samples this way may take a long time accordingly.
1412         * And that's also the reason why the sample integrity is not checked by
1413         * default whenever a gig file is loaded. So this method must be called
1414         * 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
1421         * @throws Exception if no checksum had been stored to disk for this
1422         *         sample yet, or on I/O issues
1423         * @see GetWaveDataCRC32Checksum()
1424         */
1425        bool Sample::VerifyWaveData(uint32_t* pActually) {
1426            //File* pFile = static_cast<File*>(GetParent());
1427            uint32_t crc = CalculateWaveDataChecksum();
1428            if (pActually) *pActually = crc;
1429            return crc == this->crc;
1430        }
1431    
1432        uint32_t Sample::CalculateWaveDataChecksum() {
1433            const size_t sz = 20*1024; // 20kB buffer size
1434            std::vector<uint8_t> buffer(sz);
1435            buffer.resize(sz);
1436    
1437            const size_t n = sz / FrameSize;
1438            SetPos(0);
1439            uint32_t crc = 0;
1440            __resetCRC(crc);
1441            while (true) {
1442                file_offset_t nRead = Read(&buffer[0], n);
1443                if (nRead <= 0) break;
1444                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1445            }
1446            __finalizeCRC(crc);
1447            return crc;
1448        }
1449    
1450      Sample::~Sample() {      Sample::~Sample() {
1451          Instances--;          Instances--;
1452          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1357  namespace { Line 1463  namespace {
1463  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1464  // *  // *
1465    
1466      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1467      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1468    
1469      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1551  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 1710  namespace { Line 1816  namespace {
1816          }          }
1817      }      }
1818    
1819        void DimensionRegion::serialize(Serialization::Archive* archive) {
1820            // in case this class will become backward incompatible one day,
1821            // then set a version and minimum version for this class like:
1822            //archive->setVersion(*this, 2);
1823            //archive->setMinVersion(*this, 1);
1824    
1825            SRLZ(VelocityUpperLimit);
1826            SRLZ(EG1PreAttack);
1827            SRLZ(EG1Attack);
1828            SRLZ(EG1Decay1);
1829            SRLZ(EG1Decay2);
1830            SRLZ(EG1InfiniteSustain);
1831            SRLZ(EG1Sustain);
1832            SRLZ(EG1Release);
1833            SRLZ(EG1Hold);
1834            SRLZ(EG1Controller);
1835            SRLZ(EG1ControllerInvert);
1836            SRLZ(EG1ControllerAttackInfluence);
1837            SRLZ(EG1ControllerDecayInfluence);
1838            SRLZ(EG1ControllerReleaseInfluence);
1839            SRLZ(LFO1Frequency);
1840            SRLZ(LFO1InternalDepth);
1841            SRLZ(LFO1ControlDepth);
1842            SRLZ(LFO1Controller);
1843            SRLZ(LFO1FlipPhase);
1844            SRLZ(LFO1Sync);
1845            SRLZ(EG2PreAttack);
1846            SRLZ(EG2Attack);
1847            SRLZ(EG2Decay1);
1848            SRLZ(EG2Decay2);
1849            SRLZ(EG2InfiniteSustain);
1850            SRLZ(EG2Sustain);
1851            SRLZ(EG2Release);
1852            SRLZ(EG2Controller);
1853            SRLZ(EG2ControllerInvert);
1854            SRLZ(EG2ControllerAttackInfluence);
1855            SRLZ(EG2ControllerDecayInfluence);
1856            SRLZ(EG2ControllerReleaseInfluence);
1857            SRLZ(LFO2Frequency);
1858            SRLZ(LFO2InternalDepth);
1859            SRLZ(LFO2ControlDepth);
1860            SRLZ(LFO2Controller);
1861            SRLZ(LFO2FlipPhase);
1862            SRLZ(LFO2Sync);
1863            SRLZ(EG3Attack);
1864            SRLZ(EG3Depth);
1865            SRLZ(LFO3Frequency);
1866            SRLZ(LFO3InternalDepth);
1867            SRLZ(LFO3ControlDepth);
1868            SRLZ(LFO3Controller);
1869            SRLZ(LFO3Sync);
1870            SRLZ(VCFEnabled);
1871            SRLZ(VCFType);
1872            SRLZ(VCFCutoffController);
1873            SRLZ(VCFCutoffControllerInvert);
1874            SRLZ(VCFCutoff);
1875            SRLZ(VCFVelocityCurve);
1876            SRLZ(VCFVelocityScale);
1877            SRLZ(VCFVelocityDynamicRange);
1878            SRLZ(VCFResonance);
1879            SRLZ(VCFResonanceDynamic);
1880            SRLZ(VCFResonanceController);
1881            SRLZ(VCFKeyboardTracking);
1882            SRLZ(VCFKeyboardTrackingBreakpoint);
1883            SRLZ(VelocityResponseCurve);
1884            SRLZ(VelocityResponseDepth);
1885            SRLZ(VelocityResponseCurveScaling);
1886            SRLZ(ReleaseVelocityResponseCurve);
1887            SRLZ(ReleaseVelocityResponseDepth);
1888            SRLZ(ReleaseTriggerDecay);
1889            SRLZ(Crossfade);
1890            SRLZ(PitchTrack);
1891            SRLZ(DimensionBypass);
1892            SRLZ(Pan);
1893            SRLZ(SelfMask);
1894            SRLZ(AttenuationController);
1895            SRLZ(InvertAttenuationController);
1896            SRLZ(AttenuationControllerThreshold);
1897            SRLZ(ChannelOffset);
1898            SRLZ(SustainDefeat);
1899            SRLZ(MSDecode);
1900            //SRLZ(SampleStartOffset);
1901            SRLZ(SampleAttenuation);
1902    
1903            // derived attributes from DLS::Sampler
1904            SRLZ(FineTune);
1905            SRLZ(Gain);
1906        }
1907    
1908      /**      /**
1909       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
1910       * which depends on this value.       * which depends on this value.
# Line 1750  namespace { Line 1945  namespace {
1945    
1946          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1947    
1948          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1949          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1950    
1951          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 2424  namespace { Line 2619  namespace {
2619    
2620              // unknown controller type              // unknown controller type
2621              default:              default:
2622                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type (0x%x).", EncodedController);
2623          }          }
2624          return decodedcontroller;          return decodedcontroller;
2625      }      }
# Line 3106  namespace { Line 3301  namespace {
3301          int step = 1;          int step = 1;
3302          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3303          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3304    
3305          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3306          int dim[8] = { 0 };          int dim[8] = { 0 };
3307          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3308                const int end = i + step * pDimensionDefinitions[veldim].zones;
3309    
3310                // create a velocity table for all cases where the velocity zone is zero
3311              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3312                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3313                  // create the velocity table                  // create the velocity table
# Line 3142  namespace { Line 3338  namespace {
3338                  }                  }
3339              }              }
3340    
3341                // jump to the next case where the velocity zone is zero
3342              int j;              int j;
3343              int shift = 0;              int shift = 0;
3344              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 3716  namespace { Line 3913  namespace {
3913      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3914          uint8_t bits;          uint8_t bits;
3915          int veldim = -1;          int veldim = -1;
3916          int velbitpos;          int velbitpos = 0;
3917          int bitpos = 0;          int bitpos = 0;
3918          int dimregidx = 0;          int dimregidx = 0;
3919          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 3765  namespace { Line 3962  namespace {
3962      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {      int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3963          uint8_t bits;          uint8_t bits;
3964          int veldim = -1;          int veldim = -1;
3965          int velbitpos;          int velbitpos = 0;
3966          int bitpos = 0;          int bitpos = 0;
3967          int dimregidx = 0;          int dimregidx = 0;
3968          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 4114  namespace { Line 4311  namespace {
4311              // to handle potential future extensions of the header              // to handle potential future extensions of the header
4312              ckScri->SetPos(sizeof(int32_t) + headerSize);              ckScri->SetPos(sizeof(int32_t) + headerSize);
4313              // read actual script data              // read actual script data
4314              uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();              uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4315              data.resize(scriptSize);              data.resize(scriptSize);
4316              for (int i = 0; i < scriptSize; ++i)              for (int i = 0; i < scriptSize; ++i)
4317                  data[i] = ckScri->ReadUint8();                  data[i] = ckScri->ReadUint8();
# Line 4165  namespace { Line 4362  namespace {
4362          // recalculate CRC32 check sum          // recalculate CRC32 check sum
4363          __resetCRC(crc);          __resetCRC(crc);
4364          __calculateCRC(&data[0], data.size(), crc);          __calculateCRC(&data[0], data.size(), crc);
4365          __encodeCRC(crc);          __finalizeCRC(crc);
4366          // make sure chunk exists and has the required size          // make sure chunk exists and has the required size
4367          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();
4368          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);          if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4369          else pChunk->Resize(chunkSize);          else pChunk->Resize(chunkSize);
4370          // fill the chunk data to be written to disk          // fill the chunk data to be written to disk
4371          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();          uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4372          int pos = 0;          int pos = 0;
4373          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
4374          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4375          store32(&pData[pos], Compression);          store32(&pData[pos], Compression);
4376          pos += sizeof(int32_t);          pos += sizeof(int32_t);
# Line 4185  namespace { Line 4382  namespace {
4382          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4383          store32(&pData[pos], crc);          store32(&pData[pos], crc);
4384          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4385          store32(&pData[pos], Name.size());          store32(&pData[pos], (uint32_t) Name.size());
4386          pos += sizeof(int32_t);          pos += sizeof(int32_t);
4387          for (int i = 0; i < Name.size(); ++i, ++pos)          for (int i = 0; i < Name.size(); ++i, ++pos)
4388              pData[pos] = Name[i];              pData[pos] = Name[i];
# Line 4216  namespace { Line 4413  namespace {
4413          return pGroup;          return pGroup;
4414      }      }
4415    
4416        /**
4417         * Make a (semi) deep copy of the Script object given by @a orig
4418         * and assign it to this object. Note: the ScriptGroup this Script
4419         * object belongs to remains untouched by this call.
4420         *
4421         * @param orig - original Script object to be copied from
4422         */
4423        void Script::CopyAssign(const Script* orig) {
4424            Name        = orig->Name;
4425            Compression = orig->Compression;
4426            Encoding    = orig->Encoding;
4427            Language    = orig->Language;
4428            Bypass      = orig->Bypass;
4429            data        = orig->data;
4430        }
4431    
4432      void Script::RemoveAllScriptReferences() {      void Script::RemoveAllScriptReferences() {
4433          File* pFile = pGroup->pFile;          File* pFile = pGroup->pFile;
4434          for (int i = 0; pFile->GetInstrument(i); ++i) {          for (int i = 0; pFile->GetInstrument(i); ++i) {
# Line 4362  namespace { Line 4575  namespace {
4575          EffectSend = 0;          EffectSend = 0;
4576          Attenuation = 0;          Attenuation = 0;
4577          FineTune = 0;          FineTune = 0;
4578          PitchbendRange = 0;          PitchbendRange = 2;
4579          PianoReleaseMode = false;          PianoReleaseMode = false;
4580          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4581          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
# Line 4537  namespace { Line 4750  namespace {
4750    
4751             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4752             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);             if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4753             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4754             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4755             const int slotSize  = 2 * sizeof(uint32_t);             const int slotSize  = 2 * sizeof(uint32_t);
4756             const int totalChunkSize = headerSize + slotCount * slotSize;             const int totalChunkSize = headerSize + slotCount * slotSize;
# Line 4573  namespace { Line 4786  namespace {
4786         if (pScriptRefs && pScriptRefs->size() > 0) {         if (pScriptRefs && pScriptRefs->size() > 0) {
4787             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);             RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4788             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);             RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4789             const int slotCount = pScriptRefs->size();             const int slotCount = (int) pScriptRefs->size();
4790             const int headerSize = 3 * sizeof(uint32_t);             const int headerSize = 3 * sizeof(uint32_t);
4791             ckSCSL->SetPos(headerSize);             ckSCSL->SetPos(headerSize);
4792             for (int i = 0; i < slotCount; ++i) {             for (int i = 0; i < slotCount; ++i) {
4793                 uint32_t fileOffset =                 uint32_t fileOffset = uint32_t(
4794                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -                      (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4795                      (*pScriptRefs)[i].script->pChunk->GetPos() -                      (*pScriptRefs)[i].script->pChunk->GetPos() -
4796                      CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize());                      CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4797                   );
4798                 ckSCSL->WriteUint32(&fileOffset);                 ckSCSL->WriteUint32(&fileOffset);
4799                 // jump over flags entry (containing the bypass flag)                 // jump over flags entry (containing the bypass flag)
4800                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);                 ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
# Line 4640  namespace { Line 4854  namespace {
4854          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4855          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4856          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4857          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4858          // update Region key table for fast lookup          // update Region key table for fast lookup
4859          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4860          // done          // done
# Line 4786  namespace { Line 5000  namespace {
5000                  for (uint s = 0; group->GetScript(s); ++s) {                  for (uint s = 0; group->GetScript(s); ++s) {
5001                      Script* script = group->GetScript(s);                      Script* script = group->GetScript(s);
5002                      if (script->pChunk) {                      if (script->pChunk) {
5003                          uint32_t offset = script->pChunk->GetFilePos() -                          uint32_t offset = uint32_t(
5004                                            script->pChunk->GetPos() -                              script->pChunk->GetFilePos() -
5005                                            CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize());                              script->pChunk->GetPos() -
5006                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
5007                            );
5008                          if (offset == soughtOffset)                          if (offset == soughtOffset)
5009                          {                          {
5010                              _ScriptPooolRef ref;                              _ScriptPooolRef ref;
# Line 4913  namespace { Line 5129  namespace {
5129       */       */
5130      void Instrument::RemoveScript(Script* pScript) {      void Instrument::RemoveScript(Script* pScript) {
5131          LoadScripts();          LoadScripts();
5132          for (int i = pScriptRefs->size() - 1; i >= 0; --i) {          for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5133              if ((*pScriptRefs)[i].script == pScript) {              if ((*pScriptRefs)[i].script == pScript) {
5134                  pScriptRefs->erase( pScriptRefs->begin() + i );                  pScriptRefs->erase( pScriptRefs->begin() + i );
5135              }              }
# Line 4935  namespace { Line 5151  namespace {
5151       * gigedit.       * gigedit.
5152       */       */
5153      uint Instrument::ScriptSlotCount() const {      uint Instrument::ScriptSlotCount() const {
5154          return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();          return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5155      }      }
5156    
5157      /** @brief Whether script execution shall be skipped.      /** @brief Whether script execution shall be skipped.
# Line 5359  namespace { Line 5575  namespace {
5575              }              }
5576          }          }
5577          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5578          int nameLen = name.length();          int nameLen = (int) name.length();
5579          char suffix[6];          char suffix[6];
5580          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5581    
# Line 5375  namespace { Line 5591  namespace {
5591                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5592    
5593                          file_offset_t waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5594                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5595    
5596                          iSampleIndex++;                          iSampleIndex++;
5597                      }                      }
# Line 5528  namespace { Line 5744  namespace {
5744              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5745              mSamples[pFile->GetSample(i)] = s;              mSamples[pFile->GetSample(i)] = s;
5746          }          }
5747            
5748            // clone script groups and their scripts
5749            for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
5750                ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
5751                ScriptGroup* dg = AddScriptGroup();
5752                dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
5753                for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
5754                    Script* ss = sg->GetScript(iScript);
5755                    Script* ds = dg->AddScript();
5756                    ds->CopyAssign(ss);
5757                }
5758            }
5759    
5760          //BUG: For some reason this method only works with this additional          //BUG: For some reason this method only works with this additional
5761          //     Save() call in between here.          //     Save() call in between here.
5762          //          //
# Line 5613  namespace { Line 5841  namespace {
5841          if (!_3crc) return;          if (!_3crc) return;
5842    
5843          // get the index of the sample          // get the index of the sample
5844          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;  
             }  
         }  
5845          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");
5846    
5847          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5848          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5849          uint32_t tmp = 1;          uint32_t one = 1;
5850          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5851          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5852      }      }
5853    
5854        uint32_t File::GetSampleChecksum(Sample* pSample) {
5855            // get the index of the sample
5856            int iWaveIndex = GetWaveTableIndexOf(pSample);
5857            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5858    
5859            return GetSampleChecksumByIndex(iWaveIndex);
5860        }
5861    
5862        uint32_t File::GetSampleChecksumByIndex(int index) {
5863            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5864    
5865            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5866            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5867            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5868            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5869    
5870            // read the CRC-32 checksum directly from disk
5871            size_t pos = index * 8;
5872            if (pos + 8 > _3crc->GetNewSize())
5873                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5874    
5875            uint32_t one = load32(&pData[pos]); // always 1
5876            if (one != 1)
5877                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5878    
5879            return load32(&pData[pos+4]);
5880        }
5881    
5882        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5883            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5884            File::SampleList::iterator iter = pSamples->begin();
5885            File::SampleList::iterator end  = pSamples->end();
5886            for (int index = 0; iter != end; ++iter, ++index)
5887                if (*iter == pSample)
5888                    return index;
5889            return -1;
5890        }
5891    
5892        /**
5893         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5894         * the CRC32 check sums of all samples' raw wave data.
5895         *
5896         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5897         */
5898        bool File::VerifySampleChecksumTable() {
5899            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5900            if (!_3crc) return false;
5901            if (_3crc->GetNewSize() <= 0) return false;
5902            if (_3crc->GetNewSize() % 8) return false;
5903            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5904            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5905    
5906            const file_offset_t n = _3crc->GetNewSize() / 8;
5907    
5908            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5909            if (!pData) return false;
5910    
5911            for (file_offset_t i = 0; i < n; ++i) {
5912                uint32_t one = pData[i*2];
5913                if (one != 1) return false;
5914            }
5915    
5916            return true;
5917        }
5918    
5919        /**
5920         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5921         * file's checksum table with those new checksums. This might usually
5922         * just be necessary if the checksum table was damaged.
5923         *
5924         * @e IMPORTANT: The current implementation of this method only works
5925         * with files that have not been modified since it was loaded, because
5926         * it expects that no externally caused file structure changes are
5927         * required!
5928         *
5929         * Due to the expectation above, this method is currently protected
5930         * and actually only used by the command line tool "gigdump" yet.
5931         *
5932         * @returns true if Save() is required to be called after this call,
5933         *          false if no further action is required
5934         */
5935        bool File::RebuildSampleChecksumTable() {
5936            // make sure sample chunks were scanned
5937            if (!pSamples) GetFirstSample();
5938    
5939            bool bRequiresSave = false;
5940    
5941            // make sure "3CRC" chunk exists with required size
5942            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5943            if (!_3crc) {
5944                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5945                // the order of einf and 3crc is not the same in v2 and v3
5946                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5947                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5948                bRequiresSave = true;
5949            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5950                _3crc->Resize(pSamples->size() * 8);
5951                bRequiresSave = true;
5952            }
5953    
5954            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5955                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5956                {
5957                    File::SampleList::iterator iter = pSamples->begin();
5958                    File::SampleList::iterator end  = pSamples->end();
5959                    for (; iter != end; ++iter) {
5960                        gig::Sample* pSample = (gig::Sample*) *iter;
5961                        int index = GetWaveTableIndexOf(pSample);
5962                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5963                        pData[index*2]   = 1; // always 1
5964                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5965                    }
5966                }
5967            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5968                // make sure file is in write mode
5969                pRIFF->SetMode(RIFF::stream_mode_read_write);
5970                {
5971                    File::SampleList::iterator iter = pSamples->begin();
5972                    File::SampleList::iterator end  = pSamples->end();
5973                    for (; iter != end; ++iter) {
5974                        gig::Sample* pSample = (gig::Sample*) *iter;
5975                        int index = GetWaveTableIndexOf(pSample);
5976                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5977                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5978                        SetSampleChecksum(pSample, pSample->crc);
5979                    }
5980                }
5981            }
5982    
5983            return bRequiresSave;
5984        }
5985    
5986      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5987          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5988          // there must always be at least one group          // there must always be at least one group
# Line 5948  namespace { Line 6300  namespace {
6300          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6301          // are set to zero.          // are set to zero.
6302    
6303          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6304          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6305    
6306          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 6021  namespace { Line 6373  namespace {
6373                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6374                  // next 8 bytes unknown                  // next 8 bytes unknown
6375                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6376                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6377                  // next 4 bytes unknown                  // next 4 bytes unknown
6378    
6379                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 6039  namespace { Line 6391  namespace {
6391              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6392              // next 8 bytes unknown              // next 8 bytes unknown
6393              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6394              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6395              // next 4 bytes unknown              // next 4 bytes unknown
6396          }          }
6397    
6398          // update 3crc chunk          // update 3crc chunk
6399    
6400          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6401          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6402          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6403            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6404            // member variable). This step is required, because samples might have
6405            // been deleted by the user since the file was opened, which in turn
6406            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6407            // If a sample was conciously modified by the user (that is if
6408            // Sample::Write() was called later on) then Sample::Write() will just
6409            // update the respective individual checksum(s) directly on disk and
6410            // leaves all other sample checksums untouched.
6411    
6412          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6413          if (_3crc) {          if (_3crc) {
6414              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6415          } else if (newFile) {          } else /*if (newFile)*/ {
6416              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6417              // 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
6418              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6419          }          }
6420            { // must be performed in RAM here ...
6421                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6422                if (pData) {
6423                    File::SampleList::iterator iter = pSamples->begin();
6424                    File::SampleList::iterator end  = pSamples->end();
6425                    for (int index = 0; iter != end; ++iter, ++index) {
6426                        gig::Sample* pSample = (gig::Sample*) *iter;
6427                        pData[index*2]   = 1; // always 1
6428                        pData[index*2+1] = pSample->crc;
6429                    }
6430                }
6431            }
6432      }      }
6433            
6434      void File::UpdateFileOffsets() {      void File::UpdateFileOffsets() {
# Line 6103  namespace { Line 6473  namespace {
6473  // *************** Exception ***************  // *************** Exception ***************
6474  // *  // *
6475    
6476      Exception::Exception(String Message) : DLS::Exception(Message) {      Exception::Exception() : DLS::Exception() {
6477        }
6478    
6479        Exception::Exception(String format, ...) : DLS::Exception() {
6480            va_list arg;
6481            va_start(arg, format);
6482            Message = assemble(format, arg);
6483            va_end(arg);
6484        }
6485    
6486        Exception::Exception(String format, va_list arg) : DLS::Exception() {
6487            Message = assemble(format, arg);
6488      }      }
6489    
6490      void Exception::PrintMessage() {      void Exception::PrintMessage() {

Legend:
Removed from v.2913  
changed lines
  Added in v.3198

  ViewVC Help
Powered by ViewVC