summaryrefslogtreecommitdiff
path: root/midirip.c
blob: b87d128958a2c38f072223d4952cfee0fa60dbf7 (plain)
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
/*
 * Copyright (c) 2010 Florian Jung <flo@windfisch.org>
 * for the MIDI constants and some jack-midi code, which has been
 * taken from jack-keyboard: 
 * Copyright (c) 2007, 2008 Edward Tomasz Napierała <trasz@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */


//LAST STABLE: 02


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <jack/jack.h>
#include <jack/midiport.h>
#include <jack/ringbuffer.h>


#define MIDI_PORT_NAME	"midi"
#define REC_PORT_NAME	"rec"

jack_port_t	*recport, *midiport;
double		rate_limit = 0.0;
jack_client_t	*jack_client = NULL;

#define MIDI_NOTE_ON		0x90
#define MIDI_NOTE_OFF		0x80
#define MIDI_PROGRAM_CHANGE	0xC0
#define MIDI_CONTROLLER		0xB0
#define MIDI_RESET		0xFF
#define MIDI_HOLD_PEDAL		64
#define MIDI_ALL_SOUND_OFF	120
#define MIDI_ALL_MIDI_CONTROLLERS_OFF	121
#define MIDI_ALL_NOTES_OFF	123
#define MIDI_BANK_SELECT_MSB	0
#define MIDI_BANK_SELECT_LSB	32

#define BANK_MIN		0
#define BANK_MAX		127
#define PROGRAM_MIN		0
#define PROGRAM_MAX		16383
#define CHANNEL_MIN		1
#define CHANNEL_MAX		16

#define time_offsets_are_zero 0

struct MidiMessage {
	jack_nframes_t	time;
	int		len;	/* Length of MIDI message, in bytes. */
	unsigned char	data[3];
};

#define RINGBUFFER_SIZE		1024*sizeof(struct MidiMessage)

jack_ringbuffer_t *ringbuffer;

/* Number of currently selected channel (0..15). */
int		channel = 9;



//FINDMICH
#define RECBUF_LEN 44100*60
#define SILENCE_LEN 44100*2
#define SILENCE_ADD 0.005   //schon ziemlich knapp. lieber weniger
#define QUIET_LEN 441
#define WAIT_AFTER 22050
#define MAX_NOTES 10
#define DEFAULT_LEN 10 //TODO richtigen wert finden!

jack_default_audio_sample_t buf1[RECBUF_LEN], buf2[RECBUF_LEN];
jack_default_audio_sample_t *recbuf, *workbuf;
jack_default_audio_sample_t silence;
int note=60, laut=100, notelen=22050;
int main_working, all_done;
int workstart, workend, main_rbpos;

int samp_rate;
int bytes=2;
char wavheader[44];
int flo_start=0;

struct entry_t
{
	char chan;
	char patch;
	
	char loud;
	char note[MAX_NOTES];
	int notelen;
	
	struct entry_t *next;
};
typedef struct entry_t entry_t;

entry_t *recentry, *workentry, *firstentry;

const int notemap[7]={33,35,24,26,28,29,31};

int getnum(char *s, int *i)
{
	int minus=0;
	int num=0;
	
	if (s[*i]=='-')
	{
		minus=1;
		(*i)++;
	}
	while((s[*i]>='0') && (s[*i]<='9'))
	{
		num=num*10+s[*i]-'0';
		(*i)++;
	}
	
	if (minus) return -num; else return num;
}

