move MidiPortManager from AudioEngine to Session
[ardour.git] / libs / ardour / ticker.cc
1 /*
2     Copyright (C) 2008 Hans Baier
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include "pbd/compose.h"
20 #include "pbd/stacktrace.h"
21
22 #include "evoral/midi_events.h"
23
24 #include "ardour/async_midi_port.h"
25 #include "ardour/audioengine.h"
26 #include "ardour/midi_buffer.h"
27 #include "ardour/midi_port.h"
28 #include "ardour/ticker.h"
29 #include "ardour/session.h"
30 #include "ardour/tempo.h"
31 #include "ardour/debug.h"
32
33 using namespace ARDOUR;
34 using namespace PBD;
35
36 /** MIDI Clock Position tracking */
37 class MidiClockTicker::Position : public Timecode::BBT_Time
38 {
39 public:
40
41         Position() : speed(0.0f), frame(0) { }
42         ~Position() { }
43
44         /** Sync timing information taken from the given Session
45                 @return True if timings differed */
46         bool sync (Session* s) {
47
48                 bool didit = false;
49
50                 double     sp = s->transport_speed();
51                 framecnt_t fr = s->transport_frame();
52
53                 if (speed != sp) {
54                         speed = sp;
55                         didit = true;
56                 }
57
58                 if (frame != fr) {
59                         frame = fr;
60                         didit = true;
61                 }
62
63                 /* Midi beats and clocks always gets updated for now */
64
65                 s->bbt_time (this->frame, *this);
66
67                 const TempoMap& tempo = s->tempo_map();
68
69                 const double divisions   = tempo.meter_at(frame).divisions_per_bar();
70                 const double divisor     = tempo.meter_at(frame).note_divisor();
71                 const double qnote_scale = divisor * 0.25f;
72
73                 /** Midi Beats in terms of Song Position Pointer is equivalent to total
74                         sixteenth notes at 'time' */
75
76                 midi_beats  = (((bars - 1) * divisions) + beats - 1);
77                 midi_beats += (double)ticks / (double)Position::ticks_per_beat * qnote_scale;
78                 midi_beats *= 16.0f / divisor;
79
80                 midi_clocks = midi_beats * 6.0f;
81
82                 return didit;
83         }
84
85         double      speed;
86         framecnt_t  frame;
87         double      midi_beats;
88         double      midi_clocks;
89
90         void print (std::ostream& s) {
91                 s << "frames: " << frame << " midi beats: " << midi_beats << " speed: " << speed;
92         }
93 };
94
95
96 MidiClockTicker::MidiClockTicker ()
97         : _ppqn (24)
98         , _last_tick (0.0)
99         , _send_pos (false)
100         , _send_state (false)
101 {
102         _pos.reset (new Position());
103 }
104
105 MidiClockTicker::~MidiClockTicker()
106 {
107         _pos.reset (0);
108 }
109
110 void
111 MidiClockTicker::set_session (Session* s)
112 {
113         SessionHandlePtr::set_session (s);
114         
115          if (_session) {
116                  _session->TransportStateChange.connect_same_thread (_session_connections, boost::bind (&MidiClockTicker::transport_state_changed, this));
117                  _session->TransportLooped.connect_same_thread (_session_connections, boost::bind (&MidiClockTicker::transport_looped, this));
118                  _session->Located.connect_same_thread (_session_connections, boost::bind (&MidiClockTicker::session_located, this));
119
120                  update_midi_clock_port();
121                  _pos->sync (_session);
122          }
123 }
124
125 void
126 MidiClockTicker::session_located()
127 {
128         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Session Located: %1, speed: %2\n", _session->transport_frame(), _session->transport_speed()));
129
130         if (0 == _session || ! _pos->sync (_session)) {
131                 return;
132         }
133
134         _last_tick = _pos->frame;
135
136         if (!Config->get_send_midi_clock()) {
137                 return;
138         }
139
140         _send_pos = true;
141 }
142
143 void
144 MidiClockTicker::session_going_away ()
145 {
146         SessionHandlePtr::session_going_away();
147         _midi_port.reset ();
148 }
149
150 void
151 MidiClockTicker::update_midi_clock_port()
152 {
153         _midi_port = _session->midi_clock_output_port();
154 }
155
156 void
157 MidiClockTicker::transport_state_changed()
158 {
159         if (_session->exporting()) {
160                 /* no midi clock during export, for now */
161                 return;
162         }
163
164         if (!_session->engine().running()) {
165                 /* Engine stopped, we can't do anything */
166                 return;
167         }
168
169         if (! _pos->sync (_session)) {
170                 return;
171         }
172
173         DEBUG_TRACE (DEBUG::MidiClock,
174                  string_compose ("Transport state change @ %4, speed: %1 position: %2 play loop: %3\n",
175                                                         _pos->speed, _pos->frame, _session->get_play_loop(), _pos->frame)
176         );
177
178         _last_tick = _pos->frame;
179
180         if (! Config->get_send_midi_clock()) {
181                 return;
182         }
183
184         _send_state = true;
185
186         // tick (_pos->frame);
187 }
188
189 void
190 MidiClockTicker::transport_looped()
191 {
192         Location* loop_location = _session->locations()->auto_loop_location();
193         assert(loop_location);
194
195         DEBUG_TRACE (DEBUG::MidiClock,
196                      string_compose ("Transport looped, position: %1, loop start: %2, loop end: %3, play loop: %4\n",
197                                      _session->transport_frame(), loop_location->start(), loop_location->end(), _session->get_play_loop())
198                 );
199
200         // adjust _last_tick, so that the next MIDI clock message is sent
201         // in due time (and the tick interval is still constant)
202
203         framecnt_t elapsed_since_last_tick = loop_location->end() - _last_tick;
204
205         if (loop_location->start() > elapsed_since_last_tick) {
206                 _last_tick = loop_location->start() - elapsed_since_last_tick;
207         } else {
208                 _last_tick = 0;
209         }
210 }
211
212 void
213 MidiClockTicker::tick (const framepos_t& /* transport_frame */, pframes_t nframes)
214 {
215         if (!Config->get_send_midi_clock() || _session == 0 || _session->transport_speed() != 1.0f || _midi_port == 0) {
216                 return;
217         }
218
219         if (_send_pos) {
220                 if (_pos->speed == 0.0f) {
221                         uint32_t where = llrint (_pos->midi_beats);
222                         send_position_event (where, 0, nframes);
223                 } else if (_pos->speed == 1.0f) {
224 #if 1
225                         /* Experimental.  To really do this and have accuracy, the
226                            stop/locate/continue sequence would need queued to send immediately
227                            before the next midi clock. */
228                         
229                         send_stop_event (0, nframes);
230                         
231                         if (_pos->frame == 0) {
232                                 send_start_event (0, nframes);
233                         } else {
234                                 uint32_t where = llrint (_pos->midi_beats);
235                                 send_position_event (where, 0, nframes);
236                                 send_continue_event (0, nframes);
237                         }
238 #endif
239                 } else {
240                         /* Varispeed not supported */
241                 }
242
243                 _send_pos = true;
244         }
245
246         if (_send_state) {
247                 if (_pos->speed == 1.0f) {
248                         if (_session->get_play_loop()) {
249                                 assert(_session->locations()->auto_loop_location());
250                                 
251                                 if (_pos->frame == _session->locations()->auto_loop_location()->start()) {
252                                         send_start_event (0, nframes);
253                                 } else {
254                                         send_continue_event (0, nframes);
255                                 }
256                                 
257                         } else if (_pos->frame == 0) {
258                                 send_start_event (0, nframes);
259                         } else {
260                                 send_continue_event (0, nframes);
261                         }
262                         
263                         // send_midi_clock_event (0);
264                         
265                 } else if (_pos->speed == 0.0f) {
266                         send_stop_event (0, nframes);
267                         send_position_event (llrint (_pos->midi_beats), 0, nframes);
268                 }
269
270                 _send_state = false;
271         }
272
273
274         const framepos_t end = _pos->frame + nframes;
275         double iter = _last_tick;
276
277         while (true) {
278                 double clock_delta = one_ppqn_in_frames (llrint (iter));
279                 double next_tick   = iter + clock_delta;
280                 frameoffset_t next_tick_offset = llrint (next_tick) - end;
281
282                 DEBUG_TRACE (DEBUG::MidiClock,
283                                  string_compose ("Tick: iter: %1, last tick time: %2, next tick time: %3, offset: %4, cycle length: %5\n",
284                                                  iter, _last_tick, next_tick, next_tick_offset, nframes));
285
286                 if (next_tick_offset >= nframes) {
287                         break;
288                 }
289
290                 if (next_tick_offset >= 0) {
291                         send_midi_clock_event (next_tick_offset, nframes);
292                 }
293
294                 iter = next_tick;
295         }
296
297         _last_tick  = iter;
298         _pos->frame = end;
299 }
300
301 double
302 MidiClockTicker::one_ppqn_in_frames (framepos_t transport_position)
303 {
304         const Tempo& current_tempo = _session->tempo_map().tempo_at (transport_position);
305         double frames_per_beat = current_tempo.frames_per_beat (_session->nominal_frame_rate());
306
307         double quarter_notes_per_beat = 4.0 / current_tempo.note_type();
308         double frames_per_quarter_note = frames_per_beat / quarter_notes_per_beat;
309
310         return frames_per_quarter_note / double (_ppqn);
311 }
312
313 void
314 MidiClockTicker::send_midi_clock_event (pframes_t offset, pframes_t nframes)
315 {
316         if (!_midi_port) {
317                 return;
318         }
319
320         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Tick with offset %1\n", offset));
321
322         static uint8_t tick_byte = { MIDI_CMD_COMMON_CLOCK };
323         MidiBuffer& mb (_midi_port->get_midi_buffer (nframes));
324         mb.push_back (offset, 1, &tick_byte);
325 }
326
327 void
328 MidiClockTicker::send_start_event (pframes_t offset, pframes_t nframes)
329 {
330         if (!_midi_port) {
331                 return;
332         }
333
334         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Start %1\n", _last_tick));
335
336         static uint8_t tick_byte = { MIDI_CMD_COMMON_START };
337         MidiBuffer& mb (_midi_port->get_midi_buffer (nframes));
338         mb.push_back (offset, 1, &tick_byte);
339 }
340
341 void
342 MidiClockTicker::send_continue_event (pframes_t offset, pframes_t nframes)
343 {
344         if (!_midi_port) {
345                 return;
346         }
347
348         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Continue %1\n", _last_tick));
349
350         static uint8_t tick_byte = { MIDI_CMD_COMMON_CONTINUE };
351         MidiBuffer& mb (_midi_port->get_midi_buffer (nframes));
352         mb.push_back (offset, 1, &tick_byte);
353 }
354
355 void
356 MidiClockTicker::send_stop_event (pframes_t offset, pframes_t nframes)
357 {
358         if (!_midi_port) {
359                 return;
360         }
361
362         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Stop %1\n", _last_tick));
363
364         static uint8_t tick_byte = { MIDI_CMD_COMMON_STOP };
365         MidiBuffer& mb (_midi_port->get_midi_buffer (nframes));
366         mb.push_back (offset, 1, &tick_byte);
367 }
368
369 void
370 MidiClockTicker::send_position_event (uint32_t midi_beats, pframes_t offset, pframes_t nframes)
371 {
372         if (!_midi_port) {
373                 return;
374         }
375
376         /* can only use 14bits worth */
377         if (midi_beats > 0x3fff) {
378                 return;
379         }
380
381         /* split midi beats into a 14bit value */
382         MIDI::byte msg[3];
383         msg[0] = MIDI_CMD_COMMON_SONG_POS;
384         msg[1] = midi_beats & 0x007f;
385         msg[2] = midi_beats >> 7;
386
387         MidiBuffer& mb (_midi_port->get_midi_buffer (nframes));
388         mb.push_back (offset, 3, &msg[0]);
389
390         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Song Position Sent: %1\n", midi_beats));
391 }