ft2-clone

Fasttracker 2 clone
Log | Files | Refs | README | LICENSE

ft2_load_it.c (35992B)


      1 /* (Lossy) Impulse Tracker module loader.
      2 **
      3 ** It makes little sense to convert this format to XM, as it results
      4 ** in severe conversion losses. The reason I wrote this loader anyway,
      5 ** is so that you can import IT files to extract samples, pattern data
      6 ** and so on.
      7 **
      8 ** Note: Data sanitation is done in the last stage
      9 ** of module loading, so you don't need to do that here.
     10 */
     11 
     12 #include <stdio.h>
     13 #include <stdint.h>
     14 #include <stdbool.h>
     15 #include "../ft2_header.h"
     16 #include "../ft2_module_loader.h"
     17 #include "../ft2_sample_ed.h"
     18 #include "../ft2_sysreqs.h"
     19 
     20 #ifdef _MSC_VER
     21 #pragma pack(push)
     22 #pragma pack(1)
     23 #endif
     24 typedef struct itHdr_t
     25 {
     26 	char ID[4], songName[26];
     27 	uint16_t rowHighlight, ordNum, insNum, smpNum, patNum, cwtv, cmwt, flags, special;
     28 	uint8_t globalVol, mixingVol, speed, BPM, panSep, pitchWheelDepth;
     29 	uint16_t msgLen;
     30 	uint32_t msgOffs, reserved;
     31 	uint8_t initialPans[64], initialVols[64];
     32 }
     33 #ifdef __GNUC__
     34 __attribute__ ((packed))
     35 #endif
     36 itHdr_t;
     37 
     38 typedef struct envNode_t
     39 {
     40 	int8_t magnitude;
     41 	uint16_t tick;
     42 }
     43 #ifdef __GNUC__
     44 __attribute__ ((packed))
     45 #endif
     46 envNode_t;
     47 
     48 typedef struct env_t
     49 {
     50 	uint8_t flags, num, loopBegin, loopEnd, sustainLoopBegin, sustainLoopEnd;
     51 	envNode_t nodePoints[25];
     52 	uint8_t reserved;
     53 }
     54 #ifdef __GNUC__
     55 __attribute__ ((packed))
     56 #endif
     57 env_t;
     58 
     59 typedef struct itInsHdr_t
     60 {
     61 	char ID[4], dosFilename[12+1];
     62 	uint8_t NNA, DCT, DCA;
     63 	uint16_t fadeOut;
     64 	uint8_t pitchPanSep, pitchPanCenter, globVol, defPan, randVol, randPan;
     65 	uint16_t trackerVer;
     66 	uint8_t numSamples, res1;
     67 	char instrumentName[26];
     68 	uint8_t filterCutoff, filterResonance, midiChn, midiProg;
     69 	uint16_t midiBank;
     70 	uint16_t smpNoteTable[120];
     71 	env_t volEnv, panEnv, pitchEnv;
     72 }
     73 #ifdef __GNUC__
     74 __attribute__ ((packed))
     75 #endif
     76 itInsHdr_t;
     77 
     78 typedef struct itOldInsHdr_t
     79 {
     80 	char ID[4], dosFilename[12+1];
     81 	uint8_t volEnvFlags, volEnvLoopBegin, volEnvLoopEnd, volEnvSusLoopBegin, volEnvSusLoopEnd;
     82 	uint16_t res1, fadeOut;
     83 	uint8_t NNA, DNC;
     84 	uint16_t trackerVer;
     85 	uint8_t numSamples, res2;
     86 	char instrumentName[26];
     87 	uint8_t res3[6];
     88 	uint16_t smpNoteTable[120];
     89 	uint8_t volEnv[200];
     90 	uint16_t volEnvPoints[25];
     91 }
     92 #ifdef __GNUC__
     93 __attribute__ ((packed))
     94 #endif
     95 itOldInsHdr_t;
     96 
     97 typedef struct itSmpHdr_t
     98 {
     99 	char ID[4], dosFilename[12+1];
    100 	uint8_t globVol, flags, vol;
    101 	char sampleName[26];
    102 	uint8_t cvt, defPan;
    103 	uint32_t length, loopBegin, loopEnd, c5Speed, sustainLoopBegin, sustainLoopEnd, offsetInFile;
    104 	uint8_t autoVibratoSpeed, autoVibratoDepth, autoVibratoRate, autoVibratoWaveform;
    105 }
    106 #ifdef __GNUC__
    107 __attribute__ ((packed))
    108 #endif
    109 itSmpHdr_t;
    110 
    111 #ifdef _MSC_VER
    112 #pragma pack(pop)
    113 #endif
    114 
    115 static uint8_t decompBuffer[65536];
    116 static uint8_t volPortaConv[9] = { 1, 4, 8, 16, 32, 64, 96, 128, 255 };
    117 
    118 static bool loadCompressed16BitSample(FILE *f, sample_t *s, bool deltaEncoded);
    119 static bool loadCompressed8BitSample(FILE *f, sample_t *s, bool deltaEncoded);
    120 static void setAutoVibrato(instr_t *ins, itSmpHdr_t *itSmp);
    121 static bool loadSample(FILE *f, sample_t *s, itSmpHdr_t *itSmp);
    122 
    123 bool loadIT(FILE *f, uint32_t filesize)
    124 {
    125 	uint32_t insOffs[256], smpOffs[256], patOffs[256];
    126 	itSmpHdr_t *itSmp, smpHdrs[256];
    127 	itHdr_t itHdr;
    128 
    129 	if (filesize < sizeof (itHdr))
    130 	{
    131 		loaderMsgBox("This IT module is not supported or is corrupt!");
    132 		goto error;
    133 	}
    134 
    135 	fread(&itHdr, sizeof (itHdr), 1, f);
    136 
    137 	if (itHdr.ordNum > 257 || itHdr.insNum > 256 || itHdr.smpNum > 256 || itHdr.patNum > 256)
    138 	{
    139 		loaderMsgBox("This IT module is not supported or is corrupt!");
    140 		goto error;
    141 	}
    142 
    143 	tmpLinearPeriodsFlag = !!(itHdr.flags & 8);
    144 
    145 	songTmp.pattNum = itHdr.patNum;
    146 	songTmp.speed = itHdr.speed;
    147 	songTmp.BPM = itHdr.BPM;
    148 
    149 	memcpy(songTmp.name, itHdr.songName, 20);
    150 	songTmp.name[20] = '\0';
    151 
    152 	bool oldFormat = (itHdr.cmwt < 0x200);
    153 	bool songUsesInstruments = !!(itHdr.flags & 4);
    154 	bool oldEffects = !!(itHdr.flags & 16);
    155 	bool compatGxx = !!(itHdr.flags & 32);
    156 
    157 	// read order list
    158 	for (int32_t i = 0; i < MAX_ORDERS; i++)
    159 	{
    160 		const uint8_t patt = (uint8_t)fgetc(f);
    161 		if (patt == 254) // separator ("+++"), skip it
    162 			continue;
    163 
    164 		if (patt == 255) // end of pattern list
    165 			break;
    166 
    167 		songTmp.orders[songTmp.songLength] = patt;
    168 
    169 		songTmp.songLength++;
    170 		if (songTmp.songLength == MAX_ORDERS-1)
    171 			break;
    172 	}
    173 
    174 	// read file pointers
    175 	fseek(f, sizeof (itHdr) + itHdr.ordNum, SEEK_SET);
    176 	fread(insOffs, 4, itHdr.insNum, f);
    177 	fread(smpOffs, 4, itHdr.smpNum, f);
    178 	fread(patOffs, 4, itHdr.patNum, f);
    179 
    180 	for (int32_t i = 0; i < itHdr.smpNum; i++)
    181 	{
    182 		fseek(f, smpOffs[i], SEEK_SET);
    183 		fread(&smpHdrs[i], sizeof (itSmpHdr_t), 1, f);
    184 	}
    185 
    186 	if (!songUsesInstruments) // read samples (as instruments)
    187 	{
    188 		int32_t numIns = MIN(itHdr.smpNum, MAX_INST);
    189 
    190 		itSmp = smpHdrs;
    191 		for (int16_t i = 0; i < numIns; i++, itSmp++)
    192 		{
    193 			if (!allocateTmpInstr(1 + i))
    194 			{
    195 				loaderMsgBox("Not enough memory!");
    196 				return false;
    197 			}
    198 
    199 			instr_t *ins = instrTmp[1+i];
    200 			sample_t *s = &ins->smp[0];
    201 
    202 			memcpy(songTmp.instrName[1+i], itSmp->sampleName, 22);
    203 			songTmp.instrName[1+i][22] = '\0';
    204 
    205 			ins->numSamples = (itSmp->length > 0) ? 1 : 0;
    206 			if (ins->numSamples > 0)
    207 			{
    208 				setAutoVibrato(ins, itSmp);
    209 
    210 				if (!loadSample(f, s, itSmp))
    211 				{
    212 					loaderMsgBox("Not enough memory!");
    213 					goto error;
    214 				}
    215 			}
    216 		}
    217 	}
    218 	else if (oldFormat) // read instruments (old format version)
    219 	{
    220 		itOldInsHdr_t itIns;
    221 
    222 		int32_t numIns = MIN(itHdr.insNum, MAX_INST);
    223 		for (int16_t i = 0; i < numIns; i++)
    224 		{
    225 			fseek(f, insOffs[i], SEEK_SET);
    226 			fread(&itIns, sizeof (itIns), 1, f);
    227 
    228 			if (!allocateTmpInstr(1 + i))
    229 			{
    230 				loaderMsgBox("Not enough memory!");
    231 				return false;
    232 			}
    233 
    234 			instr_t *ins = instrTmp[1+i];
    235 
    236 			memcpy(songTmp.instrName[1+i], itIns.instrumentName, 22);
    237 			songTmp.instrName[1+i][22] = '\0';
    238 
    239 			ins->fadeout = itIns.fadeOut * 64; // 0..64 -> 0..4096
    240 			if (ins->fadeout > 4095)
    241 				ins->fadeout = 4095;
    242 
    243 			// find out what samples to load into this XM instrument header
    244 
    245 			int16_t numSamples = 0;
    246 			uint8_t sampleList[MAX_SMP_PER_INST];
    247 
    248 			bool sampleAdded[256];
    249 			memset(sampleList, 0, sizeof (sampleList));
    250 			memset(sampleAdded, 0, sizeof (sampleAdded));
    251 
    252 			for (int32_t j = 0; j < 96; j++)
    253 			{
    254 				uint8_t sample = itIns.smpNoteTable[12+j] >> 8;
    255 				if (sample > 0 && !sampleAdded[sample-1] && numSamples < MAX_SMP_PER_INST)
    256 				{
    257 					sampleAdded[sample-1] = true;
    258 					sampleList[numSamples] = sample-1;
    259 					numSamples++;
    260 				}
    261 			}
    262 
    263 			/* If instrument only has one sample, copy over the sample's
    264 			** auto-vibrato parameters to this instrument.
    265 			*/
    266 			bool singleSample = true;
    267 			if (numSamples > 1)
    268 			{
    269 				uint8_t firstSample = sampleList[0];
    270 				for (int32_t j = 1; j < numSamples; j++)
    271 				{
    272 					if (sampleList[j] != firstSample)
    273 					{
    274 						singleSample = false;
    275 						break;
    276 					}
    277 				}
    278 			}
    279 
    280 			if (singleSample)
    281 				setAutoVibrato(ins, &smpHdrs[sampleList[0]]);
    282 
    283 			// create new note-to-sample table
    284 			for (int32_t j = 0; j < 8*12; j++)
    285 			{
    286 				uint8_t inSmp = itIns.smpNoteTable[(1 * 12) + j] >> 8;
    287 
    288 				uint8_t outSmp = 0;
    289 				if (inSmp > 0)
    290 				{
    291 					inSmp--;
    292 					for (; outSmp < numSamples; outSmp++)
    293 					{
    294 						if (inSmp == sampleList[outSmp])
    295 							break;
    296 					}
    297 
    298 					if (outSmp >= numSamples)
    299 						outSmp = 0;
    300 				}
    301 
    302 				ins->note2SampleLUT[j] = outSmp;
    303 			}
    304 
    305 			// load volume envelope
    306 			if (itIns.volEnvFlags & 1)
    307 			{
    308 				bool volEnvLoopOn = !!(itIns.volEnvFlags & 2);
    309 				bool volEnvSusOn = !!(itIns.volEnvFlags & 4);
    310 
    311 				ins->volEnvFlags |= ENV_ENABLED;
    312 				if (volEnvLoopOn) ins->volEnvFlags |= ENV_LOOP;
    313 				if (volEnvSusOn) ins->volEnvFlags |= ENV_SUSTAIN;
    314 				
    315 				ins->volEnvLoopStart = MIN(itIns.volEnvLoopBegin, 11);
    316 				ins->volEnvLoopEnd = MIN(itIns.volEnvLoopEnd, 11);
    317 				ins->volEnvSustain = MIN(itIns.volEnvSusLoopEnd, 11);
    318 
    319 				// hack: if sus loop only, set as normal loop + set sustain point
    320 				if (!volEnvLoopOn && volEnvSusOn)
    321 				{
    322 					ins->volEnvLoopStart = MIN(itIns.volEnvSusLoopBegin, 11);
    323 					ins->volEnvLoopEnd = MIN(itIns.volEnvSusLoopEnd, 11);
    324 					ins->volEnvSustain = MIN(itIns.volEnvSusLoopEnd, 11);
    325 					ins->volEnvFlags |= ENV_LOOP + ENV_SUSTAIN;
    326 				}
    327 
    328 				int32_t j = 0;
    329 				for (; j < 12; j++)
    330 				{
    331 					if (itIns.volEnvPoints[j] >> 8 == 0xFF)
    332 						break; // end of volume envelope
    333 
    334 					ins->volEnvPoints[j][0] = itIns.volEnvPoints[j] & 0xFF;
    335 					ins->volEnvPoints[j][1] = itIns.volEnvPoints[j] >> 8;
    336 				}
    337 				ins->volEnvLength = (uint8_t)j;
    338 
    339 				// increase loop end point tick by one to better match IT style env looping
    340 				if (ins->volEnvFlags & ENV_LOOP)
    341 					ins->volEnvPoints[ins->volEnvLoopEnd][0]++;
    342 			}
    343 
    344 			ins->numSamples = numSamples;
    345 			if (ins->numSamples > 0)
    346 			{
    347 				sample_t *s = ins->smp;
    348 				for (int32_t j = 0; j < ins->numSamples; j++, s++)
    349 				{
    350 					if (!loadSample(f, s, &smpHdrs[sampleList[j]]))
    351 					{
    352 						loaderMsgBox("Not enough memory!");
    353 						goto error;
    354 					}
    355 				}
    356 			}
    357 		}
    358 	}
    359 	else // read instruments (later format version)
    360 	{
    361 		itInsHdr_t itIns;
    362 
    363 		int32_t numIns = MIN(itHdr.insNum, MAX_INST);
    364 		for (int16_t i = 0; i < numIns; i++)
    365 		{
    366 			fseek(f, insOffs[i], SEEK_SET);
    367 			fread(&itIns, sizeof (itIns), 1, f);
    368 
    369 			if (!allocateTmpInstr(1 + i))
    370 			{
    371 				loaderMsgBox("Not enough memory!");
    372 				return false;
    373 			}
    374 
    375 			instr_t *ins = instrTmp[1+i];
    376 
    377 			memcpy(songTmp.instrName[1+i], itIns.instrumentName, 22);
    378 			songTmp.instrName[1+i][22] = '\0';
    379 
    380 			ins->fadeout = itIns.fadeOut * 32; // 0..128 -> 0..4096
    381 			if (ins->fadeout > 4095)
    382 				ins->fadeout = 4095;
    383 
    384 			// find out what samples to load into this XM instrument header
    385 
    386 			int16_t numSamples = 0;
    387 			uint8_t sampleList[MAX_SMP_PER_INST];
    388 
    389 			bool sampleAdded[256];
    390 			memset(sampleList, 0, sizeof (sampleList));
    391 			memset(sampleAdded, 0, sizeof (sampleAdded));
    392 
    393 			for (int32_t j = 0; j < 96; j++)
    394 			{
    395 				uint8_t sample = itIns.smpNoteTable[12+j] >> 8;
    396 				if (sample > 0 && !sampleAdded[sample-1] && numSamples < MAX_SMP_PER_INST)
    397 				{
    398 					sampleAdded[sample-1] = true;
    399 					sampleList[numSamples] = sample-1;
    400 					numSamples++;
    401 				}
    402 			}
    403 
    404 			/* If instrument only has one sample, copy over the sample's
    405 			** auto-vibrato parameters to this instrument.
    406 			*/
    407 			bool singleSample = true;
    408 			if (numSamples > 1)
    409 			{
    410 				uint8_t firstSample = sampleList[0];
    411 				for (int32_t j = 1; j < numSamples; j++)
    412 				{
    413 					if (sampleList[j] != firstSample)
    414 					{
    415 						singleSample = false;
    416 						break;
    417 					}
    418 				}
    419 			}
    420 
    421 			if (singleSample)
    422 				setAutoVibrato(ins, &smpHdrs[sampleList[0]]);
    423 
    424 			// create new note-to-sample table
    425 			for (int32_t j = 0; j < 8*12; j++)
    426 			{
    427 				uint8_t inSmp = itIns.smpNoteTable[(1 * 12) + j] >> 8;
    428 
    429 				uint8_t outSmp = 0;
    430 				if (inSmp > 0)
    431 				{
    432 					inSmp--;
    433 					for (; outSmp < numSamples; outSmp++)
    434 					{
    435 						if (inSmp == sampleList[outSmp])
    436 							break;
    437 					}
    438 
    439 					if (outSmp >= numSamples)
    440 						outSmp = 0;
    441 				}
    442 
    443 				ins->note2SampleLUT[j] = outSmp;
    444 			}
    445 
    446 			// load volume envelope
    447 			env_t *volEnv = &itIns.volEnv;
    448 			bool volEnvEnabled = !!(volEnv->flags & 1);
    449 			if (volEnvEnabled && volEnv->num > 0)
    450 			{
    451 				bool volEnvLoopOn = !!(volEnv->flags & 2);
    452 				bool volEnvSusOn = !!(volEnv->flags & 4);
    453 
    454 				ins->volEnvFlags |= ENV_ENABLED;
    455 				if (volEnvLoopOn) ins->volEnvFlags |= ENV_LOOP;
    456 				if (volEnvSusOn) ins->volEnvFlags |= ENV_SUSTAIN;
    457 				
    458 				ins->volEnvLength = MIN(volEnv->num, 12);
    459 				ins->volEnvLoopStart = MIN(volEnv->loopBegin, 11);
    460 				ins->volEnvLoopEnd = MIN(volEnv->loopEnd, 11);
    461 				ins->volEnvSustain = MIN(volEnv->sustainLoopEnd, 11);
    462 
    463 				// hack: if sus loop only, set as normal loop + set sustain point
    464 				if (!volEnvLoopOn && volEnvSusOn)
    465 				{
    466 					ins->volEnvLoopStart = MIN(volEnv->sustainLoopBegin, 11);
    467 					ins->volEnvLoopEnd = MIN(volEnv->sustainLoopEnd, 11);
    468 					ins->volEnvSustain = MIN(volEnv->sustainLoopEnd, 11);
    469 					ins->volEnvFlags |= ENV_LOOP + ENV_SUSTAIN;
    470 				}
    471 
    472 				for (int32_t j = 0; j < ins->volEnvLength; j++)
    473 				{
    474 					ins->volEnvPoints[j][0] = volEnv->nodePoints[j].tick;
    475 					ins->volEnvPoints[j][1] = volEnv->nodePoints[j].magnitude;
    476 				}
    477 
    478 				// increase loop end point tick by one to better match IT style env looping
    479 				if (ins->volEnvFlags & ENV_LOOP)
    480 					ins->volEnvPoints[ins->volEnvLoopEnd][0]++;
    481 			}
    482 
    483 			// load pan envelope
    484 			env_t *panEnv = &itIns.panEnv;
    485 			bool panEnvEnabled = !!(panEnv->flags & 1);
    486 			if (panEnvEnabled && panEnv->num > 0)
    487 			{
    488 				bool panEnvLoopOn = !!(panEnv->flags & 2);
    489 				bool panEnvSusOn = !!(panEnv->flags & 4);
    490 
    491 				ins->panEnvFlags |= ENV_ENABLED;
    492 				if (panEnvLoopOn) ins->panEnvFlags |= ENV_LOOP;
    493 				if (panEnvSusOn) ins->panEnvFlags |= ENV_SUSTAIN;
    494 				
    495 				ins->panEnvLength = MIN(panEnv->num, 12);
    496 				ins->panEnvLoopStart = MIN(panEnv->loopBegin, 11);
    497 				ins->panEnvLoopEnd = MIN(panEnv->loopEnd, 11);
    498 				ins->panEnvSustain = MIN(panEnv->sustainLoopEnd, 11);
    499 
    500 				// hack: if sus loop only, set as normal loop + set sustain point
    501 				if (!panEnvLoopOn && panEnvSusOn)
    502 				{
    503 					ins->panEnvLoopStart = MIN(panEnv->sustainLoopBegin, 11);
    504 					ins->panEnvLoopEnd = MIN(panEnv->sustainLoopEnd, 11);
    505 					ins->panEnvSustain = MIN(panEnv->sustainLoopEnd, 11);
    506 					ins->panEnvFlags |= ENV_LOOP + ENV_SUSTAIN;
    507 				}
    508 
    509 				for (int32_t j = 0; j < ins->panEnvLength; j++)
    510 				{
    511 					ins->panEnvPoints[j][0] = panEnv->nodePoints[j].tick;
    512 					ins->panEnvPoints[j][1] = panEnv->nodePoints[j].magnitude + 32;
    513 				}
    514 
    515 				// increase loop end point tick by one to better match IT style env looping
    516 				if (ins->panEnvFlags & ENV_LOOP)
    517 					ins->panEnvPoints[ins->panEnvLoopEnd][0] = panEnv->nodePoints[ins->panEnvLoopEnd].tick + 1;
    518 			}
    519 
    520 			ins->numSamples = numSamples;
    521 			if (ins->numSamples > 0)
    522 			{
    523 				sample_t *s = ins->smp;
    524 				for (int32_t j = 0; j < ins->numSamples; j++, s++)
    525 				{
    526 					if (!loadSample(f, s, &smpHdrs[sampleList[j]]))
    527 					{
    528 						loaderMsgBox("Not enough memory!");
    529 						goto error;
    530 					}
    531 				}
    532 			}
    533 		}
    534 	}
    535 
    536 	// load pattern data
    537 
    538 	uint32_t numChannels = 0;
    539 	for (int32_t i = 0; i < songTmp.pattNum; i++)
    540 	{
    541 		if (patOffs[i] == 0)
    542 			continue;
    543 	
    544 		fseek(f, patOffs[i], SEEK_SET);
    545 
    546 		uint16_t length, numRows;
    547 		fread(&length, 2, 1, f);
    548 		fread(&numRows, 2, 1, f);
    549 		fseek(f, 4, SEEK_CUR);
    550 
    551 		numRows = MIN(numRows, MAX_PATT_LEN);
    552 		if (numRows == 0)
    553 			continue;
    554 
    555 		if (!allocateTmpPatt(i, numRows))
    556 		{
    557 			loaderMsgBox("Not enough memory!");
    558 			goto error;
    559 		}
    560 
    561 		uint8_t lastMask[64];
    562 		memset(lastMask, 0, sizeof (lastMask));
    563 
    564 		note_t lastNote[64];
    565 		memset(lastNote, 0, sizeof (lastNote));
    566 
    567 		note_t *patt = patternTmp[i];
    568 
    569 		int32_t bytesRead = 0;
    570 		int32_t row = 0;
    571 		while (bytesRead < length && row < numRows)
    572 		{
    573 			uint8_t byte = (uint8_t)fgetc(f);
    574 			bytesRead++;
    575 
    576 			if (byte == 0)
    577 			{
    578 				row++;
    579 				continue;
    580 			}
    581 
    582 			const uint8_t ch = (byte - 1) & 63;
    583 			if (ch > numChannels)
    584 				numChannels = ch;
    585 
    586 			note_t emptyNote;
    587 			note_t *p = (ch >= MAX_CHANNELS) ? &emptyNote : &patt[(row * MAX_CHANNELS) + ch];
    588 
    589 			if (byte & 128)
    590 			{
    591 				lastMask[ch] = (uint8_t)fgetc(f);
    592 				bytesRead++;
    593 			}
    594 
    595 			if (lastMask[ch] & 16)
    596 				p->note = lastNote[ch].note;
    597 
    598 			if (lastMask[ch] & 32)
    599 				p->instr = lastNote[ch].instr;
    600 
    601 			if (lastMask[ch] & 64)
    602 				p->vol = lastNote[ch].vol;
    603 
    604 			if (lastMask[ch] & 128)
    605 			{
    606 				p->efx = lastNote[ch].efx;
    607 				p->efxData = lastNote[ch].efxData;
    608 			}
    609 
    610 			if (lastMask[ch] & 1)
    611 			{
    612 				uint8_t note = (uint8_t)fgetc(f);
    613 				bytesRead++;
    614 
    615 				if (note < 120)
    616 				{
    617 					note++;
    618 					if (note < 12 || note >= 96+12)
    619 						note = 0;
    620 					else
    621 						note -= 12;
    622 				}
    623 				else if (note != 254)
    624 				{
    625 					note = NOTE_OFF;
    626 				}
    627 
    628 				if (note > NOTE_OFF && note != 254)
    629 					note = 0; // remove note
    630 
    631 				// 254 (note cut) is handled later!
    632 
    633 				p->note = lastNote[ch].note = note;
    634 			}
    635 
    636 			if (lastMask[ch] & 2)
    637 			{
    638 				uint8_t ins = (uint8_t)fgetc(f);
    639 				bytesRead++;
    640 
    641 				if (ins > MAX_INST)
    642 					ins = 0;
    643 
    644 				p->instr = lastNote[ch].instr = ins;
    645 			}
    646 
    647 			if (lastMask[ch] & 4)
    648 			{
    649 				p->vol = lastNote[ch].vol = 1 + (uint8_t)fgetc(f);
    650 				bytesRead++;
    651 			}
    652 
    653 			if (lastMask[ch] & 8)
    654 			{
    655 				p->efx = lastNote[ch].efx = (uint8_t)fgetc(f);
    656 				bytesRead++;;
    657 
    658 				p->efxData = lastNote[ch].efxData = (uint8_t)fgetc(f);
    659 				bytesRead++;
    660 			}
    661 		}
    662 	}
    663 	numChannels++;
    664 
    665 	songTmp.numChannels = MIN((numChannels + 1) & ~1, MAX_CHANNELS);
    666 
    667 	// convert pattern data
    668 
    669 	uint8_t lastInstr[MAX_CHANNELS], lastGInstr[MAX_CHANNELS];
    670 	uint8_t lastDxy[MAX_CHANNELS], lastExy[MAX_CHANNELS], lastFxy[MAX_CHANNELS];
    671 	uint8_t lastJxy[MAX_CHANNELS], lastKxy[MAX_CHANNELS], lastLxy[MAX_CHANNELS];
    672 	uint8_t lastOxx[MAX_CHANNELS];
    673 
    674 	memset(lastInstr, 0, sizeof (lastInstr));
    675 	memset(lastGInstr, 0, sizeof (lastGInstr));
    676 	memset(lastDxy, 0, sizeof (lastDxy));
    677 	memset(lastExy, 0, sizeof (lastExy));
    678 	memset(lastFxy, 0, sizeof (lastFxy));
    679 	memset(lastJxy, 0, sizeof (lastJxy));
    680 	memset(lastKxy, 0, sizeof (lastKxy));
    681 	memset(lastLxy, 0, sizeof (lastLxy));
    682 	memset(lastOxx, 0, sizeof (lastOxx));
    683 
    684 	for (int32_t i = 0; i < songTmp.pattNum; i++)
    685 	{
    686 		note_t *p = patternTmp[i];
    687 		if (p == NULL)
    688 			continue;
    689 
    690 		for (int32_t j = 0; j < patternNumRowsTmp[i]; j++)
    691 		{
    692 			for (int32_t ch = 0; ch < songTmp.numChannels; ch++, p++)
    693 			{
    694 				if (p->instr > 0)
    695 					lastInstr[ch] = p->instr;
    696 
    697 				// effect
    698 				if (p->efx != 0)
    699 				{
    700 					const uint8_t itEfx = 'A' + (p->efx - 1);
    701 					switch (itEfx)
    702 					{
    703 						case 'A': // set speed
    704 						{
    705 							if (p->efxData == 0) // A00 is ignored in IT
    706 							{
    707 								p->efx = p->efxData = 0;
    708 							}
    709 							else
    710 							{
    711 								p->efx = 0xF;
    712 								if (p->efxData > 31)
    713 									p->efxData = 31;
    714 							}
    715 						}
    716 						break;
    717 
    718 						case 'B': p->efx = 0xB; break; // position jump
    719 						case 'C': p->efx = 0xD; break; // pattern break
    720 
    721 						case 'D': // volume slide
    722 						{
    723 							if (p->efxData == 0)
    724 							{
    725 								bool lastWasFineSlide = (lastDxy[ch] & 0x0F) == 0x0F || (lastDxy[ch] >> 4) == 0x0F;
    726 								if (lastWasFineSlide)
    727 									p->efxData = lastDxy[ch];
    728 							}
    729 							else
    730 							{
    731 								lastDxy[ch] = p->efxData;
    732 							}
    733 
    734 							if ((p->efxData & 0x0F) == 0x0F && (p->efxData >> 4) > 0)
    735 							{
    736 								p->efx = 0xE;
    737 								p->efxData = 0xA0 + (p->efxData >> 4);
    738 							}
    739 							else if ((p->efxData >> 4) == 0x0F && (p->efxData & 0x0F) > 0)
    740 							{
    741 								p->efx = 0xE;
    742 								p->efxData = 0xB0 + (p->efxData & 0x0F);
    743 							}
    744 							else
    745 							{
    746 								p->efx = 0xA;
    747 							}
    748 						}
    749 						break;
    750 
    751 						case 'E': // portamento down
    752 						{
    753 							if (p->efxData == 0)
    754 							{
    755 								bool lastWasFineSlide = (lastExy[ch] & 0x0F) == 0x0F || (lastExy[ch] >> 4) == 0x0F;
    756 								bool lastWasExtraFineSlide = (lastExy[ch] & 0x0F) == 0x0E || (lastExy[ch] >> 4) == 0x0E;
    757 
    758 								if (lastWasFineSlide || lastWasExtraFineSlide)
    759 									p->efxData = lastExy[ch];
    760 							}
    761 							else
    762 							{
    763 								lastExy[ch] = p->efxData;
    764 							}
    765 
    766 							if (p->efxData < 224)
    767 							{
    768 								p->efx = 0x2;
    769 							}
    770 							else if ((p->efxData >> 4) == 0x0E)
    771 							{
    772 								p->efx = 16 + ('X' - 'G');
    773 								p->efxData = 0x20 + (p->efxData & 0x0F);
    774 							}
    775 							else if ((p->efxData >> 4) == 0x0F)
    776 							{
    777 								p->efx = 0xE;
    778 								p->efxData = 0x20 + (p->efxData & 0x0F);
    779 							}
    780 						}
    781 						break;
    782 
    783 						case 'F': // portamento up
    784 						{
    785 							if (p->efxData == 0)
    786 							{
    787 								bool lastWasFineSlide = (lastFxy[ch] & 0x0F) == 0x0F || (lastFxy[ch] >> 4) == 0x0F;
    788 								bool lastWasExtraFineSlide = (lastFxy[ch] & 0x0F) == 0x0E || (lastFxy[ch] >> 4) == 0x0E;
    789 
    790 								if (lastWasFineSlide || lastWasExtraFineSlide)
    791 									p->efxData = lastFxy[ch];
    792 							}
    793 							else
    794 							{
    795 								lastFxy[ch] = p->efxData;
    796 							}
    797 
    798 							if (p->efxData < 224)
    799 							{
    800 								p->efx = 0x1;
    801 							}
    802 							else if ((p->efxData >> 4) == 0x0E)
    803 							{
    804 								p->efx = 16 + ('X' - 'G');
    805 								p->efxData = 0x10 + (p->efxData & 0x0F);
    806 							}
    807 							else if ((p->efxData >> 4) == 0x0F)
    808 							{
    809 								p->efx = 0xE;
    810 								p->efxData = 0x10 + (p->efxData & 0x0F);
    811 							}
    812 						}
    813 						break;
    814 
    815 						case 'G': // tone portamento
    816 						{
    817 							p->efx = 3;
    818 
    819 							// remove illegal slides (this is not quite right, but good enough)
    820 							if (!compatGxx && p->instr != 0 && p->instr != lastGInstr[ch])
    821 								p->efx = p->efxData = 0;
    822 						}
    823 						break;
    824 
    825 						case 'H': // vibrato
    826 						{
    827 							p->efx = 4;
    828 							if (!oldEffects && p->efxData > 0)
    829 								p->efxData = (p->efxData & 0xF0) | ((p->efxData & 0x0F) >> 1);
    830 						}
    831 						break;
    832 
    833 						case 'I': // tremor
    834 						{
    835 							p->efx = 16 + ('T' - 'G');
    836 
    837 							int8_t onTime = p->efxData >> 4;
    838 							if (onTime > 0) // closer to IT2 (but still off)
    839 								onTime--;
    840 
    841 							int8_t offTime = p->efxData & 0x0F;
    842 							if (offTime > 0) // ---
    843 								offTime--;
    844 
    845 							p->efxData = (onTime << 4) | offTime;
    846 						}
    847 						break;
    848 
    849 						case 'J': // arpeggio
    850 						{
    851 							p->efx = 0;
    852 
    853 							if (p->efxData != 0)
    854 								p->efxData = lastJxy[ch] = (p->efxData >> 4) | (p->efxData << 4); // swap order (FT2 = reversed)
    855 							else
    856 								p->efxData = lastJxy[ch];
    857 						}
    858 						break;
    859 
    860 						case 'K': // volume slide + vibrato
    861 						{
    862 							if (p->efxData == 0)
    863 							{
    864 								bool lastWasFineSlide = (lastKxy[ch] & 0x0F) == 0x0F || (lastKxy[ch] >> 4) == 0x0F;
    865 								if (lastWasFineSlide)
    866 									p->efxData = lastKxy[ch];
    867 							}
    868 							else
    869 							{
    870 								lastKxy[ch] = p->efxData;
    871 							}
    872 
    873 							if ((p->efxData & 0x0F) == 0x0F && (p->efxData >> 4) > 0)
    874 							{
    875 								if (p->vol == 0)
    876 									p->vol = 1+203; // IT2 vibrato of param 0 (to be converted)
    877 
    878 								p->efx = 0xE;
    879 								p->efxData = 0xA0 + (p->efxData >> 4);
    880 							}
    881 							else if ((p->efxData >> 4) == 0x0F && (p->efxData & 0x0F) > 0)
    882 							{
    883 								if (p->vol == 0)
    884 									p->vol = 1+203; // IT2 vibrato of param 0 (to be converted)
    885 
    886 								p->efx = 0xE;
    887 								p->efxData = 0xB0 + (p->efxData & 0x0F);
    888 							}
    889 							else
    890 							{
    891 								p->efx = 0x6;
    892 							}
    893 						}
    894 						break;
    895 
    896 						case 'L': // volume slide + tone portamento
    897 						{
    898 							if (p->efxData == 0)
    899 							{
    900 								bool lastWasFineSlide = (lastLxy[ch] & 0x0F) == 0x0F || (lastLxy[ch] >> 4) == 0x0F;
    901 								if (lastWasFineSlide)
    902 									p->efxData = lastLxy[ch];
    903 							}
    904 							else
    905 							{
    906 								lastLxy[ch] = p->efxData;
    907 							}
    908 
    909 							if ((p->efxData & 0x0F) == 0x0F && (p->efxData >> 4) > 0)
    910 							{
    911 								if (p->vol == 0)
    912 									p->vol = 1+193; // IT2 tone portamento of param 0 (to be converted)
    913 
    914 								p->efx = 0xE;
    915 								p->efxData = 0xA0 + (p->efxData >> 4);
    916 							}
    917 							else if ((p->efxData >> 4) == 0x0F && (p->efxData & 0x0F) > 0)
    918 							{
    919 								if (p->vol == 0)
    920 									p->vol = 1+193; // IT2 tone portamento of param 0 (to be converted)
    921 
    922 								p->efx = 0xE;
    923 								p->efxData = 0xB0 + (p->efxData & 0x0F);
    924 							}
    925 							else
    926 							{
    927 								p->efx = 0x5;
    928 							}
    929 						}
    930 						break;
    931 
    932 						case 'O': // set sample offset
    933 						{
    934 							p->efx = 0x9;
    935 
    936 							if (p->efxData > 0)
    937 								lastOxx[ch] = p->efxData;
    938 
    939 							// handle cases where the sample offset is after the end of the sample
    940 							if (lastInstr[ch] > 0 && lastOxx[ch] > 0 && p->note > 0 && p->note <= 96)
    941 							{
    942 								instr_t *ins = instrTmp[lastInstr[ch]];
    943 								if (ins != NULL)
    944 								{
    945 									const uint8_t sample = ins->note2SampleLUT[p->note-1];
    946 									if (sample < MAX_SMP_PER_INST)
    947 									{
    948 										sample_t *s = &ins->smp[sample];
    949 										if (s->length > 0)
    950 										{
    951 											const bool loopEnabled = (GET_LOOPTYPE(s->flags) != LOOP_DISABLED);
    952 											const uint32_t sampleEnd = loopEnabled ? s->loopStart+s->loopLength : s->length;
    953 
    954 											if (lastOxx[ch]*256UL >= sampleEnd)
    955 											{
    956 												if (oldEffects)
    957 												{
    958 													if (loopEnabled)
    959 														p->efxData = (uint8_t)(sampleEnd >> 8);
    960 												}
    961 												else
    962 												{
    963 													p->efx = p->efxData = 0;
    964 												}
    965 											}
    966 										}
    967 									}
    968 								}
    969 							}
    970 						}
    971 						break;
    972 
    973 						case 'P': // panning slide
    974 						{
    975 							p->efx = 16 + ('P' - 'G');
    976 
    977 							if ((p->efxData >> 4) == 0)
    978 							{
    979 								uint8_t param = (((p->efxData & 0x0F) * 255) + 32) / 64;
    980 								if (param > 15)
    981 									param = 15;
    982 
    983 								p->efxData = param << 4;
    984 							}
    985 							else if ((p->efxData & 0x0F) == 0)
    986 							{
    987 								uint8_t param = (((p->efxData >> 4) * 255) + 32) / 64;
    988 								if (param > 15)
    989 									param = 15;
    990 
    991 								p->efxData = param;
    992 							}
    993 						}
    994 						break;
    995 
    996 						case 'Q': // note retrigger
    997 						{
    998 							p->efx = 16 + ('R' - 'G');
    999 
   1000 							if ((p->efxData & 0xF0) == 0x00)
   1001 								p->efxData |= 0x80;
   1002 						}
   1003 						break;
   1004 
   1005 						case 'R': // tremolo
   1006 						{
   1007 							p->efx = 7;
   1008 							p->efxData = (p->efxData & 0xF0) | ((p->efxData & 0x0F) >> 1);
   1009 						}
   1010 						break;
   1011 
   1012 						case 'S': // special effects
   1013 						{
   1014 							switch (p->efxData >> 4)
   1015 							{
   1016 								case 0x1: p->efx = 0xE3; break; // set glissando control
   1017 
   1018 								case 0x3: // set vibrato waveform
   1019 								{
   1020 									if ((p->efxData & 0x0F) > 2)
   1021 										p->efx = p->efxData = 0;
   1022 									else
   1023 										p->efx = 0xE4;
   1024 								}
   1025 								break;
   1026 
   1027 								case 0x4: // set tremolo waveform
   1028 								{
   1029 									if ((p->efxData & 0x0F) > 2)
   1030 										p->efx = p->efxData = 0;
   1031 									else
   1032 										p->efx = 0xE7;
   1033 								}
   1034 								break;
   1035 
   1036 								case 0x8:
   1037 									p->efx = 0x08;
   1038 									p->efxData = (p->efxData << 4) | (p->efxData & 0x0F);
   1039 								break;
   1040 
   1041 								case 0xB: p->efx = 0xE6; break; // pattern loop
   1042 								case 0xC: p->efx = 0xEC; break; // note cut
   1043 								case 0xD: p->efx = 0xED; break; // note delay
   1044 								case 0xE: p->efx = 0xEE; break; // pattern delay
   1045 
   1046 								default:
   1047 									p->efx = p->efxData = 0;
   1048 								break;
   1049 							}
   1050 						}
   1051 						break;
   1052 
   1053 						case 'T': // set tempo (BPM)
   1054 						{
   1055 							p->efx = 0xF;
   1056 							if (p->efxData < 32)
   1057 								p->efx = p->efxData = 0; // tempo slide is not supported
   1058 						}
   1059 						break;
   1060 
   1061 						case 'V': // set global volume
   1062 						{
   1063 							p->efx = 16 + ('G' - 'G');
   1064 							p->efxData >>= 1; // IT2 g.vol. ranges 0..128, FT2 g.vol. ranges 0..64
   1065 
   1066 							if (p->efxData > 64)
   1067 								p->efxData = 64;
   1068 						}
   1069 						break;
   1070 
   1071 						case 'W': // global volume slide
   1072 						{
   1073 							p->efx = 16 + ('H' - 'G');
   1074 
   1075 							// IT2 g.vol. ranges 0..128, FT2 g.vol. ranges 0..64
   1076 							if (p->efxData >> 4 == 0)
   1077 							{
   1078 								uint8_t param = p->efxData & 0x0F;
   1079 								if (param > 1)
   1080 									p->efxData = param >> 1;
   1081 							}
   1082 							else if ((p->efxData & 0x0F) == 0)
   1083 							{
   1084 								uint8_t param = p->efxData >> 4;
   1085 								if (param > 1)
   1086 									p->efxData = (param >> 1) << 4;
   1087 							}
   1088 						}
   1089 						break;
   1090 
   1091 						case 'X': p->efx = 8; break; // set 8-bit panning
   1092 
   1093 						default:
   1094 							p->efx = p->efxData = 0;
   1095 						break;
   1096 					}
   1097 				}
   1098 				else
   1099 				{
   1100 					p->efxData = 0;
   1101 				}
   1102 
   1103 				if (p->instr != 0 && p->efx != 0x3)
   1104 					lastGInstr[ch] = p->instr;
   1105 
   1106 				// volume column
   1107 				if (p->vol > 0)
   1108 				{
   1109 					p->vol--;
   1110 					if (p->vol <= 64) // set volume
   1111 					{
   1112 						p->vol += 0x10;
   1113 					}
   1114 					else if (p->vol <= 74) // fine volume slide up
   1115 					{
   1116 						p->vol = 0x90 + (p->vol - 65);
   1117 					}
   1118 					else if (p->vol <= 84) // fine volume slide down
   1119 					{
   1120 						p->vol = 0x80 + (p->vol - 75);
   1121 					}
   1122 					else if (p->vol <= 94) // volume slide up
   1123 					{
   1124 						p->vol = 0x70 + (p->vol - 85);
   1125 					}
   1126 					else if (p->vol <= 104) // volume slide down
   1127 					{
   1128 						p->vol = 0x60 + (p->vol - 95);
   1129 					}
   1130 					else if (p->vol <= 114) // pitch slide down
   1131 					{
   1132 						uint8_t param = p->vol - 105;
   1133 						p->vol = 0;
   1134 
   1135 						if (p->efx == 0 && p->efxData == 0)
   1136 						{
   1137 							p->efx = 2;
   1138 							p->efxData = param * 4;
   1139 						}
   1140 					}
   1141 					else if (p->vol <= 124) // pitch slide up
   1142 					{
   1143 						uint8_t param = p->vol - 115;
   1144 						p->vol = 0;
   1145 
   1146 						if (p->efx == 0 && p->efxData == 0)
   1147 						{
   1148 							p->efx = 1;
   1149 							p->efxData = param * 4;
   1150 						}
   1151 					}
   1152 					else if (p->vol <= 192) // set panning
   1153 					{
   1154 						p->vol = 0xC0 + (((p->vol - 128) * 15) / 64);
   1155 					}
   1156 					else if (p->vol >= 193 && p->vol <= 202) // portamento
   1157 					{
   1158 						uint8_t param = p->vol - 193;
   1159 					
   1160 						if (p->efx == 0 && p->efxData == 0)
   1161 						{
   1162 							p->vol = 0;
   1163 
   1164 							p->efx = 3;
   1165 							p->efxData = (param == 0) ? 0 : volPortaConv[param-1];
   1166 						}
   1167 						else
   1168 						{
   1169 							p->vol = 0xF0 + param;
   1170 						}
   1171 					}
   1172 					else if (p->vol <= 212) // vibrato
   1173 					{
   1174 						p->vol = 0xB0 + (p->vol - 203);
   1175 					}
   1176 				}
   1177 
   1178 				// note
   1179 				if (p->note == 254) // note cut
   1180 				{
   1181 					p->note = 0;
   1182 					if (p->efx == 0 && p->efxData == 0)
   1183 					{
   1184 						// EC0 (instant note cut)
   1185 						p->efx = 0xE;
   1186 						p->efxData = 0xC0;
   1187 					}
   1188 					else if (p->vol == 0)
   1189 					{
   1190 						// volume command vol 0
   1191 						p->vol = 0x10;
   1192 					}
   1193 				}
   1194 			}
   1195 
   1196 			p += MAX_CHANNELS - songTmp.numChannels;
   1197 		}
   1198 	}
   1199 
   1200 	// removing this message is considered a criminal act!!!
   1201 	loaderMsgBox("Loading of this format has severe issues. Don't use this for listening to .ITs!");
   1202 
   1203 	return true;
   1204 
   1205 error:
   1206 	return false;
   1207 }
   1208 
   1209 static void decompress16BitData(int16_t *dst, const uint8_t *src, uint32_t blockLength)
   1210 {
   1211 	uint8_t byte8, bitDepth, bitDepthInv, bitsRead;
   1212 	uint16_t bytes16, lastVal;
   1213 	uint32_t bytes32;
   1214 
   1215 	lastVal = 0;
   1216 	bitDepth = 17;
   1217 	bitDepthInv = bitsRead = 0;
   1218 
   1219 	blockLength >>= 1;
   1220 	while (blockLength != 0)
   1221 	{
   1222 		bytes32 = (*(uint32_t *)src) >> bitsRead;
   1223 
   1224 		bitsRead += bitDepth;
   1225 		src += bitsRead >> 3;
   1226 		bitsRead &= 7;
   1227 
   1228 		if (bitDepth <= 6)
   1229 		{
   1230 			bytes32 <<= bitDepthInv & 0x1F;
   1231 
   1232 			bytes16 = (uint16_t)bytes32;
   1233 			if (bytes16 != 0x8000)
   1234 			{
   1235 				lastVal += (int16_t)bytes16 >> (bitDepthInv & 0x1F); // arithmetic shift
   1236 				*dst++ = lastVal;
   1237 				blockLength--;
   1238 			}
   1239 			else
   1240 			{
   1241 				byte8 = ((bytes32 >> 16) & 0xF) + 1;
   1242 				if (byte8 >= bitDepth)
   1243 					byte8++;
   1244 				bitDepth = byte8;
   1245 
   1246 				bitDepthInv = 16;
   1247 				if (bitDepthInv < bitDepth)
   1248 					bitDepthInv++;
   1249 				bitDepthInv -= bitDepth;
   1250 
   1251 				bitsRead += 4;
   1252 			}
   1253 
   1254 			continue;
   1255 		}
   1256 
   1257 		bytes16 = (uint16_t)bytes32;
   1258 
   1259 		if (bitDepth <= 16)
   1260 		{
   1261 			uint16_t tmp16 = 0xFFFF >> (bitDepthInv & 0x1F);
   1262 			bytes16 &= tmp16;
   1263 			tmp16 = (tmp16 >> 1) - 8;
   1264 
   1265 			if (bytes16 > tmp16+16 || bytes16 <= tmp16)
   1266 			{
   1267 				bytes16 <<= bitDepthInv & 0x1F;
   1268 				bytes16 = (int16_t)bytes16 >> (bitDepthInv & 0x1F); // arithmetic shift
   1269 				lastVal += bytes16;
   1270 				*dst++ = lastVal;
   1271 				blockLength--;
   1272 				continue;
   1273 			}
   1274 
   1275 			byte8 = (uint8_t)(bytes16 - tmp16);
   1276 			if (byte8 >= bitDepth)
   1277 				byte8++;
   1278 			bitDepth = byte8;
   1279 
   1280 			bitDepthInv = 16;
   1281 			if (bitDepthInv < bitDepth)
   1282 				bitDepthInv++;
   1283 			bitDepthInv -= bitDepth;
   1284 			continue;
   1285 		}
   1286 
   1287 		if (bytes32 & 0x10000)
   1288 		{
   1289 			bitDepth = (uint8_t)(bytes16 + 1);
   1290 			bitDepthInv = 16 - bitDepth;
   1291 		}
   1292 		else
   1293 		{
   1294 			lastVal += bytes16;
   1295 			*dst++ = lastVal;
   1296 			blockLength--;
   1297 		}
   1298 	}
   1299 }
   1300 
   1301 static void decompress8BitData(int8_t *dst, const uint8_t *src, uint32_t blockLength)
   1302 {
   1303 	uint8_t lastVal, byte8, bitDepth, bitDepthInv, bitsRead;
   1304 	uint16_t bytes16;
   1305 
   1306 	lastVal = 0;
   1307 	bitDepth = 9;
   1308 	bitDepthInv = bitsRead = 0;
   1309 
   1310 	while (blockLength != 0)
   1311 	{
   1312 		bytes16 = (*(uint16_t *)src) >> bitsRead;
   1313 
   1314 		bitsRead += bitDepth;
   1315 		src += (bitsRead >> 3);
   1316 		bitsRead &= 7;
   1317 
   1318 		byte8 = bytes16 & 0xFF;
   1319 
   1320 		if (bitDepth <= 6)
   1321 		{
   1322 			bytes16 <<= (bitDepthInv & 0x1F);
   1323 			byte8 = bytes16 & 0xFF;
   1324 
   1325 			if (byte8 != 0x80)
   1326 			{
   1327 				lastVal += (int8_t)byte8 >> (bitDepthInv & 0x1F); // arithmetic shift
   1328 				*dst++ = lastVal;
   1329 				blockLength--;
   1330 				continue;
   1331 			}
   1332 
   1333 			byte8 = (bytes16 >> 8) & 7;
   1334 			bitsRead += 3;
   1335 			src += (bitsRead >> 3);
   1336 			bitsRead &= 7;
   1337 		}
   1338 		else
   1339 		{
   1340 			if (bitDepth == 8)
   1341 			{
   1342 				if (byte8 < 0x7C || byte8 > 0x83)
   1343 				{
   1344 					lastVal += byte8;
   1345 					*dst++ = lastVal;
   1346 					blockLength--;
   1347 					continue;
   1348 				}
   1349 				byte8 -= 0x7C;
   1350 			}
   1351 			else if (bitDepth < 8)
   1352 			{
   1353 				byte8 <<= 1;
   1354 				if (byte8 < 0x78 || byte8 > 0x86)
   1355 				{
   1356 					lastVal += (int8_t)byte8 >> (bitDepthInv & 0x1F); // arithmetic shift
   1357 					*dst++ = lastVal;
   1358 					blockLength--;
   1359 					continue;
   1360 				}
   1361 				byte8 = (byte8 >> 1) - 0x3C;
   1362 			}
   1363 			else
   1364 			{
   1365 				bytes16 &= 0x1FF;
   1366 				if ((bytes16 & 0x100) == 0)
   1367 				{
   1368 					lastVal += byte8;
   1369 					*dst++ = lastVal;
   1370 					blockLength--;
   1371 					continue;
   1372 				}
   1373 			}
   1374 		}
   1375 
   1376 		byte8++;
   1377 		if (byte8 >= bitDepth)
   1378 			byte8++;
   1379 		bitDepth = byte8;
   1380 
   1381 		bitDepthInv = 8;
   1382 		if (bitDepthInv < bitDepth)
   1383 			bitDepthInv++;
   1384 		bitDepthInv -= bitDepth;
   1385 	}
   1386 }
   1387 
   1388 static bool loadCompressed16BitSample(FILE *f, sample_t *s, bool deltaEncoded)
   1389 {
   1390 	int8_t *dstPtr = (int8_t *)s->dataPtr;
   1391 
   1392 	uint32_t i = s->length * 2;
   1393 	while (i > 0)
   1394 	{
   1395 		uint32_t bytesToUnpack = 32768;
   1396 		if (bytesToUnpack > i)
   1397 			bytesToUnpack = i;
   1398 
   1399 		uint16_t packedLen;
   1400 		fread(&packedLen, sizeof (uint16_t), 1, f);
   1401 		fread(decompBuffer, 1, packedLen, f);
   1402 
   1403 		decompress16BitData((int16_t *)dstPtr, decompBuffer, bytesToUnpack);
   1404 
   1405 		if (deltaEncoded) // convert from delta values to PCM
   1406 		{
   1407 			int16_t *ptr16 = (int16_t *)dstPtr;
   1408 			int16_t lastSmp16 = 0; // yes, reset this every block!
   1409 
   1410 			const uint32_t length = bytesToUnpack >> 1;
   1411 			for (uint32_t j = 0; j < length; j++)
   1412 			{
   1413 				lastSmp16 += ptr16[j];
   1414 				ptr16[j] = lastSmp16;
   1415 			}
   1416 		}
   1417 
   1418 		dstPtr += bytesToUnpack;
   1419 		i -= bytesToUnpack;
   1420 	}
   1421 
   1422 	return true;
   1423 }
   1424 
   1425 static bool loadCompressed8BitSample(FILE *f, sample_t *s, bool deltaEncoded)
   1426 {
   1427 	int8_t *dstPtr = (int8_t *)s->dataPtr;
   1428 
   1429 	uint32_t i = s->length;
   1430 	while (i > 0)
   1431 	{
   1432 		uint32_t bytesToUnpack = 32768;
   1433 		if (bytesToUnpack > i)
   1434 			bytesToUnpack = i;
   1435 
   1436 		uint16_t packedLen;
   1437 		fread(&packedLen, sizeof (uint16_t), 1, f);
   1438 		fread(decompBuffer, 1, packedLen, f);
   1439 
   1440 		decompress8BitData(dstPtr, decompBuffer, bytesToUnpack);
   1441 
   1442 		if (deltaEncoded) // convert from delta values to PCM
   1443 		{
   1444 			int8_t lastSmp8 = 0; // yes, reset this every block!
   1445 			for (uint32_t j = 0; j < bytesToUnpack; j++)
   1446 			{
   1447 				lastSmp8 += dstPtr[j];
   1448 				dstPtr[j] = lastSmp8;
   1449 			}
   1450 		}
   1451 
   1452 		dstPtr += bytesToUnpack;
   1453 		i -= bytesToUnpack;
   1454 	}
   1455 
   1456 	return true;
   1457 }
   1458 
   1459 static void setAutoVibrato(instr_t *ins, itSmpHdr_t *itSmp)
   1460 {
   1461 	ins->autoVibType = itSmp->autoVibratoWaveform;
   1462 	if (ins->autoVibType > 3 || itSmp->autoVibratoRate == 0)
   1463 	{
   1464 		// turn off auto-vibrato
   1465 		ins->autoVibDepth = ins->autoVibRate = ins->autoVibSweep = ins->autoVibType = 0;
   1466 		return;
   1467 	}
   1468 
   1469 	ins->autoVibRate = itSmp->autoVibratoSpeed;
   1470 	if (ins->autoVibRate > 63)
   1471 		ins->autoVibRate = 63;
   1472 
   1473 	int32_t autoVibSweep = ((itSmp->autoVibratoDepth * 256) + 128) / itSmp->autoVibratoRate;
   1474 	if (autoVibSweep > 255)
   1475 		autoVibSweep = 255;
   1476 	ins->autoVibSweep = (uint8_t)autoVibSweep;
   1477 
   1478 	ins->autoVibDepth = itSmp->autoVibratoDepth;
   1479 	if (ins->autoVibDepth > 15)
   1480 		ins->autoVibDepth = 15;
   1481 }
   1482 
   1483 static bool loadSample(FILE *f, sample_t *s, itSmpHdr_t *itSmp)
   1484 {
   1485 	bool sampleIs16Bit = !!(itSmp->flags & 2);
   1486 	bool compressed = !!(itSmp->flags & 8);
   1487 	bool hasLoop = !!(itSmp->flags & 16);
   1488 	bool bidiLoop = !!(itSmp->flags & 64);
   1489 	bool signedSamples = !!(itSmp->cvt & 1);
   1490 	bool deltaEncoded = !!(itSmp->cvt & 4);
   1491 
   1492 	if (sampleIs16Bit)
   1493 		s->flags |= SAMPLE_16BIT;
   1494 
   1495 	if (hasLoop)
   1496 		s->flags |= bidiLoop ? LOOP_BIDI : LOOP_FWD;
   1497 
   1498 	s->length = itSmp->length;
   1499 	s->loopStart = itSmp->loopBegin;
   1500 	s->loopLength = itSmp->loopEnd - itSmp->loopBegin;
   1501 	s->volume = itSmp->vol;
   1502 
   1503 	s->panning = 128;
   1504 	if (itSmp->defPan & 128) // use panning?
   1505 	{
   1506 		int32_t pan = (itSmp->defPan & 127) * 4; // 0..64 -> 0..256
   1507 		if (pan > 255)
   1508 			pan = 255;
   1509 
   1510 		s->panning = (uint8_t)pan;
   1511 	}
   1512 
   1513 	memcpy(s->name, itSmp->sampleName, 22);
   1514 	s->name[22] = '\0';
   1515 
   1516 	setSampleC4Hz(s, itSmp->c5Speed);
   1517 
   1518 	if (s->length <= 0 || itSmp->offsetInFile == 0)
   1519 		return true; // empty sample, skip data loading
   1520 
   1521 	if (!allocateSmpData(s, s->length, sampleIs16Bit))
   1522 		return false;
   1523 
   1524 	// begin sample loading
   1525 
   1526 	fseek(f, itSmp->offsetInFile, SEEK_SET);
   1527 
   1528 	if (compressed)
   1529 	{
   1530 		if (sampleIs16Bit)
   1531 			loadCompressed16BitSample(f, s, deltaEncoded);
   1532 		else
   1533 			loadCompressed8BitSample(f, s, deltaEncoded);
   1534 	}
   1535 	else
   1536 	{
   1537 		fread(s->dataPtr, 1+(size_t)sampleIs16Bit, s->length, f);
   1538 
   1539 		if (!signedSamples)
   1540 		{
   1541 			if (sampleIs16Bit)
   1542 			{
   1543 				int16_t *ptr16 = (int16_t *)s->dataPtr;
   1544 				for (int32_t i = 0; i < s->length; i++)
   1545 					ptr16[i] ^= 0x8000;
   1546 			}
   1547 			else
   1548 			{
   1549 				int8_t *ptr8 = (int8_t *)s->dataPtr;
   1550 				for (int32_t i = 0; i < s->length; i++)
   1551 					ptr8[i] ^= 0x80;
   1552 			}
   1553 		}
   1554 	}
   1555 
   1556 	return true;
   1557 }