Repository navigation
Add examples for for JACK transport and timebase master #74
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
99adaf8
6bfad0f
d4e3852
25071c0
f03487e
b107251
b9ec7aa
ead365d
da75599
e5c018e
7b9b956
60e57a8
29603b1
4d35bf9
337910f
0bac2e6
131b8a5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| #!/usr/bin/env python3 | ||
| """A simple JACK timebase master.""" | ||
|
|
||
| import argparse | ||
| import sys | ||
| from threading import Event | ||
|
|
||
| import jack | ||
|
|
||
|
|
||
| class TimebaseMasterClient(jack.Client): | ||
| def __init__(self, name, *, bpm=120.0, beats_per_bar=4, beat_type=4, | ||
| ticks_per_beat=1920, conditional=False, debug=False, **kw): | ||
| super().__init__(name, **kw) | ||
| self.beats_per_bar = int(beats_per_bar) | ||
| self.beat_type = int(beat_type) | ||
| self.bpm = bpm | ||
| self.conditional = conditional | ||
| self.debug = debug | ||
| self.ticks_per_beat = int(ticks_per_beat) | ||
| self.stop_event = Event() | ||
| self.set_shutdown_callback(self.shutdown) | ||
|
|
||
| def shutdown(self, status, reason): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That indeed sounds a bit much. Strictly speaking, all instance variables should have an underscore, but I think this would be distracting in this simple example. But I still think it would make sense for the two callback functions to have the same private-ness, wouldn't it? |
||
| print('JACK shutdown:', reason, status) | ||
| self.stop_event.set() | ||
|
|
||
| def _tb_callback(self, state, nframes, pos, new_pos): | ||
| if self.debug and new_pos: | ||
| print("New pos:", jack.position2dict(pos)) | ||
|
mgeier marked this conversation as resolved.
Resolved
|
||
|
|
||
| # Adapted from: | ||
| # https://github.com/jackaudio/jack2/blob/develop/example-clients/transport.c#L66 | ||
| if new_pos: | ||
| pos.beats_per_bar = float(self.beats_per_bar) | ||
| pos.beats_per_minute = self.bpm | ||
| pos.beat_type = float(self.beat_type) | ||
| pos.ticks_per_beat = float(self.ticks_per_beat) | ||
| pos.valid = jack._lib.JackPositionBBT | ||
|
|
||
| minutes = pos.frame / (pos.frame_rate * 60.0) | ||
| abs_tick = minutes * self.bpm * self.ticks_per_beat | ||
| abs_beat = abs_tick / self.ticks_per_beat | ||
|
mgeier marked this conversation as resolved.
Resolved
|
||
|
|
||
| pos.bar = int(abs_beat / self.beats_per_bar) | ||
| pos.beat = int(abs_beat - (pos.bar * self.beats_per_bar) + 1) | ||
| pos.tick = int(abs_tick - (abs_beat * self.ticks_per_beat)) | ||
| pos.bar_start_tick = pos.bar * self.beats_per_bar * self.ticks_per_beat | ||
| pos.bar += 1 # adjust start to bar 1 | ||
| else: | ||
| # Compute BBT info based on previous period. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not sure, but don't you have to check If it's guaranteed to be valid, you should probably add an
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. My interpretation of http://jackaudio.org/api/structjack__position__t.html is that
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. OK, sounds interesting. What about slapping an We can remove it if it turns out to be wrong. |
||
| pos.tick += int(nframes * pos.ticks_per_beat * | ||
| pos.beats_per_minute / (pos.frame_rate * 60)) | ||
|
|
||
| while pos.tick >= pos.ticks_per_beat: | ||
| pos.tick -= int(pos.ticks_per_beat) | ||
| pos.beat += 1 | ||
|
|
||
| if pos.beat > pos.beats_per_bar: | ||
| pos.beat = 1 | ||
| pos.bar += 1 | ||
| pos.bar_start_tick += pos.beats_per_bar * pos.ticks_per_beat | ||
|
|
||
| if self.debug: | ||
| print("Pos:", jack.position2dict(pos)) | ||
|
|
||
| def become_timebase_master(self, conditional=None): | ||
|
mgeier marked this conversation as resolved.
Resolved
|
||
| return self.set_timebase_callback(self._tb_callback, conditional | ||
| if conditional is not None | ||
| else self.conditional) | ||
|
|
||
|
|
||
| def main(args=None): | ||
| ap = argparse.ArgumentParser(description=__doc__) | ||
| ap.add_argument( | ||
| '-d', '--debug', | ||
| action='store_true', | ||
| help="Enable debug messages") | ||
| ap.add_argument( | ||
| '-c', '--conditional', | ||
| action='store_true', | ||
| help="Exit if another timebase master is already active") | ||
| ap.add_argument( | ||
| '-n', '--client-name', | ||
| metavar='NAME', | ||
| default='timebase', | ||
| help="JACK client name (default: %(default)s)") | ||
| ap.add_argument( | ||
| '-m', '--meter', | ||
| default='4/4', | ||
| help="Meter as <beats-per-bar>/<beat-type> (default: %(default)s)") | ||
| ap.add_argument( | ||
| '-t', '--ticks-per-beat', | ||
| type=int, | ||
| metavar='NUM', | ||
| default=1920, | ||
| help="Ticks per beat (default: %(default)s)") | ||
| ap.add_argument( | ||
| 'tempo', | ||
| nargs='?', | ||
| type=float, | ||
| default=120.0, | ||
| help="Tempo in beats per minute (0.1-300.0, default: %(default)s)") | ||
|
|
||
| args = ap.parse_args(args) | ||
|
|
||
| try: | ||
| beats_per_bar, beat_type = (int(x) for x in args.meter.split('/', 1)) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The second argument to
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You get a better error, because
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
vs. I would argue that the second is better, especially since the error for too few But it doesn't matter at all, since you are catching this exception, and nobody ever sees it, right?
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. BTW, this would be a perfect opportunity to use map(int, args.meter.split('/'))
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ... or of course with |
||
| except (TypeError, ValueError): | ||
| print("Error: invalid meter: {}\n".format(args.meter)) | ||
| ap.print_help() | ||
| return 2 | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would use https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.error
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
|
||
| try: | ||
| tbmaster = TimebaseMasterClient( | ||
| args.client_name, | ||
| bpm=max(0.1, min(300.0, args.tempo)), | ||
| beats_per_bar=beats_per_bar, | ||
| beat_type=beat_type, | ||
| ticks_per_beat=args.ticks_per_beat, | ||
| debug=args.debug) | ||
| except jack.JackError as exc: | ||
| return "Could not create timebase master JACK client: {}".format(exc) | ||
|
|
||
| with tbmaster: | ||
| if tbmaster.become_timebase_master(args.conditional): | ||
| try: | ||
| print("Press Ctrl-C to quit...") | ||
| tbmaster.stop_event.wait() | ||
| except KeyboardInterrupt: | ||
| print('') | ||
| finally: | ||
| try: | ||
| tbmaster.release_timebase() | ||
|
mgeier marked this conversation as resolved.
Resolved
|
||
| except jack.JackError: | ||
| # another JACK client might have grabbed timebase master | ||
| pass | ||
| else: | ||
| return "Timebase master already present. Exiting..." | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| sys.exit(main() or 0) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| #!/usr/bin/env python3 | ||
| """Query or change the JACK transport state.""" | ||
|
|
||
| import argparse | ||
| import string | ||
| import sys | ||
|
|
||
| import jack | ||
|
|
||
|
|
||
| STATE_LABELS = { | ||
| jack.ROLLING: "rolling", | ||
| jack.STOPPED: "stopped", | ||
| jack.STARTING: "starting", | ||
| jack.NETSTARTING: "waiting for network sync", | ||
| } | ||
|
|
||
|
|
||
| def main(args=None): | ||
| ap = argparse.ArgumentParser(description=__doc__) | ||
| ap.add_argument( | ||
| '-c', '--client-name', | ||
| metavar='NAME', | ||
| default='transporter', | ||
| help="JACK client name (default: %(default)s)") | ||
| ap.add_argument( | ||
| 'command', | ||
| nargs='?', | ||
| default='status', | ||
| choices=['query', 'rewind', 'start', 'status', 'stop', 'toggle'], | ||
| help="Transport command") | ||
|
|
||
| args = ap.parse_args(args) | ||
|
|
||
| try: | ||
| client = jack.Client(args.client_name) | ||
| except jack.JackError as exc: | ||
| return "Could not create JACK client: {}".format(exc) | ||
|
|
||
| state = client.transport_state | ||
| result = 0 | ||
|
|
||
| if args.command == 'status': | ||
| print("JACK transport is {}.".format(STATE_LABELS[state])) | ||
| result = 1 if state == jack.STOPPED else 0 | ||
| elif args.command == 'query': | ||
| print("State: {}".format(STATE_LABELS[state])) | ||
| info = client.transport_query()[1] | ||
|
|
||
| for field in sorted(info): | ||
| label = string.capwords(field.replace('_', ' ')) | ||
| print("{}: {}".format(label, info[field])) | ||
|
|
||
| result = 1 if state == jack.STOPPED else 0 | ||
| elif args.command == 'start': | ||
| if state == jack.STOPPED: | ||
| client.transport_start() | ||
| elif args.command == 'stop': | ||
| if state != jack.STOPPED: | ||
| client.transport_stop() | ||
| elif args.command == 'toggle': | ||
| if state == jack.STOPPED: | ||
| client.transport_start() | ||
| else: | ||
| client.transport_stop() | ||
| elif args.command == 'rewind': | ||
| client.transport_frame = 0 | ||
|
|
||
| client.close() | ||
| return result | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| sys.exit(main() or 0) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is this
int()here?According to http://jackaudio.org/files/docs/html/structjack__position__t.html, a
doubleis expected.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That doesn't make much sense to me, musically, but I can convert the instance attribute via
float()when setting theposattribute.Also, since tick is an
int32_t, we need to be careful when assigning expressions to it that involveticks_per_beat, that the type of the expression result is anint, otherwisecffiwill throw an error.I noticed that
beats_per_barandbeat_typeare also of typefloat(again, makes no sense to me, musically), so I changed the code to convert these as well when assigning topos, while keeping the instance attributes as typeint: e5c018eThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Probably not, probably it does?
I would simply allow
floatvalues because JACK allows them.Yes, but it doesn't help if we assign an
inttoticks_per_beat, because it will be immediately converted to adouble.Again, I don't know, I would still allow it if JACK thinks that's a good idea.
I would just pass it through to the JACK functions, CFFI will check it and complain if it isn't right.
I think converting the inputs with
int()is not a good idea, because it silently converts user-providedfloatvalues.If you really want to require
ints (which I think you shouldn't), you should at least fail loudly when the uses tries to use afloatvalue.Also, it's very confusing if your local copy of the values have different data types than the values in the
posstruct, isn't it?