Skip to content

Instantly share code, notes, and snippets.

@JRHeaton
Last active December 24, 2015 20:49
Show Gist options
  • Save JRHeaton/6861209 to your computer and use it in GitHub Desktop.
Save JRHeaton/6861209 to your computer and use it in GitHub Desktop.
This code subscribes to all currently connected midi devices, listens to the messages they're sending to the computer, and if uses pitch bend messages as scrolling instructions. Try it, it works great! TODO: have continuous scrolling when position is held.
//
// main.c
// midiscroll
//
// Created by John Heaton on 10/6/13.
// Copyright (c) 2013 John Heaton. All rights reserved.
//
#include <CoreFoundation/CoreFoundation.h>
#include <CoreMIDI/CoreMIDI.h>
#include <CoreGraphics/CoreGraphics.h>
#define SENSITIVITY_ADJUSTMENT 1.25
struct {
MIDIClientRef client;
MIDIPortRef p_in;
} ctx;
void ms_kill_all_the_things(int sig) {
printf("closing up shop\n");
MIDIPortDispose(ctx.p_in);
MIDIClientDispose(ctx.client);
exit(0);
}
void ms_midi_read_cb(const MIDIPacketList *pktlist, void *readProcRefCon, void *srcConnRefCon) {
const MIDIPacket *packet = &pktlist->packet[0];
for (int i=0;i<pktlist->numPackets;++i) {
int is_pb = packet->data[0] == 0xe0;
int pb_val = packet->data[2];
if(is_pb && pb_val != 64) {
double adjusted = ((pb_val + 1) - (128 / 2)) / 6.4;
adjusted *= SENSITIVITY_ADJUSTMENT;
if(adjusted < 0)
adjusted = MIN(-1, adjusted);
else
adjusted = MAX(1, adjusted);
CGEventRef scrollEvent = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitLine, 1, adjusted);
CGEventPost(kCGHIDEventTap, scrollEvent);
CFRelease(scrollEvent);
}
packet = MIDIPacketNext(packet);
}
}
int main(int argc, const char * argv[]) {
MIDIClientCreate(CFSTR("midiscroll.cli"), NULL, NULL, &ctx.client);
MIDIInputPortCreate(ctx.client, CFSTR("midiscroll-listener"), ms_midi_read_cb, NULL, &ctx.p_in);
for(int i=0;i<MIDIGetNumberOfDevices();++i) {
MIDIDeviceRef device = MIDIGetDevice(i);
MIDIEntityRef entity = MIDIDeviceGetEntity(device, 0);
MIDIEndpointRef source = MIDIEntityGetSource(entity, 0);
MIDIPortConnectSource(ctx.p_in, source, NULL);
}
signal(SIGINT, ms_kill_all_the_things);
CFRunLoopRun();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment