summaryrefslogtreecommitdiffstatshomepage
path: root/src/emu/sound/samples.c
blob: 35847f654b8d299df7ca385aabfa7d30f2d3aad8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
#include "emu.h"
#include "emuopts.h"
#include "samples.h"
#include "../../lib/libflac/include/flac/all.h"

typedef struct _sample_channel sample_channel;
struct _sample_channel
{
	sound_stream *stream;
	const INT16 *source;
	INT32		source_length;
	INT32		source_num;
	UINT32		pos;
	UINT32		frac;
	UINT32		step;
	UINT32		basefreq;
	UINT8		loop;
	UINT8		paused;
};


typedef struct _samples_info samples_info;
struct _samples_info
{
	device_t *device;
	int			numchannels;	/* how many channels */
	sample_channel *channel;/* array of channels */
	loaded_samples *samples;/* array of samples */
};


INLINE samples_info *get_safe_token(device_t *device)
{
	assert(device != NULL);
	assert(device->type() == SAMPLES);
	return (samples_info *)downcast<legacy_device_base *>(device)->token();
}



#define FRAC_BITS		24
#define FRAC_ONE		(1 << FRAC_BITS)
#define FRAC_MASK		(FRAC_ONE - 1)
#define MAX_CHANNELS    100

struct flac_reader
{
	UINT8* rawdata;
	INT16* write_data;
	int position;
	int length;
	int decoded_size;
	int sample_rate;
	int channels;
	int bits_per_sample;
	int total_samples;
	int write_position;
} flacread;

static flac_reader* flacreadptr;

void my_error_callback(const FLAC__StreamDecoder * decoder, FLAC__StreamDecoderErrorStatus status, void * client_data)
{
	fatalerror("FLAC error Callback\n");
}

void my_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
{

	flac_reader* flacrd =  ((flac_reader*)client_data);
	//printf("Metadata callback\n");
	//printf("metadata->type == %d\n", metadata->type);

	if (metadata->type==0)
	{
		const FLAC__StreamMetadata_StreamInfo *streaminfo = &(metadata->data.stream_info);

		//printf("streaminfo channels %d, sample_rate %d total %d\n", streaminfo->channels, streaminfo->sample_rate, streaminfo->total_samples);

		flacrd->sample_rate = streaminfo->sample_rate;
		flacrd->channels = streaminfo->channels;
		flacrd->bits_per_sample = streaminfo->bits_per_sample;
		flacrd->total_samples = streaminfo->total_samples;
	}
}




FLAC__StreamDecoderReadStatus my_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
{
	flac_reader* flacrd =  ((flac_reader*)client_data);

	//printf("read in length %d\n", flacrd->length);
	if(*bytes > 0)
	{
		if (*bytes <=  flacrd->length)
		{
			memcpy(buffer, flacrd->rawdata+flacrd->position, *bytes);
			flacrd->position+=*bytes;
			flacrd->length-=*bytes;
			return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
		}
		else
		{
			memcpy(buffer, flacrd->rawdata+flacrd->position,  flacrd->length);
		    flacrd->position+= flacrd->length;
			flacrd->length = 0;

			return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
		}
	}
	else
	{
		return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
	}

	if ( flacrd->length==0)
	{
		return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
	}

	return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;

}

FLAC__StreamDecoderWriteStatus my_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *const buffer[], void *client_data) 
{
	//printf("my_write_callback\n");
	//printf("array size %d\n",frame->header.blocksize);

	flac_reader* flacrd =  ((flac_reader*)client_data);

	flacrd->decoded_size += frame->header.blocksize;
	//printf("total array size %d\n",flacrd->decoded_size);

	for (int i=0;i<frame->header.blocksize;i++)
	{
		flacrd->write_data[i+flacrd->write_position] = buffer[0][i];
	}

	flacrd->write_position +=  frame->header.blocksize;
	
	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}






/*-------------------------------------------------
    read_wav_sample - read a WAV file as a sample
-------------------------------------------------*/

