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