int parserange(char *s, int l[])
{
	int i, state=0;
	int j=0;
	int num, end;
	
	for (i=0;;i++)
		if ((s[i]!=' ') && (s[i]!='\t'))
		{
			switch(state)
			{
				case 0: //expects the (first) number
					if ((s[i]>='0') && (s[i]<='9')) //a number?
					{
						num=getnum(s,&i);
						i--;
						state=1;
					}
					break;
				case 1: //expects a , or a -
					if (s[i]=='-')
					{
						state=2;
					}
					else if ((s[i]==',') || (s[i]==0))
					{
						l[j]=num;
						j++;
//						printf ("num=%i\n",num);
						state=0;
					}
					else
					{
						printf("ERROR: expected ',' or '-', found '%c'\n",s[i]);
						return -1;
					}
					break;
					
				case 2: //expects the second number that ends a range
					if ((s[i]>='0') && (s[i]<='9')) //a number?
					{
						end=getnum(s,&i);
//						printf("numrange=%i-%i\n",num,end);
						for (;num<=end;num++)
						{
							l[j]=num;
							j++;
						}
						
						i--;
						state=3;
					}
					else
					{
						printf("ERROR: expected number, found '%c'\n",s[i]);
						return -1;
					}
					break;
				
				case 3: //expects ','
					if ((s[i]==',') || (s[i]==0))
						state=0;
					else
					{
						printf("ERROR: expected ',', found '%c'\n",s[i]);
						return -1;
					}
			}
			if (s[i]==0) break;
		}
		
		return j;
		
}


void u16cpy(char *dest, int src)
{
	dest[0]=src%256;
	dest[1]=src/256;
}

void s16cpy(char *dest, int src)
{
	if (src<0)
		src=(~(-src))+1;

	u16cpy(dest,src);
}

void u32cpy(char *dest, long int src)
{
	dest[0]=src%256;
	dest[1]=(src/256)%256;
	dest[2]=(src/256/256)%256;
	dest[3]=(src/256/256/256)%256;
}



jack_default_audio_sample_t arr_dist (jack_default_audio_sample_t a[], int l)
{
	int i;
	jack_default_audio_sample_t max,min;
	min=max=a[0];
	
	for (i=0;i<l;i++)
		if (a[i]>max)
			max=a[i];
		else if (a[i]<min)
			min=a[i];
			
	return max-min;
}


