pax_global_header00006660000000000000000000000064127740231070014515gustar00rootroot0000000000000052 comment=ab2f4b30f3fa0e7b2e724e3ab30c12f6795ee971 jack_midi_clock-0.4.3/000077500000000000000000000000001277402310700146065ustar00rootroot00000000000000jack_midi_clock-0.4.3/AUTHORS000066400000000000000000000001151277402310700156530ustar00rootroot00000000000000Gabriel M. Beddingfield Robin Gareus jack_midi_clock-0.4.3/COPYING000066400000000000000000000432541277402310700156510ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. jack_midi_clock-0.4.3/ChangeLog000066400000000000000000000032421277402310700163610ustar00rootroot000000000000002016-10-01 (0.4.3) Robin Gareus * fix JACK API usage (jack_get_time) * ignore compiler warning -Wunused-result 2015-11-16 (0.4.2) Robin Gareus * wake main thread with pipe msg instead of sleep(1) polling * add --strict-bpm option for tempo interpretation * add jitter option (instrumentation tool for testing) * code review & documentation 2013-05-27 (0.4.1) Robin Gareus * remove reference to [packed] jack_double 2013-05-18 (0.4.0) Robin Gareus * accurate song-position + start/continue sync * send song-position on transport locate * allow to compare BBT dump w/jack-transport 2013-05-17 (0.3.2) Robin Gareus * transmit song position pointer - beats since the start of the song * dump BBT pos info 2013-05-17 (0.3.1) Robin Gareus * fix missing -lpthread (newer gcc) * expose DLL bandwidth as option to jack_mclk_dump 2013-05-16 (0.3.0) Robin Gareus * fix cycle of first Mclk message (Starting vs Rolling) * add debug tool - midi-clock dump 2013-05-16 (0.2.0) Robin Gareus * rewrite in POSIX-C * fix (ignore) metrum. midi beat clock is only concearned with beats * auto-generate man-page from source * honor jack-shutdown callback * allow to auto-connect ports * allow to specify/override timecode-master BPM * add upstream debian packaging 2013-05-15 (0.1.1) Robin Gareus * fix rounding error and alignment (robin) * clean up and standardize build environment (robin) * implement MIDI start, stop and continue (gabriel) 2009-08-01 (0.1.0) Gabriel M. Beddingfield * initial release jack_midi_clock-0.4.3/Makefile000066400000000000000000000037661277402310700162620ustar00rootroot00000000000000PREFIX ?= /usr/local bindir ?= $(PREFIX)/bin mandir ?= $(PREFIX)/share/man CFLAGS ?= -Wall -O3 VERSION?=$(shell (git describe --tags HEAD 2>/dev/null || echo "v0.4.3") | sed 's/^v//') ############################################################################### ifeq ($(shell pkg-config --exists jack || echo no), no) $(warning *** libjack from http://jackaudio.org is required) $(error Please install libjack-dev, libjack-jackd2-dev) endif ############################################################################### override CFLAGS += -DWITH_JITTER override CFLAGS += -DVERSION="\"$(VERSION)\"" override CFLAGS += `pkg-config --cflags jack` LOADLIBES = `pkg-config --cflags --libs jack` -lm -lpthread man1dir = $(mandir)/man1 ############################################################################### default: all jack_midi_clock: jack_midi_clock.c jack_mclk_dump: jack_mclk_dump.c install-bin: jack_midi_clock jack_mclk_dump install -d $(DESTDIR)$(bindir) install -m755 jack_midi_clock $(DESTDIR)$(bindir) install -m755 jack_mclk_dump $(DESTDIR)$(bindir) install-man: jack_midi_clock.1 jack_mclk_dump.1 install -d $(DESTDIR)$(man1dir) install -m644 jack_midi_clock.1 $(DESTDIR)$(man1dir) install -m644 jack_mclk_dump.1 $(DESTDIR)$(man1dir) uninstall-bin: rm -f $(DESTDIR)$(bindir)/jack_midi_clock rm -f $(DESTDIR)$(bindir)/jack_mclk_dump -rmdir $(DESTDIR)$(bindir) uninstall-man: rm -f $(DESTDIR)$(man1dir)/jack_midi_clock.1 rm -f $(DESTDIR)$(man1dir)/jack_mclk_dump.1 -rmdir $(DESTDIR)$(man1dir) -rmdir $(DESTDIR)$(mandir) clean: rm -f jack_midi_clock jack_mclk_dump man: jack_midi_clock jack_mclk_dump help2man -N -n 'JACK MIDI Beat Clock Generator' -o jack_midi_clock.1 ./jack_midi_clock help2man -N -n 'JACK MIDI Beat Clock Decoder' -o jack_mclk_dump.1 ./jack_mclk_dump all: jack_midi_clock jack_mclk_dump install: install-bin install-man uninstall: uninstall-bin uninstall-man .PHONY: default all man clean install install-bin install-man uninstall uninstall-bin uninstall-man jack_midi_clock-0.4.3/README.md000066400000000000000000000040741277402310700160720ustar00rootroot00000000000000Jack MIDI Clock =============== This program is a [JACK](http://jackaudio.org/) client that sends MIDI beat clock pulses based on the current tempo given by the JACK transport. Dependencies ------------ * Standard C development tools (cc, make, libc) * Jack Audio Connection Kit (libjack-dev) Installation ------------ ```bash git clone git://github.com/x42/jack_midi_clock.git cd jack_midi_clock make sudo make install ``` The makefile honors `CFLAGS`, `LDFLAGS`, `DESTDIR` and `PREFIX` variables. e.g. `make install PREFIX=/usr` and also supports `uninstall` target as well as individual `[un]install-bin`, `[un]install-man` targets. Usage ----- Start jackd and some application to act as JACK-timecode master, then launch: ```bash jack_midi_clock & ``` The application runs until it receives a TERM or QUIT signal or jackd terminates. Also see `jack_midi_clock -h` or the included manual page. License ------- `jack_midi_clock` is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 or (at your option) any later version. Copyright (C) 2009 by Gabriel M. Beddingfield Copyright (C) 2013 by Robin Gareus See COPYING for the complete license text. About JACK MIDI Clock --------------------- Jack Midi Clock is free software written to glorify God and His Savior Jesus Christ. I dedicate this code to spreading His word and His love. If you have found this software useful, please make a donation to a Christian missionary (of your choice).[1] Suggested donation is US $10 or US $20. Questions? Drop me a line: gabriel@teuton.org Grace and peace to you all! [1] Suggestion on missionaries: Wycliffe Bible Translators (www.wycliffe.org) PS. Updates and fixes to the source as well as build-system - contributed by R. Gareus in 2013 - were motivated by the superdirt.net live performance at the Linux Audio Conference 2013. Robin neither approves nor advises against monetary donations, but he subscribes to the virtue of altruistic love and wishes you to do likewise. jack_midi_clock-0.4.3/jack_mclk_dump.1000066400000000000000000000016751277402310700176440ustar00rootroot00000000000000.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.4. .TH JACK_MCLK_DUMP "1" "October 2016" "jack_mclk_dump version v0.4.3" "User Commands" .SH NAME jack_mclk_dump \- JACK MIDI Beat Clock Decoder .SH SYNOPSIS .B jack_mclk_dump [ \fI\,OPTIONS \/\fR] [\fI\,JACK-port\/\fR] .SH DESCRIPTION jack_mclk_dump \- JACK MIDI Clock dump. .SH OPTIONS .TP \fB\-b\fR, \fB\-\-bandwidth\fR <1/Hz> DLL bandwidth in 1/Hz (default: 6.0) .TP \fB\-h\fR, \fB\-\-help\fR display this help and exit .TP \fB\-n\fR, \fB\-\-newline\fR print a newline after each Tick .TP \fB\-V\fR, \fB\-\-version\fR print version information and exit .PP This tool subscribes to a JACK Midi Port and prints received Midi beat clock and BPM to stdout. .PP See also: jack_midi_clock(1) .SH "REPORTING BUGS" Report bugs to Robin Gareus .br Website and manual: .SH COPYRIGHT Copyright \(co GPL 2013 Robin Gareus jack_midi_clock-0.4.3/jack_mclk_dump.c000066400000000000000000000314041277402310700177170ustar00rootroot00000000000000/* JACK MIDI Beat Clock Parser * * (C) 2013 Robin Gareus * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ //#define JACK_TRANSPORT_SYNC_CHECK // not rt-safe #ifdef WIN32 #include #include #define pthread_t //< override jack.h def #endif #include #include #include #include #include #include #include #include #ifndef WIN32 #include #include #endif #include #include #include #include #define RBSIZE 20 #define METRUM (4) // TODO allow to configure. typedef struct { uint8_t msg; int pos; unsigned long long int tme; } timenfo; typedef struct { double t0; ///< time of the current Mclk tick double t1; ///< expected next Mclk tick double e2; ///< second order loop error double b, c, omega; ///< DLL filter coefficients } DelayLockedLoop; struct appstate { timenfo pt; // previous timeinfo DelayLockedLoop dll; uint64_t transport; /// timestamp of transport start/continue, 0 if stopped uint64_t sequence; /// beat clock signals since transport-state change int bcnt; /// last song position }; /* jack connection */ jack_client_t *j_client = NULL; jack_port_t *mclk_input_port; /* threaded communication */ static jack_ringbuffer_t *rb = NULL; static pthread_mutex_t msg_thread_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t data_ready = PTHREAD_COND_INITIALIZER; /* application state */ static double samplerate = 48000.0; static volatile unsigned long long monotonic_cnt = 0; static int run = 1; /* options */ static char newline = '\r'; // or '\n'; static short keeplastclk = 1; // print newline on events static double dll_bandwidth = 6.0; // 1/Hz static struct appstate state; static void print_time_event(struct appstate *s, timenfo *t); /** * parse Midi Beat Clock events * enqueue to ring buffer and wake-up 'dump' thread */ static void process_jmidi_event(jack_midi_event_t *ev, unsigned long long mfcnt) { timenfo tnfo; memset(&tnfo, 0, sizeof(timenfo)); if (ev->size != 1 && !((ev->size == 3 && ev->buffer[0] == 0xf2 ))) return; switch(ev->buffer[0]) { case 0xf2: // position tnfo.pos = (ev->buffer[2]<<7) | ev->buffer[1]; break; case 0xf8: // clock case 0xfa: // start case 0xfb: // continue case 0xfc: // stop break; default: return; } tnfo.msg = ev->buffer[0]; tnfo.tme = mfcnt + ev->time; #ifdef JACK_TRANSPORT_SYNC_CHECK print_time_event(&state, &tnfo); #else if (jack_ringbuffer_write_space(rb) >= sizeof(timenfo)) { jack_ringbuffer_write(rb, (void *) &tnfo, sizeof(timenfo)); } if (pthread_mutex_trylock (&msg_thread_lock) == 0) { pthread_cond_signal (&data_ready); pthread_mutex_unlock (&msg_thread_lock); } #endif } /** * jack process callback */ static int process(jack_nframes_t nframes, void *arg) { void *jack_buf = jack_port_get_buffer(mclk_input_port, nframes); int nevents = jack_midi_get_event_count(jack_buf); int n; for (n=0; n < nevents; n++) { jack_midi_event_t ev; jack_midi_event_get(&ev, jack_buf, n); process_jmidi_event(&ev, monotonic_cnt); } monotonic_cnt += nframes; return 0; } /** * callback if jack server terminates */ void jack_shutdown(void *arg) { j_client=NULL; pthread_cond_signal (&data_ready); fprintf (stderr, "jack server shutdown\n"); } /** * cleanup and exit * call this function only after everything has been initialized! */ void cleanup(void) { if (j_client) { jack_deactivate (j_client); jack_client_close (j_client); } if (rb) { jack_ringbuffer_free(rb); } j_client = NULL; } /** * open a client connection to the JACK server */ static int init_jack(const char *client_name) { jack_status_t status; j_client = jack_client_open (client_name, JackNullOption, &status); if (j_client == NULL) { fprintf (stderr, "jack_client_open() failed, status = 0x%2.0x\n", status); if (status & JackServerFailed) { fprintf (stderr, "Unable to connect to JACK server\n"); } return (-1); } if (status & JackServerStarted) { fprintf (stderr, "JACK server started\n"); } if (status & JackNameNotUnique) { client_name = jack_get_client_name(j_client); fprintf (stderr, "jack-client name: `%s'\n", client_name); } jack_set_process_callback (j_client, process, 0); #ifndef WIN32 jack_on_shutdown (j_client, jack_shutdown, NULL); #endif samplerate = (double) jack_get_sample_rate (j_client); return (0); } static int jack_portsetup(void) { if ((mclk_input_port = jack_port_register(j_client, "mclk_in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0)) == 0) { fprintf (stderr, "cannot register mclk input port !\n"); return (-1); } return (0); } static void port_connect(char *mclk_port) { if (mclk_port && jack_connect(j_client, mclk_port, jack_port_name(mclk_input_port))) { fprintf(stderr, "cannot connect port %s to %s\n", mclk_port, jack_port_name(mclk_input_port)); } } /** * initialize DLL * set current time and period in samples */ static void init_dll(DelayLockedLoop *dll, double tme, double period) { const double omega = 2.0 * M_PI * period / dll_bandwidth / samplerate; dll->b = 1.4142135623730950488 * omega; dll->c = omega * omega; dll->e2 = period / samplerate; dll->t0 = tme / samplerate; dll->t1 = dll->t0 + dll->e2; } /** * run one loop iteration. * @param tme time of event (in samples) * @return smoothed interval (period) [1/Hz] */ static double run_dll(DelayLockedLoop *dll, double tme) { const double e = tme / samplerate - dll->t1; dll->t0 = dll->t1; dll->t1 += dll->b * e + dll->e2; dll->e2 += dll->c * e; return (dll->t1 - dll->t0); } const char *msg_to_string(uint8_t msg) { switch(msg) { case 0xf8: return "clk"; case 0xfa: return "start"; case 0xfb: return "continue"; case 0xfc: return "stop"; default: return "??"; } } #ifdef JACK_TRANSPORT_SYNC_CHECK static const char *jt_to_string(jack_transport_state_t jts) { switch(jts) { case JackTransportStopped: return "."; case JackTransportRolling: return ">"; case JackTransportStarting: return "*"; default: return "?"; } } static void print_jt(jack_transport_state_t jts, jack_position_t *jtpos) { if(jtpos->valid & JackPositionBBT) { printf(" %s:%4d|%d|%d", jt_to_string(jts), jtpos->bar, jtpos->beat, (int) floor(4.0 * jtpos->tick / (double) jtpos->ticks_per_beat)); } else { printf(" X:----|-|-"); } } #endif static void print_time_event(struct appstate *s, timenfo *t) { double flt_bpm = 0; #ifdef JACK_TRANSPORT_SYNC_CHECK jack_position_t jtpos; jack_transport_state_t jts = jack_transport_query(j_client, &jtpos); #endif if (t->msg == 0xf2) { /* song position */ s->bcnt = t->pos; if (newline == '\r' && keeplastclk) printf("\n"); fprintf(stdout, "POS (0x%04x) %4d.%d[beats] %4d|%d|%d [BBT@4/4] %-16s", t->pos, 1 + t->pos/4, t->pos%4, 1 + (t->pos/4/METRUM), 1 + ((t->pos/4)%METRUM), t->pos%4, ""); #ifdef JACK_TRANSPORT_SYNC_CHECK printf(" "); #endif fprintf(stdout, " @ %lld \n", t->tme); } else if (t->msg == 0xfa || t->msg == 0xfb || t->msg == 0xfc) { /* start, stop, continue -> reset */ s->sequence = 0; if (t->msg == 0xfc) s->transport = 0; // stop else s->transport = t->tme; if (t->msg == 0xfa) s->bcnt = 0; // start if (newline == '\r' && keeplastclk) printf("\n"); fprintf(stdout, "EVENT (0x%02x) %-49s", t->msg, msg_to_string(t->msg)); #ifdef JACK_TRANSPORT_SYNC_CHECK printf(" "); #endif fprintf(stdout, " @ %lld \n", t->tme); } else if (s->sequence == 1) { /* 2nd event in sequence -> initialize DLL with time difference */ init_dll(&s->dll, t->tme, (t->tme - s->pt.tme)); flt_bpm = samplerate * 60.0 / (24.0 * (double)(t->tme - s->pt.tme)); } else if (s->sequence > 1) { /* run dll, calculate filtered bpm */ flt_bpm = 60.0 / (24.0 * run_dll(&s->dll, t->tme)); } /* print clock & bpm */ if (t->msg == 0xf8 && s->sequence > 0) { const double samples_per_quarter_note = (t->tme - s->pt.tme) * 24.0; const double bpm = samplerate * 60.0 / samples_per_quarter_note; fprintf(stdout, "CLK cur: %7.2f[BPM] flt: %7.2f[BPM] dt: %4lld[sm]", bpm, flt_bpm, (t->tme - s->pt.tme)); if (s->transport) { int bp = s->bcnt + s->sequence / 6; printf(" %4d|%d|%d", 1 + (bp/4/METRUM), 1 + ((bp/4)%METRUM), bp%4); } else { printf(" ----|-|-"); } #ifdef JACK_TRANSPORT_SYNC_CHECK print_jt(jts, &jtpos); #endif fprintf(stdout, " @ %lld %c", t->tme, newline); } else if (t->msg == 0xf8) { fprintf(stdout, "CLK cur: ??[BPM] flt: ??[BPM] dt: ??[sm] "); #ifdef JACK_TRANSPORT_SYNC_CHECK print_jt(jts, &jtpos); #endif fprintf(stdout, " @ %lld %c", t->tme, newline); } if (t->msg == 0xf8) { memcpy(&s->pt, t, sizeof(timenfo)); s->sequence++; } } /* TODO: it's not safe to call pthread_cond_signal from a signal handler * See http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cond_broadcast.html */ static void wearedone(int sig) { fprintf(stderr,"caught signal - shutting down.\n"); run=0; pthread_cond_signal (&data_ready); } /************************** * main application code */ static struct option const long_options[] = { {"bandwidth", required_argument, 0, 'b'}, {"help", no_argument, 0, 'h'}, {"newline", no_argument, 0, 'n'}, {"version", no_argument, 0, 'V'}, {NULL, 0, NULL, 0} }; static void usage (int status) { printf ("jack_mclk_dump - JACK MIDI Clock dump.\n\n"); printf ("Usage: jack_mclk_dump [ OPTIONS ] [JACK-port]\n\n"); printf ("Options:\n\ -b, --bandwidth <1/Hz> DLL bandwidth in 1/Hz (default: 6.0)\n\ -h, --help display this help and exit\n\ -n, --newline print a newline after each Tick\n\ -V, --version print version information and exit\n\ \n"); printf ("\n\ This tool subscribes to a JACK Midi Port and prints received Midi\n\ beat clock and BPM to stdout.\n\ \n\ See also: jack_midi_clock(1)\n\ \n"); printf ("Report bugs to Robin Gareus \n" "Website and manual: \n" ); exit (status); } static int decode_switches (int argc, char **argv) { int c; while ((c = getopt_long (argc, argv, "b:" /* bandwidth */ "h" /* help */ "n" /* newline */ "V", /* version */ long_options, (int *) 0)) != EOF) { switch (c) { case 'b': dll_bandwidth = atof(optarg); if (dll_bandwidth < 0.1 || dll_bandwidth > 100.0) { fprintf(stderr, "Invalid bandwidth, should be 0.1 <= bw <= 100.0. Using 6.0sec\n"); dll_bandwidth = 6.0; } break; case 'n': newline = '\n'; break; case 'V': printf ("jack_mclk_dump version %s\n\n", VERSION); printf ("Copyright (C) GPL 2013 Robin Gareus \n"); exit (0); case 'h': usage (0); default: usage (EXIT_FAILURE); } } return optind; } int main (int argc, char ** argv) { int i; decode_switches (argc, argv); if (init_jack("jack_mclk_dump")) goto out; if (jack_portsetup()) goto out; rb = jack_ringbuffer_create(RBSIZE * sizeof(timenfo)); if (mlockall (MCL_CURRENT | MCL_FUTURE)) { fprintf(stderr, "Warning: Can not lock memory.\n"); } if (jack_activate (j_client)) { fprintf (stderr, "cannot activate client.\n"); goto out; } while (optind < argc) port_connect(argv[optind++]); #ifndef _WIN32 signal(SIGHUP, wearedone); signal(SIGINT, wearedone); #endif memset(&state, 0, sizeof(struct appstate)); pthread_mutex_lock (&msg_thread_lock); /* all systems go */ while (run && j_client) { const int mqlen = jack_ringbuffer_read_space (rb) / sizeof(timenfo); for (i=0; i < mqlen; ++i) { /* process Mclk event */ timenfo t; jack_ringbuffer_read(rb, (char*) &t, sizeof(timenfo)); print_time_event(&state, &t); } fflush(stdout); pthread_cond_wait (&data_ready, &msg_thread_lock); } pthread_mutex_unlock (&msg_thread_lock); out: cleanup(); return 0; } /* vi:set ts=8 sts=2 sw=2: */ jack_midi_clock-0.4.3/jack_midi_clock.1000066400000000000000000000054241277402310700177620ustar00rootroot00000000000000.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.4. .TH JACK_MIDI_CLOCK "1" "October 2016" "jack_midi_clock version v0.4.3" "User Commands" .SH NAME jack_midi_clock \- JACK MIDI Beat Clock Generator .SH SYNOPSIS .B jack_midi_clock [ \fI\,OPTIONS \/\fR] [\fI\,JACK-port\/\fR]\fI\,*\/\fR .SH DESCRIPTION jack_midi_clock \- JACK app to generate MCLK from JACK transport. .SH OPTIONS .TP \fB\-b\fR , \fB\-\-bpm\fR default BPM (if jack timecode master in not available) .TP \fB\-B\fR, \fB\-\-force\-bpm\fR ignore jack timecode master .TP \fB\-d\fR , \fB\-\-resync\-delay\fR seconds between 'song\-position' and 'continue' message .TP \fB\-J\fR, \fB\-\-jitter\-level\fR add artificial jitter to the signal 0..20% default: off (0) .TP \fB\-P\fR, \fB\-\-no\-position\fR do not send song\-position (0xf2) messages .TP \fB\-T\fR, \fB\-\-no\-transport\fR do not send start/stop/continue messages .TP \fB\-s\fR, \fB\-\-strict\-bpm\fR interpret tempo strictly as beats per minute (default is quarter\-notes per minute) .TP \fB\-h\fR, \fB\-\-help\fR display this help and exit .TP \fB\-V\fR, \fB\-\-version\fR print version information and exit .PP jack_midi_clock sends MIDI beat clock message if jack\-transport is rolling. it also sends start, continue and stop MIDI realtime messages whenever the transport changes state (unless \fB\-T\fR option is used). .PP In order for jack_midi_clock to send clock messages, a JACK timecode master must be present and provide the tempo map (bar, beat, tick). Alternatively the \fB\-b\fR option can be used to set a default BPM value. If a value larger than zero is given, it will be used if no timecode master is present. Combined with the \fB\-B\fR option it can used to override and ignore the JACK timecode master and only act on transport state alone. .PP Either way, jack_midi_clock will never act as timecode master itself. .PP Note that song\-position information is only sent if a timecode master is present ad the \fB\-P\fR option is not given. .PP To allow external synths to accurately sync to song\-position, there is a two second delay between the 'song\-position changed' message (which is not a MIDI realtime message) and the 'continue transport' message. This delay can be configured with the \fB\-d\fR option and is only relevant for if playback starts at a bar|beat|tick other than 1|1|0 in which case a 'start' message is sent immediately. .PP jack_midi_clock runs until it receives a HUP or INT signal or jackd is terminated. .PP See also: jack_transport(1), jack_mclk_dump(1) .SH "REPORTING BUGS" Report bugs to Robin Gareus .br Website: https://github.com/x42/jack_midi_clock/ .SH COPYRIGHT Copyright \(co GPL 2013 Robin Gareus .br Copyright \(co GPL 2009 Gabriel M. Beddingfield jack_midi_clock-0.4.3/jack_midi_clock.c000066400000000000000000000463271277402310700200530ustar00rootroot00000000000000/* JACK-Transport MIDI Beat Clock Generator * * Copyright (C) 2013 Robin Gareus * Copyright (C) 2009 Gabriel M. Beddingfield * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include #include #include #include #ifndef WIN32 #include #endif /* bitwise flags -- used w/ msg_filter */ enum { MSG_NO_TRANSPORT = 1, /**< do not send start/stop/continue messages */ MSG_NO_POSITION = 2 /**< do not send absolute song position */ }; /* jack_position_t - excerpt */ struct bbtpos { jack_position_bits_t valid; /**< which other fields are valid */ int32_t bar; /**< current bar */ int32_t beat; /**< current beat-within-bar */ int32_t tick; /**< current tick-within-beat */ double bar_start_tick; /**< number of ticks that have elapsed between frame 0 and the first beat of the current measure. */ }; /* jack connection */ static jack_port_t *mclk_output_port = NULL; static jack_client_t *j_client = NULL; /* application state */ static jack_transport_state_t m_xstate = JackTransportStopped; static double mclk_last_tick = 0.0; static int64_t song_position_sync = -1; static struct bbtpos last_xpos; /** keep track of transport locates */ static volatile enum { Init, Run, Exit } client_state = Init; static int wake_main_read = -1; static int wake_main_write = -1; /* commandline options */ static double user_bpm = 0.0; static short force_bpm = 0; static short tempo_is_qnpm = 1; /** tempo is quarter notes per minute instead of BPM */ static short msg_filter = 0; /** bitwise flags, MSG_NO_.. */ static double resync_delay = 2.0; /**< seconds between 'pos' and 'continue' message */ #ifdef WITH_JITTER static double jitter_level = 0.0; static double jitter_rand = 0.0; static uint32_t _rseed = 1; static float randf() { // 31bit Park-Miller-Carta Pseudo-Random Number Generator uint32_t hi, lo; lo = 16807 * (_rseed & 0xffff); hi = 16807 * (_rseed >> 16); lo += (hi & 0x7fff) << 16; lo += hi >> 15; lo = (lo & 0x7fffffff) + (lo >> 31); return (_rseed = lo) / 1073741824.f - 1.f; } #endif /* MIDI System Real-Time Messages * https://en.wikipedia.org/wiki/MIDI_beat_clock * http://www.midi.org/techspecs/midimessages.php */ #define MIDI_RT_CLOCK (0xF8) #define MIDI_RT_START (0xFA) #define MIDI_RT_CONTINUE (0xFB) #define MIDI_RT_STOP (0xFC) static void wake_main_init(void) { #ifndef WIN32 int pipefd[2] = {-1, -1}; if (pipe(pipefd) == -1) { fprintf(stderr, "Warning: unable to create pipe for signaling main thread.\n"); return; } wake_main_read = pipefd[0]; wake_main_write = pipefd[1]; #endif } /** * Wake the main thread (for shutdown) * Call this function when the main application needs to shut down. */ static void wake_main_now(void) { #ifndef WIN32 char c = 0; (void) write(wake_main_write, &c, sizeof(c)); #endif } /** * Wait for wake signal * This blocks until either a signal is received or a wake * message is received on the pipe. */ static void wake_main_wait(void) { #ifndef WIN32 if (wake_main_read != -1) { char c = 0; (void) read(wake_main_read, &c, sizeof(c)); } else { /* fall back on using sleep if pipe fd is invalid */ sleep(1); } #else sleep(1); #endif } /** * cleanup and exit * call this function only _after_ everything has been initialized! */ static void cleanup(int sig) { if (j_client) { jack_client_close (j_client); j_client = NULL; } } /** * compare two BBT positions */ static int pos_changed (struct bbtpos *xp0, jack_position_t *xp1) { if (!(xp0->valid & JackPositionBBT)) return -1; if (!(xp1->valid & JackPositionBBT)) return -2; if ( xp0->bar == xp1->bar && xp0->beat == xp1->beat && xp0->tick == xp1->tick ) return 0; return 1; } /** * copy relevant BBT info from jack_position_t */ static void remember_pos (struct bbtpos *xp0, jack_position_t *xp1) { if (!(xp1->valid & JackPositionBBT)) return; xp0->valid = xp1->valid; xp0->bar = xp1->bar; xp0->beat = xp1->beat; xp0->tick = xp1->tick; xp0->bar_start_tick = xp1->bar_start_tick; } /** * calculate song position (14 bit integer) * from current jack BBT info. * * see "Song Position Pointer" at * http://www.midi.org/techspecs/midimessages.php * * Because this value is also used internally to sync/send * start/continue realtime messages, a 64 bit integer * is used to cover the full range of jack transport. */ static const int64_t calc_song_pos(jack_position_t *xpos, int off) { if (!(xpos->valid & JackPositionBBT)) return -1; if (off < 0) { /* auto offset */ if (xpos->bar == 1 && xpos->beat == 1 && xpos->tick == 0) off = 0; else off = rintf(xpos->beats_per_minute * 4.0 * resync_delay / 60.0); } /* MIDI Beat Clock: 24 ticks per quarter note * one MIDI-beat = six MIDI clocks * -> 4 MIDI-beats per quarter note (jack beat) * Note: jack counts bars and beats starting at 1 */ int64_t pos = off + 4 * ((xpos->bar - 1) * xpos->beats_per_bar + (xpos->beat - 1)) + floor(4.0 * xpos->tick / xpos->ticks_per_beat); return pos; } static const int64_t send_pos_message(void* port_buf, jack_position_t *xpos, int off) { if (msg_filter & MSG_NO_POSITION) return -1; uint8_t *buffer; const int64_t bcnt = calc_song_pos(xpos, off); /* send '0xf2' Song Position Pointer. * This is an internal 14 bit register that holds the number of * MIDI beats (1 beat = six MIDI clocks) since the start of the song. */ if (bcnt < 0 || bcnt >= 16384) { return -1; } buffer = jack_midi_event_reserve(port_buf, 0, 3); if(!buffer) { return -1; } buffer[0] = 0xf2; buffer[1] = (bcnt)&0x7f; // LSB buffer[2] = (bcnt>>7)&0x7f; // MSB return bcnt; } /** * send 1 byte MIDI Message * @param port_buf buffer to write event to * @param time sample offset of event * @param rt_msg message byte */ static void send_rt_message(void* port_buf, jack_nframes_t time, uint8_t rt_msg) { uint8_t *buffer; buffer = jack_midi_event_reserve(port_buf, time, 1); if(buffer) { buffer[0] = rt_msg; } } /** * jack process callback. * do the work: query jack-transport, send MIDI messages.. */ static int process (jack_nframes_t nframes, void *arg) { jack_position_t xpos; double samples_per_beat; jack_nframes_t bbt_offset = 0; int ticks_sent_this_cycle = 0; /* query jack transport state */ jack_transport_state_t xstate = jack_transport_query(j_client, &xpos); void* port_buf = jack_port_get_buffer(mclk_output_port, nframes); /* prepare MIDI buffer */ jack_midi_clear_buffer(port_buf); if (client_state != Run) { return 0; } /* send position updates if stopped and located */ if (xstate == JackTransportStopped && xstate == m_xstate) { if (pos_changed(&last_xpos, &xpos) > 0) { song_position_sync = send_pos_message(port_buf, &xpos, -1); } } remember_pos(&last_xpos, &xpos); /* send RT messages start/stop/continue if transport state changed */ if( xstate != m_xstate ) { switch(xstate) { case JackTransportStopped: if (!(msg_filter & MSG_NO_TRANSPORT)) { send_rt_message(port_buf, 0, MIDI_RT_STOP); } song_position_sync = send_pos_message(port_buf, &xpos, -1); break; case JackTransportRolling: /* handle transport locate while rolling. * jack transport state changes Rolling -> Starting -> Rolling */ if(m_xstate == JackTransportStarting && !(msg_filter & MSG_NO_POSITION)) { if (song_position_sync < 0) { /* send stop IFF not stopped, yet */ send_rt_message(port_buf, 0, MIDI_RT_STOP); } if (song_position_sync != 0) { /* re-set 'continue' message sync point */ if ((song_position_sync = send_pos_message(port_buf, &xpos, -1)) < 0) { if (!(msg_filter & MSG_NO_TRANSPORT)) { send_rt_message(port_buf, 0, MIDI_RT_CONTINUE); } } } else { /* 'start' at 0, don't queue 'continue' message */ song_position_sync = -1; } break; } case JackTransportStarting: if(m_xstate == JackTransportStarting) { break; } if( xpos.frame == 0 ) { if (!(msg_filter & MSG_NO_TRANSPORT)) { send_rt_message(port_buf, 0, MIDI_RT_START); song_position_sync = 0; } } else { /* only send continue message here if song-position * is not used . * w/song-pos it queued just-in-time */ if (!(msg_filter & MSG_NO_TRANSPORT) && (msg_filter & MSG_NO_POSITION)) { send_rt_message(port_buf, 0, MIDI_RT_CONTINUE); } } break; default: break; } /* initial beat tick */ if (xstate == JackTransportRolling && ((xpos.frame == 0) || (msg_filter & MSG_NO_POSITION)) ) { send_rt_message(port_buf, 0, MIDI_RT_CLOCK); } mclk_last_tick = xpos.frame; m_xstate = xstate; } if((xstate != JackTransportRolling)) { return 0; } /* calculate clock tick interval */ if(force_bpm && user_bpm > 0) { samples_per_beat = (double) xpos.frame_rate * 60.0 / user_bpm; } else if(xpos.valid & JackPositionBBT) { samples_per_beat = (double) xpos.frame_rate * 60.0 / xpos.beats_per_minute; if (xpos.valid & JackBBTFrameOffset) { bbt_offset = xpos.bbt_offset; } } else if(user_bpm > 0) { samples_per_beat = (double) xpos.frame_rate * 60.0 / user_bpm; } else { return 0; /* no tempo known */ } /* It is an industry convention that tempo, while reported as "beats * per minute" is actually "quarter notes per minute" in many DAW's. * However, some DAW's/musicians actually use beats per minute * (using the definition of "beat" as the denomitor of the time * signature). While it appears that the JACK transport's intent * is the latter, it's totally up to the DAW to define the tempo/note * relationship. Currently Ardour does "quarter notes per minute." * * Viz. https://community.ardour.org/node/1433 * http://www.steinberg.net/forums/viewtopic.php?t=56065 */ const double quarter_notes_per_beat = (tempo_is_qnpm) ? 1.0 : (xpos.beat_type / 4.0); /* MIDI Beat Clock: Send 24 ticks per quarter note */ const double samples_per_quarter_note = samples_per_beat / quarter_notes_per_beat; const double clock_tick_interval = samples_per_quarter_note / 24.0; /* send clock ticks for this cycle */ while(1) { #ifdef WITH_JITTER const double next_tick = mclk_last_tick + clock_tick_interval + jitter_rand; #else const double next_tick = mclk_last_tick + clock_tick_interval; #endif const int64_t next_tick_offset = llrint(next_tick) - xpos.frame - bbt_offset; if (next_tick_offset >= nframes) break; if (next_tick_offset >= 0) { if (song_position_sync > 0 && !(msg_filter & MSG_NO_POSITION)) { /* send 'continue' realtime message on time */ const int64_t sync = calc_song_pos(&xpos, 0); /* 4 MIDI-beats per quarter note (jack beat) */ if (sync + ticks_sent_this_cycle / 4 >= song_position_sync) { if (!(msg_filter & MSG_NO_TRANSPORT)) { send_rt_message(port_buf, next_tick_offset, MIDI_RT_CONTINUE); } song_position_sync = -1; } } /* enqueue clock tick */ send_rt_message(port_buf, next_tick_offset, MIDI_RT_CLOCK); } #ifdef WITH_JITTER if (jitter_level > 0) { jitter_rand = randf() * jitter_level * clock_tick_interval; } #endif mclk_last_tick = next_tick; ticks_sent_this_cycle++; } return 0; } /** * callback if jack server terminates */ static void jack_shutdown (void *arg) { fprintf(stderr, "recv. shutdown request from jackd.\n"); client_state = Exit; wake_main_now(); } /** * open a client connection to the JACK server */ static int init_jack(const char *client_name) { jack_status_t status; j_client = jack_client_open (client_name, JackNullOption, &status); if (j_client == NULL) { fprintf (stderr, "jack_client_open() failed, status = 0x%2.0x\n", status); if (status & JackServerFailed) { fprintf (stderr, "Unable to connect to JACK server\n"); } return (-1); } if (status & JackServerStarted) { fprintf (stderr, "JACK server started\n"); } if (status & JackNameNotUnique) { client_name = jack_get_client_name(j_client); fprintf (stderr, "jack-client name: `%s'\n", client_name); } jack_set_process_callback (j_client, process, 0); #ifndef WIN32 jack_on_shutdown (j_client, jack_shutdown, NULL); #endif return (0); } static int jack_portsetup(void) { if ((mclk_output_port = jack_port_register(j_client, "mclk_out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0)) == 0) { fprintf (stderr, "cannot register mclk output port !\n"); return (-1); } return (0); } static void port_connect(char *mclk_port) { if (mclk_port && jack_connect(j_client, jack_port_name(mclk_output_port), mclk_port)) { fprintf(stderr, "cannot connect port %s to %s\n", jack_port_name(mclk_output_port), mclk_port); } } static void catchsig (int sig) { #ifndef _WIN32 signal(SIGHUP, catchsig); #endif client_state = Exit; wake_main_now(); } /************************** * main application code */ static struct option const long_options[] = { {"bpm", required_argument, 0, 'b'}, {"force-bpm", no_argument, 0, 'B'}, {"resync-delay", required_argument, 0, 'd'}, {"jitter-level", required_argument, 0, 'J'}, {"help", no_argument, 0, 'h'}, {"no-position", no_argument, 0, 'P'}, {"no-transport", no_argument, 0, 'T'}, {"strict-bpm", no_argument, 0, 's'}, {"version", no_argument, 0, 'V'}, {NULL, 0, NULL, 0} }; static void usage (int status) { printf ("jack_midi_clock - JACK app to generate MCLK from JACK transport.\n\n"); printf ("Usage: jack_midi_clock [ OPTIONS ] [JACK-port]*\n\n"); printf ("Options:\n" " -b , --bpm \n" " default BPM (if jack timecode master in not available)\n" " -B, --force-bpm ignore jack timecode master\n" " -d , --resync-delay \n" " seconds between 'song-position' and 'continue' message\n" " -J, --jitter-level \n" " add artificial jitter to the signal 0..20%%\n" " default: off (0)\n" " -P, --no-position do not send song-position (0xf2) messages\n" " -T, --no-transport do not send start/stop/continue messages\n" " -s, --strict-bpm interpret tempo strictly as beats per minute (default\n" " is quarter-notes per minute)\n" " -h, --help display this help and exit\n" " -V, --version print version information and exit\n" "\n"); printf ("\n" /* longest help text w/80 chars per line ---->|\n" */ "jack_midi_clock sends MIDI beat clock message if jack-transport is rolling.\n" "it also sends start, continue and stop MIDI realtime messages whenever\n" "the transport changes state (unless -T option is used).\n" "\n" "In order for jack_midi_clock to send clock messages, a JACK timecode master\n" "must be present and provide the tempo map (bar, beat, tick).\n" "Alternatively the -b option can be used to set a default BPM value.\n" "If a value larger than zero is given, it will be used if no timecode master\n" "is present. Combined with the -B option it can used to override and ignore\n" "the JACK timecode master and only act on transport state alone.\n" "\n" "Either way, jack_midi_clock will never act as timecode master itself.\n" "\n" "Note that song-position information is only sent if a timecode master is\n" "present ad the -P option is not given.\n" "\n" "To allow external synths to accurately sync to song-position, there is a two\n" "second delay between the 'song-position changed' message (which is not a MIDI\n" "realtime message) and the 'continue transport' message.\n" "This delay can be configured with the -d option and is only relevant for if\n" "playback starts at a bar|beat|tick other than 1|1|0 in which case a 'start'\n" "message is sent immediately.\n" "\n" "jack_midi_clock runs until it receives a HUP or INT signal or jackd is\n" "terminated.\n" "\n" "See also: jack_transport(1), jack_mclk_dump(1)\n" "\n"); printf ("Report bugs to Robin Gareus \n" "Website: https://github.com/x42/jack_midi_clock/\n" ); exit (status); } static int decode_switches (int argc, char **argv) { int c; while ((c = getopt_long (argc, argv, "b:" /* bpm */ "B" /* force-bpm */ "d:" /* resync-delay */ "J:" /* jittery output */ "h" /* help */ "P" /* no-position */ "T" /* no-transport */ "s" /* strict-bpm */ "V", /* version */ long_options, (int *) 0)) != EOF) { switch (c) { case 'b': user_bpm = atof(optarg); break; case 'B': force_bpm = 1; break; case 'P': msg_filter |= MSG_NO_POSITION; break; case 'd': resync_delay = atof(optarg); if (resync_delay < 0 || resync_delay > 20) { fprintf(stderr, "Invalid resync-delay, should be 0 <= dly <= 20.0. Using 2.0sec.\n"); resync_delay = 2.0; } break; case 'J': #ifdef WITH_JITTER jitter_level = atof(optarg) / 100.f; if (jitter_level < 0.f || jitter_level > 0.2f) { fprintf(stderr, "Invalid jiter-level, should be 0 <= dly <= 20.%%.\n"); jitter_level = 0; } #else fprintf(stderr, "This version was compiled without support for jitter.\n"); #endif break; case 'T': msg_filter |= MSG_NO_TRANSPORT; break; case 's': tempo_is_qnpm = 0; break; case 'V': printf ("jack_midi_clock version %s\n\n", VERSION); printf ("Copyright (C) GPL 2013 Robin Gareus \n"); printf ("Copyright (C) GPL 2009 Gabriel M. Beddingfield \n"); exit (0); case 'h': usage (0); default: usage (EXIT_FAILURE); } } return optind; } int main (int argc, char **argv) { memset(&last_xpos, 0, sizeof(struct bbtpos)); decode_switches (argc, argv); if (init_jack("jack_midi_clock")) goto out; if (jack_portsetup()) goto out; if (mlockall (MCL_CURRENT | MCL_FUTURE)) { fprintf(stderr, "Warning: Can not lock memory.\n"); } if (jack_activate (j_client)) { fprintf (stderr, "cannot activate client.\n"); goto out; } while (optind < argc) port_connect(argv[optind++]); #ifndef _WIN32 signal (SIGHUP, catchsig); signal (SIGINT, catchsig); #endif #ifdef WITH_JITTER _rseed = jack_get_time (); if (_rseed == 0) _rseed = 1; #endif wake_main_init(); /* all systems go. * processs() does the work in jack realtime context */ client_state = Run; while (client_state != Exit) { wake_main_wait(); } out: cleanup(0); return(0); } /* vi:set ts=8 sts=2 sw=2: */