Assists music production by grouping standalone programs into sessions. Community version of "Non Session Manager".
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

644 lines
19KB

  1. /*******************************************************************************/
  2. /* Copyright (C) 2007-2008 Jonathan Moore Liles */
  3. /* */
  4. /* This program is free software; you can redistribute it and/or modify it */
  5. /* under the terms of the GNU General Public License as published by the */
  6. /* Free Software Foundation; either version 2 of the License, or (at your */
  7. /* option) any later version. */
  8. /* */
  9. /* This program is distributed in the hope that it will be useful, but WITHOUT */
  10. /* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
  11. /* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for */
  12. /* more details. */
  13. /* */
  14. /* You should have received a copy of the GNU General Public License along */
  15. /* with This program; see the file COPYING. If not,write to the Free Software */
  16. /* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
  17. /*******************************************************************************/
  18. #include <stdlib.h>
  19. #include <stdio.h>
  20. #include <unistd.h>
  21. #include <math.h>
  22. /* jack */
  23. #include <jack/jack.h>
  24. #include <jack/midiport.h>
  25. #include <jack/ringbuffer.h>
  26. #include <jack/thread.h>
  27. #include "jack.H"
  28. #include "non.H"
  29. #include "transport.H"
  30. #include "pattern.H"
  31. #include "phrase.H"
  32. #include <MIDI/event_list.H>
  33. #include <MIDI/midievent.H>
  34. using namespace MIDI;
  35. #ifdef JACK_MIDI_PROTO_API
  36. /* correct for prototype version of API */
  37. #define jack_midi_event_reserve( p, f, l ) jack_midi_event_reserve( p, f, l, nframes )
  38. #define jack_midi_event_get( e, b, f ) jack_midi_event_get( e, b, f, nframes )
  39. #define jack_midi_get_event_count( b ) jack_midi_get_event_count( b, nframes )
  40. #define jack_midi_clear_buffer( b ) jack_midi_clear_buffer( b, nframes )
  41. #define jack_midi_event_write( b, f, d, s ) jack_midi_event_write( b, f, d, s, nframes )
  42. #endif
  43. /* MIDI channel to listen for pattern control changes on */
  44. int pattern_control_channel = 0;
  45. /* which control change number to use for pattern control */
  46. int pattern_control_cc = 20;
  47. jack_client_t *client;
  48. int sample_rate;
  49. const int MAX_PORT = 16;
  50. const int subticks_per_tick = 4096;
  51. /* timers for notes on all channels and ports. When a note is played,
  52. * the respective value in this array is set to the note duraction in
  53. * subticks (an arbitrary division of the tick used only for this
  54. * purpose). Decremented in each process cycle, when this value
  55. * reaches zero, a note off is generated--regardless of the state of
  56. * the transport */
  57. int note_duration[MAX_PORT][16][128];
  58. /* tracks the number of concurrent note ons for the same note so that
  59. * we can be sure to emit the correct number of note offs */
  60. int notes_on[MAX_PORT][16][128];
  61. typedef unsigned char byte_t;
  62. int num_output_ports = 1;
  63. event_list freelist;
  64. typedef struct {
  65. void *buf;
  66. jack_ringbuffer_t *ring_buf; /* for realtime output and recording */
  67. event_list events; /* events to be output this cycle */
  68. jack_port_t *port;
  69. } port_t;
  70. static port_t output[MAX_PORT];
  71. static port_t input[2]; /* control, performance */
  72. jack_nframes_t nframes; /* for compatibility with older jack */
  73. bool
  74. midi_is_active ( void )
  75. {
  76. return client != NULL;
  77. }
  78. /** get next recorded event, if any--runs in UI thread */
  79. bool
  80. midi_input_event ( int port, midievent *me )
  81. {
  82. if ( ! midi_is_active() )
  83. return NULL;
  84. if ( jack_ringbuffer_read_space( input[ port ].ring_buf ) >= sizeof( midievent ) )
  85. {
  86. if ( jack_ringbuffer_read( input[ port ].ring_buf, (char *)me, sizeof( midievent ) ) )
  87. return true;
  88. }
  89. return false;
  90. }
  91. /**
  92. * Queue an event for output. /tick/ is relative to the current cycle! */
  93. void
  94. midi_output_event ( int port, const midievent *e )
  95. {
  96. if ( ! midi_is_active() )
  97. return;
  98. event *fe = freelist.first();
  99. if ( ! fe )
  100. {
  101. WARNING( "output buffer underrun" );
  102. }
  103. else
  104. {
  105. if ( e->is_note_on() )
  106. {
  107. if ( notes_on[ port ][ e->channel() ][ e->note() ] == 0 )
  108. {
  109. freelist.unlink( fe );
  110. *fe = *e;
  111. output[ port ].events.insert( fe );
  112. ++notes_on[ port ][ e->channel() ][ e->note() ];
  113. }
  114. else
  115. {
  116. DMESSAGE( "Dropping extra Note ON" );
  117. }
  118. }
  119. else if ( e->is_note_off() )
  120. {
  121. if ( notes_on[ port ][ e->channel() ][ e->note() ] == 0 )
  122. {
  123. DMESSAGE( "Dropping extra Note OFF" );
  124. }
  125. else
  126. {
  127. freelist.unlink( fe );
  128. *fe = *e;
  129. output[ port ].events.insert( fe );
  130. --notes_on[ port ][ e->channel() ][ e->note() ];
  131. }
  132. }
  133. else
  134. {
  135. freelist.unlink( fe );
  136. *fe = *e;
  137. output[ port ].events.insert( fe );
  138. }
  139. }
  140. }
  141. /** same as above, but only for note-on + duration */
  142. void
  143. midi_output_event ( int port, const midievent *e, tick_t duration )
  144. {
  145. if ( ! midi_is_active() )
  146. return;
  147. if ( duration )
  148. {
  149. note_duration[ port ][ e->channel() ][ e->note() ] = (duration + e->timestamp()) * subticks_per_tick;
  150. midi_output_event( port, e );
  151. }
  152. else
  153. {
  154. /* We allow duplicate notes on and pass notes off through as
  155. * is in order to support poly synths. */
  156. midi_output_event( port, e );
  157. }
  158. }
  159. void
  160. midi_write_event ( int port, const midievent *e )
  161. {
  162. byte_t *buffer;
  163. // what I want here is to translate a PPQN tick into the
  164. // current period.
  165. jack_nframes_t frame = transport.frames_per_tick * e->timestamp();
  166. int l = e->size();
  167. buffer = jack_midi_event_reserve( output[ port ].buf, frame, l );
  168. if ( ! buffer )
  169. {
  170. WARNING( "could not reserve buffer at frame %d, note event dropped!", frame );
  171. return;
  172. }
  173. #ifdef DEBUG_EVENTS
  174. e->pretty_print();
  175. #endif
  176. e->raw( buffer, l );
  177. }
  178. /** Call this to send an event immediately from UI thread. Timestamp is meaningless */
  179. void
  180. midi_output_immediate_event ( int port, const midievent *e )
  181. {
  182. if ( ! midi_is_active() )
  183. return;
  184. if ( jack_ringbuffer_write( output[ port ].ring_buf, (const char *)e, sizeof( midievent ) ) != sizeof( midievent ) )
  185. WARNING( "output ringbuffer overrun" );
  186. else
  187. if ( e->is_note_on() )
  188. {
  189. /* use timestamp as duration */
  190. note_duration[ port ][ e->channel() ][ e->note() ] = e->timestamp() * subticks_per_tick;
  191. }
  192. }
  193. /** stop all notes on all channels of all ports */
  194. void
  195. midi_all_sound_off ( void )
  196. {
  197. if ( ! midi_is_active() )
  198. return;
  199. MESSAGE( "stopping all sound" );
  200. midievent e;
  201. /* all notes off */
  202. e.status( midievent::CONTROL_CHANGE );
  203. e.data( 123, 0 );
  204. e.timestamp( 0 );
  205. for ( int p = MAX_PORT; p--; )
  206. for ( int c = 16; c--; )
  207. {
  208. e.channel( c );
  209. midi_output_immediate_event( p, &e );
  210. }
  211. }
  212. static void
  213. stop_all_patterns ( void )
  214. {
  215. for ( uint i = pattern::patterns(); i--; )
  216. {
  217. pattern *p = pattern::pattern_by_number( i + 1 );
  218. p->stop();
  219. }
  220. }
  221. static int
  222. sync ( jack_transport_state_t state, jack_position_t *pos, void * )
  223. {
  224. static bool seeking = false;
  225. switch ( state )
  226. {
  227. case JackTransportStopped: /* new position requested */
  228. /* JACK docs lie. This is only called when the transport
  229. is *really* stopped, not when starting a slow-sync
  230. cycle */
  231. stop_all_patterns();
  232. return 1;
  233. case JackTransportStarting: /* this means JACK is polling slow-sync clients */
  234. {
  235. stop_all_patterns();
  236. return 1;
  237. }
  238. case JackTransportRolling: /* JACK's timeout has expired */
  239. /* FIXME: what's the right thing to do here? */
  240. // request_locate( pos->frame );
  241. return 1;
  242. break;
  243. default:
  244. WARNING( "unknown transport state" );
  245. }
  246. return 0;
  247. }
  248. static int
  249. process ( jack_nframes_t nframes, void *arg )
  250. {
  251. static tick_t oph = 0;
  252. static tick_t onph = 0;
  253. static int old_play_mode = PATTERN;
  254. static int not_dropped = 0;
  255. ::nframes = nframes;
  256. transport.nframes = nframes;
  257. transport.poll();
  258. /* ph-nph is exclusive. It is important that in normal continuous playback each tick is covered exactly once! */
  259. const tick_t ph = transport.ticks;
  260. const tick_t nph = transport.ticks + transport.ticks_per_period;
  261. if ( ! transport.valid )
  262. goto schedule;
  263. if ( ( ! transport.rolling ) || ph == oph )
  264. goto schedule;
  265. /* if ( ph != onph ) */
  266. /* { */
  267. /* if ( onph > ph ) */
  268. /* DWARNING( "duplicated %lu ticks (out of %d)", onph - ph, (int)(not_dropped * transport.ticks_per_period) ); */
  269. /* else */
  270. /* DWARNING( "dropped %lu ticks (out of %d), ticks per period = %f", ph - onph, (int)(not_dropped * transport.ticks_per_period) ); */
  271. /* not_dropped = 0; */
  272. /* } */
  273. ++not_dropped;
  274. onph = nph;
  275. if ( old_play_mode != song.play_mode )
  276. {
  277. switch ( old_play_mode )
  278. {
  279. case PATTERN:
  280. case TRIGGER:
  281. case QUEUE:
  282. DMESSAGE( "Stopping all patterns" );
  283. stop_all_patterns();
  284. break;
  285. }
  286. old_play_mode = song.play_mode;
  287. }
  288. // DMESSAGE( "tpp %f %lu-%lu", transport.ticks_per_period, ph, nph );
  289. /* now handle control input */
  290. {
  291. int j = CONTROL;
  292. static midievent e;
  293. input[j].buf = jack_port_get_buffer( input[j].port, nframes );
  294. jack_midi_event_t ev;
  295. jack_nframes_t count = jack_midi_get_event_count( input[j].buf );
  296. for ( uint i = 0; i < count; ++i )
  297. {
  298. // MESSAGE( "Got midi input!" );
  299. jack_midi_event_get( &ev, input[j].buf, i );
  300. /* time is frame within cycle, convert to absolute tick */
  301. e.timestamp( ph + (ev.time / transport.frames_per_tick) );
  302. e.status( ev.buffer[0] );
  303. e.lsb( ev.buffer[1] );
  304. if ( ev.size == 3 )
  305. e.msb( ev.buffer[2] );
  306. /* no need to pass it to the GUI, we can trigger patterns here */
  307. if ( e.channel() == pattern_control_channel &&
  308. e.opcode() == midievent::CONTROL_CHANGE &&
  309. e.lsb() == pattern_control_cc )
  310. {
  311. if ( e.msb() < pattern::patterns() )
  312. {
  313. pattern *p = pattern::pattern_by_number( e.msb() + 1 );
  314. if ( TRIGGER == song.play_mode )
  315. {
  316. if ( p->playing() )
  317. {
  318. DMESSAGE( "Untriggering pattern %i ph=%lu, ts=%lu", e.msb(), ph, e.timestamp() );
  319. p->trigger( ph, e.timestamp() );
  320. }
  321. else
  322. {
  323. DMESSAGE( "Triggering pattern %i ph=%lu, ts=%lu", e.msb(), ph, e.timestamp() );
  324. p->trigger( e.timestamp(), INFINITY );
  325. }
  326. }
  327. else
  328. {
  329. if ( p->mode() == PLAY )
  330. {
  331. DMESSAGE( "Dequeuing pattern %i ph=%lu, ts=%lu", e.msb(), ph, e.timestamp() );
  332. p->mode( MUTE );
  333. }
  334. else
  335. {
  336. DMESSAGE( "Queuing pattern %i ph=%lu, ts=%lu", e.msb(), ph, e.timestamp() );
  337. p->mode( PLAY );
  338. }
  339. }
  340. }
  341. }
  342. }
  343. }
  344. switch ( song.play_mode )
  345. {
  346. case SEQUENCE:
  347. playlist->play( ph, nph );
  348. break;
  349. case QUEUE:
  350. case PATTERN:
  351. {
  352. for ( uint i = pattern::patterns(); i--; )
  353. {
  354. pattern *p = pattern::pattern_by_number( i + 1 );
  355. p->trigger( 0, INFINITY );
  356. p->play( ph, nph );
  357. }
  358. break;
  359. }
  360. case TRIGGER:
  361. {
  362. for ( uint i = pattern::patterns(); i--; )
  363. {
  364. pattern *p = pattern::pattern_by_number( i + 1 );
  365. p->play( ph, nph );
  366. }
  367. break;
  368. }
  369. }
  370. oph = ph;
  371. /* handle midi input */
  372. // for ( int j = transport.recording ? 2 : 1; j--; )
  373. if ( transport.recording )
  374. {
  375. int j = PERFORMANCE;
  376. static midievent e;
  377. input[j].buf = jack_port_get_buffer( input[j].port, nframes );
  378. jack_midi_event_t ev;
  379. jack_nframes_t count = jack_midi_get_event_count( input[j].buf );
  380. for ( uint i = 0; i < count; ++i )
  381. {
  382. // MESSAGE( "Got midi input!" );
  383. jack_midi_event_get( &ev, input[j].buf, i );
  384. /* time is frame within cycle, convert to absolute tick */
  385. e.timestamp( ph + (ev.time / transport.frames_per_tick) );
  386. e.status( ev.buffer[0] );
  387. e.lsb( ev.buffer[1] );
  388. if ( ev.size == 3 )
  389. e.msb( ev.buffer[2] );
  390. if ( jack_ringbuffer_write( input[j].ring_buf, (char*)&e, sizeof( midievent ) ) != sizeof( midievent ) )
  391. WARNING( "input buffer overrun" );
  392. }
  393. }
  394. schedule:
  395. const int subticks_per_period = transport.ticks_per_period * subticks_per_tick;
  396. for ( uint i = MAX_PORT; i-- ; )
  397. {
  398. /* reserve and clear buffers */
  399. output[ i ].buf = jack_port_get_buffer( output[ i ].port, nframes );
  400. jack_midi_clear_buffer( output[ i ].buf );
  401. /* handle scheduled note offs */
  402. for ( uint j = 16; j-- ; )
  403. {
  404. register int *note = &note_duration[ i ][ j ][ 0 ];
  405. for ( register uint k = 0; k < 128; ++note, ++k )
  406. if ( *note > 0 )
  407. if ( ( *note -= subticks_per_period ) <= 0 )
  408. {
  409. while ( notes_on[ i ][ j ][ k] > 0 )
  410. {
  411. static midievent e;
  412. e.status( midievent::NOTE_OFF );
  413. e.channel( j );
  414. e.note( k );
  415. e.note_velocity( 64 );
  416. e.timestamp( (subticks_per_period + *note) / subticks_per_tick );
  417. midi_output_event( i, &e );
  418. }
  419. *note = 0;
  420. }
  421. }
  422. static midievent e;
  423. /* first, write any immediate events from the UI thread */
  424. while ( jack_ringbuffer_read( output[ i ].ring_buf, (char *)&e, sizeof( midievent ) ) )
  425. {
  426. // MESSAGE( "sending immediate event" );
  427. // FIXME: could we do better?
  428. e.timestamp( 0 );
  429. midi_output_event( i, &e );
  430. }
  431. /* Write queued events */
  432. event *n;
  433. for ( event *e = output[ i ].events.first(); e; e = n )
  434. {
  435. n = e->next();
  436. midi_write_event( i, e );
  437. output[ i ].events.unlink( e );
  438. freelist.append( e );
  439. }
  440. }
  441. return 0;
  442. }
  443. const char *
  444. midi_init ( const char *name )
  445. {
  446. MESSAGE( "Initializing Jack MIDI" );
  447. if (( client = jack_client_open ( name, (jack_options_t)0, NULL )) == 0 )
  448. return NULL;
  449. /* create output ports */
  450. for ( int i = 0; i < MAX_PORT; i++ )
  451. {
  452. char pat[40];
  453. sprintf( pat, "midi_out-%d", i + 1 );
  454. output[i].port = jack_port_register( client, pat, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 );
  455. output[i].ring_buf = jack_ringbuffer_create( 16 * 16 * sizeof( midievent ) ); // why this value?
  456. jack_ringbuffer_reset( output[i].ring_buf );
  457. }
  458. /* create input ports */
  459. input[0].port = jack_port_register( client, "control_in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 );
  460. input[0].ring_buf = jack_ringbuffer_create( 128 * sizeof( midievent ) ); // why this value?
  461. jack_ringbuffer_reset( input[0].ring_buf );
  462. input[1].port = jack_port_register( client, "midi_in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 );
  463. input[1].ring_buf = jack_ringbuffer_create( 128 * sizeof( midievent ) ); // why this value?
  464. jack_ringbuffer_reset( input[1].ring_buf );
  465. /* preallocate events */
  466. for ( int i = 32 * 16 * MAX_PORT; i-- ; )
  467. freelist.append( new event );
  468. DMESSAGE( "allocated output buffer space for %lu events", freelist.size() );
  469. /* clear notes */
  470. for ( int p = MAX_PORT; p--; )
  471. {
  472. for ( int c = 16; c-- ; )
  473. for ( int n = 128; n-- ; )
  474. {
  475. note_duration[ p ][ c ][ n ] = 0;
  476. notes_on[ p ][ c ][ n ] = 0;
  477. }
  478. }
  479. //1 jack_set_buffer_size_callback( client, bufsize, 0 );
  480. jack_set_process_callback( client, process, 0 );
  481. jack_set_sync_callback( client, sync, 0 );
  482. /* /\* initialize buffer size *\/ */
  483. /* transport_poll(); */
  484. /* bufsize( jack_get_buffer_size( client ), 0 ); */
  485. if ( jack_set_timebase_callback( client, 1, Transport::timebase, NULL ) == 0 )
  486. {
  487. MESSAGE( "running as timebase master" );
  488. transport.master = true;
  489. }
  490. else
  491. WARNING( "could not take over as timebase master" );
  492. jack_activate( client );
  493. sample_rate = jack_get_sample_rate( client );
  494. /* FIXME: hack! we need to wait until jack finally calls our
  495. * timebase and process callbacks in order to be able to test for
  496. * valid transport info. */
  497. MESSAGE( "Waiting for JACK..." );
  498. usleep( 500000 );
  499. return (const char *) jack_get_client_name(client);
  500. }
  501. void
  502. midi_shutdown ( void )
  503. {
  504. // TODO: wait for all queued events to play.
  505. if ( client )
  506. {
  507. jack_deactivate( client );
  508. jack_client_close( client );
  509. client = NULL;
  510. }
  511. }