int process_callback(jack_nframes_t nframes, void *notused) //WICHTIG FINDMICH
{
	static int state = 0;
	static int frame_cnt;
	static int rbpos=0, recend;
	int i;
	void           *midipb;
	jack_nframes_t	last_frame_time;
	unsigned char data[3];

	last_frame_time = jack_last_frame_time(jack_client);


	jack_default_audio_sample_t *recpb=
			(jack_default_audio_sample_t *) jack_port_get_buffer (recport, nframes);
	if (recpb==NULL) printf("rec fail\n");

	midipb = jack_port_get_buffer(midiport, nframes);
	if (midipb==NULL) printf("midi fail\n");
	jack_midi_clear_buffer(midipb);

	
	switch(state) //TODO: statt segfault tainted setzen und im letzten bufferteil loopen
	{
		case 0: // warte auf freigabe und initialisiere
			if (flo_start)
			{
				state=1;
				rbpos=0;
				recentry=firstentry;
				printf("messe stille\n");
			}
			break;
			
		case 1: // sammle daten über stille
			for (i=0;i<nframes;i++)
			{
				recbuf[rbpos]=recpb[i];
				rbpos++;
			}
			if (rbpos>=SILENCE_LEN) //genug?
			{
				silence=arr_dist(recbuf,SILENCE_LEN)  +  SILENCE_ADD;
				printf("  stille=%f\n",silence);
				state=2;
			}
			break;
		
		case 2: // spiele note, wie in recentry beschrieben
			printf("NOTE ON\n");
			data[0]=MIDI_NOTE_ON; //TODO
			data[1]=note; 
			data[2]=laut; 
			if (jack_midi_event_write(midipb, 0, data, 3))
				fprintf(stderr,"Note loss when writing\n");
			frame_cnt=notelen; //TODO
			
			rbpos=0;
			recend=-1;
			
			state=3;
			break;
			
		case 3: // nehme auf und sende ggf note off
			if (frame_cnt != -1) //ggf note off
			{
				if (frame_cnt < nframes) //noteoff in diesem frame?
				{
					printf("NOTE OFF in %i\n",frame_cnt); //TODO
					data[0]=MIDI_NOTE_OFF;
					data[1]=note; 
					data[2]=laut; 

					if (jack_midi_event_write(midipb, frame_cnt, data, 3))
						fprintf(stderr,"Note loss when writing\n");
					
					frame_cnt=-1;
				}
				else
					frame_cnt-=nframes;
			}
			
			for (i=0;i<nframes;i++) //aufnehmen
			{
				if (rbpos>=RECBUF_LEN)
					printf("WARNING: segfault\n"); //TODO
				recbuf[rbpos]=recpb[i];
				rbpos++;
			}
			if (rbpos>QUIET_LEN) //TODO FINDMICH: QUIET_LEN mit nframes ersetzen???
			{
				if (arr_dist(&recbuf[rbpos-QUIET_LEN],QUIET_LEN)<=silence) //es wird still...
				{
					if (recend==-1) recend=rbpos-QUIET_LEN;
					
					if (frame_cnt==-1) //ggf aufs noteoff warten
					{
						printf ("aufnahme fertig\n"); 
						
						state=4;
					}
				}
				else //nicht (mehr?) still
				{
					if (recend!=-1)
						printf("komisch... erst still, dann laut? %i\n",rbpos);
					recend=-1;
				}
			}
			break;
		
		case 4: //auf verarbeitungs-thread warten
			if (main_working==0) //main ist fertig?
			{
				if (recbuf==buf1) //buffer wechseln
				{
					recbuf=buf2;
					workbuf=buf1;
				}
				else
				{
					recbuf=buf1;
					workbuf=buf2;
				}
				workend=recend; //TODO evtl noch mehr?
				main_rbpos=rbpos;
				workentry=recentry;
				
				main_working=1; //befehl zum starten geben
				
				
				recentry=recentry->next;
				if (recentry==NULL) //fertig?
				{
					all_done=1;
					state=99;
				}
				else
				{
					frame_cnt=WAIT_AFTER;
					state=5;
				}
			}
			break;
		
		case 5: //noch einige zeit warten
			frame_cnt-=nframes;
			if (frame_cnt<=0)
			{									
				frame_cnt=-1;
				printf ("fertig mit warten\n");
				state=2;
			}
			break;
		
		case 99: //nichts tun, main wird alles fertig machen, aufräumen und beenden.
			break;
	}
	
	if (nframes <= 0) {
		fprintf(stderr,"Process callback called with nframes = 0; bug in JACK?\n");
		return 0;
	}
	

	return 0;
}

void init_jack(void) //WICHTIG !!!
{
	jack_client = jack_client_open("ripmidi", JackNullOption, NULL);
	if (jack_client == NULL)
	{
		fprintf(stderr,"Registering client failed.\n");
		exit(1);
	}

	ringbuffer = jack_ringbuffer_create(RINGBUFFER_SIZE);
	if (ringbuffer == NULL)
	{
		fprintf(stderr,"Creating ringbuffer failed.\n");
		exit(1);
	}
	jack_ringbuffer_mlock(ringbuffer);

	if (jack_set_process_callback(jack_client, process_callback, 0)) 
	{
		fprintf(stderr,"Registering callback failed.\n");
		exit(1);
	}

	recport=jack_port_register(jack_client, REC_PORT_NAME, JACK_DEFAULT_AUDIO_TYPE,
		JackPortIsInput, 0);
	midiport = jack_port_register(jack_client, MIDI_PORT_NAME, JACK_DEFAULT_MIDI_TYPE,
		JackPortIsOutput, 0);

	if ((midiport == NULL) || (recport == NULL)) {
		fprintf(stderr,"Registering ports failed.\n");
		exit(1);
	}

	if (jack_activate(jack_client)) 
	{
		fprintf(stderr,"Activating client failed.\n");
		exit(1);
	}
}

