external/libmodplug-0.8.8.4/src/sndfile.cpp
author Sam Lantinga <slouken@libsdl.org>
Sun, 09 Jun 2013 16:22:42 -0700
changeset 639 f8901a7ff3f1
permissions -rw-r--r--
Switched from mikmod to libmodplug, which is now in the public domain.
This allows us to add MOD support for iOS and Android, yay!
     1 /*
     2  * This source code is public domain.
     3  *
     4  * Authors: Olivier Lapicque <olivierl@jps.net>,
     5  *          Adam Goode       <adam@evdebs.org> (endian and char fixes for PPC)
     6 */
     7 
     8 #include <math.h> //for GCCFIX
     9 #include <libmodplug/stdafx.h>
    10 #include <libmodplug/sndfile.h>
    11 
    12 #define MMCMP_SUPPORT
    13 
    14 #ifdef MMCMP_SUPPORT
    15 extern BOOL MMCMP_Unpack(LPCBYTE *ppMemFile, LPDWORD pdwMemLength);
    16 #endif
    17 
    18 // External decompressors
    19 extern void AMSUnpack(const char *psrc, UINT inputlen, char *pdest, UINT dmax, char packcharacter);
    20 extern WORD MDLReadBits(DWORD &bitbuf, UINT &bitnum, LPBYTE &ibuf, CHAR n);
    21 extern int DMFUnpack(LPBYTE psample, LPBYTE ibuf, LPBYTE ibufmax, UINT maxlen);
    22 extern DWORD ITReadBits(DWORD &bitbuf, UINT &bitnum, LPBYTE &ibuf, CHAR n);
    23 extern void ITUnpack8Bit(signed char *pSample, DWORD dwLen, LPBYTE lpMemFile, DWORD dwMemLength, BOOL b215);
    24 extern void ITUnpack16Bit(signed char *pSample, DWORD dwLen, LPBYTE lpMemFile, DWORD dwMemLength, BOOL b215);
    25 
    26 
    27 #define MAX_PACK_TABLES		3
    28 
    29 
    30 // Compression table
    31 static const signed char UnpackTable[MAX_PACK_TABLES][16] =
    32 //--------------------------------------------
    33 {
    34 	// CPU-generated dynamic table
    35 	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    36 	// u-Law table
    37 	{0, 1, 2, 4, 8, 16, 32, 64,
    38 	-1, -2, -4, -8, -16, -32, -48, -64},
    39 	// Linear table
    40 	{0, 1, 2, 3, 5, 7, 12, 19,
    41 	-1, -2, -3, -5, -7, -12, -19, -31}
    42 };
    43 
    44 
    45 //////////////////////////////////////////////////////////
    46 // CSoundFile
    47 
    48 CSoundFile::CSoundFile()
    49 //----------------------
    50 {
    51 	m_nType = MOD_TYPE_NONE;
    52 	m_dwSongFlags = 0;
    53 	m_nChannels = 0;
    54 	m_nMixChannels = 0;
    55 	m_nSamples = 0;
    56 	m_nInstruments = 0;
    57 	m_nPatternNames = 0;
    58 	m_lpszPatternNames = NULL;
    59 	m_lpszSongComments = NULL;
    60 	m_nFreqFactor = m_nTempoFactor = 128;
    61 	m_nMasterVolume = 128;
    62 	m_nMinPeriod = 0x20;
    63 	m_nMaxPeriod = 0x7FFF;
    64 	m_nRepeatCount = 0;
    65 	memset(Chn, 0, sizeof(Chn));
    66 	memset(ChnMix, 0, sizeof(ChnMix));
    67 	memset(Ins, 0, sizeof(Ins));
    68 	memset(ChnSettings, 0, sizeof(ChnSettings));
    69 	memset(Headers, 0, sizeof(Headers));
    70 	memset(Order, 0xFF, sizeof(Order));
    71 	memset(Patterns, 0, sizeof(Patterns));
    72 	memset(m_szNames, 0, sizeof(m_szNames));
    73 	memset(m_MixPlugins, 0, sizeof(m_MixPlugins));
    74 }
    75 
    76 
    77 CSoundFile::~CSoundFile()
    78 //-----------------------
    79 {
    80 	Destroy();
    81 }
    82 
    83 
    84 BOOL CSoundFile::Create(LPCBYTE lpStream, DWORD dwMemLength)
    85 //----------------------------------------------------------
    86 {
    87 	int i;
    88 
    89 	m_nType = MOD_TYPE_NONE;
    90 	m_dwSongFlags = 0;
    91 	m_nChannels = 0;
    92 	m_nMixChannels = 0;
    93 	m_nSamples = 0;
    94 	m_nInstruments = 0;
    95 	m_nFreqFactor = m_nTempoFactor = 128;
    96 	m_nMasterVolume = 128;
    97 	m_nDefaultGlobalVolume = 256;
    98 	m_nGlobalVolume = 256;
    99 	m_nOldGlbVolSlide = 0;
   100 	m_nDefaultSpeed = 6;
   101 	m_nDefaultTempo = 125;
   102 	m_nPatternDelay = 0;
   103 	m_nFrameDelay = 0;
   104 	m_nNextRow = 0;
   105 	m_nRow = 0;
   106 	m_nPattern = 0;
   107 	m_nCurrentPattern = 0;
   108 	m_nNextPattern = 0;
   109 	m_nRestartPos = 0;
   110 	m_nMinPeriod = 16;
   111 	m_nMaxPeriod = 32767;
   112 	m_nSongPreAmp = 0x30;
   113 	m_nPatternNames = 0;
   114 	m_nMaxOrderPosition = 0;
   115 	m_lpszPatternNames = NULL;
   116 	m_lpszSongComments = NULL;
   117 	memset(Ins, 0, sizeof(Ins));
   118 	memset(ChnMix, 0, sizeof(ChnMix));
   119 	memset(Chn, 0, sizeof(Chn));
   120 	memset(Headers, 0, sizeof(Headers));
   121 	memset(Order, 0xFF, sizeof(Order));
   122 	memset(Patterns, 0, sizeof(Patterns));
   123 	memset(m_szNames, 0, sizeof(m_szNames));
   124 	memset(m_MixPlugins, 0, sizeof(m_MixPlugins));
   125 	ResetMidiCfg();
   126 	for (UINT npt=0; npt<MAX_PATTERNS; npt++) PatternSize[npt] = 64;
   127 	for (UINT nch=0; nch<MAX_BASECHANNELS; nch++)
   128 	{
   129 		ChnSettings[nch].nPan = 128;
   130 		ChnSettings[nch].nVolume = 64;
   131 		ChnSettings[nch].dwFlags = 0;
   132 		ChnSettings[nch].szName[0] = 0;
   133 	}
   134 	if (lpStream)
   135 	{
   136 #ifdef MMCMP_SUPPORT
   137 		BOOL bMMCmp = MMCMP_Unpack(&lpStream, &dwMemLength);
   138 #endif
   139 		if ((!ReadXM(lpStream, dwMemLength))
   140 		 && (!ReadS3M(lpStream, dwMemLength))
   141 		 && (!ReadIT(lpStream, dwMemLength))
   142 		 && (!ReadWav(lpStream, dwMemLength))
   143 #ifndef MODPLUG_BASIC_SUPPORT
   144 /* Sequencer File Format Support */
   145 		 && (!ReadABC(lpStream, dwMemLength))
   146 		 && (!ReadMID(lpStream, dwMemLength))
   147 		 && (!ReadPAT(lpStream, dwMemLength))
   148 		 && (!ReadSTM(lpStream, dwMemLength))
   149 		 && (!ReadMed(lpStream, dwMemLength))
   150 		 && (!ReadMTM(lpStream, dwMemLength))
   151 		 && (!ReadMDL(lpStream, dwMemLength))
   152 		 && (!ReadDBM(lpStream, dwMemLength))
   153 		 && (!Read669(lpStream, dwMemLength))
   154 		 && (!ReadFAR(lpStream, dwMemLength))
   155 		 && (!ReadAMS(lpStream, dwMemLength))
   156 		 && (!ReadOKT(lpStream, dwMemLength))
   157 		 && (!ReadPTM(lpStream, dwMemLength))
   158 		 && (!ReadUlt(lpStream, dwMemLength))
   159 		 && (!ReadDMF(lpStream, dwMemLength))
   160 		 && (!ReadDSM(lpStream, dwMemLength))
   161 		 && (!ReadUMX(lpStream, dwMemLength))
   162 		 && (!ReadAMF(lpStream, dwMemLength))
   163 		 && (!ReadPSM(lpStream, dwMemLength))
   164 		 && (!ReadMT2(lpStream, dwMemLength))
   165 #endif // MODPLUG_BASIC_SUPPORT
   166 		 && (!ReadMod(lpStream, dwMemLength))) m_nType = MOD_TYPE_NONE;
   167 #ifdef MMCMP_SUPPORT
   168 		if (bMMCmp)
   169 		{
   170 			GlobalFreePtr(lpStream);
   171 			lpStream = NULL;
   172 		}
   173 #endif
   174 	}
   175 	// Adjust song names
   176 	for (i=0; i<MAX_SAMPLES; i++)
   177 	{
   178 		LPSTR p = m_szNames[i];
   179 		int j = 31;
   180 		p[j] = 0;
   181 		while ((j>=0) && (p[j]<=' ')) p[j--] = 0;
   182 		while (j>=0)
   183 		{
   184 			if (((BYTE)p[j]) < ' ') p[j] = ' ';
   185 			j--;
   186 		}
   187 	}
   188 	// Adjust channels
   189 	for (i=0; i<MAX_BASECHANNELS; i++)
   190 	{
   191 		if (ChnSettings[i].nVolume > 64) ChnSettings[i].nVolume = 64;
   192 		if (ChnSettings[i].nPan > 256) ChnSettings[i].nPan = 128;
   193 		Chn[i].nPan = ChnSettings[i].nPan;
   194 		Chn[i].nGlobalVol = ChnSettings[i].nVolume;
   195 		Chn[i].dwFlags = ChnSettings[i].dwFlags;
   196 		Chn[i].nVolume = 256;
   197 		Chn[i].nCutOff = 0x7F;
   198 	}
   199 	// Checking instruments
   200 	MODINSTRUMENT *pins = Ins;
   201 
   202 	for (i=0; i<MAX_INSTRUMENTS; i++, pins++)
   203 	{
   204 		if (pins->pSample)
   205 		{
   206 			if (pins->nLoopEnd > pins->nLength) pins->nLoopEnd = pins->nLength;
   207 			if (pins->nLoopStart + 3 >= pins->nLoopEnd)
   208 			{
   209 				pins->nLoopStart = 0;
   210 				pins->nLoopEnd = 0;
   211 			}
   212 			if (pins->nSustainEnd > pins->nLength) pins->nSustainEnd = pins->nLength;
   213 			if (pins->nSustainStart + 3 >= pins->nSustainEnd)
   214 			{
   215 				pins->nSustainStart = 0;
   216 				pins->nSustainEnd = 0;
   217 			}
   218 		} else
   219 		{
   220 			pins->nLength = 0;
   221 			pins->nLoopStart = 0;
   222 			pins->nLoopEnd = 0;
   223 			pins->nSustainStart = 0;
   224 			pins->nSustainEnd = 0;
   225 		}
   226 		if (!pins->nLoopEnd) pins->uFlags &= ~CHN_LOOP;
   227 		if (!pins->nSustainEnd) pins->uFlags &= ~CHN_SUSTAINLOOP;
   228 		if (pins->nGlobalVol > 64) pins->nGlobalVol = 64;
   229 	}
   230 	// Check invalid instruments
   231 	while ((m_nInstruments > 0) && (!Headers[m_nInstruments])) 
   232 		m_nInstruments--;
   233 	// Set default values
   234 	if (m_nSongPreAmp < 0x20) m_nSongPreAmp = 0x20;
   235 	if (m_nDefaultTempo < 32) m_nDefaultTempo = 125;
   236 	if (!m_nDefaultSpeed) m_nDefaultSpeed = 6;
   237 	m_nMusicSpeed = m_nDefaultSpeed;
   238 	m_nMusicTempo = m_nDefaultTempo;
   239 	m_nGlobalVolume = m_nDefaultGlobalVolume;
   240 	m_nNextPattern = 0;
   241 	m_nCurrentPattern = 0;
   242 	m_nPattern = 0;
   243 	m_nBufferCount = 0;
   244 	m_nTickCount = m_nMusicSpeed;
   245 	m_nNextRow = 0;
   246 	m_nRow = 0;
   247 	if ((m_nRestartPos >= MAX_ORDERS) || (Order[m_nRestartPos] >= MAX_PATTERNS)) m_nRestartPos = 0;
   248 	// Load plugins
   249 	if (gpMixPluginCreateProc)
   250 	{
   251 		for (UINT iPlug=0; iPlug<MAX_MIXPLUGINS; iPlug++)
   252 		{
   253 			if ((m_MixPlugins[iPlug].Info.dwPluginId1)
   254 			 || (m_MixPlugins[iPlug].Info.dwPluginId2))
   255 			{
   256 				gpMixPluginCreateProc(&m_MixPlugins[iPlug]);
   257 				if (m_MixPlugins[iPlug].pMixPlugin)
   258 				{
   259 					m_MixPlugins[iPlug].pMixPlugin->RestoreAllParameters();
   260 				}
   261 			}
   262 		}
   263 	}
   264 	if (m_nType)
   265 	{
   266 		UINT maxpreamp = 0x10+(m_nChannels*8);
   267 		if (maxpreamp > 100) maxpreamp = 100;
   268 		if (m_nSongPreAmp > maxpreamp) m_nSongPreAmp = maxpreamp;
   269 		return TRUE;
   270 	}
   271 	return FALSE;
   272 }
   273 
   274 
   275 BOOL CSoundFile::Destroy()
   276 
   277 //------------------------
   278 {
   279 	int i;
   280 	for (i=0; i<MAX_PATTERNS; i++) if (Patterns[i])
   281 	{
   282 		FreePattern(Patterns[i]);
   283 		Patterns[i] = NULL;
   284 	}
   285 	m_nPatternNames = 0;
   286 	if (m_lpszPatternNames)
   287 	{
   288 		delete [] m_lpszPatternNames;
   289 		m_lpszPatternNames = NULL;
   290 	}
   291 	if (m_lpszSongComments)
   292 	{
   293 		delete [] m_lpszSongComments;
   294 		m_lpszSongComments = NULL;
   295 	}
   296 	for (i=1; i<MAX_SAMPLES; i++)
   297 	{
   298 		MODINSTRUMENT *pins = &Ins[i];
   299 		if (pins->pSample)
   300 		{
   301 			FreeSample(pins->pSample);
   302 			pins->pSample = NULL;
   303 		}
   304 	}
   305 	for (i=0; i<MAX_INSTRUMENTS; i++)
   306 	{
   307 		if (Headers[i])
   308 		{
   309 			delete Headers[i];
   310 			Headers[i] = NULL;
   311 		}
   312 	}
   313 	for (i=0; i<MAX_MIXPLUGINS; i++)
   314 	{
   315 		if ((m_MixPlugins[i].nPluginDataSize) && (m_MixPlugins[i].pPluginData))
   316 		{
   317 			m_MixPlugins[i].nPluginDataSize = 0;
   318 			delete [] (signed char*)m_MixPlugins[i].pPluginData;
   319 			m_MixPlugins[i].pPluginData = NULL;
   320 		}
   321 		m_MixPlugins[i].pMixState = NULL;
   322 		if (m_MixPlugins[i].pMixPlugin)
   323 		{
   324 			m_MixPlugins[i].pMixPlugin->Release();
   325 			m_MixPlugins[i].pMixPlugin = NULL;
   326 		}
   327 	}
   328 	m_nType = MOD_TYPE_NONE;
   329 	m_nChannels = m_nSamples = m_nInstruments = 0;
   330 	return TRUE;
   331 }
   332 
   333 
   334 //////////////////////////////////////////////////////////////////////////
   335 // Memory Allocation
   336 
   337 MODCOMMAND *CSoundFile::AllocatePattern(UINT rows, UINT nchns)
   338 //------------------------------------------------------------
   339 {
   340 	MODCOMMAND *p = new MODCOMMAND[rows*nchns];
   341 	if (p) memset(p, 0, rows*nchns*sizeof(MODCOMMAND));
   342 	return p;
   343 }
   344 
   345 
   346 void CSoundFile::FreePattern(LPVOID pat)
   347 //--------------------------------------
   348 {
   349 	if (pat) delete [] (signed char*)pat;
   350 }
   351 
   352 
   353 signed char* CSoundFile::AllocateSample(UINT nbytes)
   354 //-------------------------------------------
   355 {
   356 	signed char * p = (signed char *)GlobalAllocPtr(GHND, (nbytes+39) & ~7);
   357 	if (p) p += 16;
   358 	return p;
   359 }
   360 
   361 
   362 void CSoundFile::FreeSample(LPVOID p)
   363 //-----------------------------------
   364 {
   365 	if (p)
   366 	{
   367 		GlobalFreePtr(((LPSTR)p)-16);
   368 	}
   369 }
   370 
   371 
   372 //////////////////////////////////////////////////////////////////////////
   373 // Misc functions
   374 
   375 void CSoundFile::ResetMidiCfg()
   376 //-----------------------------
   377 {
   378 	memset(&m_MidiCfg, 0, sizeof(m_MidiCfg));
   379 	lstrcpy(&m_MidiCfg.szMidiGlb[MIDIOUT_START*32], "FF");
   380 	lstrcpy(&m_MidiCfg.szMidiGlb[MIDIOUT_STOP*32], "FC");
   381 	lstrcpy(&m_MidiCfg.szMidiGlb[MIDIOUT_NOTEON*32], "9c n v");
   382 	lstrcpy(&m_MidiCfg.szMidiGlb[MIDIOUT_NOTEOFF*32], "9c n 0");
   383 	lstrcpy(&m_MidiCfg.szMidiGlb[MIDIOUT_PROGRAM*32], "Cc p");
   384 	lstrcpy(&m_MidiCfg.szMidiSFXExt[0], "F0F000z");
   385 	for (int iz=0; iz<16; iz++) wsprintf(&m_MidiCfg.szMidiZXXExt[iz*32], "F0F001%02X", iz*8);
   386 }
   387 
   388 
   389 UINT CSoundFile::GetNumChannels() const
   390 //-------------------------------------
   391 {
   392 	UINT n = 0;
   393 	for (UINT i=0; i<m_nChannels; i++) if (ChnSettings[i].nVolume) n++;
   394 	return n;
   395 }
   396 
   397 
   398 UINT CSoundFile::GetSongComments(LPSTR s, UINT len, UINT linesize)
   399 //----------------------------------------------------------------
   400 {
   401 	LPCSTR p = m_lpszSongComments;
   402 	if (!p) return 0;
   403 	UINT i = 2, ln=0;
   404 	if ((len) && (s)) s[0] = '\x0D';
   405 	if ((len > 1) && (s)) s[1] = '\x0A';
   406 	while ((*p)	&& (i+2 < len))
   407 	{
   408 		BYTE c = (BYTE)*p++;
   409 		if ((c == 0x0D) || ((c == ' ') && (ln >= linesize)))
   410 			{ if (s) { s[i++] = '\x0D'; s[i++] = '\x0A'; } else i+= 2; ln=0; }
   411 		else
   412 		if (c >= 0x20) { if (s) s[i++] = c; else i++; ln++; }
   413 	}
   414 	if (s) s[i] = 0;
   415 	return i;
   416 }
   417 
   418 
   419 UINT CSoundFile::GetRawSongComments(LPSTR s, UINT len, UINT linesize)
   420 //-------------------------------------------------------------------
   421 {
   422 	LPCSTR p = m_lpszSongComments;
   423 	if (!p) return 0;
   424 	UINT i = 0, ln=0;
   425 	while ((*p)	&& (i < len-1))
   426 	{
   427 		BYTE c = (BYTE)*p++;
   428 		if ((c == 0x0D)	|| (c == 0x0A))
   429 		{
   430 			if (ln)
   431 			{
   432 				while (ln < linesize) { if (s) s[i] = ' '; i++; ln++; }
   433 				ln = 0;
   434 			}
   435 		} else
   436 		if ((c == ' ') && (!ln))
   437 		{
   438 			UINT k=0;
   439 			while ((p[k]) && (p[k] >= ' '))	k++;
   440 			if (k <= linesize)
   441 			{
   442 				if (s) s[i] = ' ';
   443 				i++;
   444 				ln++;
   445 			}
   446 		} else
   447 		{
   448 			if (s) s[i] = c;
   449 			i++;
   450 			ln++;
   451 			if (ln == linesize) ln = 0;
   452 		}
   453 	}
   454 	if (ln)
   455 	{
   456 		while ((ln < linesize) && (i < len))
   457 		{
   458 			if (s) s[i] = ' ';
   459 			i++;
   460 			ln++;
   461 		}
   462 	}
   463 	if (s) s[i] = 0;
   464 	return i;
   465 }
   466 
   467 
   468 BOOL CSoundFile::SetWaveConfig(UINT nRate,UINT nBits,UINT nChannels,BOOL bMMX)
   469 //----------------------------------------------------------------------------
   470 {
   471 	BOOL bReset = FALSE;
   472 	DWORD d = gdwSoundSetup & ~SNDMIX_ENABLEMMX;
   473 	if (bMMX) d |= SNDMIX_ENABLEMMX;
   474 	if ((gdwMixingFreq != nRate) || (gnBitsPerSample != nBits) || (gnChannels != nChannels) || (d != gdwSoundSetup)) bReset = TRUE;
   475 	gnChannels = nChannels;
   476 	gdwSoundSetup = d;
   477 	gdwMixingFreq = nRate;
   478 	gnBitsPerSample = nBits;
   479 	InitPlayer(bReset);
   480 	return TRUE;
   481 }
   482 
   483 BOOL CSoundFile::SetMixConfig(UINT nStereoSeparation, UINT nMaxMixChannels)
   484 //-------------------------------------------------------------------------
   485 {
   486 	if (nMaxMixChannels < 2) return FALSE;
   487 
   488 	m_nMaxMixChannels = nMaxMixChannels;
   489 	m_nStereoSeparation = nStereoSeparation;
   490 	return TRUE;
   491 }
   492 
   493 
   494 BOOL CSoundFile::SetResamplingMode(UINT nMode)
   495 //--------------------------------------------
   496 {
   497 	DWORD d = gdwSoundSetup & ~(SNDMIX_NORESAMPLING|SNDMIX_HQRESAMPLER|SNDMIX_ULTRAHQSRCMODE);
   498 	switch(nMode)
   499 	{
   500 	case SRCMODE_NEAREST:	d |= SNDMIX_NORESAMPLING; break;
   501 	case SRCMODE_LINEAR:	break;
   502 	case SRCMODE_SPLINE:	d |= SNDMIX_HQRESAMPLER; break;
   503 	case SRCMODE_POLYPHASE:	d |= (SNDMIX_HQRESAMPLER|SNDMIX_ULTRAHQSRCMODE); break;
   504 	default:
   505 		return FALSE;
   506 	}
   507 	gdwSoundSetup = d;
   508 	return TRUE;
   509 }
   510 
   511 
   512 BOOL CSoundFile::SetMasterVolume(UINT nVol, BOOL bAdjustAGC)
   513 //----------------------------------------------------------
   514 {
   515 	if (nVol < 1) nVol = 1;
   516 	if (nVol > 0x200) nVol = 0x200;	// x4 maximum
   517 	if ((nVol < m_nMasterVolume) && (nVol) && (gdwSoundSetup & SNDMIX_AGC) && (bAdjustAGC))
   518 	{
   519 		gnAGC = gnAGC * m_nMasterVolume / nVol;
   520 		if (gnAGC > AGC_UNITY) gnAGC = AGC_UNITY;
   521 	}
   522 	m_nMasterVolume = nVol;
   523 	return TRUE;
   524 }
   525 
   526 
   527 void CSoundFile::SetAGC(BOOL b)
   528 //-----------------------------
   529 {
   530 	if (b)
   531 	{
   532 		if (!(gdwSoundSetup & SNDMIX_AGC))
   533 		{
   534 			gdwSoundSetup |= SNDMIX_AGC;
   535 			gnAGC = AGC_UNITY;
   536 		}
   537 	} else gdwSoundSetup &= ~SNDMIX_AGC;
   538 }
   539 
   540 
   541 UINT CSoundFile::GetNumPatterns() const
   542 //-------------------------------------
   543 {
   544 	UINT i = 0;
   545 	while ((i < MAX_ORDERS) && (Order[i] < 0xFF)) i++;
   546 	return i;
   547 }
   548 
   549 
   550 UINT CSoundFile::GetNumInstruments() const
   551 //----------------------------------------
   552 {
   553 	UINT n=0;
   554 	for (UINT i=0; i<MAX_INSTRUMENTS; i++) if (Ins[i].pSample) n++;
   555 	return n;
   556 }
   557 
   558 
   559 UINT CSoundFile::GetMaxPosition() const
   560 //-------------------------------------
   561 {
   562 	UINT max = 0;
   563 	UINT i = 0;
   564 
   565 	while ((i < MAX_ORDERS) && (Order[i] != 0xFF))
   566 	{
   567 		if (Order[i] < MAX_PATTERNS) max += PatternSize[Order[i]];
   568 		i++;
   569 	}
   570 	return max;
   571 }
   572 
   573 
   574 UINT CSoundFile::GetCurrentPos() const
   575 //------------------------------------
   576 {
   577 	UINT pos = 0;
   578 
   579 	for (UINT i=0; i<m_nCurrentPattern; i++) if (Order[i] < MAX_PATTERNS)
   580 		pos += PatternSize[Order[i]];
   581 	return pos + m_nRow;
   582 }
   583 
   584 
   585 void CSoundFile::SetCurrentPos(UINT nPos)
   586 //---------------------------------------
   587 {
   588 	UINT i, nPattern;
   589 
   590 	for (i=0; i<MAX_CHANNELS; i++)
   591 	{
   592 		Chn[i].nNote = Chn[i].nNewNote = Chn[i].nNewIns = 0;
   593 		Chn[i].pInstrument = NULL;
   594 		Chn[i].pHeader = NULL;
   595 		Chn[i].nPortamentoDest = 0;
   596 		Chn[i].nCommand = 0;
   597 		Chn[i].nPatternLoopCount = 0;
   598 		Chn[i].nPatternLoop = 0;
   599 		Chn[i].nFadeOutVol = 0;
   600 		Chn[i].dwFlags |= CHN_KEYOFF|CHN_NOTEFADE;
   601 		Chn[i].nTremorCount = 0;
   602 	}
   603 	if (!nPos)
   604 	{
   605 		for (i=0; i<MAX_CHANNELS; i++)
   606 		{
   607 			Chn[i].nPeriod = 0;
   608 			Chn[i].nPos = Chn[i].nLength = 0;
   609 			Chn[i].nLoopStart = 0;
   610 			Chn[i].nLoopEnd = 0;
   611 			Chn[i].nROfs = Chn[i].nLOfs = 0;
   612 			Chn[i].pSample = NULL;
   613 			Chn[i].pInstrument = NULL;
   614 			Chn[i].pHeader = NULL;
   615 			Chn[i].nCutOff = 0x7F;
   616 			Chn[i].nResonance = 0;
   617 			Chn[i].nLeftVol = Chn[i].nRightVol = 0;
   618 			Chn[i].nNewLeftVol = Chn[i].nNewRightVol = 0;
   619 			Chn[i].nLeftRamp = Chn[i].nRightRamp = 0;
   620 			Chn[i].nVolume = 256;
   621 			if (i < MAX_BASECHANNELS)
   622 			{
   623 				Chn[i].dwFlags = ChnSettings[i].dwFlags;
   624 				Chn[i].nPan = ChnSettings[i].nPan;
   625 				Chn[i].nGlobalVol = ChnSettings[i].nVolume;
   626 			} else
   627 			{
   628 				Chn[i].dwFlags = 0;
   629 				Chn[i].nPan = 128;
   630 				Chn[i].nGlobalVol = 64;
   631 			}
   632 		}
   633 		m_nGlobalVolume = m_nDefaultGlobalVolume;
   634 		m_nMusicSpeed = m_nDefaultSpeed;
   635 		m_nMusicTempo = m_nDefaultTempo;
   636 	}
   637 	m_dwSongFlags &= ~(SONG_PATTERNLOOP|SONG_CPUVERYHIGH|SONG_FADINGSONG|SONG_ENDREACHED|SONG_GLOBALFADE);
   638 	for (nPattern = 0; nPattern < MAX_ORDERS; nPattern++)
   639 	{
   640 		UINT ord = Order[nPattern];
   641 		if (ord == 0xFE) continue;
   642 		if (ord == 0xFF) break;
   643 		if (ord < MAX_PATTERNS)
   644 		{
   645 			if (nPos < (UINT)PatternSize[ord]) break;
   646 			nPos -= PatternSize[ord];
   647 		}
   648 	}
   649 	// Buggy position ?
   650 	if ((nPattern >= MAX_ORDERS)
   651 	 || (Order[nPattern] >= MAX_PATTERNS)
   652 	 || (nPos >= PatternSize[Order[nPattern]]))
   653 	{
   654 		nPos = 0;
   655 		nPattern = 0;
   656 	}
   657 	UINT nRow = nPos;
   658 	if ((nRow) && (Order[nPattern] < MAX_PATTERNS))
   659 	{
   660 		MODCOMMAND *p = Patterns[Order[nPattern]];
   661 		if ((p) && (nRow < PatternSize[Order[nPattern]]))
   662 		{
   663 			BOOL bOk = FALSE;
   664 			while ((!bOk) && (nRow > 0))
   665 			{
   666 				UINT n = nRow * m_nChannels;
   667 				for (UINT k=0; k<m_nChannels; k++, n++)
   668 				{
   669 					if (p[n].note)
   670 					{
   671 						bOk = TRUE;
   672 						break;
   673 					}
   674 				}
   675 				if (!bOk) nRow--;
   676 			}
   677 		}
   678 	}
   679 	m_nNextPattern = nPattern;
   680 	m_nNextRow = nRow;
   681 	m_nTickCount = m_nMusicSpeed;
   682 	m_nBufferCount = 0;
   683 	m_nPatternDelay = 0;
   684 	m_nFrameDelay = 0;
   685 }
   686 
   687 
   688 void CSoundFile::SetCurrentOrder(UINT nPos)
   689 //-----------------------------------------
   690 {
   691 	while ((nPos < MAX_ORDERS) && (Order[nPos] == 0xFE)) nPos++;
   692 	if ((nPos >= MAX_ORDERS) || (Order[nPos] >= MAX_PATTERNS)) return;
   693 	for (UINT j=0; j<MAX_CHANNELS; j++)
   694 	{
   695 		Chn[j].nPeriod = 0;
   696 		Chn[j].nNote = 0;
   697 		Chn[j].nPortamentoDest = 0;
   698 		Chn[j].nCommand = 0;
   699 		Chn[j].nPatternLoopCount = 0;
   700 		Chn[j].nPatternLoop = 0;
   701 		Chn[j].nTremorCount = 0;
   702 	}
   703 	if (!nPos)
   704 	{
   705 		SetCurrentPos(0);
   706 	} else
   707 	{
   708 		m_nNextPattern = nPos;
   709 		m_nRow = m_nNextRow = 0;
   710 		m_nPattern = 0;
   711 		m_nTickCount = m_nMusicSpeed;
   712 		m_nBufferCount = 0;
   713 		m_nTotalCount = 0;
   714 		m_nPatternDelay = 0;
   715 		m_nFrameDelay = 0;
   716 	}
   717 	m_dwSongFlags &= ~(SONG_PATTERNLOOP|SONG_CPUVERYHIGH|SONG_FADINGSONG|SONG_ENDREACHED|SONG_GLOBALFADE);
   718 }
   719 
   720 
   721 void CSoundFile::ResetChannels()
   722 //------------------------------
   723 {
   724 	m_dwSongFlags &= ~(SONG_CPUVERYHIGH|SONG_FADINGSONG|SONG_ENDREACHED|SONG_GLOBALFADE);
   725 	m_nBufferCount = 0;
   726 	for (UINT i=0; i<MAX_CHANNELS; i++)
   727 	{
   728 		Chn[i].nROfs = Chn[i].nLOfs = 0;
   729 	}
   730 }
   731 
   732 
   733 void CSoundFile::LoopPattern(int nPat, int nRow)
   734 //----------------------------------------------
   735 {
   736 	if ((nPat < 0) || (nPat >= MAX_PATTERNS) || (!Patterns[nPat]))
   737 	{
   738 		m_dwSongFlags &= ~SONG_PATTERNLOOP;
   739 	} else
   740 	{
   741 		if ((nRow < 0) || (nRow >= PatternSize[nPat])) nRow = 0;
   742 		m_nPattern = nPat;
   743 		m_nRow = m_nNextRow = nRow;
   744 		m_nTickCount = m_nMusicSpeed;
   745 		m_nPatternDelay = 0;
   746 		m_nFrameDelay = 0;
   747 		m_nBufferCount = 0;
   748 		m_dwSongFlags |= SONG_PATTERNLOOP;
   749 	}
   750 }
   751 
   752 
   753 UINT CSoundFile::GetBestSaveFormat() const
   754 //----------------------------------------
   755 {
   756 	if ((!m_nSamples) || (!m_nChannels)) return MOD_TYPE_NONE;
   757 	if (!m_nType) return MOD_TYPE_NONE;
   758 	if (m_nType & (MOD_TYPE_MOD|MOD_TYPE_OKT))
   759 		return MOD_TYPE_MOD;
   760 	if (m_nType & (MOD_TYPE_S3M|MOD_TYPE_STM|MOD_TYPE_ULT|MOD_TYPE_FAR|MOD_TYPE_PTM))
   761 		return MOD_TYPE_S3M;
   762 	if (m_nType & (MOD_TYPE_XM|MOD_TYPE_MED|MOD_TYPE_MTM|MOD_TYPE_MT2))
   763 		return MOD_TYPE_XM;
   764 	return MOD_TYPE_IT;
   765 }
   766 
   767 
   768 UINT CSoundFile::GetSaveFormats() const
   769 //-------------------------------------
   770 {
   771 	UINT n = 0;
   772 	if ((!m_nSamples) || (!m_nChannels) || (m_nType == MOD_TYPE_NONE)) return 0;
   773 	switch(m_nType)
   774 	{
   775 	case MOD_TYPE_MOD:	n = MOD_TYPE_MOD;
   776 	case MOD_TYPE_S3M:	n = MOD_TYPE_S3M;
   777 	}
   778 	n |= MOD_TYPE_XM | MOD_TYPE_IT;
   779 	if (!m_nInstruments)
   780 	{
   781 		if (m_nSamples < 32) n |= MOD_TYPE_MOD;
   782 		n |= MOD_TYPE_S3M;
   783 	}
   784 	return n;
   785 }
   786 
   787 
   788 UINT CSoundFile::GetSampleName(UINT nSample,LPSTR s) const
   789 //--------------------------------------------------------
   790 {
   791         char sztmp[40] = "";      // changed from CHAR
   792 	memcpy(sztmp, m_szNames[nSample],32);
   793 	sztmp[31] = 0;
   794 	if (s) strcpy(s, sztmp);
   795 	return strlen(sztmp);
   796 }
   797 
   798 
   799 UINT CSoundFile::GetInstrumentName(UINT nInstr,LPSTR s) const
   800 //-----------------------------------------------------------
   801 {
   802         char sztmp[40] = "";  // changed from CHAR
   803 	if ((nInstr >= MAX_INSTRUMENTS) || (!Headers[nInstr]))
   804 	{
   805 		if (s) *s = 0;
   806 		return 0;
   807 	}
   808 	INSTRUMENTHEADER *penv = Headers[nInstr];
   809 	memcpy(sztmp, penv->name, 32);
   810 	sztmp[31] = 0;
   811 	if (s) strcpy(s, sztmp);
   812 	return strlen(sztmp);
   813 }
   814 
   815 
   816 #ifndef NO_PACKING
   817 UINT CSoundFile::PackSample(int &sample, int next)
   818 //------------------------------------------------
   819 {
   820 	UINT i = 0;
   821 	int delta = next - sample;
   822 	if (delta >= 0)
   823 	{
   824 		for (i=0; i<7; i++) if (delta <= (int)CompressionTable[i+1]) break;
   825 	} else
   826 	{
   827 		for (i=8; i<15; i++) if (delta >= (int)CompressionTable[i+1]) break;
   828 	}
   829 	sample += (int)CompressionTable[i];
   830 	return i;
   831 }
   832 
   833 
   834 BOOL CSoundFile::CanPackSample(LPSTR pSample, UINT nLen, UINT nPacking, BYTE *result)
   835 //-----------------------------------------------------------------------------------
   836 {
   837 	int pos, old, oldpos, besttable = 0;
   838 	DWORD dwErr, dwTotal, dwResult;
   839 	int i,j;
   840 
   841 	if (result) *result = 0;
   842 	if ((!pSample) || (nLen < 1024)) return FALSE;
   843 	// Try packing with different tables
   844 	dwResult = 0;
   845 	for (j=1; j<MAX_PACK_TABLES; j++)
   846 	{
   847 		memcpy(CompressionTable, UnpackTable[j], 16);
   848 		dwErr = 0;
   849 		dwTotal = 1;
   850 		old = pos = oldpos = 0;
   851 		for (i=0; i<(int)nLen; i++)
   852 		{
   853 			int s = (int)pSample[i];
   854 			PackSample(pos, s);
   855 			dwErr += abs(pos - oldpos);
   856 			dwTotal += abs(s - old);
   857 			old = s;
   858 			oldpos = pos;
   859 		}
   860 		dwErr = _muldiv(dwErr, 100, dwTotal);
   861 		if (dwErr >= dwResult)
   862 		{
   863 			dwResult = dwErr;
   864 			besttable = j;
   865 		}
   866 	}
   867 	memcpy(CompressionTable, UnpackTable[besttable], 16);
   868 	if (result)
   869 	{
   870 		if (dwResult > 100) *result	= 100; else *result = (BYTE)dwResult;
   871 	}
   872 	return (dwResult >= nPacking) ? TRUE : FALSE;
   873 }
   874 #endif // NO_PACKING
   875 
   876 #ifndef MODPLUG_NO_FILESAVE
   877 
   878 UINT CSoundFile::WriteSample(FILE *f, MODINSTRUMENT *pins, UINT nFlags, UINT nMaxLen)
   879 //-----------------------------------------------------------------------------------
   880 {
   881 	UINT len = 0, bufcount;
   882 	signed char buffer[4096];
   883 	signed char *pSample = (signed char *)pins->pSample;
   884 	UINT nLen = pins->nLength;
   885 
   886 	if ((nMaxLen) && (nLen > nMaxLen)) nLen = nMaxLen;
   887 	if ((!pSample) || (f == NULL) || (!nLen)) return 0;
   888 	switch(nFlags)
   889 	{
   890 #ifndef NO_PACKING
   891 	// 3: 4-bit ADPCM data
   892 	case RS_ADPCM4:
   893 		{
   894 			int pos;
   895 			len = (nLen + 1) / 2;
   896 			fwrite(CompressionTable, 16, 1, f);
   897 			bufcount = 0;
   898 			pos = 0;
   899 			for (UINT j=0; j<len; j++)
   900 			{
   901 				BYTE b;
   902 				// Sample #1
   903 				b = PackSample(pos, (int)pSample[j*2]);
   904 				// Sample #2
   905 				b |= PackSample(pos, (int)pSample[j*2+1]) << 4;
   906 				buffer[bufcount++] = (signed char)b;
   907 				if (bufcount >= sizeof(buffer))
   908 				{
   909 					fwrite(buffer, 1, bufcount, f);
   910 					bufcount = 0;
   911 				}
   912 			}
   913 			if (bufcount) fwrite(buffer, 1, bufcount, f);
   914 			len += 16;
   915 		}
   916 		break;
   917 #endif // NO_PACKING
   918 
   919 	// 16-bit samples
   920 	case RS_PCM16U:
   921 	case RS_PCM16D:
   922 	case RS_PCM16S:
   923 		{
   924 			int16_t *p = (int16_t *)pSample;
   925 			int s_old = 0, s_ofs;
   926 			len = nLen * 2;
   927 			bufcount = 0;
   928 			s_ofs = (nFlags == RS_PCM16U) ? 0x8000 : 0;
   929 			for (UINT j=0; j<nLen; j++)
   930 			{
   931 				int s_new = *p;
   932 				p++;
   933 				if (pins->uFlags & CHN_STEREO)
   934 				{
   935 					s_new = (s_new + (*p) + 1) >> 1;
   936 					p++;
   937 				}
   938 				if (nFlags == RS_PCM16D)
   939 				{
   940 					int16_t temp = bswapLE16((int16_t)(s_new - s_old));
   941 					*((int16_t*)(&buffer[bufcount])) = temp;
   942 					s_old = s_new;
   943 				} else
   944 				{
   945 					int16_t temp = bswapLE16((int16_t)(s_new + s_ofs));
   946 					*((int16_t *)(&buffer[bufcount])) = temp;
   947 				}
   948 				bufcount += 2;
   949 				if (bufcount >= sizeof(buffer) - 1)
   950 				{
   951 					fwrite(buffer, 1, bufcount, f);
   952 					bufcount = 0;
   953 				}
   954 			}
   955 			if (bufcount) fwrite(buffer, 1, bufcount, f);
   956 		}
   957 		break;
   958 
   959 
   960 	// 8-bit Stereo samples (not interleaved)
   961 	case RS_STPCM8S:
   962 	case RS_STPCM8U:
   963 	case RS_STPCM8D:
   964 		{
   965 			int s_ofs = (nFlags == RS_STPCM8U) ? 0x80 : 0;
   966 			for (UINT iCh=0; iCh<2; iCh++)
   967 			{
   968 				signed char *p = pSample + iCh;
   969 				int s_old = 0;
   970 
   971 				bufcount = 0;
   972 				for (UINT j=0; j<nLen; j++)
   973 				{
   974 					int s_new = *p;
   975 					p += 2;
   976 					if (nFlags == RS_STPCM8D)
   977 					{
   978 						buffer[bufcount++] = (signed char)(s_new - s_old);
   979 						s_old = s_new;
   980 					} else
   981 					{
   982 						buffer[bufcount++] = (signed char)(s_new + s_ofs);
   983 					}
   984 					if (bufcount >= sizeof(buffer))
   985 					{
   986 						fwrite(buffer, 1, bufcount, f);
   987 						bufcount = 0;
   988 					}
   989 				}
   990 				if (bufcount) fwrite(buffer, 1, bufcount, f);
   991 			}
   992 		}
   993 		len = nLen * 2;
   994 		break;
   995 
   996 	// 16-bit Stereo samples (not interleaved)
   997 	case RS_STPCM16S:
   998 	case RS_STPCM16U:
   999 	case RS_STPCM16D:
  1000 		{
  1001 			int s_ofs = (nFlags == RS_STPCM16U) ? 0x8000 : 0;
  1002 			for (UINT iCh=0; iCh<2; iCh++)
  1003 			{
  1004 				int16_t *p = ((int16_t *)pSample) + iCh;
  1005 				int s_old = 0;
  1006 
  1007 				bufcount = 0;
  1008 				for (UINT j=0; j<nLen; j++)
  1009 				{
  1010 					int s_new = *p;
  1011 					p += 2;
  1012 					if (nFlags == RS_STPCM16D)
  1013 					{
  1014 						int16_t temp = bswapLE16((int16_t)(s_new - s_old));
  1015 						*((int16_t *)(&buffer[bufcount])) = temp;
  1016 						s_old = s_new;
  1017 					} else
  1018 					{
  1019 						int16_t temp = bswapLE16((int16_t)(s_new - s_ofs));
  1020 						*((int16_t*)(&buffer[bufcount])) = temp;
  1021 					}
  1022 					bufcount += 2;
  1023 					if (bufcount >= sizeof(buffer))
  1024 					{
  1025 						fwrite(buffer, 1, bufcount, f);
  1026 						bufcount = 0;
  1027 					}
  1028 				}
  1029 				if (bufcount) fwrite(buffer, 1, bufcount, f);
  1030 			}
  1031 		}
  1032 		len = nLen*4;
  1033 		break;
  1034 
  1035 	//	Stereo signed interleaved
  1036 	case RS_STIPCM8S:
  1037 	case RS_STIPCM16S:
  1038 		len = nLen * 2;
  1039 		if (nFlags == RS_STIPCM16S) len *= 2;
  1040 		fwrite(pSample, 1, len, f);
  1041 		break;
  1042 
  1043 	// Default: assume 8-bit PCM data
  1044 	default:
  1045 		len = nLen;
  1046 		bufcount = 0;
  1047 		{
  1048 			signed char *p = pSample;
  1049 			int sinc = (pins->uFlags & CHN_16BIT) ? 2 : 1;
  1050 			int s_old = 0, s_ofs = (nFlags == RS_PCM8U) ? 0x80 : 0;
  1051 			if (pins->uFlags & CHN_16BIT) p++;
  1052 			for (UINT j=0; j<len; j++)
  1053 			{
  1054 				int s_new = (signed char)(*p);
  1055 				p += sinc;
  1056 				if (pins->uFlags & CHN_STEREO)
  1057 				{
  1058 					s_new = (s_new + ((int)*p) + 1) >> 1;
  1059 					p += sinc;
  1060 				}
  1061 				if (nFlags == RS_PCM8D)
  1062 				{
  1063 					buffer[bufcount++] = (signed char)(s_new - s_old);
  1064 					s_old = s_new;
  1065 				} else
  1066 				{
  1067 					buffer[bufcount++] = (signed char)(s_new + s_ofs);
  1068 				}
  1069 				if (bufcount >= sizeof(buffer))
  1070 				{
  1071 					fwrite(buffer, 1, bufcount, f);
  1072 					bufcount = 0;
  1073 				}
  1074 			}
  1075 			if (bufcount) fwrite(buffer, 1, bufcount, f);
  1076 		}
  1077 	}
  1078 	return len;
  1079 }
  1080 
  1081 #endif // MODPLUG_NO_FILESAVE
  1082 
  1083 
  1084 // Flags:
  1085 //	0 = signed 8-bit PCM data (default)
  1086 //	1 = unsigned 8-bit PCM data
  1087 //	2 = 8-bit ADPCM data with linear table
  1088 //	3 = 4-bit ADPCM data
  1089 //	4 = 16-bit ADPCM data with linear table
  1090 //	5 = signed 16-bit PCM data
  1091 //	6 = unsigned 16-bit PCM data
  1092 
  1093 
  1094 UINT CSoundFile::ReadSample(MODINSTRUMENT *pIns, UINT nFlags, LPCSTR lpMemFile, DWORD dwMemLength)
  1095 //------------------------------------------------------------------------------
  1096 {
  1097 	UINT len = 0, mem = pIns->nLength+6;
  1098 
  1099 	// Disable >2Gb samples,(preventing buffer overflow in AllocateSample)
  1100 	if ((!pIns) || ((int)pIns->nLength < 4) || (!lpMemFile)) return 0;
  1101 	if (pIns->nLength > MAX_SAMPLE_LENGTH) pIns->nLength = MAX_SAMPLE_LENGTH;
  1102 	pIns->uFlags &= ~(CHN_16BIT|CHN_STEREO);
  1103 	if (nFlags & RSF_16BIT)
  1104 	{
  1105 		mem *= 2;
  1106 		pIns->uFlags |= CHN_16BIT;
  1107 	}
  1108 	if (nFlags & RSF_STEREO)
  1109 	{
  1110 		mem *= 2;
  1111 		pIns->uFlags |= CHN_STEREO;
  1112 	}
  1113 	if ((pIns->pSample = AllocateSample(mem)) == NULL)
  1114 	{
  1115 		pIns->nLength = 0;
  1116 		return 0;
  1117 	}
  1118 	switch(nFlags)
  1119 	{
  1120 	// 1: 8-bit unsigned PCM data
  1121 	case RS_PCM8U:
  1122 		{
  1123 			len = pIns->nLength;
  1124 			if (len > dwMemLength) len = pIns->nLength = dwMemLength;
  1125 			signed char *pSample = pIns->pSample;
  1126 			for (UINT j=0; j<len; j++) pSample[j] = (signed char)(lpMemFile[j] - 0x80);
  1127 		}
  1128 		break;
  1129 
  1130 	// 2: 8-bit ADPCM data with linear table
  1131 	case RS_PCM8D:
  1132 		{
  1133 			len = pIns->nLength;
  1134 			if (len > dwMemLength) break;
  1135 			signed char *pSample = pIns->pSample;
  1136 			const signed char *p = (const signed char *)lpMemFile;
  1137 			int delta = 0;
  1138 
  1139 			for (UINT j=0; j<len; j++)
  1140 			{
  1141 				delta += p[j];
  1142 				*pSample++ = (signed char)delta;
  1143 			}
  1144 		}
  1145 		break;
  1146 
  1147 	// 3: 4-bit ADPCM data
  1148 	case RS_ADPCM4:
  1149 		{
  1150 			len = (pIns->nLength + 1) / 2;
  1151 			if (len > dwMemLength - 16) break;
  1152 			memcpy(CompressionTable, lpMemFile, 16);
  1153 			lpMemFile += 16;
  1154 			signed char *pSample = pIns->pSample;
  1155 			signed char delta = 0;
  1156 			for (UINT j=0; j<len; j++)
  1157 			{
  1158 				BYTE b0 = (BYTE)lpMemFile[j];
  1159 				BYTE b1 = (BYTE)(lpMemFile[j] >> 4);
  1160 				delta = (signed char)GetDeltaValue((int)delta, b0);
  1161 				pSample[0] = delta;
  1162 				delta = (signed char)GetDeltaValue((int)delta, b1);
  1163 				pSample[1] = delta;
  1164 				pSample += 2;
  1165 			}
  1166 			len += 16;
  1167 		}
  1168 		break;
  1169 
  1170 	// 4: 16-bit ADPCM data with linear table
  1171 	case RS_PCM16D:
  1172 		{
  1173 			len = pIns->nLength * 2;
  1174 			if (len > dwMemLength) break;
  1175 			int16_t *pSample = (int16_t *)pIns->pSample;
  1176 			int16_t *p = (int16_t *)lpMemFile;
  1177 			int delta16 = 0;
  1178 			for (UINT j=0; j<len; j+=2)
  1179 			{
  1180 				delta16 += bswapLE16(*p++);
  1181 				*pSample++ = (int16_t )delta16;
  1182 			}
  1183 		}
  1184 		break;
  1185 
  1186 	// 5: 16-bit signed PCM data
  1187 	case RS_PCM16S:
  1188 	        {
  1189 		len = pIns->nLength * 2;
  1190 		if (len <= dwMemLength) memcpy(pIns->pSample, lpMemFile, len);
  1191 			int16_t *pSample = (int16_t *)pIns->pSample;
  1192 			for (UINT j=0; j<len; j+=2)
  1193 			{
  1194 				int16_t rawSample = *pSample;
  1195 			        *pSample++ = bswapLE16(rawSample);
  1196 			}
  1197 		}
  1198 		break;
  1199 
  1200 	// 16-bit signed mono PCM motorola byte order
  1201 	case RS_PCM16M:
  1202 		len = pIns->nLength * 2;
  1203 		if (len > dwMemLength) len = dwMemLength & ~1;
  1204 		if (len > 1)
  1205 		{
  1206 			signed char *pSample = (signed char *)pIns->pSample;
  1207 			signed char *pSrc = (signed char *)lpMemFile;
  1208 			for (UINT j=0; j<len; j+=2)
  1209 			{
  1210 			  	// pSample[j] = pSrc[j+1];
  1211 				// pSample[j+1] = pSrc[j];
  1212 			        *((uint16_t *)(pSample+j)) = bswapBE16(*((uint16_t *)(pSrc+j)));
  1213 			}
  1214 		}
  1215 		break;
  1216 
  1217 	// 6: 16-bit unsigned PCM data
  1218 	case RS_PCM16U:
  1219 		{
  1220 			len = pIns->nLength * 2;
  1221 			if (len > dwMemLength) break;
  1222 			int16_t *pSample = (int16_t *)pIns->pSample;
  1223 			int16_t *pSrc = (int16_t *)lpMemFile;
  1224 			for (UINT j=0; j<len; j+=2) *pSample++ = bswapLE16(*(pSrc++)) - 0x8000;
  1225 		}
  1226 		break;
  1227 
  1228 	// 16-bit signed stereo big endian
  1229 	case RS_STPCM16M:
  1230 		len = pIns->nLength * 2;
  1231 		if (len*2 <= dwMemLength)
  1232 		{
  1233 			signed char *pSample = (signed char *)pIns->pSample;
  1234 			signed char *pSrc = (signed char *)lpMemFile;
  1235 			for (UINT j=0; j<len; j+=2)
  1236 			{
  1237 			        // pSample[j*2] = pSrc[j+1];
  1238 				// pSample[j*2+1] = pSrc[j];
  1239 				// pSample[j*2+2] = pSrc[j+1+len];
  1240 				// pSample[j*2+3] = pSrc[j+len];
  1241 			        *((uint16_t *)(pSample+j*2)) = bswapBE16(*((uint16_t *)(pSrc+j)));
  1242 				*((uint16_t *)(pSample+j*2+2)) = bswapBE16(*((uint16_t *)(pSrc+j+len)));
  1243 			}
  1244 			len *= 2;
  1245 		}
  1246 		break;
  1247 
  1248 	// 8-bit stereo samples
  1249 	case RS_STPCM8S:
  1250 	case RS_STPCM8U:
  1251 	case RS_STPCM8D:
  1252 		{
  1253 			int iadd_l = 0, iadd_r = 0;
  1254 			if (nFlags == RS_STPCM8U) { iadd_l = iadd_r = -128; }
  1255 			len = pIns->nLength;
  1256 			signed char *psrc = (signed char *)lpMemFile;
  1257 			signed char *pSample = (signed char *)pIns->pSample;
  1258 			if (len*2 > dwMemLength) break;
  1259 			for (UINT j=0; j<len; j++)
  1260 			{
  1261 				pSample[j*2] = (signed char)(psrc[0] + iadd_l);
  1262 				pSample[j*2+1] = (signed char)(psrc[len] + iadd_r);
  1263 				psrc++;
  1264 				if (nFlags == RS_STPCM8D)
  1265 				{
  1266 					iadd_l = pSample[j*2];
  1267 					iadd_r = pSample[j*2+1];
  1268 				}
  1269 			}
  1270 			len *= 2;
  1271 		}
  1272 		break;
  1273 
  1274 	// 16-bit stereo samples
  1275 	case RS_STPCM16S:
  1276 	case RS_STPCM16U:
  1277 	case RS_STPCM16D:
  1278 		{
  1279 			int iadd_l = 0, iadd_r = 0;
  1280 			if (nFlags == RS_STPCM16U) { iadd_l = iadd_r = -0x8000; }
  1281 			len = pIns->nLength;
  1282 			int16_t *psrc = (int16_t *)lpMemFile;
  1283 			int16_t *pSample = (int16_t *)pIns->pSample;
  1284 			if (len*4 > dwMemLength) break;
  1285 			for (UINT j=0; j<len; j++)
  1286 			{
  1287 				pSample[j*2] = (int16_t) (bswapLE16(psrc[0]) + iadd_l);
  1288 				pSample[j*2+1] = (int16_t) (bswapLE16(psrc[len]) + iadd_r);
  1289 				psrc++;
  1290 				if (nFlags == RS_STPCM16D)
  1291 				{
  1292 					iadd_l = pSample[j*2];
  1293 					iadd_r = pSample[j*2+1];
  1294 				}
  1295 			}
  1296 			len *= 4;
  1297 		}
  1298 		break;
  1299 
  1300 	// IT 2.14 compressed samples
  1301 	case RS_IT2148:
  1302 	case RS_IT21416:
  1303 	case RS_IT2158:
  1304 	case RS_IT21516:
  1305 		len = dwMemLength;
  1306 		if (len < 4) break;
  1307 		if ((nFlags == RS_IT2148) || (nFlags == RS_IT2158))
  1308 			ITUnpack8Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT2158));
  1309 		else
  1310 			ITUnpack16Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT21516));
  1311 		break;
  1312 
  1313 #ifndef MODPLUG_BASIC_SUPPORT
  1314 #ifndef MODPLUG_FASTSOUNDLIB
  1315 	// 8-bit interleaved stereo samples
  1316 	case RS_STIPCM8S:
  1317 	case RS_STIPCM8U:
  1318 		{
  1319 			int iadd = 0;
  1320 			if (nFlags == RS_STIPCM8U) { iadd = -0x80; }
  1321 			len = pIns->nLength;
  1322 			if (len*2 > dwMemLength) len = dwMemLength >> 1;
  1323 			LPBYTE psrc = (LPBYTE)lpMemFile;
  1324 			LPBYTE pSample = (LPBYTE)pIns->pSample;
  1325 			for (UINT j=0; j<len; j++)
  1326 			{
  1327 				pSample[j*2] = (signed char)(psrc[0] + iadd);
  1328 				pSample[j*2+1] = (signed char)(psrc[1] + iadd);
  1329 				psrc+=2;
  1330 			}
  1331 			len *= 2;
  1332 		}
  1333 		break;
  1334 
  1335 	// 16-bit interleaved stereo samples
  1336 	case RS_STIPCM16S:
  1337 	case RS_STIPCM16U:
  1338 		{
  1339 			int iadd = 0;
  1340 			if (nFlags == RS_STIPCM16U) iadd = -32768;
  1341 			len = pIns->nLength;
  1342 			if (len*4 > dwMemLength) len = dwMemLength >> 2;
  1343 			int16_t *psrc = (int16_t *)lpMemFile;
  1344 			int16_t *pSample = (int16_t *)pIns->pSample;
  1345 			for (UINT j=0; j<len; j++)
  1346 			{
  1347 				pSample[j*2] = (int16_t)(bswapLE16(psrc[0]) + iadd);
  1348 				pSample[j*2+1] = (int16_t)(bswapLE16(psrc[1]) + iadd);
  1349 				psrc += 2;
  1350 			}
  1351 			len *= 4;
  1352 		}
  1353 		break;
  1354 
  1355 	// AMS compressed samples
  1356 	case RS_AMS8:
  1357 	case RS_AMS16:
  1358 		len = 9;
  1359 		if (dwMemLength > 9)
  1360 		{
  1361 			const char *psrc = lpMemFile;
  1362 			char packcharacter = lpMemFile[8], *pdest = (char *)pIns->pSample;
  1363 			len += bswapLE32(*((LPDWORD)(lpMemFile+4)));
  1364 			if (len > dwMemLength) len = dwMemLength;
  1365 			UINT dmax = pIns->nLength;
  1366 			if (pIns->uFlags & CHN_16BIT) dmax <<= 1;
  1367 			AMSUnpack(psrc+9, len-9, pdest, dmax, packcharacter);
  1368 		}
  1369 		break;
  1370 
  1371 	// PTM 8bit delta to 16-bit sample
  1372 	case RS_PTM8DTO16:
  1373 		{
  1374 			len = pIns->nLength * 2;
  1375 			if (len > dwMemLength) break;
  1376 			int8_t *pSample = (int8_t *)pIns->pSample;
  1377 			int8_t delta8 = 0;
  1378 			for (UINT j=0; j<len; j++)
  1379 			{
  1380 				delta8 += lpMemFile[j];
  1381 				*pSample++ = delta8;
  1382 			}
  1383 			uint16_t *pSampleW = (uint16_t *)pIns->pSample;
  1384 			for (UINT j=0; j<len; j+=2)   // swaparoni!
  1385 			{
  1386 				uint16_t rawSample = *pSampleW;
  1387 			        *pSampleW++ = bswapLE16(rawSample);
  1388 			}
  1389 		}
  1390 		break;
  1391 
  1392 	// Huffman MDL compressed samples
  1393 	case RS_MDL8:
  1394 	case RS_MDL16:
  1395 		len = dwMemLength;
  1396 		if (len >= 4)
  1397 		{
  1398 			LPBYTE pSample = (LPBYTE)pIns->pSample;
  1399 			LPBYTE ibuf = (LPBYTE)lpMemFile;
  1400 			DWORD bitbuf = bswapLE32(*((DWORD *)ibuf));
  1401 			UINT bitnum = 32;
  1402 			BYTE dlt = 0, lowbyte = 0;
  1403 			ibuf += 4;
  1404 			for (UINT j=0; j<pIns->nLength; j++)
  1405 			{
  1406 				BYTE hibyte;
  1407 				BYTE sign;
  1408 				if (nFlags == RS_MDL16) lowbyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 8);
  1409 				sign = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 1);
  1410 				if (MDLReadBits(bitbuf, bitnum, ibuf, 1))
  1411 				{
  1412 					hibyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 3);
  1413 				} else
  1414 				{
  1415 					hibyte = 8;
  1416 					while (!MDLReadBits(bitbuf, bitnum, ibuf, 1)) hibyte += 0x10;
  1417 					hibyte += MDLReadBits(bitbuf, bitnum, ibuf, 4);
  1418 				}
  1419 				if (sign) hibyte = ~hibyte;
  1420 				dlt += hibyte;
  1421 				if (nFlags != RS_MDL16)
  1422 					pSample[j] = dlt;
  1423 				else
  1424 				{
  1425 					pSample[j<<1] = lowbyte;
  1426 					pSample[(j<<1)+1] = dlt;
  1427 				}
  1428 			}
  1429 		}
  1430 		break;
  1431 
  1432 	case RS_DMF8:
  1433 	case RS_DMF16:
  1434 		len = dwMemLength;
  1435 		if (len >= 4)
  1436 		{
  1437 			UINT maxlen = pIns->nLength;
  1438 			if (pIns->uFlags & CHN_16BIT) maxlen <<= 1;
  1439 			LPBYTE ibuf = (LPBYTE)lpMemFile, ibufmax = (LPBYTE)(lpMemFile+dwMemLength);
  1440 			len = DMFUnpack((LPBYTE)pIns->pSample, ibuf, ibufmax, maxlen);
  1441 		}
  1442 		break;
  1443 
  1444 #ifdef MODPLUG_TRACKER
  1445 	// PCM 24-bit signed -> load sample, and normalize it to 16-bit
  1446 	case RS_PCM24S:
  1447 	case RS_PCM32S:
  1448 		len = pIns->nLength * 3;
  1449 		if (nFlags == RS_PCM32S) len += pIns->nLength;
  1450 		if (len > dwMemLength) break;
  1451 		if (len > 4*8)
  1452 		{
  1453 			UINT slsize = (nFlags == RS_PCM32S) ? 4 : 3;
  1454 			LPBYTE pSrc = (LPBYTE)lpMemFile;
  1455 			LONG max = 255;
  1456 			if (nFlags == RS_PCM32S) pSrc++;
  1457 			for (UINT j=0; j<len; j+=slsize)
  1458 			{
  1459 				LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8;
  1460 				l /= 256;
  1461 				if (l > max) max = l;
  1462 				if (-l > max) max = -l;
  1463 			}
  1464 			max = (max / 128) + 1;
  1465 			int16_t *pDest = (int16_t *)pIns->pSample;
  1466 			for (UINT k=0; k<len; k+=slsize)
  1467 			{
  1468 				LONG l = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8;
  1469 				*pDest++ = (uint16_t)(l / max);
  1470 			}
  1471 		}
  1472 		break;
  1473 
  1474 	// Stereo PCM 24-bit signed -> load sample, and normalize it to 16-bit
  1475 	case RS_STIPCM24S:
  1476 	case RS_STIPCM32S:
  1477 		len = pIns->nLength * 6;
  1478 		if (nFlags == RS_STIPCM32S) len += pIns->nLength * 2;
  1479 		if (len > dwMemLength) break;
  1480 		if (len > 8*8)
  1481 		{
  1482 			UINT slsize = (nFlags == RS_STIPCM32S) ? 4 : 3;
  1483 			LPBYTE pSrc = (LPBYTE)lpMemFile;
  1484 			LONG max = 255;
  1485 			if (nFlags == RS_STIPCM32S) pSrc++;
  1486 			for (UINT j=0; j<len; j+=slsize)
  1487 			{
  1488 				LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8;
  1489 				l /= 256;
  1490 				if (l > max) max = l;
  1491 				if (-l > max) max = -l;
  1492 			}
  1493 			max = (max / 128) + 1;
  1494 			int16_t *pDest = (int16_t *)pIns->pSample;
  1495 			for (UINT k=0; k<len; k+=slsize)
  1496 			{
  1497 				LONG lr = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8;
  1498 				k += slsize;
  1499 				LONG ll = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8;
  1500 				pDest[0] = (int16_t)ll;
  1501 				pDest[1] = (int16_t)lr;
  1502 				pDest += 2;
  1503 			}
  1504 		}
  1505 		break;
  1506 
  1507 	// 16-bit signed big endian interleaved stereo
  1508 	case RS_STIPCM16M:
  1509 		{
  1510 			len = pIns->nLength;
  1511 			if (len*4 > dwMemLength) len = dwMemLength >> 2;
  1512 			LPCBYTE psrc = (LPCBYTE)lpMemFile;
  1513 			int16_t *pSample = (int16_t *)pIns->pSample;
  1514 			for (UINT j=0; j<len; j++)
  1515 			{
  1516 				pSample[j*2] = (int16_t)(((UINT)psrc[0] << 8) | (psrc[1]));
  1517 				pSample[j*2+1] = (int16_t)(((UINT)psrc[2] << 8) | (psrc[3]));
  1518 				psrc += 4;
  1519 			}
  1520 			len *= 4;
  1521 		}
  1522 		break;
  1523 
  1524 #endif // MODPLUG_TRACKER
  1525 #endif // !MODPLUG_FASTSOUNDLIB
  1526 #endif // !MODPLUG_BASIC_SUPPORT
  1527 
  1528 	// Default: 8-bit signed PCM data
  1529 	default:
  1530 		len = pIns->nLength;
  1531 		if (len > dwMemLength) len = pIns->nLength = dwMemLength;
  1532 		memcpy(pIns->pSample, lpMemFile, len);
  1533 	}
  1534 	if (len > dwMemLength)
  1535 	{
  1536 		if (pIns->pSample)
  1537 		{
  1538 			pIns->nLength = 0;
  1539 			FreeSample(pIns->pSample);
  1540 			pIns->pSample = NULL;
  1541 		}
  1542 		return 0;
  1543 	}
  1544 	AdjustSampleLoop(pIns);
  1545 	return len;
  1546 }
  1547 
  1548 
  1549 void CSoundFile::AdjustSampleLoop(MODINSTRUMENT *pIns)
  1550 //----------------------------------------------------
  1551 {
  1552 	if (!pIns->pSample) return;
  1553 	if (pIns->nLength > MAX_SAMPLE_LENGTH) pIns->nLength = MAX_SAMPLE_LENGTH;
  1554 	if (pIns->nLoopEnd > pIns->nLength) pIns->nLoopEnd = pIns->nLength;
  1555 	if (pIns->nLoopStart > pIns->nLength+2) pIns->nLoopStart = pIns->nLength+2;
  1556 	if (pIns->nLoopStart+2 >= pIns->nLoopEnd)
  1557 	{
  1558 		pIns->nLoopStart = pIns->nLoopEnd = 0;
  1559 		pIns->uFlags &= ~CHN_LOOP;
  1560 	}
  1561 	UINT len = pIns->nLength;
  1562 	if (pIns->uFlags & CHN_16BIT)
  1563 	{
  1564 		int16_t *pSample = (int16_t *)pIns->pSample;
  1565 		// Adjust end of sample
  1566 		if (pIns->uFlags & CHN_STEREO)
  1567 		{
  1568 			pSample[len*2+6] = pSample[len*2+4] = pSample[len*2+2] = pSample[len*2] = 0;
  1569 			pSample[len*2+7] = pSample[len*2+5] = pSample[len*2+3] = pSample[len*2+1] = 0;
  1570 		} else
  1571 		{
  1572 			pSample[len+4] = pSample[len+3] = pSample[len+2] = pSample[len+1] = pSample[len] = 0;
  1573 		}
  1574 		if ((pIns->uFlags & (CHN_LOOP|CHN_PINGPONGLOOP|CHN_STEREO)) == CHN_LOOP)
  1575 		{
  1576 			// Fix bad loops
  1577 			if ((pIns->nLoopEnd+3 >= pIns->nLength) || (m_nType & MOD_TYPE_S3M))
  1578 			{
  1579 				pSample[pIns->nLoopEnd] = pSample[pIns->nLoopStart];
  1580 				pSample[pIns->nLoopEnd+1] = pSample[pIns->nLoopStart+1];
  1581 				pSample[pIns->nLoopEnd+2] = pSample[pIns->nLoopStart+2];
  1582 				pSample[pIns->nLoopEnd+3] = pSample[pIns->nLoopStart+3];
  1583 				pSample[pIns->nLoopEnd+4] = pSample[pIns->nLoopStart+4];
  1584 			}
  1585 		}
  1586 	} else
  1587 	{
  1588 		signed char *pSample = pIns->pSample;
  1589 #ifndef MODPLUG_FASTSOUNDLIB
  1590 		// Crappy samples (except chiptunes) ?
  1591 		if ((pIns->nLength > 0x100) && (m_nType & (MOD_TYPE_MOD|MOD_TYPE_S3M))
  1592 		 && (!(pIns->uFlags & CHN_STEREO)))
  1593 		{
  1594 			int smpend = pSample[pIns->nLength-1], smpfix = 0, kscan;
  1595 			for (kscan=pIns->nLength-1; kscan>0; kscan--)
  1596 			{
  1597 				smpfix = pSample[kscan-1];
  1598 				if (smpfix != smpend) break;
  1599 			}
  1600 			int delta = smpfix - smpend;
  1601 			if (((!(pIns->uFlags & CHN_LOOP)) || (kscan > (int)pIns->nLoopEnd))
  1602 			 && ((delta < -8) || (delta > 8)))
  1603 			{
  1604 				while (kscan<(int)pIns->nLength)
  1605 				{
  1606 					if (!(kscan & 7))
  1607 					{
  1608 						if (smpfix > 0) smpfix--;
  1609 						if (smpfix < 0) smpfix++;
  1610 					}
  1611 					pSample[kscan] = (signed char)smpfix;
  1612 					kscan++;
  1613 				}
  1614 			}
  1615 		}
  1616 #endif
  1617 		// Adjust end of sample
  1618 		if (pIns->uFlags & CHN_STEREO)
  1619 		{
  1620 			pSample[len*2+6] = pSample[len*2+4] = pSample[len*2+2] = pSample[len*2] = 0;
  1621 			pSample[len*2+7] = pSample[len*2+5] = pSample[len*2+3] = pSample[len*2+1] = 0;
  1622 
  1623 		} else
  1624 		{
  1625 			pSample[len+4] = pSample[len+3] = pSample[len+2] = pSample[len+1] = pSample[len] = 0;
  1626 		}
  1627 		if ((pIns->uFlags & (CHN_LOOP|CHN_PINGPONGLOOP|CHN_STEREO)) == CHN_LOOP)
  1628 		{
  1629 			if ((pIns->nLoopEnd+3 >= pIns->nLength) || (m_nType & (MOD_TYPE_MOD|MOD_TYPE_S3M)))
  1630 			{
  1631 				pSample[pIns->nLoopEnd] = pSample[pIns->nLoopStart];
  1632 				pSample[pIns->nLoopEnd+1] = pSample[pIns->nLoopStart+1];
  1633 				pSample[pIns->nLoopEnd+2] = pSample[pIns->nLoopStart+2];
  1634 				pSample[pIns->nLoopEnd+3] = pSample[pIns->nLoopStart+3];
  1635 				pSample[pIns->nLoopEnd+4] = pSample[pIns->nLoopStart+4];
  1636 			}
  1637 		}
  1638 	}
  1639 }
  1640 
  1641 
  1642 /////////////////////////////////////////////////////////////
  1643 // Transpose <-> Frequency conversions
  1644 
  1645 // returns 8363*2^((transp*128+ftune)/(12*128))
  1646 DWORD CSoundFile::TransposeToFrequency(int transp, int ftune)
  1647 //-----------------------------------------------------------
  1648 {
  1649 
  1650 #ifdef MSC_VER
  1651 	const float _fbase = 8363;
  1652 	const float _factor = 1.0f/(12.0f*128.0f);
  1653 	int result;
  1654 	DWORD freq;
  1655 
  1656 	transp = (transp << 7) + ftune;
  1657 	_asm {
  1658 	fild transp
  1659 	fld _factor
  1660 	fmulp st(1), st(0)
  1661 	fist result
  1662 	fisub result
  1663 	f2xm1
  1664 	fild result
  1665 	fld _fbase
  1666 	fscale
  1667 	fstp st(1)
  1668 	fmul st(1), st(0)
  1669 	faddp st(1), st(0)
  1670 	fistp freq
  1671 	}
  1672 	UINT derr = freq % 11025;
  1673 	if (derr <= 8) freq -= derr;
  1674 	if (derr >= 11015) freq += 11025-derr;
  1675 	derr = freq % 1000;
  1676 	if (derr <= 5) freq -= derr;
  1677 	if (derr >= 995) freq += 1000-derr;
  1678 	return freq;
  1679 #else
  1680 	//---GCCFIX:  Removed assembly.
  1681 	return (DWORD)(8363*pow(2, (double)(transp*128+ftune)/(1536)));
  1682 #endif
  1683 }
  1684 
  1685 
  1686 // returns 12*128*log2(freq/8363)
  1687 int CSoundFile::FrequencyToTranspose(DWORD freq)
  1688 //----------------------------------------------
  1689 {
  1690 
  1691 #ifdef MSC_VER
  1692 	const float _f1_8363 = 1.0f / 8363.0f;
  1693 	const float _factor = 128 * 12;
  1694 	LONG result;
  1695 
  1696 	if (!freq) return 0;
  1697 	_asm {
  1698 	fld _factor
  1699 	fild freq
  1700 	fld _f1_8363
  1701 	fmulp st(1), st(0)
  1702 	fyl2x
  1703 	fistp result
  1704 	}
  1705 	return result;
  1706 #else
  1707 	//---GCCFIX: Removed assembly.
  1708 	return int(1536*(log(freq/8363.0)/log(2.0)));
  1709 #endif
  1710 }
  1711 
  1712 
  1713 void CSoundFile::FrequencyToTranspose(MODINSTRUMENT *psmp)
  1714 //--------------------------------------------------------
  1715 {
  1716 	int f2t = FrequencyToTranspose(psmp->nC4Speed);
  1717 	int transp = f2t >> 7;
  1718 	int ftune = f2t & 0x7F;
  1719 	if (ftune > 80)
  1720 	{
  1721 		transp++;
  1722 		ftune -= 128;
  1723 	}
  1724 	if (transp > 127) transp = 127;
  1725 	if (transp < -127) transp = -127;
  1726 	psmp->RelativeTone = transp;
  1727 	psmp->nFineTune = ftune;
  1728 }
  1729 
  1730 
  1731 void CSoundFile::CheckCPUUsage(UINT nCPU)
  1732 //---------------------------------------
  1733 {
  1734 	if (nCPU > 100) nCPU = 100;
  1735 	gnCPUUsage = nCPU;
  1736 	if (nCPU < 90)
  1737 	{
  1738 		m_dwSongFlags &= ~SONG_CPUVERYHIGH;
  1739 	} else
  1740 	if ((m_dwSongFlags & SONG_CPUVERYHIGH) && (nCPU >= 94))
  1741 	{
  1742 		UINT i=MAX_CHANNELS;
  1743 		while (i >= 8)
  1744 		{
  1745 			i--;
  1746 			if (Chn[i].nLength)
  1747 			{
  1748 				Chn[i].nLength = Chn[i].nPos = 0;
  1749 				nCPU -= 2;
  1750 				if (nCPU < 94) break;
  1751 			}
  1752 		}
  1753 	} else
  1754 	if (nCPU > 90)
  1755 	{
  1756 		m_dwSongFlags |= SONG_CPUVERYHIGH;
  1757 	}
  1758 }
  1759 
  1760 
  1761 BOOL CSoundFile::SetPatternName(UINT nPat, LPCSTR lpszName)
  1762 //---------------------------------------------------------
  1763 {
  1764         char szName[MAX_PATTERNNAME] = "";   // changed from CHAR
  1765 	if (nPat >= MAX_PATTERNS) return FALSE;
  1766 	if (lpszName) lstrcpyn(szName, lpszName, MAX_PATTERNNAME);
  1767 	szName[MAX_PATTERNNAME-1] = 0;
  1768 	if (!m_lpszPatternNames) m_nPatternNames = 0;
  1769 	if (nPat >= m_nPatternNames)
  1770 	{
  1771 		if (!lpszName[0]) return TRUE;
  1772 		UINT len = (nPat+1)*MAX_PATTERNNAME;
  1773 		char *p = new char[len];   // changed from CHAR
  1774 		if (!p) return FALSE;
  1775 		memset(p, 0, len);
  1776 		if (m_lpszPatternNames)
  1777 		{
  1778 			memcpy(p, m_lpszPatternNames, m_nPatternNames * MAX_PATTERNNAME);
  1779 			delete [] m_lpszPatternNames;
  1780 			m_lpszPatternNames = NULL;
  1781 		}
  1782 		m_lpszPatternNames = p;
  1783 		m_nPatternNames = nPat + 1;
  1784 	}
  1785 	memcpy(m_lpszPatternNames + nPat * MAX_PATTERNNAME, szName, MAX_PATTERNNAME);
  1786 	return TRUE;
  1787 }
  1788 
  1789 
  1790 BOOL CSoundFile::GetPatternName(UINT nPat, LPSTR lpszName, UINT cbSize) const
  1791 //---------------------------------------------------------------------------
  1792 {
  1793 	if ((!lpszName) || (!cbSize)) return FALSE;
  1794 	lpszName[0] = 0;
  1795 	if (cbSize > MAX_PATTERNNAME) cbSize = MAX_PATTERNNAME;
  1796 	if ((m_lpszPatternNames) && (nPat < m_nPatternNames))
  1797 	{
  1798 		memcpy(lpszName, m_lpszPatternNames + nPat * MAX_PATTERNNAME, cbSize);
  1799 		lpszName[cbSize-1] = 0;
  1800 		return TRUE;
  1801 	}
  1802 	return FALSE;
  1803 }
  1804 
  1805 
  1806 #ifndef MODPLUG_FASTSOUNDLIB
  1807 
  1808 UINT CSoundFile::DetectUnusedSamples(BOOL *pbIns)
  1809 //-----------------------------------------------
  1810 {
  1811 	UINT nExt = 0;
  1812 
  1813 	if (!pbIns) return 0;
  1814 	if (m_nInstruments)
  1815 	{
  1816 		memset(pbIns, 0, MAX_SAMPLES * sizeof(BOOL));
  1817 		for (UINT ipat=0; ipat<MAX_PATTERNS; ipat++)
  1818 		{
  1819 			MODCOMMAND *p = Patterns[ipat];
  1820 			if (p)
  1821 			{
  1822 				UINT jmax = PatternSize[ipat] * m_nChannels;
  1823 				for (UINT j=0; j<jmax; j++, p++)
  1824 				{
  1825 					if ((p->note) && (p->note <= NOTE_MAX))
  1826 					{
  1827 						if ((p->instr) && (p->instr < MAX_INSTRUMENTS))
  1828 						{
  1829 							INSTRUMENTHEADER *penv = Headers[p->instr];
  1830 							if (penv)
  1831 							{
  1832 								UINT n = penv->Keyboard[p->note-1];
  1833 								if (n < MAX_SAMPLES) pbIns[n] = TRUE;
  1834 							}
  1835 						} else
  1836 						{
  1837 							for (UINT k=1; k<=m_nInstruments; k++)
  1838 							{
  1839 								INSTRUMENTHEADER *penv = Headers[k];
  1840 								if (penv)
  1841 								{
  1842 									UINT n = penv->Keyboard[p->note-1];
  1843 									if (n < MAX_SAMPLES) pbIns[n] = TRUE;
  1844 								}
  1845 							}
  1846 						}
  1847 					}
  1848 				}
  1849 			}
  1850 		}
  1851 		for (UINT ichk=1; ichk<=m_nSamples; ichk++)
  1852 		{
  1853 			if ((!pbIns[ichk]) && (Ins[ichk].pSample)) nExt++;
  1854 		}
  1855 	}
  1856 	return nExt;
  1857 }
  1858 
  1859 
  1860 BOOL CSoundFile::RemoveSelectedSamples(BOOL *pbIns)
  1861 //-------------------------------------------------
  1862 {
  1863 	if (!pbIns) return FALSE;
  1864 	for (UINT j=1; j<MAX_SAMPLES; j++)
  1865 	{
  1866 		if ((!pbIns[j]) && (Ins[j].pSample))
  1867 		{
  1868 			DestroySample(j);
  1869 			if ((j == m_nSamples) && (j > 1)) m_nSamples--;
  1870 		}
  1871 	}
  1872 	return TRUE;
  1873 }
  1874 
  1875 
  1876 BOOL CSoundFile::DestroySample(UINT nSample)
  1877 //------------------------------------------
  1878 {
  1879 	if ((!nSample) || (nSample >= MAX_SAMPLES)) return FALSE;
  1880 	if (!Ins[nSample].pSample) return TRUE;
  1881 	MODINSTRUMENT *pins = &Ins[nSample];
  1882 	signed char *pSample = pins->pSample;
  1883 	pins->pSample = NULL;
  1884 	pins->nLength = 0;
  1885 	pins->uFlags &= ~(CHN_16BIT);
  1886 	for (UINT i=0; i<MAX_CHANNELS; i++)
  1887 	{
  1888 		if (Chn[i].pSample == pSample)
  1889 		{
  1890 			Chn[i].nPos = Chn[i].nLength = 0;
  1891 			Chn[i].pSample = Chn[i].pCurrentSample = NULL;
  1892 		}
  1893 	}
  1894 	FreeSample(pSample);
  1895 	return TRUE;
  1896 }
  1897 
  1898 #endif // MODPLUG_FASTSOUNDLIB
  1899