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.

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