int main(int argc, char *argv[])
{
	int i,l;
	FILE* f;
	char line[1000];
	char *range, *param;
	int patchlist[128];
	
	int oct,loud,len;
	int notenum, note[10];
	int j,k;
	int state;
	int dontignore;
	int rangelen;
	
	entry_t *curr_entry;
	
	curr_entry=firstentry=NULL;
	
	f=fopen ("config.txt","r");
	l=0;
	while(!feof(f))
	{
		fgets(line,sizeof(line),f);
		l++;

		dontignore=0;		
		for (i=0;line[i];i++)
			if ((line[i]!=' ') && (line[i]!='\t') && (line[i]!='\n'))
			{
				dontignore=1;
			}
		
		if (dontignore)
		{
			for (i=0;(line[i]!=0) && (line[i]!=')');i++); //find ')'
			if (line[i]==0)
			{
				printf("ERROR: expected ), found EOL in line %i\n",l);
				goto invalid;
			}

			line[i]=0;
			range=line;
			param=line+i+1;
			
			rangelen=parserange(range,patchlist);
			if (rangelen==-1)
			{
				printf ("ERROR: invalid range specified in line %i\n",l);
				goto invalid;
			}
			
			while(1)
			{
				for (i=0;(param[i]!=0) && (param[i]!=',') && (param[i]!='\n');i++); //find ','
				
				state=0;
				len=DEFAULT_LEN;
				notenum=0;
				note[notenum]=0; oct=99;
				
				for (j=0;j<i;j++)
				{
					switch (state)
					{
						case 0: //expects a note (a4) or loudness (<num>) or \0
							if ((param[j]>='a') && (param[j]<='g')) //found a note
							{
//									printf("found a note\n");
								note[notenum]=notemap[param[j]-'a'];
								if ((param[j+1]=='b') || param[j+1]=='#') //vorzeichen?
								{
									if (param[j+1]=='b')
										note[notenum]--;
									else
										note[notenum]++;
									j++;
								}
								state=1;
							}
							else if ((param[j]>='0') && (param[j]<='9')) //found a number
							{
//									printf("found loudness\n");
								loud=getnum(param,&j);
								state=2;
							}
							else if ((param[j]!=' ') && (param[j]!='\t'))
							{
								printf("ERROR: expected note or number, found %c in line %i\n",param[j],l);
								goto invalid;
							}
							break;
						
						case 1: //expects octave (-1 or 4)
							if ((param[j]=='-') || ((param[j]>='0') && (param[j]<='9')))
							{
//									printf("found octave\n");
								oct=getnum(param,&j);
								
								note[notenum]+=oct*12;
								if ((note[notenum]<0) || (note[notenum]>127)) //illegal note
								{
									printf("ERROR: invalid note in line %i\n",l);
									goto invalid;
								}
								else
								 notenum++;
								state=0;
							}
							else
							{
								printf ("ERROR: expected - or 0-9, found %c in line %i\n",param[j],l);
								goto invalid;
							}
							break;
						
							
						case 2: //expects notelen or 0
							if ((param[j]>='0') && (param[j]<='9'))
							{
//									printf("found notelen\n");
								len=getnum(param,&j);
								if (len<0)
								{
									printf("WARNING: len was negative in line %i; using absolute value\n",l);
									len=-len;
								}
								state=4;
							}
							else if ((param[j]!=' ') && (param[j]!='\t'))
							{
								printf("ERROR: expected number, found %c in line %i\n",param[j],l);
								goto invalid;
							}
					}
				}
				
				//in die liste eintragen
				for (k=0;k<rangelen;k++)
				{
					entry_t *tmpptr=malloc(sizeof(entry_t));
					if (tmpptr==NULL)
					{
						printf("GAAAH... malloc error\n");
						exit(1);
					}
					if (firstentry==NULL)
						firstentry=tmpptr;
					else
						curr_entry->next=tmpptr;
						
					tmpptr->loud=loud;
					tmpptr->notelen=len*samp_rate /1000; //von msec in samples umrechnen
					tmpptr->chan=0;
					tmpptr->patch=patchlist[k];
					
					for (j=0;j<notenum;j++)
						tmpptr->note[j]=note[j];
					tmpptr->note[notenum]=-1;
					tmpptr->next=NULL;
					
					curr_entry=tmpptr;
				}
				
				if (param[i]==',') //is there a next param?
					param=&param[i+1];
				else
					break;
			}
		}
	}

	curr_entry=firstentry;
	while(curr_entry)
	{
		printf("%i\n",curr_entry->loud);
		
		curr_entry=curr_entry->next;
	}
	
	
	
	
	//init
	recbuf=buf1; workbuf=buf2;
	main_working=0; all_done=0;

	
	samp_rate=44100; bytes=2;
	
	//init header
	strcpy(wavheader+ 0, "RIFF");
	//u32cpy(wavheader+ 4, filelen-8);
	strcpy(wavheader+ 8, "WAVE");
	
	strcpy(wavheader+12, "fmt ");
	u32cpy(wavheader+16, 16);
	u16cpy(wavheader+20, 1);
	u16cpy(wavheader+22, 1);
	u32cpy(wavheader+24, samp_rate);
	u32cpy(wavheader+28, samp_rate*bytes);
	u16cpy(wavheader+32, bytes);
	u16cpy(wavheader+34, bytes*8);
	
	strcpy(wavheader+36, "data");
	//u32cpy(wavheader+40, datalen);

	
	init_jack();
	
	char foo[10]; gets(foo);
	
	flo_start=1;
	
	main_working=0;
	printf("main: entering loop\n");
	while(1)
	{
		while ((main_working==0) && (all_done==0)) usleep(100000); // 0.1 sec
		//TODO: all_done auswerten
		printf("main: starting work cycle\n");
		
		workstart=-1;
		for (i=1;i<=QUIET_LEN;i++) //Find begin of non-silence
			if (arr_dist(workbuf,i) > silence)
			{
				workstart=i-1;
				break;
			}

		if (workstart==-1) // [ continued ] 
			for (i=QUIET_LEN;i<workend;i++)
				if (arr_dist(&workbuf[i-QUIET_LEN],QUIET_LEN) > silence)
				{
					workstart=i-1;
					break;
				}

		if (workstart!=-1)
		{
			printf("main: gotcha. %i - %i [%i - %i]\n",workstart,workend,0,main_rbpos);
			jack_default_audio_sample_t max=0.0; //find max amplitude
			for (i=workstart; i<=workend; i++)
			{
				if (workbuf[i]>0)
				{
					if (workbuf[i]>max) max=workbuf[i];
				}
				else
				{
					if (-workbuf[i]>max) max=-workbuf[i];
				}
			}
		
			int datalen,filelen;
			datalen=(workend-workstart+1)*bytes;
			filelen=44+datalen;
			u32cpy(wavheader+ 4, filelen-8);
			u32cpy(wavheader+40, datalen);
			

			f=fopen("flo1.wav","w");
			
			unsigned char tmp[2];
			
			fwrite(wavheader, 1, 44, f);
			if (bytes==1)
				for (i=workstart;i<=workend;i++)
				{
					*tmp=(workbuf[i]/max*127.0)+127;
					fwrite(tmp,1,1,f);
				}
			else
				for (i=workstart;i<=workend;i++)
				{
					s16cpy(tmp, (long)(workbuf[i]/max*32767.0));
					fwrite(&tmp,1,2,f);
				}
						
			fclose(f);
						
			
		}
		else
		{
			printf ("main: komisch. nur stille aufgenommen...\n"); //TODO handlen!
		}
		
		
		printf("main: work done\n");
		main_working=0;
	}

	return 0;
	
	
	
	invalid:
	printf("config file invalid, exiting...\n");
	exit(1);
}