static int read_wav_sample(running_machine &machine, emu_file &file, loaded_sample *sample)
{
	unsigned long offset = 0;
	UINT32 length, rate, filesize;
	UINT16 bits, temp16;
	char buf[32];
	UINT32 sindex;
	int type = 0;

	/* read the core header and make sure it's a WAVE file */
	offset += file.read(buf, 4);
	if (offset < 4)
		return 0;
	if (memcmp(&buf[0], "RIFF", 4) == 0)
		type = 1;
	else if (memcmp(&buf[0], "fLaC", 4) == 0)
		type = 2;
	else
		return 0;

	if (type==1)
	{
		/* get the total size */
		offset += file.read(&filesize, 4);
		if (offset < 8)
			return 0;
		filesize = LITTLE_ENDIANIZE_INT32(filesize);

		/* read the RIFF file type and make sure it's a WAVE file */
		offset += file.read(buf, 4);
		if (offset < 12)
			return 0;
		if (memcmp(&buf[0], "WAVE", 4) != 0)
			return 0;

		/* seek until we find a format tag */
		while (1)
		{
			offset += file.read(buf, 4);
			offset += file.read(&length, 4);
			length = LITTLE_ENDIANIZE_INT32(length);
			if (memcmp(&buf[0], "fmt ", 4) == 0)
				break;

			/* seek to the next block */
			file.seek(length, SEEK_CUR);
			offset += length;
			if (offset >= filesize)
				return 0;
		}

		/* read the format -- make sure it is PCM */
		offset += file.read(&temp16, 2);
		temp16 = LITTLE_ENDIANIZE_INT16(temp16);
		if (temp16 != 1)
			return 0;

		/* number of channels -- only mono is supported */
		offset += file.read(&temp16, 2);
		temp16 = LITTLE_ENDIANIZE_INT16(temp16);
		if (temp16 != 1)
			return 0;

		/* sample rate */
		offset += file.read(&rate, 4);
		rate = LITTLE_ENDIANIZE_INT32(rate);

		/* bytes/second and block alignment are ignored */
		offset += file.read(buf, 6);

		/* bits/sample */
		offset += file.read(&bits, 2);
		bits = LITTLE_ENDIANIZE_INT16(bits);
		if (bits != 8 && bits != 16)
			return 0;

		/* seek past any extra data */
		file.seek(length - 16, SEEK_CUR);
		offset += length - 16;

		/* seek until we find a data tag */
		while (1)
		{
			offset += file.read(buf, 4);
			offset += file.read(&length, 4);
			length = LITTLE_ENDIANIZE_INT32(length);
			if (memcmp(&buf[0], "data", 4) == 0)
				break;

			/* seek to the next block */
			file.seek(length, SEEK_CUR);
			offset += length;
			if (offset >= filesize)
				return 0;
		}

		/* if there was a 0 length data block, we're done */
		if (length == 0)
			return 0;

		/* fill in the sample data */
		sample->length = length;
		sample->frequency = rate;

		/* read the data in */
		if (bits == 8)
		{
			unsigned char *tempptr;
			int sindex;

			sample->data = auto_alloc_array(machine, INT16, length);
			file.read(sample->data, length);

			/* convert 8-bit data to signed samples */
			tempptr = (unsigned char *)sample->data;
			for (sindex = length - 1; sindex >= 0; sindex--)
				sample->data[sindex] = (INT8)(tempptr[sindex] ^ 0x80) * 256;

		}
		else
		{
			/* 16-bit data is fine as-is */
			sample->data = auto_alloc_array(machine, INT16, length/2);
			file.read(sample->data, length);

				sample->length /= 2;
			if (ENDIANNESS_NATIVE != ENDIANNESS_LITTLE)
				for (sindex = 0; sindex < sample->length; sindex++)
					sample->data[sindex] = LITTLE_ENDIANIZE_INT16(sample->data[sindex]);
		}
	}
	else
	{
		int length;

		file.seek(0, SEEK_END);
		length = file.tell();
		file.seek(0, 0);

		flacread.rawdata = auto_alloc_array(machine, UINT8, length);
		flacread.length = length;
		flacread.position = 0;
		flacread.decoded_size = 0;

		flacreadptr = &flacread;

		file.read(flacread.rawdata, length);

		FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();

		if (!decoder)
			fatalerror("Fail FLAC__stream_decoder_new\n");

		if(FLAC__stream_decoder_init_stream(
			decoder,
			my_read_callback,
			NULL, //my_seek_callback,      // or NULL
			NULL, //my_tell_callback,      // or NULL
			NULL, //my_length_callback,    // or NULL
			NULL, //my_eof_callback,       // or NULL
			my_write_callback,
			my_metadata_callback, //my_metadata_callback,  // or NULL
			my_error_callback,
			(void*)flacreadptr /*my_client_data*/ ) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
			fatalerror("Fail FLAC__stream_decoder_init_stream\n");

		if (FLAC__stream_decoder_process_until_end_of_metadata(decoder) != FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM)
			fatalerror("Fail FLAC__stream_decoder_process_until_end_of_metadata\n");

		//printf("got metadata?\n");

		if (flacread.channels != 1) // only Mono supported
			return 0;

		int size = flacread.total_samples * (flacread.bits_per_sample/8);
	
		sample->data = auto_alloc_array(machine, INT16, size);
		flacread.write_position = 0;
		flacread.write_data = sample->data;

		if (FLAC__stream_decoder_process_until_end_of_stream (decoder) != FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM)
			fatalerror("Fail FLAC__stream_decoder_process_until_end_of_stream\n");

		if (FLAC__stream_decoder_finish (decoder) != true)
			fatalerror("Fail FLAC__stream_decoder_finish\n");

		FLAC__stream_decoder_delete(decoder);

		/* fill in the sample data */
		
		sample->frequency = flacread.sample_rate;
		sample->length = size;

		if (flacread.bits_per_sample == 8)
		{
			for (sindex = 0; sindex <= sample->length; sindex++)
				sample->data[sindex] = ((sample->data[sindex])&0xff)*256;
		}
		else // don't need to process 16-bit samples?
		{
			sample->length = sample->length /2; //??
		}
	}

	return 1;
}


/*-------------------------------------------------
    readsamples - load all samples
-------------------------------------------------*/

loaded_samples *readsamples(running_machine &machine, const char *const *samplenames, const char *basename)
{
	loaded_samples *samples;
	int skipfirst = 0;
	int i;

	/* if the user doesn't want to use samples, bail */
	if (!machine.options().samples())
		return NULL;
	if (samplenames == 0 || samplenames[0] == 0)
		return NULL;

	/* if a name begins with '*', we will also look under that as an alternate basename */
	if (samplenames[0][0] == '*')
		skipfirst = 1;

	/* count the samples */
	for (i = 0; samplenames[i+skipfirst] != 0; i++) ;
	if (i == 0)
		return NULL;

	/* allocate the array */
	samples = (loaded_samples *)auto_alloc_array_clear(machine, UINT8, sizeof(loaded_samples) + (i-1) * sizeof(loaded_sample));
	samples->total = i;

	/* load the samples */
	for (i = 0; i < samples->total; i++)
		if (samplenames[i+skipfirst][0])
		{
			emu_file file(machine.options().sample_path(), OPEN_FLAG_READ);

			file_error filerr = file.open(basename, PATH_SEPARATOR, samplenames[i+skipfirst]);
			if (filerr != FILERR_NONE && skipfirst)
				filerr = file.open(samplenames[0] + 1, PATH_SEPARATOR, samplenames[i+skipfirst]);

			if (filerr == FILERR_NONE)
				read_wav_sample(machine, file, &samples->sample[i]);
		}

	return samples;
}




/* Start one of the samples loaded from disk. Note: channel must be in the range */
/* 0 .. Samplesinterface->channels-1. It is NOT the discrete channel to pass to */
/* mixer_play_sample() */
void sample_start(device_t *device,int channel,int samplenum,int loop)
{
    samples_info *info = get_safe_token(device);
    sample_channel *chan;
    loaded_sample *sample;

	/* if samples are disabled, just return quietly */
	if (info->samples == NULL)
		return;

    assert( samplenum < info->samples->total );
    assert( channel < info->numchannels );

    chan = &info->channel[channel];

	/* force an update before we start */
	chan->stream->update();

	/* update the parameters */
	sample = &info->samples->sample[samplenum];
	chan->source = sample->data;
	chan->source_length = sample->length;
	chan->source_num = sample->data ? samplenum : -1;
	chan->pos = 0;
	chan->frac = 0;
	chan->basefreq = sample->frequency;
	chan->step = ((INT64)chan->basefreq << FRAC_BITS) / info->device->machine().sample_rate();
	chan->loop = loop;
}


void sample_start_raw(device_t *device,int channel,const INT16 *sampledata,int samples,int frequency,int loop)
{
    samples_info *info = get_safe_token(device);
    sample_channel *chan;

    assert( channel < info->numchannels );

    chan = &info->channel[channel];

	/* force an update before we start */
	chan->stream->update();

	/* update the parameters */
	chan->source = sampledata;
	chan->source_length = samples;
	chan->source_num = -1;
	chan->pos = 0;
	chan->frac = 0;
	chan->basefreq = frequency;
	chan->step = ((INT64)chan->basefreq << FRAC_BITS) / info->device->machine().sample_rate();
	chan->loop = loop;
}


void sample_set_freq(device_t *device,int channel,int freq)
{
    samples_info *info = get_safe_token(device);
    sample_channel *chan;

    assert( channel < info->numchannels );

    chan = &info->channel[channel];

	/* force an update before we start */
	chan->stream->update();

	chan->step = ((INT64)freq << FRAC_BITS) / info->device->machine().sample_rate();
}


void sample_set_volume(device_t *device,int channel,float volume)
{
    samples_info *info = get_safe_token(device);
    sample_channel *chan;

    assert( channel < info->numchannels );

    chan = &info->channel[channel];

	chan->stream->set_output_gain(0, volume);
}


void sample_set_pause(device_t *device,int channel,int pause)
{
    samples_info *info = get_safe_token(device);
    sample_channel *chan;

    assert( channel < info->numchannels );

    chan = &info->channel[channel];

	/* force an update before we start */
	chan->stream->update();

	chan->paused = pause;
}


void sample_stop(device_t *device,int channel)
{
    samples_info *info = get_safe_token(device);
    sample_channel *chan;

    assert( channel < info->numchannels );

    chan = &info->channel[channel];

    /* force an update before we start */
    chan->stream->update();
    chan->source = NULL;
    chan->source_num = -1;
}


int sample_get_base_freq(device_t *device,int channel)
{
    samples_info *info = get_safe_token(device);
    sample_channel *chan;

    assert( channel < info->numchannels );

    chan = &info->channel[channel];

	/* force an update before we start */
	chan->stream->update();
	return chan->basefreq;
}


int sample_playing(device_t *device,int channel)
{
    samples_info *info = get_safe_token(device);
    sample_channel *chan;

    assert( channel < info->numchannels );

    chan = &info->channel[channel];

	/* force an update before we start */
	chan->stream->update();
	return (chan->source != NULL);
}


static STREAM_UPDATE( sample_update_sound )
{
	sample_channel *chan = (sample_channel *)param;
	stream_sample_t *buffer = outputs[0];

	if (chan->source && !chan->paused)
	{
		/* load some info locally */
		UINT32 pos = chan->pos;
		UINT32 frac = chan->frac;
		UINT32 step = chan->step;
		const INT16 *sample = chan->source;
		UINT32 sample_length = chan->source_length;

		while (samples--)
		{
			/* do a linear interp on the sample */
			INT32 sample1 = sample[pos];
			INT32 sample2 = sample[(pos + 1) % sample_length];
			INT32 fracmult = frac >> (FRAC_BITS - 14);
			*buffer++ = ((0x4000 - fracmult) * sample1 + fracmult * sample2) >> 14;

			/* advance */
			frac += step;
			pos += frac >> FRAC_BITS;
			frac = frac & ((1 << FRAC_BITS) - 1);

			/* handle looping/ending */
			if (pos >= sample_length)
			{
				if (chan->loop)
					pos %= sample_length;
				else
				{
					chan->source = NULL;
					chan->source_num = -1;
					if (samples > 0)
						memset(buffer, 0, samples * sizeof(*buffer));
					break;
				}
			}
		}

		/* push position back out */
		chan->pos = pos;
		chan->frac = frac;
	}
	else
		memset(buffer, 0, samples * sizeof(*buffer));
}


static void samples_postload(samples_info *info)
{
	int i;

	/* loop over channels */
	for (i = 0; i < info->numchannels; i++)
	{
		sample_channel *chan = &info->channel[i];

		/* attach any samples that were loaded and playing */
		if (chan->source_num >= 0 && chan->source_num < info->samples->total)
		{
			loaded_sample *sample = &info->samples->sample[chan->source_num];
			chan->source = sample->data;
			chan->source_length = sample->length;
			if (!sample->data)
				chan->source_num = -1;
		}

		/* validate the position against the length in case the sample is smaller */
		if (chan->source && chan->pos >= chan->source_length)
		{
			if (chan->loop)
				chan->pos %= chan->source_length;
			else
			{
				chan->source = NULL;
				chan->source_num = -1;
			}
		}
	}
}


static DEVICE_START( samples )
{
	int i;
	const samples_interface *intf = (const samples_interface *)device->static_config();
	samples_info *info = get_safe_token(device);

	info->device = device;

	/* read audio samples */
	if (intf->samplenames)
		info->samples = readsamples(device->machine(), intf->samplenames,device->machine().system().name);

	/* allocate channels */
	info->numchannels = intf->channels;
	assert(info->numchannels < MAX_CHANNELS);
	info->channel = auto_alloc_array(device->machine(), sample_channel, info->numchannels);
	for (i = 0; i < info->numchannels; i++)
	{
	    info->channel[i].stream = device->machine().sound().stream_alloc(*device, 0, 1, device->machine().sample_rate(), &info->channel[i], sample_update_sound);

		info->channel[i].source = NULL;
		info->channel[i].source_num = -1;
		info->channel[i].step = 0;
		info->channel[i].loop = 0;
		info->channel[i].paused = 0;

		/* register with the save state system */
        device->save_item(NAME(info->channel[i].source_length), i);
        device->save_item(NAME(info->channel[i].source_num), i);
        device->save_item(NAME(info->channel[i].pos), i);
        device->save_item(NAME(info->channel[i].frac), i);
        device->save_item(NAME(info->channel[i].step), i);
        device->save_item(NAME(info->channel[i].loop), i);
        device->save_item(NAME(info->channel[i].paused), i);
	}
	device->machine().save().register_postload(save_prepost_delegate(FUNC(samples_postload), info));

	/* initialize any custom handlers */
	if (intf->start)
		(*intf->start)(device);
}



/**************************************************************************
 * Generic get_info
 **************************************************************************/

DEVICE_GET_INFO( samples )
{
	switch (state)
	{
		/* --- the following bits of info are returned as 64-bit signed integers --- */
		case DEVINFO_INT_TOKEN_BYTES:					info->i = sizeof(samples_info);			break;

		/* --- the following bits of info are returned as pointers to data or functions --- */
        case DEVINFO_FCT_START:                         info->start = DEVICE_START_NAME( samples );		break;
        case DEVINFO_FCT_STOP:                          /* Nothing */                           		break;
        case DEVINFO_FCT_RESET:                         /* Nothing */                           		break;

		/* --- the following bits of info are returned as NULL-terminated strings --- */
        case DEVINFO_STR_NAME:                          strcpy(info->s, "Samples");                 	break;
        case DEVINFO_STR_FAMILY:                   strcpy(info->s, "Big Hack");                 	break;
        case DEVINFO_STR_VERSION:                  strcpy(info->s, "1.1");                      	break;
        case DEVINFO_STR_SOURCE_FILE:                     strcpy(info->s, __FILE__);                    		break;
        case DEVINFO_STR_CREDITS:                  strcpy(info->s, "Copyright Nicola Salmoria and the MAME Team"); break;
	}
}


DEFINE_LEGACY_SOUND_DEVICE(SAMPLES, samples);