1 // for finding memory leaks in debug mode with Visual Studio
2 #if defined _DEBUG && defined _MSC_VER
3 #include <crtdbg.h>
4 #endif
5 
6 #include <stdio.h>
7 #include <string.h>
8 #include <stdint.h>
9 #include <stdbool.h>
10 #include "pt2_header.h"
11 #include "pt2_textout.h"
12 #include "pt2_mouse.h"
13 #include "pt2_structs.h"
14 #include "pt2_sampler.h" // fixSampleBeep()
15 #include "pt2_audio.h"
16 #include "pt2_visuals.h"
17 #include "pt2_helpers.h"
18 #include "pt2_unicode.h"
19 #include "pt2_config.h"
20 #include "pt2_sampling.h"
21 #include "pt2_downsample2x.h"
22 
23 enum
24 {
25 	WAV_FORMAT_PCM = 0x0001,
26 	WAV_FORMAT_IEEE_FLOAT = 0x0003
27 };
28 
29 enum
30 {
31 	SAMPLE_IFF = 0,
32 	SAMPLE_AIFF = 1,
33 	SAMPLE_WAV = 2
34 };
35 
36 
37 static int8_t loadedSampleType;
38 
39 static bool loadWAVSample(UNICHAR *fileName, char *entryName, int8_t forceDownSampling);
40 static bool loadIFFSample(UNICHAR *fileName, char *entryName, int8_t forceDownSampling);
41 static bool loadRAWSample(UNICHAR *fileName, char *entryName);
42 static bool loadAIFFSample(UNICHAR *fileName, char *entryName, int8_t forceDownSampling);
43 
extLoadWAVOrAIFFSampleCallback(bool downsample)44 void extLoadWAVOrAIFFSampleCallback(bool downsample)
45 {
46 	switch (loadedSampleType)
47 	{
48 		case SAMPLE_IFF:   loadIFFSample(editor.fileNameTmpU, editor.entryNameTmp, downsample); break;
49 		case SAMPLE_AIFF: loadAIFFSample(editor.fileNameTmpU, editor.entryNameTmp, downsample); break;
50 		case SAMPLE_WAV:   loadWAVSample(editor.fileNameTmpU, editor.entryNameTmp, downsample); break;
51 		default: break;
52 	}
53 }
54 
loadWAVSample(UNICHAR * fileName,char * entryName,int8_t forceDownSampling)55 bool loadWAVSample(UNICHAR *fileName, char *entryName, int8_t forceDownSampling)
56 {
57 	bool wavSampleNameFound;
58 	uint8_t *audioDataU8;
59 	int16_t *audioDataS16, tempVol;
60 	uint16_t audioFormat, numChannels, bitsPerSample;
61 	int32_t *audioDataS32, smp32;
62 	uint32_t *audioDataU32, i, nameLen, chunkID, chunkSize;
63 	uint32_t sampleLength, sampleRate, filesize, loopFlags;
64 	uint32_t loopStart, loopEnd, dataPtr, dataLen, fmtPtr, endOfChunk, bytesRead;
65 	uint32_t fmtLen, inamPtr, inamLen, smplPtr, smplLen, xtraPtr, xtraLen;
66 	float *fAudioDataFloat;
67 	double *dAudioDataDouble;
68 	FILE *f;
69 	moduleSample_t *s;
70 
71 	loadedSampleType = SAMPLE_WAV;
72 
73 	// zero out chunk pointers and lengths
74 	fmtPtr  = 0; fmtLen = 0;
75 	dataPtr = 0; dataLen = 0;
76 	inamPtr = 0; inamLen = 0;
77 	xtraPtr = 0; xtraLen = 0;
78 	smplPtr = 0; smplLen = 0;
79 
80 	wavSampleNameFound = false;
81 
82 	s = &song->samples[editor.currSample];
83 
84 	if (forceDownSampling == -1)
85 	{
86 		// these two *must* be fully wiped, for outputting reasons
87 		memset(editor.fileNameTmpU, 0, PATH_MAX);
88 		memset(editor.entryNameTmp, 0, PATH_MAX);
89 		UNICHAR_STRCPY(editor.fileNameTmpU, fileName);
90 		strcpy(editor.entryNameTmp, entryName);
91 	}
92 
93 	f = UNICHAR_FOPEN(fileName, "rb");
94 	if (f == NULL)
95 	{
96 		displayErrorMsg("FILE I/O ERROR !");
97 		return false;
98 	}
99 
100 	fseek(f, 0, SEEK_END);
101 	filesize = ftell(f);
102 	if (filesize == 0)
103 	{
104 		fclose(f);
105 
106 		displayErrorMsg("NOT A WAV !");
107 		return false;
108 	}
109 
110 	// look for wanted chunks and set up pointers + lengths
111 	fseek(f, 12, SEEK_SET);
112 
113 	bytesRead = 0;
114 	while (!feof(f) && bytesRead < filesize-12)
115 	{
116 		fread(&chunkID, 4, 1, f); if (feof(f)) break;
117 		fread(&chunkSize, 4, 1, f); if (feof(f)) break;
118 
119 		endOfChunk = (ftell(f) + chunkSize) + (chunkSize & 1);
120 		switch (chunkID)
121 		{
122 			case 0x20746D66: // "fmt "
123 			{
124 				fmtPtr = ftell(f);
125 				fmtLen = chunkSize;
126 			}
127 			break;
128 
129 			case 0x61746164: // "data"
130 			{
131 				dataPtr = ftell(f);
132 				dataLen = chunkSize;
133 			}
134 			break;
135 
136 			case 0x5453494C: // "LIST"
137 			{
138 				if (chunkSize >= 4)
139 				{
140 					fread(&chunkID, 4, 1, f);
141 					if (chunkID == 0x4F464E49) // "INFO"
142 					{
143 						bytesRead = 0;
144 						while (!feof(f) && (bytesRead < chunkSize))
145 						{
146 							fread(&chunkID, 4, 1, f);
147 							fread(&chunkSize, 4, 1, f);
148 
149 							switch (chunkID)
150 							{
151 								case 0x4D414E49: // "INAM"
152 								{
153 									inamPtr = ftell(f);
154 									inamLen = chunkSize;
155 								}
156 								break;
157 
158 								default: break;
159 							}
160 
161 							bytesRead += (chunkSize + (chunkSize & 1));
162 						}
163 					}
164 				}
165 			}
166 			break;
167 
168 			case 0x61727478: // "xtra"
169 			{
170 				xtraPtr = ftell(f);
171 				xtraLen = chunkSize;
172 			}
173 			break;
174 
175 			case 0x6C706D73: // "smpl"
176 			{
177 				smplPtr = ftell(f);
178 				smplLen = chunkSize;
179 			}
180 			break;
181 
182 			default: break;
183 		}
184 
185 		bytesRead += chunkSize + (chunkSize & 1);
186 		fseek(f, endOfChunk, SEEK_SET);
187 	}
188 
189 	// we need at least "fmt " and "data" - check if we found them sanely
190 	if ((fmtPtr == 0 || fmtLen < 16) || (dataPtr == 0 || dataLen == 0))
191 	{
192 		fclose(f);
193 		displayErrorMsg("NOT A WAV !");
194 		return false;
195 	}
196 
197 	// ---- READ "fmt " CHUNK ----
198 	fseek(f, fmtPtr, SEEK_SET);
199 	fread(&audioFormat, 2, 1, f);
200 	fread(&numChannels, 2, 1, f);
201 	fread(&sampleRate,  4, 1, f);
202 	fseek(f, 6, SEEK_CUR);
203 	fread(&bitsPerSample, 2, 1, f);
204 	sampleLength = dataLen;
205 	// ---------------------------
206 
207 	if (sampleRate == 0 || sampleLength == 0 || sampleLength >= filesize*(bitsPerSample/8))
208 	{
209 		fclose(f);
210 		displayErrorMsg("WAV CORRUPT !");
211 		return false;
212 	}
213 
214 	if (audioFormat != WAV_FORMAT_PCM && audioFormat != WAV_FORMAT_IEEE_FLOAT)
215 	{
216 		fclose(f);
217 		displayErrorMsg("WAV UNSUPPORTED !");
218 		return false;
219 	}
220 
221 	if ((numChannels == 0) || (numChannels > 2))
222 	{
223 		fclose(f);
224 		displayErrorMsg("WAV UNSUPPORTED !");
225 		return false;
226 	}
227 
228 	if (audioFormat == WAV_FORMAT_IEEE_FLOAT && bitsPerSample != 32 && bitsPerSample != 64)
229 	{
230 		fclose(f);
231 		displayErrorMsg("WAV UNSUPPORTED !");
232 		return false;
233 	}
234 
235 	if (bitsPerSample != 8 && bitsPerSample != 16 && bitsPerSample != 24 && bitsPerSample != 32 && bitsPerSample != 64)
236 	{
237 		fclose(f);
238 		displayErrorMsg("WAV UNSUPPORTED !");
239 		return false;
240 	}
241 
242 	if (sampleRate > 22050 && !config.noDownsampleOnSmpLoad)
243 	{
244 		if (forceDownSampling == -1)
245 		{
246 			showDownsampleAskDialog();
247 			fclose(f);
248 			return true;
249 		}
250 	}
251 	else
252 	{
253 		forceDownSampling = false;
254 	}
255 
256 	// ---- READ SAMPLE DATA ----
257 	fseek(f, dataPtr, SEEK_SET);
258 
259 	int8_t *smpPtr = &song->sampleData[editor.currSample * MAX_SAMPLE_LEN];
260 
261 	if (bitsPerSample == 8) // 8-BIT INTEGER SAMPLE
262 	{
263 		if (sampleLength > MAX_SAMPLE_LEN*4)
264 			sampleLength = MAX_SAMPLE_LEN*4;
265 
266 		audioDataU8 = (uint8_t *)malloc(sampleLength * sizeof (uint8_t));
267 		if (audioDataU8 == NULL)
268 		{
269 			fclose(f);
270 			statusOutOfMemory();
271 			return false;
272 		}
273 
274 		// read sample data
275 		if (fread(audioDataU8, 1, sampleLength, f) != sampleLength)
276 		{
277 			fclose(f);
278 			free(audioDataU8);
279 			displayErrorMsg("I/O ERROR !");
280 			return false;
281 		}
282 
283 		// convert from stereo to mono (if needed)
284 		if (numChannels == 2)
285 		{
286 			sampleLength >>= 1;
287 			for (i = 0; i < sampleLength-1; i++) // add right channel to left channel
288 			{
289 				smp32 = (audioDataU8[(i << 1) + 0] - 128) + (audioDataU8[(i << 1) + 1] - 128);
290 				smp32 = 128 + (smp32 >> 1);
291 				audioDataU8[i] = (uint8_t)smp32;
292 			}
293 		}
294 
295 		// 2x downsampling
296 		if (forceDownSampling)
297 		{
298 			downsample2x8BitU(audioDataU8, sampleLength);
299 			sampleLength >>= 1;
300 		}
301 
302 		if (sampleLength > MAX_SAMPLE_LEN)
303 			sampleLength = MAX_SAMPLE_LEN;
304 
305 		turnOffVoices();
306 		for (i = 0; i < sampleLength; i++)
307 			smpPtr[i] = audioDataU8[i] - 128;
308 
309 		free(audioDataU8);
310 	}
311 	else if (bitsPerSample == 16) // 16-BIT INTEGER SAMPLE
312 	{
313 		sampleLength >>= 1;
314 		if (sampleLength > MAX_SAMPLE_LEN*4)
315 			sampleLength = MAX_SAMPLE_LEN*4;
316 
317 		audioDataS16 = (int16_t *)malloc(sampleLength * sizeof (int16_t));
318 		if (audioDataS16 == NULL)
319 		{
320 			fclose(f);
321 			statusOutOfMemory();
322 			return false;
323 		}
324 
325 		// read sample data
326 		if (fread(audioDataS16, 2, sampleLength, f) != sampleLength)
327 		{
328 			fclose(f);
329 			free(audioDataS16);
330 			displayErrorMsg("I/O ERROR !");
331 			return false;
332 		}
333 
334 		// convert from stereo to mono (if needed)
335 		if (numChannels == 2)
336 		{
337 			sampleLength >>= 1;
338 			for (i = 0; i < sampleLength-1; i++) // add right channel to left channel
339 				audioDataS16[i] = (audioDataS16[(i << 1) + 0] + audioDataS16[(i << 1) + 1]) >> 1;;
340 		}
341 
342 		// 2x downsampling
343 		if (forceDownSampling)
344 		{
345 			downsample2x16Bit(audioDataS16, sampleLength);
346 			sampleLength >>= 1;
347 		}
348 
349 		if (sampleLength > MAX_SAMPLE_LEN)
350 			sampleLength = MAX_SAMPLE_LEN;
351 
352 		double dAmp = 1.0;
353 		if (forceDownSampling) // we already normalized
354 		{
355 			dAmp = INT8_MAX / (double)INT16_MAX;
356 		}
357 		else
358 		{
359 			const double dPeak = get16BitPeak(audioDataS16, sampleLength);
360 			if (dPeak > 0.0)
361 				dAmp = INT8_MAX / dPeak;
362 		}
363 
364 		turnOffVoices();
365 		for (i = 0; i < sampleLength; i++)
366 		{
367 			smp32 = (int32_t)round(audioDataS16[i] * dAmp);
368 			assert(smp32 >= -128 && smp32 <= 127); // shouldn't happen according to dAmp (but just in case)
369 			smpPtr[i] = (int8_t)smp32;
370 		}
371 
372 		free(audioDataS16);
373 	}
374 	else if (bitsPerSample == 24) // 24-BIT INTEGER SAMPLE
375 	{
376 		sampleLength /= 3;
377 		if (sampleLength > MAX_SAMPLE_LEN*4)
378 			sampleLength = MAX_SAMPLE_LEN*4;
379 
380 		audioDataS32 = (int32_t *)malloc(sampleLength * sizeof (int32_t));
381 		if (audioDataS32 == NULL)
382 		{
383 			fclose(f);
384 			statusOutOfMemory();
385 			return false;
386 		}
387 
388 		// read sample data
389 		audioDataU8 = (uint8_t *)audioDataS32;
390 		for (i = 0; i < sampleLength; i++)
391 		{
392 			audioDataU8[0] = 0;
393 			fread(&audioDataU8[1], 3, 1, f);
394 			audioDataU8 += sizeof (int32_t);
395 		}
396 
397 		// convert from stereo to mono (if needed)
398 		if (numChannels == 2)
399 		{
400 			sampleLength >>= 1;
401 			for (i = 0; i < sampleLength-1; i++) // add right channel to left channel
402 			{
403 				int64_t smp = ((int64_t)audioDataS32[(i << 1) + 0] + audioDataS32[(i << 1) + 1]) >> 1;
404 				audioDataS32[i] = (int32_t)smp;
405 			}
406 		}
407 
408 		// 2x downsampling
409 		if (forceDownSampling)
410 		{
411 			downsample2x32Bit(audioDataS32, sampleLength);
412 			sampleLength >>= 1;
413 		}
414 
415 		if (sampleLength > MAX_SAMPLE_LEN)
416 			sampleLength = MAX_SAMPLE_LEN;
417 
418 		double dAmp = 1.0;
419 		if (forceDownSampling) // we already normalized
420 		{
421 			dAmp = INT8_MAX / (double)INT32_MAX;
422 		}
423 		else
424 		{
425 			const double dPeak = get32BitPeak(audioDataS32, sampleLength);
426 			if (dPeak > 0.0)
427 				dAmp = INT8_MAX / dPeak;
428 		}
429 
430 		turnOffVoices();
431 		for (i = 0; i < sampleLength; i++)
432 		{
433 			smp32 = (int32_t)round(audioDataS32[i] * dAmp);
434 			assert(smp32 >= -128 && smp32 <= 127); // shouldn't happen according to dAmp (but just in case)
435 			smpPtr[i] = (int8_t)smp32;
436 		}
437 
438 		free(audioDataS32);
439 	}
440 	else if (audioFormat == WAV_FORMAT_PCM && bitsPerSample == 32) // 32-BIT INTEGER SAMPLE
441 	{
442 		sampleLength >>= 2;
443 		if (sampleLength > MAX_SAMPLE_LEN*4)
444 			sampleLength = MAX_SAMPLE_LEN*4;
445 
446 		audioDataS32 = (int32_t *)malloc(sampleLength * sizeof (int32_t));
447 		if (audioDataS32 == NULL)
448 		{
449 			fclose(f);
450 			statusOutOfMemory();
451 			return false;
452 		}
453 
454 		// read sample data
455 		if (fread(audioDataS32, 4, sampleLength, f) != sampleLength)
456 		{
457 			fclose(f);
458 			free(audioDataS32);
459 			displayErrorMsg("I/O ERROR !");
460 			return false;
461 		}
462 
463 		// convert from stereo to mono (if needed)
464 		if (numChannels == 2)
465 		{
466 			sampleLength >>= 1;
467 			for (i = 0; i < sampleLength-1; i++) // add right channel to left channel
468 			{
469 				int64_t smp = ((int64_t)audioDataS32[(i << 1) + 0] + audioDataS32[(i << 1) + 1]) >> 1;
470 				audioDataS32[i] = (int32_t)smp;
471 			}
472 		}
473 
474 		// 2x downsampling
475 		if (forceDownSampling)
476 		{
477 			downsample2x32Bit(audioDataS32, sampleLength);
478 			sampleLength >>= 1;
479 		}
480 
481 		if (sampleLength > MAX_SAMPLE_LEN)
482 			sampleLength = MAX_SAMPLE_LEN;
483 
484 		double dAmp = 1.0;
485 		if (forceDownSampling) // we already normalized
486 		{
487 			dAmp = INT8_MAX / (double)INT32_MAX;
488 		}
489 		else
490 		{
491 			const double dPeak = get32BitPeak(audioDataS32, sampleLength);
492 			if (dPeak > 0.0)
493 				dAmp = INT8_MAX / dPeak;
494 		}
495 
496 		turnOffVoices();
497 		for (i = 0; i < sampleLength; i++)
498 		{
499 			smp32 = (int32_t)round(audioDataS32[i] * dAmp);
500 			assert(smp32 >= -128 && smp32 <= 127); // shouldn't happen according to dAmp (but just in case)
501 			smpPtr[i] = (int8_t)smp32;
502 		}
503 
504 		free(audioDataS32);
505 	}
506 	else if (audioFormat == WAV_FORMAT_IEEE_FLOAT && bitsPerSample == 32) // 32-BIT FLOATING POINT SAMPLE
507 	{
508 		sampleLength >>= 2;
509 		if (sampleLength > MAX_SAMPLE_LEN*4)
510 			sampleLength = MAX_SAMPLE_LEN*4;
511 
512 		audioDataU32 = (uint32_t *)malloc(sampleLength * sizeof (uint32_t));
513 		if (audioDataU32 == NULL)
514 		{
515 			fclose(f);
516 			statusOutOfMemory();
517 			return false;
518 		}
519 
520 		// read sample data
521 		if (fread(audioDataU32, 4, sampleLength, f) != sampleLength)
522 		{
523 			fclose(f);
524 			free(audioDataU32);
525 			displayErrorMsg("I/O ERROR !");
526 			return false;
527 		}
528 
529 		fAudioDataFloat = (float *)audioDataU32;
530 
531 		// convert from stereo to mono (if needed)
532 		if (numChannels == 2)
533 		{
534 			sampleLength >>= 1;
535 			for (i = 0; i < sampleLength-1; i++) // add right channel to left channel
536 				fAudioDataFloat[i] = (fAudioDataFloat[(i * 2) + 0] + fAudioDataFloat[(i * 2) + 1]) * 0.5f;
537 		}
538 
539 		// 2x downsampling
540 		if (forceDownSampling)
541 		{
542 			downsample2xFloat(fAudioDataFloat, sampleLength);
543 			sampleLength >>= 1;
544 		}
545 
546 		if (sampleLength > MAX_SAMPLE_LEN)
547 			sampleLength = MAX_SAMPLE_LEN;
548 
549 		float fAmp = 1.0f;
550 		const float fPeak = getFloatPeak(fAudioDataFloat, sampleLength);
551 		if (fPeak > 0.0f)
552 			fAmp = INT8_MAX / fPeak;
553 
554 		turnOffVoices();
555 		for (i = 0; i < sampleLength; i++)
556 		{
557 			smp32 = (int32_t)roundf(fAudioDataFloat[i] * fAmp);
558 			assert(smp32 >= -128 && smp32 <= 127); // shouldn't happen according to dAmp (but just in case)
559 			smpPtr[i] = (int8_t)smp32;
560 		}
561 
562 		free(audioDataU32);
563 	}
564 	else if (audioFormat == WAV_FORMAT_IEEE_FLOAT && bitsPerSample == 64) // 64-BIT FLOATING POINT SAMPLE
565 	{
566 		sampleLength >>= 3;
567 		if (sampleLength > MAX_SAMPLE_LEN*4)
568 			sampleLength = MAX_SAMPLE_LEN*4;
569 
570 		audioDataU32 = (uint32_t *)malloc(sampleLength * (sizeof (uint32_t) * 2));
571 		if (audioDataU32 == NULL)
572 		{
573 			fclose(f);
574 			statusOutOfMemory();
575 			return false;
576 		}
577 
578 		// read sample data
579 		if (fread(audioDataU32, 8, sampleLength, f) != sampleLength)
580 		{
581 			fclose(f);
582 			free(audioDataU32);
583 			displayErrorMsg("I/O ERROR !");
584 			return false;
585 		}
586 
587 		dAudioDataDouble = (double *)audioDataU32;
588 
589 		// convert from stereo to mono (if needed)
590 		if (numChannels == 2)
591 		{
592 			sampleLength >>= 1;
593 			for (i = 0; i < sampleLength-1; i++) // add right channel to left channel
594 				dAudioDataDouble[i] = (dAudioDataDouble[(i * 2) + 0] + dAudioDataDouble[(i * 2) + 1]) * 0.5;
595 		}
596 
597 		// 2x downsampling
598 		if (forceDownSampling)
599 		{
600 			downsample2xDouble(dAudioDataDouble, sampleLength);
601 			sampleLength >>= 1;
602 		}
603 
604 		if (sampleLength > MAX_SAMPLE_LEN)
605 			sampleLength = MAX_SAMPLE_LEN;
606 
607 		double dAmp = 1.0;
608 		const double dPeak = getDoublePeak(dAudioDataDouble, sampleLength);
609 		if (dPeak > 0.0)
610 			dAmp = INT8_MAX / dPeak;
611 
612 		turnOffVoices();
613 		for (i = 0; i < sampleLength; i++)
614 		{
615 			smp32 = (int32_t)round(dAudioDataDouble[i] * dAmp);
616 			assert(smp32 >= -128 && smp32 <= 127); // shouldn't happen according to dAmp (but just in case)
617 			smpPtr[i] = (int8_t)smp32;
618 		}
619 
620 		free(audioDataU32);
621 	}
622 
623 	if (sampleLength < MAX_SAMPLE_LEN) // clear rest of sample data
624 		memset(&song->sampleData[s->offset + sampleLength], 0, MAX_SAMPLE_LEN - sampleLength);
625 
626 	// set sample length
627 	if (sampleLength & 1)
628 	{
629 		if (++sampleLength > MAX_SAMPLE_LEN)
630 			sampleLength = MAX_SAMPLE_LEN;
631 	}
632 
633 	s->length = (uint16_t)sampleLength;
634 	s->fineTune = 0;
635 	s->volume = 64;
636 	s->loopStart = 0;
637 	s->loopLength = 2;
638 
639 	// ---- READ "smpl" chunk ----
640 	if (smplPtr != 0 && smplLen > 52)
641 	{
642 		fseek(f, smplPtr + 28, SEEK_SET); // seek to first wanted byte
643 
644 		fread(&loopFlags, 4, 1, f);
645 		fseek(f, 12, SEEK_CUR);
646 		fread(&loopStart, 4, 1, f);
647 		fread(&loopEnd, 4, 1, f);
648 		loopEnd++;
649 
650 		if (forceDownSampling)
651 		{
652 			// we already downsampled 2x, so we're half the original length
653 			loopStart >>= 1;
654 			loopEnd >>= 1;
655 		}
656 
657 		loopStart &= 0xFFFFFFFE;
658 		loopEnd &= 0xFFFFFFFE;
659 
660 		if (loopFlags)
661 		{
662 			if (loopStart+(loopEnd-loopStart) <= s->length)
663 			{
664 				s->loopStart = (uint16_t)loopStart;
665 				s->loopLength = (uint16_t)(loopEnd - loopStart);
666 
667 				if (s->loopLength < 2)
668 				{
669 					s->loopStart = 0;
670 					s->loopLength = 2;
671 				}
672 			}
673 		}
674 	}
675 	// ---------------------------
676 
677 	// ---- READ "xtra" chunk ----
678 	if (xtraPtr != 0 && xtraLen >= 8)
679 	{
680 		fseek(f, xtraPtr + 4, SEEK_SET); // seek to first wanted byte
681 
682 		// volume (0..256)
683 		fseek(f, 2, SEEK_CUR);
684 		fread(&tempVol, 2, 1, f);
685 		if (tempVol > 256)
686 			tempVol = 256;
687 
688 		tempVol >>= 2; // 0..256 -> 0..64
689 
690 		s->volume = (int8_t)tempVol;
691 	}
692 	// ---------------------------
693 
694 	// ---- READ "INAM" chunk ----
695 	if (inamPtr != 0 && inamLen > 0)
696 	{
697 		fseek(f, inamPtr, SEEK_SET); // seek to first wanted byte
698 
699 		for (i = 0; i < 21; i++)
700 		{
701 			if (i < inamLen)
702 				s->text[i] = (char)fgetc(f);
703 			else
704 				s->text[i] = '\0';
705 		}
706 
707 		s->text[21] = '\0';
708 		s->text[22] = '\0';
709 
710 		wavSampleNameFound = true;
711 	}
712 	// ---------------------------
713 
714 	fclose(f);
715 
716 	// copy over sample name
717 	if (!wavSampleNameFound)
718 	{
719 		nameLen = (uint32_t)strlen(entryName);
720 		for (i = 0; i < 21; i++)
721 			s->text[i] = (i < nameLen) ? (char)entryName[i] : '\0';
722 
723 		s->text[21] = '\0';
724 		s->text[22] = '\0';
725 	}
726 
727 	// remove .wav from end of sample name (if present)
728 	nameLen = (uint32_t)strlen(s->text);
729 	if (nameLen >= 4 && !_strnicmp(&s->text[nameLen-4], ".WAV", 4))
730 		 memset(&s->text[nameLen-4], '\0', 4);
731 
732 	editor.sampleZero = false;
733 	editor.samplePos = 0;
734 
735 	fixSampleBeep(s);
736 	fillSampleRedoBuffer(editor.currSample);
737 
738 	if (ui.samplingBoxShown)
739 	{
740 		removeSamplingBox();
741 		ui.samplingBoxShown = false;
742 	}
743 
744 	updateCurrSample();
745 
746 	updateWindowTitle(MOD_IS_MODIFIED);
747 	return true;
748 }
749 
loadIFFSample(UNICHAR * fileName,char * entryName,int8_t forceDownSampling)750 bool loadIFFSample(UNICHAR *fileName, char *entryName, int8_t forceDownSampling)
751 {
752 	bool nameFound, is16Bit;
753 	char tmpCharBuf[23];
754 	int8_t *sampleData;
755 	int16_t *ptr16;
756 	int32_t filesize, smp32;
757 	uint16_t sampleRate;
758 	uint32_t i, sampleLength, sampleLoopStart, sampleLoopLength;
759 	uint32_t sampleVolume, blockName, blockSize;
760 	uint32_t vhdrPtr, vhdrLen, bodyPtr, bodyLen, namePtr, nameLen;
761 	FILE *f;
762 	moduleSample_t *s;
763 
764 	loadedSampleType = SAMPLE_IFF;
765 
766 	s = &song->samples[editor.currSample];
767 
768 	vhdrPtr = 0; vhdrLen = 0;
769 	bodyPtr = 0; bodyLen = 0;
770 	namePtr = 0; nameLen = 0;
771 
772 	if (forceDownSampling == -1)
773 	{
774 		// these two *must* be fully wiped, for outputting reasons
775 		memset(editor.fileNameTmpU, 0, PATH_MAX);
776 		memset(editor.entryNameTmp, 0, PATH_MAX);
777 		UNICHAR_STRCPY(editor.fileNameTmpU, fileName);
778 		strcpy(editor.entryNameTmp, entryName);
779 	}
780 
781 	f = UNICHAR_FOPEN(fileName, "rb");
782 	if (f == NULL)
783 	{
784 		displayErrorMsg("FILE I/O ERROR !");
785 		return false;
786 	}
787 
788 	fseek(f, 0, SEEK_END);
789 	filesize = ftell(f);
790 	if (filesize == 0)
791 	{
792 		displayErrorMsg("IFF IS CORRUPT !");
793 		return false;
794 	}
795 
796 	fseek(f, 8, SEEK_SET);
797 	fread(tmpCharBuf, 1, 4, f);
798 	is16Bit = !strncmp(tmpCharBuf, "16SV", 4);
799 
800 	sampleLength = 0;
801 	nameFound = false;
802 	sampleVolume = 65536; // max volume
803 
804 	fseek(f, 12, SEEK_SET);
805 	while (!feof(f) && ftell(f) < filesize-12)
806 	{
807 		fread(&blockName, 4, 1, f); if (feof(f)) break;
808 		fread(&blockSize, 4, 1, f); if (feof(f)) break;
809 
810 		blockName = SWAP32(blockName);
811 		blockSize = SWAP32(blockSize);
812 
813 		switch (blockName)
814 		{
815 			case 0x56484452: // VHDR
816 			{
817 				vhdrPtr = ftell(f);
818 				vhdrLen = blockSize;
819 			}
820 			break;
821 
822 			case 0x4E414D45: // NAME
823 			{
824 				namePtr = ftell(f);
825 				nameLen = blockSize;
826 			}
827 			break;
828 
829 			case 0x424F4459: // BODY
830 			{
831 				bodyPtr = ftell(f);
832 				bodyLen = blockSize;
833 			}
834 			break;
835 
836 			default: break;
837 		}
838 
839 		fseek(f, blockSize + (blockSize & 1), SEEK_CUR);
840 	}
841 
842 	if (vhdrPtr == 0 || vhdrLen < 20 || bodyPtr == 0)
843 	{
844 		fclose(f);
845 		displayErrorMsg("NOT A VALID IFF !");
846 		return false;
847 	}
848 
849 	// kludge for some really strange IFFs
850 	if (bodyLen == 0)
851 		bodyLen = filesize - bodyPtr;
852 
853 	if (bodyPtr+bodyLen > (uint32_t)filesize)
854 		bodyLen = filesize - bodyPtr;
855 
856 	fseek(f, vhdrPtr, SEEK_SET);
857 	fread(&sampleLoopStart,  4, 1, f); sampleLoopStart  = SWAP32(sampleLoopStart);
858 	fread(&sampleLoopLength, 4, 1, f); sampleLoopLength = SWAP32(sampleLoopLength);
859 	fseek(f, 4, SEEK_CUR);
860 	fread(&sampleRate, 2, 1, f); sampleRate = SWAP16(sampleRate);
861 	fseek(f, 1, SEEK_CUR);
862 
863 	if (fgetc(f) != 0) // sample type
864 	{
865 		fclose(f);
866 		displayErrorMsg("UNSUPPORTED IFF !");
867 		return false;
868 	}
869 
870 	fread(&sampleVolume, 4, 1, f); sampleVolume = SWAP32(sampleVolume);
871 	if (sampleVolume > 65536)
872 		sampleVolume = 65536;
873 
874 	sampleVolume = (sampleVolume + 512) / 1024; // rounded
875 	if (sampleVolume > 64)
876 		sampleVolume = 64;
877 
878 	sampleLength = bodyLen;
879 
880 	if (sampleLength == 0)
881 	{
882 		fclose(f);
883 		displayErrorMsg("NOT A VALID IFF !");
884 		return false;
885 	}
886 
887 	if (sampleRate > 22050 && !config.noDownsampleOnSmpLoad)
888 	{
889 		if (forceDownSampling == -1)
890 		{
891 			showDownsampleAskDialog();
892 			fclose(f);
893 			return true;
894 		}
895 	}
896 	else
897 	{
898 		forceDownSampling = false;
899 	}
900 
901 	uint32_t maxSampleLength = MAX_SAMPLE_LEN;
902 	if (is16Bit)
903 		maxSampleLength *= 2;
904 
905 	if (forceDownSampling)
906 		maxSampleLength *= 2;
907 
908 	if (sampleLength > maxSampleLength)
909 		sampleLength = maxSampleLength;
910 
911 	sampleData = (int8_t *)malloc(sampleLength);
912 	if (sampleData == NULL)
913 	{
914 		fclose(f);
915 		statusOutOfMemory();
916 		return false;
917 	}
918 
919 	if (is16Bit)
920 	{
921 		sampleLength >>= 1;
922 		sampleLoopStart >>= 1;
923 		sampleLoopLength >>= 1;
924 	}
925 
926 	if (forceDownSampling)
927 	{
928 		sampleLoopStart >>= 1;
929 		sampleLoopLength >>= 1;
930 	}
931 
932 	turnOffVoices();
933 
934 	fseek(f, bodyPtr, SEEK_SET);
935 	if (is16Bit) // FT2-specific 16SV format (little-endian samples)
936 	{
937 		fread(sampleData, 1, sampleLength << 1, f);
938 		ptr16 = (int16_t *)sampleData;
939 
940 		// 2x downsampling
941 		if (forceDownSampling)
942 		{
943 			downsample2x16Bit(ptr16, sampleLength);
944 			sampleLength >>= 1;
945 		}
946 
947 		if (sampleLength > MAX_SAMPLE_LEN)
948 			sampleLength = MAX_SAMPLE_LEN;
949 
950 		double dAmp = 1.0;
951 		if (forceDownSampling) // we already normalized
952 		{
953 			dAmp = INT8_MAX / (double)INT16_MAX;
954 		}
955 		else
956 		{
957 			const double dPeak = get16BitPeak(ptr16, sampleLength);
958 			if (dPeak > 0.0)
959 				dAmp = INT8_MAX / dPeak;
960 		}
961 
962 		int8_t *smpPtr = &song->sampleData[s->offset];
963 		for (i = 0; i < sampleLength; i++)
964 		{
965 			smp32 = (int32_t)round(ptr16[i] * dAmp);
966 			assert(smp32 >= -128 && smp32 <= 127); // shouldn't happen according to dAmp (but just in case)
967 			smpPtr[i] = (int8_t)smp32;
968 		}
969 	}
970 	else
971 	{
972 		fread(sampleData, 1, sampleLength, f);
973 
974 		// 2x downsampling
975 		if (forceDownSampling)
976 		{
977 			downsample2x8Bit(sampleData, sampleLength);
978 			sampleLength >>= 1;
979 		}
980 
981 		if (sampleLength > MAX_SAMPLE_LEN)
982 			sampleLength = MAX_SAMPLE_LEN;
983 
984 		memcpy(&song->sampleData[s->offset], sampleData, sampleLength);
985 	}
986 
987 	free(sampleData);
988 
989 	if (sampleLength < MAX_SAMPLE_LEN) // clear rest of sample data
990 		memset(&song->sampleData[s->offset + sampleLength], 0, MAX_SAMPLE_LEN - sampleLength);
991 
992 	// set sample length
993 	if (sampleLength & 1)
994 	{
995 		if (++sampleLength > MAX_SAMPLE_LEN)
996 			sampleLength = MAX_SAMPLE_LEN;
997 	}
998 
999 	sampleLoopStart &= 0xFFFFFFFE;
1000 	sampleLoopLength &= 0xFFFFFFFE;
1001 
1002 	if (sampleLoopLength < 2)
1003 	{
1004 		sampleLoopStart = 0;
1005 		sampleLoopLength = 2;
1006 	}
1007 
1008 	if (sampleLoopStart >= sampleLength || sampleLoopLength > sampleLength)
1009 	{
1010 		sampleLoopStart = 0;
1011 		sampleLoopLength = 2;
1012 	}
1013 
1014 	if (sampleLoopStart+sampleLoopLength > sampleLength)
1015 	{
1016 		sampleLoopStart = 0;
1017 		sampleLoopLength = 2;
1018 	}
1019 
1020 	if (sampleLoopStart > sampleLength-2)
1021 	{
1022 		sampleLoopStart = 0;
1023 		sampleLoopLength = 2;
1024 	}
1025 
1026 	// set sample attributes
1027 	s->volume = (int8_t)sampleVolume;
1028 	s->fineTune = 0;
1029 	s->length = (uint16_t)sampleLength;
1030 	s->loopStart = (uint16_t)sampleLoopStart;
1031 	s->loopLength = (uint16_t)sampleLoopLength;
1032 
1033 	// read name
1034 	if (namePtr != 0 && nameLen > 0)
1035 	{
1036 		fseek(f, namePtr, SEEK_SET);
1037 		memset(tmpCharBuf, 0, sizeof (tmpCharBuf));
1038 
1039 		if (nameLen > 21)
1040 		{
1041 			fread(tmpCharBuf, 1, 21, f);
1042 			fseek(f, nameLen - 21, SEEK_CUR);
1043 		}
1044 		else
1045 		{
1046 			fread(tmpCharBuf, 1, nameLen, f);
1047 		}
1048 
1049 		nameFound = true;
1050 	}
1051 
1052 	fclose(f);
1053 
1054 	// copy over sample name
1055 	memset(s->text, '\0', sizeof (s->text));
1056 
1057 	if (nameFound)
1058 	{
1059 		nameLen = (uint32_t)strlen(tmpCharBuf);
1060 		if (nameLen > 21)
1061 			nameLen = 21;
1062 
1063 		memcpy(s->text, tmpCharBuf, nameLen);
1064 	}
1065 	else
1066 	{
1067 		nameLen = (uint32_t)strlen(entryName);
1068 		if (nameLen > 21)
1069 			nameLen = 21;
1070 
1071 		memcpy(s->text, entryName, nameLen);
1072 	}
1073 
1074 	// remove .iff from end of sample name (if present)
1075 	nameLen = (uint32_t)strlen(s->text);
1076 	if (nameLen >= 4 && !strncmp(&s->text[nameLen-4], ".IFF", 4))
1077 		memset(&s->text[nameLen-4], '\0', 4);
1078 
1079 	editor.sampleZero = false;
1080 	editor.samplePos = 0;
1081 
1082 	fixSampleBeep(s);
1083 	fillSampleRedoBuffer(editor.currSample);
1084 	updateCurrSample();
1085 
1086 	updateWindowTitle(MOD_IS_MODIFIED);
1087 	return false;
1088 }
1089 
loadRAWSample(UNICHAR * fileName,char * entryName)1090 bool loadRAWSample(UNICHAR *fileName, char *entryName)
1091 {
1092 	uint8_t i;
1093 	uint32_t nameLen, fileSize;
1094 	FILE *f;
1095 	moduleSample_t *s;
1096 
1097 	s = &song->samples[editor.currSample];
1098 
1099 	f = UNICHAR_FOPEN(fileName, "rb");
1100 	if (f == NULL)
1101 	{
1102 		displayErrorMsg("FILE I/O ERROR !");
1103 		return false;
1104 	}
1105 
1106 	fseek(f, 0, SEEK_END);
1107 	fileSize = ftell(f);
1108 	fseek(f, 0, SEEK_SET);
1109 
1110 	fileSize &= 0xFFFFFFFE;
1111 	if (fileSize > MAX_SAMPLE_LEN)
1112 		fileSize = MAX_SAMPLE_LEN;
1113 
1114 	turnOffVoices();
1115 
1116 	fread(&song->sampleData[s->offset], 1, fileSize, f);
1117 	fclose(f);
1118 
1119 	if (fileSize < MAX_SAMPLE_LEN)
1120 		memset(&song->sampleData[s->offset + fileSize], 0, MAX_SAMPLE_LEN - fileSize);
1121 
1122 	// set sample attributes
1123 	s->volume = 64;
1124 	s->fineTune = 0;
1125 	s->length = (uint16_t)fileSize;
1126 	s->loopStart = 0;
1127 	s->loopLength = 2;
1128 
1129 	// copy over sample name
1130 	nameLen = (uint32_t)strlen(entryName);
1131 	for (i = 0; i < 21; i++)
1132 		s->text[i] = (i < nameLen) ? (char)entryName[i] : '\0';
1133 
1134 	s->text[21] = '\0';
1135 	s->text[22] = '\0';
1136 
1137 	editor.sampleZero = false;
1138 	editor.samplePos = 0;
1139 
1140 	fixSampleBeep(s);
1141 	fillSampleRedoBuffer(editor.currSample);
1142 
1143 	if (ui.samplingBoxShown)
1144 	{
1145 		removeSamplingBox();
1146 		ui.samplingBoxShown = false;
1147 	}
1148 
1149 	updateCurrSample();
1150 
1151 	updateWindowTitle(MOD_IS_MODIFIED);
1152 	return true;
1153 }
1154 
getAIFFRate(uint8_t * in)1155 static int32_t getAIFFRate(uint8_t *in)
1156 {
1157 	int32_t exp;
1158 	uint32_t lo, hi;
1159 	double dOut;
1160 
1161 	exp = (int32_t)(((in[0] & 0x7F) << 8) | in[1]);
1162 	lo  = (in[2] << 24) | (in[3] << 16) | (in[4] << 8) | in[5];
1163 	hi  = (in[6] << 24) | (in[7] << 16) | (in[8] << 8) | in[9];
1164 
1165 	if (exp == 0 && lo == 0 && hi == 0)
1166 		return 0;
1167 
1168 	exp -= 16383;
1169 
1170 	dOut = ldexp(lo, -31 + exp) + ldexp(hi, -63 + exp);
1171 	return (int32_t)(dOut + 0.5);
1172 }
1173 
loadAIFFSample(UNICHAR * fileName,char * entryName,int8_t forceDownSampling)1174 bool loadAIFFSample(UNICHAR *fileName, char *entryName, int8_t forceDownSampling)
1175 {
1176 	bool unsigned8bit;
1177 	char compType[4];
1178 	int8_t *audioDataS8;
1179 	uint8_t *audioDataU8, sampleRateBytes[10];
1180 	int16_t *audioDataS16;
1181 	uint16_t bitDepth, numChannels;
1182 	int32_t filesize, *audioDataS32, smp32;
1183 	uint32_t nameLen, i, offset, sampleRate, sampleLength, blockName, blockSize;
1184 	uint32_t commPtr, commLen, ssndPtr, ssndLen;
1185 	FILE *f;
1186 	moduleSample_t *s;
1187 
1188 	unsigned8bit = false;
1189 	loadedSampleType = SAMPLE_AIFF;
1190 
1191 	if (forceDownSampling == -1)
1192 	{
1193 		// these two *must* be fully wiped, for outputting reasons
1194 		memset(editor.fileNameTmpU, 0, PATH_MAX);
1195 		memset(editor.entryNameTmp, 0, PATH_MAX);
1196 		UNICHAR_STRCPY(editor.fileNameTmpU, fileName);
1197 		strcpy(editor.entryNameTmp, entryName);
1198 	}
1199 
1200 	s = &song->samples[editor.currSample];
1201 
1202 	commPtr = 0; commLen = 0;
1203 	ssndPtr = 0; ssndLen = 0;
1204 
1205 	f = UNICHAR_FOPEN(fileName, "rb");
1206 	if (f == NULL)
1207 	{
1208 		displayErrorMsg("FILE I/O ERROR !");
1209 		return false;
1210 	}
1211 
1212 	fseek(f, 0, SEEK_END);
1213 	filesize = ftell(f);
1214 	if (filesize == 0)
1215 	{
1216 		displayErrorMsg("AIFF IS CORRUPT !");
1217 		return false;
1218 	}
1219 
1220 	fseek(f, 12, SEEK_SET);
1221 	while (!feof(f) && ftell(f) < filesize-12)
1222 	{
1223 		fread(&blockName, 4, 1, f); if (feof(f)) break;
1224 		fread(&blockSize, 4, 1, f); if (feof(f)) break;
1225 
1226 		blockName = SWAP32(blockName);
1227 		blockSize = SWAP32(blockSize);
1228 
1229 		switch (blockName)
1230 		{
1231 			case 0x434F4D4D: // "COMM"
1232 			{
1233 				commPtr = ftell(f);
1234 				commLen = blockSize;
1235 			}
1236 			break;
1237 
1238 			case 0x53534E44: // "SSND"
1239 			{
1240 				ssndPtr = ftell(f);
1241 				ssndLen = blockSize;
1242 			}
1243 			break;
1244 
1245 			default: break;
1246 		}
1247 
1248 		fseek(f, blockSize + (blockSize & 1), SEEK_CUR);
1249 	}
1250 
1251 	if (commPtr == 0 || commLen < 18 || ssndPtr == 0)
1252 	{
1253 		fclose(f);
1254 		displayErrorMsg("NOT A VALID AIFF!");
1255 		return false;
1256 	}
1257 
1258 	// kludge for some really strange AIFFs
1259 	if (ssndLen == 0)
1260 		ssndLen = filesize - ssndPtr;
1261 
1262 	if (ssndPtr+ssndLen > (uint32_t)filesize)
1263 		ssndLen = filesize - ssndPtr;
1264 
1265 	fseek(f, commPtr, SEEK_SET);
1266 	fread(&numChannels, 2, 1, f); numChannels = SWAP16(numChannels);
1267 	fseek(f, 4, SEEK_CUR);
1268 	fread(&bitDepth, 2, 1, f); bitDepth = SWAP16(bitDepth);
1269 	fread(sampleRateBytes, 1, 10, f);
1270 
1271 	fseek(f, 4 + 2 + 1, SEEK_CUR);
1272 
1273 	if (numChannels != 1 && numChannels != 2) // sample type
1274 	{
1275 		fclose(f);
1276 		displayErrorMsg("UNSUPPORTED AIFF!");
1277 		return false;
1278 	}
1279 
1280 	if (bitDepth != 8 && bitDepth != 16 && bitDepth != 24 && bitDepth != 32)
1281 	{
1282 		fclose(f);
1283 		displayErrorMsg("UNSUPPORTED AIFF!");
1284 		return false;
1285 	}
1286 
1287 	// read compression type (if present)
1288 	if (commLen > 18)
1289 	{
1290 		fread(&compType, 1, 4, f);
1291 		if (memcmp(compType, "NONE", 4))
1292 		{
1293 			fclose(f);
1294 			displayErrorMsg("UNSUPPORTED AIFF!");
1295 			return false;
1296 		}
1297 	}
1298 
1299 	sampleRate = getAIFFRate(sampleRateBytes);
1300 
1301 	// sample data chunk
1302 
1303 	fseek(f, ssndPtr, SEEK_SET);
1304 
1305 	fread(&offset, 4, 1, f);
1306 	if (offset > 0)
1307 	{
1308 		fclose(f);
1309 		displayErrorMsg("UNSUPPORTED AIFF!");
1310 		return false;
1311 	}
1312 
1313 	fseek(f, 4, SEEK_CUR);
1314 
1315 	ssndLen -= 8; // don't include offset and blockSize datas
1316 
1317 	sampleLength = ssndLen;
1318 	if (sampleLength == 0)
1319 	{
1320 		fclose(f);
1321 		displayErrorMsg("NOT A VALID AIFF!");
1322 		return false;
1323 	}
1324 
1325 	if (sampleRate > 22050 && !config.noDownsampleOnSmpLoad)
1326 	{
1327 		if (forceDownSampling == -1)
1328 		{
1329 			showDownsampleAskDialog();
1330 			fclose(f);
1331 			return true;
1332 		}
1333 	}
1334 	else
1335 	{
1336 		forceDownSampling = false;
1337 	}
1338 
1339 	int8_t *smpPtr = &song->sampleData[editor.currSample * MAX_SAMPLE_LEN];
1340 
1341 	if (bitDepth == 8) // 8-BIT INTEGER SAMPLE
1342 	{
1343 		if (sampleLength > MAX_SAMPLE_LEN*4)
1344 			sampleLength = MAX_SAMPLE_LEN*4;
1345 
1346 		audioDataS8 = (int8_t *)malloc(sampleLength * sizeof (int8_t));
1347 		if (audioDataS8 == NULL)
1348 		{
1349 			fclose(f);
1350 			statusOutOfMemory();
1351 			return false;
1352 		}
1353 
1354 		// read sample data
1355 		if (fread(audioDataS8, 1, sampleLength, f) != sampleLength)
1356 		{
1357 			fclose(f);
1358 			free(audioDataS8);
1359 			displayErrorMsg("I/O ERROR !");
1360 			return false;
1361 		}
1362 
1363 		if (unsigned8bit)
1364 		{
1365 			for (i = 0; i < sampleLength; i++)
1366 				audioDataS8[i] ^= 0x80;
1367 		}
1368 
1369 		// convert from stereo to mono (if needed)
1370 		if (numChannels == 2)
1371 		{
1372 			sampleLength >>= 1;
1373 			for (i = 0; i < sampleLength-1; i++) // add right channel to left channel
1374 				audioDataS8[i] = (audioDataS8[(i * 2) + 0] + audioDataS8[(i * 2) + 1]) >> 1;;
1375 		}
1376 
1377 		// 2x downsampling
1378 		if (forceDownSampling)
1379 		{
1380 			downsample2x8Bit(audioDataS8, sampleLength);
1381 			sampleLength >>= 1;
1382 		}
1383 
1384 		if (sampleLength > MAX_SAMPLE_LEN)
1385 			sampleLength = MAX_SAMPLE_LEN;
1386 
1387 		turnOffVoices();
1388 		for (i = 0; i < sampleLength; i++)
1389 			smpPtr[i] = audioDataS8[i];
1390 
1391 		free(audioDataS8);
1392 	}
1393 	else if (bitDepth == 16) // 16-BIT INTEGER SAMPLE
1394 	{
1395 		sampleLength >>= 1;
1396 		if (sampleLength > MAX_SAMPLE_LEN*4)
1397 			sampleLength = MAX_SAMPLE_LEN*4;
1398 
1399 		audioDataS16 = (int16_t *)malloc(sampleLength * sizeof (int16_t));
1400 		if (audioDataS16 == NULL)
1401 		{
1402 			fclose(f);
1403 			statusOutOfMemory();
1404 			return false;
1405 		}
1406 
1407 		// read sample data
1408 		if (fread(audioDataS16, 2, sampleLength, f) != sampleLength)
1409 		{
1410 			fclose(f);
1411 			free(audioDataS16);
1412 			displayErrorMsg("I/O ERROR !");
1413 			return false;
1414 		}
1415 
1416 		// fix endianness
1417 		for (i = 0; i < sampleLength; i++)
1418 			audioDataS16[i] = SWAP16(audioDataS16[i]);
1419 
1420 		// convert from stereo to mono (if needed)
1421 		if (numChannels == 2)
1422 		{
1423 			sampleLength >>= 1;
1424 			for (i = 0; i < sampleLength-1; i++) // add right channel to left channel
1425 				audioDataS16[i] = (audioDataS16[(i << 1) + 0] + audioDataS16[(i << 1) + 1]) >> 1;
1426 		}
1427 
1428 		// 2x downsampling
1429 		if (forceDownSampling)
1430 		{
1431 			downsample2x16Bit(audioDataS16, sampleLength);
1432 			sampleLength >>= 1;
1433 		}
1434 
1435 		if (sampleLength > MAX_SAMPLE_LEN)
1436 			sampleLength = MAX_SAMPLE_LEN;
1437 
1438 		double dAmp = 1.0;
1439 		if (forceDownSampling) // we already normalized
1440 		{
1441 			dAmp = INT8_MAX / (double)INT16_MAX;
1442 		}
1443 		else
1444 		{
1445 			const double dPeak = get16BitPeak(audioDataS16, sampleLength);
1446 			if (dPeak > 0.0)
1447 				dAmp = INT8_MAX / dPeak;
1448 		}
1449 
1450 		turnOffVoices();
1451 		for (i = 0; i < sampleLength; i++)
1452 		{
1453 			smp32 = (int32_t)round(audioDataS16[i] * dAmp);
1454 			assert(smp32 >= -128 && smp32 <= 127); // shouldn't happen according to dAmp (but just in case)
1455 			smpPtr[i] = (int8_t)smp32;
1456 		}
1457 
1458 		free(audioDataS16);
1459 	}
1460 	else if (bitDepth == 24) // 24-BIT INTEGER SAMPLE
1461 	{
1462 		sampleLength /= 3;
1463 		if (sampleLength > MAX_SAMPLE_LEN*4)
1464 			sampleLength = MAX_SAMPLE_LEN*4;
1465 
1466 		audioDataS32 = (int32_t *)malloc(sampleLength * sizeof (int32_t));
1467 		if (audioDataS32 == NULL)
1468 		{
1469 			fclose(f);
1470 			statusOutOfMemory();
1471 			return false;
1472 		}
1473 
1474 		// read sample data
1475 		if (fread(&audioDataS32[sampleLength >> 2], 3, sampleLength, f) != sampleLength)
1476 		{
1477 			fclose(f);
1478 			free(audioDataS32);
1479 			displayErrorMsg("I/O ERROR !");
1480 			return false;
1481 		}
1482 
1483 		// convert to 32-bit
1484 		audioDataU8 = (uint8_t *)audioDataS32 + sampleLength;
1485 		for (i = 0; i < sampleLength; i++)
1486 		{
1487 			audioDataS32[i] = (audioDataU8[0] << 24) | (audioDataU8[1] << 16) | (audioDataU8[2] << 8);
1488 			audioDataU8 += 3;
1489 		}
1490 
1491 		// convert from stereo to mono (if needed)
1492 		if (numChannels == 2)
1493 		{
1494 			sampleLength >>= 1;
1495 			for (i = 0; i < sampleLength-1; i++) // add right channel to left channel
1496 			{
1497 				int64_t smp = ((int64_t)audioDataS32[(i << 1) + 0] + audioDataS32[(i << 1) + 1]) >> 1;
1498 				audioDataS32[i] = (int32_t)smp;
1499 			}
1500 		}
1501 
1502 		// 2x downsampling
1503 		if (forceDownSampling)
1504 		{
1505 			downsample2x32Bit(audioDataS32, sampleLength);
1506 			sampleLength >>= 1;
1507 		}
1508 
1509 		if (sampleLength > MAX_SAMPLE_LEN)
1510 			sampleLength = MAX_SAMPLE_LEN;
1511 
1512 		double dAmp = 1.0;
1513 		if (forceDownSampling) // we already normalized
1514 		{
1515 			dAmp = INT8_MAX / (double)INT32_MAX;
1516 		}
1517 		else
1518 		{
1519 			const double dPeak = get32BitPeak(audioDataS32, sampleLength);
1520 			if (dPeak > 0.0)
1521 				dAmp = INT8_MAX / dPeak;
1522 		}
1523 
1524 		turnOffVoices();
1525 		for (i = 0; i < sampleLength; i++)
1526 		{
1527 			smp32 = (int32_t)round(audioDataS32[i] * dAmp);
1528 			smpPtr[i] = (int8_t)smp32;
1529 		}
1530 
1531 		free(audioDataS32);
1532 	}
1533 	else if (bitDepth == 32) // 32-BIT INTEGER SAMPLE
1534 	{
1535 		sampleLength >>= 2;
1536 		if (sampleLength > MAX_SAMPLE_LEN*4)
1537 			sampleLength = MAX_SAMPLE_LEN*4;
1538 
1539 		audioDataS32 = (int32_t *)malloc(sampleLength * sizeof (int32_t));
1540 		if (audioDataS32 == NULL)
1541 		{
1542 			fclose(f);
1543 			statusOutOfMemory();
1544 			return false;
1545 		}
1546 
1547 		// read sample data
1548 		if (fread(audioDataS32, 4, sampleLength, f) != sampleLength)
1549 		{
1550 			fclose(f);
1551 			free(audioDataS32);
1552 			displayErrorMsg("I/O ERROR !");
1553 			return false;
1554 		}
1555 
1556 		// fix endianness
1557 		for (i = 0; i < sampleLength; i++)
1558 			audioDataS32[i] = SWAP32(audioDataS32[i]);
1559 
1560 		// convert from stereo to mono (if needed)
1561 		if (numChannels == 2)
1562 		{
1563 			sampleLength >>= 1;
1564 			for (i = 0; i < sampleLength-1; i++) // add right channel to left channel
1565 			{
1566 				int64_t smp = ((int64_t)audioDataS32[(i << 1) + 0] + audioDataS32[(i << 1) + 1]) >> 1;
1567 				audioDataS32[i] = (int32_t)smp;
1568 			}
1569 		}
1570 
1571 		// 2x downsampling
1572 		if (forceDownSampling)
1573 		{
1574 			downsample2x32Bit(audioDataS32, sampleLength);
1575 			sampleLength >>= 1;
1576 		}
1577 
1578 		if (sampleLength > MAX_SAMPLE_LEN)
1579 			sampleLength = MAX_SAMPLE_LEN;
1580 
1581 		double dAmp = 1.0;
1582 		if (forceDownSampling) // we already normalized
1583 		{
1584 			dAmp = INT8_MAX / (double)INT32_MAX;
1585 		}
1586 		else
1587 		{
1588 			const double dPeak = get32BitPeak(audioDataS32, sampleLength);
1589 			if (dPeak > 0.0)
1590 				dAmp = INT8_MAX / dPeak;
1591 		}
1592 
1593 		turnOffVoices();
1594 		for (i = 0; i < sampleLength; i++)
1595 		{
1596 			smp32 = (int32_t)round(audioDataS32[i] * dAmp);
1597 			smpPtr[i] = (int8_t)smp32;
1598 		}
1599 
1600 		free(audioDataS32);
1601 	}
1602 
1603 	if (sampleLength < MAX_SAMPLE_LEN) // clear rest of sample data
1604 		memset(&song->sampleData[s->offset + sampleLength], 0, MAX_SAMPLE_LEN - sampleLength);
1605 
1606 	// set sample length
1607 	if (sampleLength & 1)
1608 	{
1609 		if (++sampleLength > MAX_SAMPLE_LEN)
1610 			sampleLength = MAX_SAMPLE_LEN;
1611 	}
1612 
1613 	s->length = (uint16_t)sampleLength;
1614 	s->fineTune = 0;
1615 	s->volume = 64;
1616 	s->loopStart = 0;
1617 	s->loopLength = 2;
1618 
1619 	fclose(f);
1620 
1621 	// copy over sample name
1622 	nameLen = (uint32_t)strlen(entryName);
1623 	for (i = 0; i < 21; i++)
1624 		s->text[i] = (i < nameLen) ? (char)entryName[i] : '\0';
1625 
1626 	s->text[21] = '\0';
1627 	s->text[22] = '\0';
1628 
1629 	// remove .aiff from end of sample name (if present)
1630 	nameLen = (uint32_t)strlen(s->text);
1631 	if (nameLen >= 5 && !_strnicmp(&s->text[nameLen-5], ".AIFF", 5))
1632 		memset(&s->text[nameLen-5], '\0', 5);
1633 
1634 	editor.sampleZero = false;
1635 	editor.samplePos = 0;
1636 
1637 	fixSampleBeep(s);
1638 	fillSampleRedoBuffer(editor.currSample);
1639 
1640 	if (ui.samplingBoxShown)
1641 	{
1642 		removeSamplingBox();
1643 		ui.samplingBoxShown = false;
1644 	}
1645 
1646 	updateCurrSample();
1647 
1648 	updateWindowTitle(MOD_IS_MODIFIED);
1649 	return true;
1650 }
1651 
loadSample(UNICHAR * fileName,char * entryName)1652 bool loadSample(UNICHAR *fileName, char *entryName)
1653 {
1654 	uint32_t fileSize, ID;
1655 	FILE *f;
1656 
1657 	if (editor.sampleZero)
1658 	{
1659 		statusNotSampleZero();
1660 		return false;
1661 	}
1662 
1663 	f = UNICHAR_FOPEN(fileName, "rb");
1664 	if (f == NULL)
1665 	{
1666 		displayErrorMsg("FILE I/O ERROR !");
1667 		return false;
1668 	}
1669 
1670 	fseek(f, 0, SEEK_END);
1671 	fileSize = ftell(f);
1672 	fseek(f, 0, SEEK_SET);
1673 
1674 	// first, check heades before we eventually load as RAW
1675 	if (fileSize > 16)
1676 	{
1677 		fread(&ID, 4, 1, f);
1678 
1679 		/* Reject FLAC files, since they are not supported.
1680 		** This is a dumb test since any sample *could* start
1681 		** with "fLaC", but in 99.999% of cases it won't happen.
1682 		*/
1683 		if (ID == 0x43614C66) // "fLaC"
1684 		{
1685 			displayErrorMsg("NOT SUPPORTED !");
1686 			return false;
1687 		}
1688 
1689 		// check if it's actually a WAV sample
1690 		if (ID == 0x46464952) // "RIFF"
1691 		{
1692 			fseek(f, 4, SEEK_CUR);
1693 			fread(&ID, 4, 1, f);
1694 
1695 			if (ID == 0x45564157) // "WAVE"
1696 			{
1697 				fclose(f);
1698 				return loadWAVSample(fileName, entryName, -1);
1699 			}
1700 		}
1701 		else if (ID == 0x4D524F46) // "FORM"
1702 		{
1703 			fseek(f, 4, SEEK_CUR);
1704 			fread(&ID, 4, 1, f);
1705 
1706 			// check if it's an Amiga IFF sample
1707 			if (ID == 0x58565338 || ID == 0x56533631) // "8SVX" (normal) and "16SV" (FT2 sample)
1708 			{
1709 				fclose(f);
1710 				return loadIFFSample(fileName, entryName, -1);
1711 			}
1712 
1713 			// check if it's an AIFF sample
1714 			else if (ID == 0x46464941) // "AIFF"
1715 			{
1716 				fclose(f);
1717 				return loadAIFFSample(fileName, entryName, -1);
1718 			}
1719 
1720 			else if (ID == 0x43464941) // "AIFC" (compressed AIFF)
1721 			{
1722 				fclose(f);
1723 				displayErrorMsg("UNSUPPORTED AIFF!");
1724 				return false;
1725 			}
1726 		}
1727 	}
1728 
1729 	// nope, continue loading as RAW
1730 	fclose(f);
1731 
1732 	return loadRAWSample(fileName, entryName);
1733 }
1734