xref: /freebsd/share/examples/sound/midi.c (revision 38a52bd3b5cac3da6f7f6eef3dd050e6aa08ebb3)
1 /*
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2022 Goran Mekić
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <unistd.h>
29 
30 #include "ossmidi.h"
31 
32 int
33 main()
34 {
35 	midi_event_t event;
36 	midi_config_t midi_config;
37 	int l = -1;
38 	unsigned char raw;
39 
40 	midi_config.device = "/dev/umidi1.0";
41 	oss_midi_init(&midi_config);
42 
43 	while ((l = read(midi_config.fd, &raw, sizeof(raw))) != -1) {
44 		if (!(raw & 0x80)) {
45 			continue;
46 		}
47 		event.type = raw & CMD_MASK;
48 		event.channel = raw & CHANNEL_MASK;
49 		switch (event.type) {
50 		case NOTE_ON:
51 		case NOTE_OFF:
52 		case CONTROLER_ON:
53 			if ((l = read(midi_config.fd, &(event.note), sizeof(event.note))) == -1) {
54 				perror("Error reading MIDI note");
55 				exit(1);
56 			}
57 			if ((l = read(midi_config.fd, &(event.velocity), sizeof(event.velocity))) == -1) {
58 				perror("Error reading MIDI velocity");
59 				exit(1);
60 			}
61 			break;
62 		}
63 		switch (event.type) {
64 		case NOTE_ON:
65 		case NOTE_OFF:
66 			printf("Channel %d, note %d, velocity %d\n", event.channel, event.note, event.velocity);
67 			break;
68 		case CONTROLER_ON:
69 			printf("Channel %d, controller %d, value %d\n", event.channel, event.controller, event.value);
70 			break;
71 		default:
72 			printf("Unknown event type %d\n", event.type);
73 		}
74 	}
75 	return 0;
76 }
77