MTC: map between timecodes
[ardour.git] / libs / ardour / session_time.cc
1
2 /*
3   Copyright (C) 1999-2002 Paul Davis
4
5   This program is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation; either version 2 of the License, or
8   (at your option) any later version.
9
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program; if not, write to the Free Software
17   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #ifdef WAF_BUILD
22 #include "libardour-config.h"
23 #endif
24
25 #include <iostream>
26 #include <cmath>
27 #include <unistd.h>
28
29 #include "ardour/timestamps.h"
30
31 #include "pbd/error.h"
32 #include "pbd/enumwriter.h"
33 #include "pbd/stacktrace.h"
34
35 #include "ardour/session.h"
36 #include "ardour/tempo.h"
37
38 #include "i18n.h"
39
40 using namespace std;
41 using namespace ARDOUR;
42 using namespace PBD;
43
44 /* BBT TIME*/
45
46 void
47 Session::bbt_time (framepos_t when, Timecode::BBT_Time& bbt)
48 {
49         _tempo_map->bbt_time (when, bbt);
50 }
51
52 /* Timecode TIME */
53
54 float
55 Session::timecode_frames_per_second() const
56 {
57         return Timecode::timecode_to_frames_per_second (config.get_timecode_format());
58 }
59
60 bool
61 Session::timecode_drop_frames() const
62 {
63         return Timecode::timecode_has_drop_frames(config.get_timecode_format());
64 }
65
66 void
67 Session::sync_time_vars ()
68 {
69         _current_frame_rate = (framecnt_t) round (_base_frame_rate * (1.0 + (config.get_video_pullup()/100.0)));
70         _frames_per_timecode_frame = (double) _current_frame_rate / (double) timecode_frames_per_second();
71         if (timecode_drop_frames()) {
72           _frames_per_hour = (int32_t)(107892 * _frames_per_timecode_frame);
73         } else {
74           _frames_per_hour = (int32_t)(3600 * rint(timecode_frames_per_second()) * _frames_per_timecode_frame);
75         }
76         _timecode_frames_per_hour = rint(timecode_frames_per_second() * 3600.0);
77
78         last_timecode_valid = false;
79         // timecode type bits are the middle two in the upper nibble
80         switch ((int) ceil (timecode_frames_per_second())) {
81         case 24:
82                 mtc_timecode_bits = 0;
83                 break;
84
85         case 25:
86                 mtc_timecode_bits = 0x20;
87                 break;
88
89         case 30:
90         default:
91                 if (timecode_drop_frames()) {
92                         mtc_timecode_bits = 0x40;
93                 } else {
94                         mtc_timecode_bits =  0x60;
95                 }
96                 break;
97         };
98 }
99
100 void
101 Session::timecode_to_sample( Timecode::Time& timecode, framepos_t& sample, bool use_offset, bool use_subframes ) const
102 {
103         double my_frames_per_timecode_frame = _frames_per_timecode_frame;
104         if (timecode.rate > 0) {
105                 my_frames_per_timecode_frame = (double) _current_frame_rate / (double) timecode.rate;
106         }
107
108         if (timecode.drop) {
109                 // The drop frame format was created to better approximate the 30000/1001 = 29.97002997002997....
110                 // framerate of NTSC color TV. The used frame rate of drop frame is 29.97, which drifts by about
111                 // 0.108 frame per hour, or about 1.3 frames per 12 hours. This is not perfect, but a lot better
112                 // than using 30 non drop, which will drift with about 1.8 frame per minute.
113                 // Using 29.97, drop frame real time can be accurate only every 10th minute (10 minutes of 29.97 fps
114                 // is exactly 17982 frames). One minute is 1798.2 frames, but we count 30 frames per second
115                 // (30 * 60 = 1800). This means that at the first minute boundary (at the end of 0:0:59:29) we
116                 // are 1.8 frames too late relative to real time. By dropping 2 frames (jumping to 0:1:0:2) we are
117                 // approx. 0.2 frames too early. This adds up with 0.2 too early for each minute until we are 1.8
118                 // frames too early at 0:9:0:2 (9 * 0.2 = 1.8). The 10th minute brings us 1.8 frames later again
119                 // (at end of 0:9:59:29), which sums up to 0 (we are back to zero at 0:10:0:0 :-).
120                 //
121                 // In table form:
122                 //
123                 // Timecode value    frames offset   subframes offset   seconds (rounded)  44100 sample (rounded)
124                 //  0:00:00:00        0.0             0                     0.000                0 (accurate)
125                 //  0:00:59:29        1.8           144                    60.027          2647177
126                 //  0:01:00:02       -0.2           -16                    60.060          2648648
127                 //  0:01:59:29        1.6           128                   120.020          5292883
128                 //  0:02:00:02       -0.4           -32                   120.053          5294354
129                 //  0:02:59:29        1.4           112                   180.013          7938588
130                 //  0:03:00:02       -0.6           -48                   180.047          7940060
131                 //  0:03:59:29        1.2            96                   240.007         10584294
132                 //  0:04:00:02       -0.8           -64                   240.040         10585766
133                 //  0:04:59:29        1.0            80                   300.000         13230000
134                 //  0:05:00:02       -1.0           -80                   300.033         13231471
135                 //  0:05:59:29        0.8            64                   359.993         15875706
136                 //  0:06:00:02       -1.2           -96                   360.027         15877177
137                 //  0:06:59:29        0.6            48                   419.987         18521411
138                 //  0:07:00:02       -1.4          -112                   420.020         18522883
139                 //  0:07:59:29        0.4            32                   478.980         21167117
140                 //  0:08:00:02       -1.6          -128                   480.013         21168589
141                 //  0:08:59:29        0.2            16                   539.973         23812823
142                 //  0:09:00:02       -1.8          -144                   540.007         23814294
143                 //  0:09:59:29        0.0+            0+                  599.967         26458529
144                 //  0:10:00:00        0.0             0                   600.000         26460000 (accurate)
145                 //
146                 //  Per Sigmond <per@sigmond.no>
147
148                 // Samples inside time dividable by 10 minutes (real time accurate)
149                 framecnt_t base_samples = (framecnt_t) (((timecode.hours * 107892) + ((timecode.minutes / 10) * 17982)) * my_frames_per_timecode_frame);
150
151                 // Samples inside time exceeding the nearest 10 minutes (always offset, see above)
152                 int32_t exceeding_df_minutes = timecode.minutes % 10;
153                 int32_t exceeding_df_seconds = (exceeding_df_minutes * 60) + timecode.seconds;
154                 int32_t exceeding_df_frames = (30 * exceeding_df_seconds) + timecode.frames - (2 * exceeding_df_minutes);
155                 framecnt_t exceeding_samples = (framecnt_t) rint(exceeding_df_frames * my_frames_per_timecode_frame);
156                 sample = base_samples + exceeding_samples;
157         } else {
158                 /*
159                    Non drop is easy.. just note the use of
160                    rint(timecode.rate) * _frames_per_timecode_frame
161                    (frames per Timecode second), which is larger than
162                    frame_rate() in the non-integer Timecode rate case.
163                 */
164
165                 sample = (framecnt_t)rint((((timecode.hours * 60 * 60) + (timecode.minutes * 60) + timecode.seconds) * (rint(timecode.rate) * my_frames_per_timecode_frame)) + (timecode.frames * my_frames_per_timecode_frame));
166         }
167
168         if (use_subframes) {
169                 sample += (int32_t) (((double)timecode.subframes * my_frames_per_timecode_frame) / config.get_subframes_per_frame());
170         }
171
172         if (use_offset) {
173                 if (config.get_timecode_offset_negative()) {
174                         if (sample >= config.get_timecode_offset()) {
175                                 sample -= config.get_timecode_offset();
176                         } else {
177                                 /* Prevent song-time from becoming negative */
178                                 sample = 0;
179                         }
180                 } else {
181                         if (timecode.negative) {
182                                 if (sample <= config.get_timecode_offset()) {
183                                         sample = config.get_timecode_offset() - sample;
184                                 } else {
185                                         sample = 0;
186                                 }
187                         } else {
188                                 sample += config.get_timecode_offset();
189                         }
190                 }
191         }
192
193 }
194
195
196 void
197 Session::sample_to_timecode (framepos_t sample, Timecode::Time& timecode, bool use_offset, bool use_subframes ) const
198 {
199         framepos_t offset_sample;
200
201         if (!use_offset) {
202                 offset_sample = sample;
203                 timecode.negative = false;
204         } else {
205                 if (config.get_timecode_offset_negative()) {
206                         offset_sample = sample + config.get_timecode_offset ();
207                         timecode.negative = false;
208                 } else {
209                         if (sample < config.get_timecode_offset()) {
210                                 offset_sample = (config.get_timecode_offset() - sample);
211                                 timecode.negative = true;
212                         } else {
213                                 offset_sample =  sample - config.get_timecode_offset();
214                                 timecode.negative = false;
215                         }
216                 }
217         }
218
219         double timecode_frames_left_exact;
220         double timecode_frames_fraction;
221         uint32_t timecode_frames_left;
222
223         // Extract whole hours. Do this to prevent rounding errors with
224         // high sample numbers in the calculations that follow.
225         timecode.hours = offset_sample / _frames_per_hour;
226         offset_sample = offset_sample % _frames_per_hour;
227
228         // Calculate exact number of (exceeding) timecode frames and fractional frames
229         timecode_frames_left_exact = (double) offset_sample / _frames_per_timecode_frame;
230         timecode_frames_fraction = timecode_frames_left_exact - floor( timecode_frames_left_exact );
231         timecode.subframes = (int32_t) rint(timecode_frames_fraction * config.get_subframes_per_frame());
232
233         // XXX Not sure if this is necessary anymore...
234         if (timecode.subframes == config.get_subframes_per_frame()) {
235                 // This can happen with 24 fps (and 29.97 fps ?)
236                 timecode_frames_left_exact = ceil( timecode_frames_left_exact );
237                 timecode.subframes = 0;
238         }
239
240         // Extract hour-exceeding frames for minute, second and frame calculations
241         timecode_frames_left = (uint32_t) floor (timecode_frames_left_exact);
242
243         if (timecode_drop_frames()) {
244                 // See int32_t explanation in timecode_to_sample()...
245
246                 // Number of 10 minute chunks
247                 timecode.minutes = (timecode_frames_left / 17982) * 10; // exactly 17982 frames in 10 minutes
248                 // frames exceeding the nearest 10 minute barrier
249                 int32_t exceeding_df_frames = timecode_frames_left % 17982;
250
251                 // Find minutes exceeding the nearest 10 minute barrier
252                 if (exceeding_df_frames >= 1800) { // nothing to do if we are inside the first minute (0-1799)
253                         exceeding_df_frames -= 1800; // take away first minute (different number of frames than the others)
254                         int32_t extra_minutes_minus_1 = exceeding_df_frames / 1798; // how many minutes after the first one
255                         exceeding_df_frames -= extra_minutes_minus_1 * 1798; // take away the (extra) minutes just found
256                         timecode.minutes += extra_minutes_minus_1 + 1; // update with exceeding minutes
257                 }
258
259                 // Adjust frame numbering for dropped frames (frame 0 and 1 skipped at start of every minute except every 10th)
260                 if (timecode.minutes % 10) {
261                         // Every minute except every 10th
262                         if (exceeding_df_frames < 28) {
263                                 // First second, frames 0 and 1 are skipped
264                                 timecode.seconds = 0;
265                                 timecode.frames = exceeding_df_frames + 2;
266                         } else {
267                                 // All other seconds, all 30 frames are counted
268                                 exceeding_df_frames -= 28;
269                                 timecode.seconds = (exceeding_df_frames / 30) + 1;
270                                 timecode.frames = exceeding_df_frames % 30;
271                         }
272                 } else {
273                         // Every 10th minute, all 30 frames counted in all seconds
274                         timecode.seconds = exceeding_df_frames / 30;
275                         timecode.frames = exceeding_df_frames % 30;
276                 }
277         } else {
278                 // Non drop is easy
279                 timecode.minutes = timecode_frames_left / ((int32_t) rint (timecode_frames_per_second ()) * 60);
280                 timecode_frames_left = timecode_frames_left % ((int32_t) rint (timecode_frames_per_second ()) * 60);
281                 timecode.seconds = timecode_frames_left / (int32_t) rint(timecode_frames_per_second ());
282                 timecode.frames = timecode_frames_left % (int32_t) rint(timecode_frames_per_second ());
283         }
284
285         if (!use_subframes) {
286                 timecode.subframes = 0;
287         }
288         /* set frame rate and drop frame */
289         timecode.rate = timecode_frames_per_second ();
290         timecode.drop = timecode_drop_frames();
291 }
292
293 void
294 Session::timecode_time (framepos_t when, Timecode::Time& timecode)
295 {
296         if (last_timecode_valid && when == last_timecode_when) {
297                 timecode = last_timecode;
298                 return;
299         }
300
301         sample_to_timecode( when, timecode, true /* use_offset */, false /* use_subframes */ );
302
303         last_timecode_when = when;
304         last_timecode = timecode;
305         last_timecode_valid = true;
306 }
307
308 void
309 Session::timecode_time_subframes (framepos_t when, Timecode::Time& timecode)
310 {
311         if (last_timecode_valid && when == last_timecode_when) {
312                 timecode = last_timecode;
313                 return;
314         }
315
316         sample_to_timecode( when, timecode, true /* use_offset */, true /* use_subframes */ );
317
318         last_timecode_when = when;
319         last_timecode = timecode;
320         last_timecode_valid = true;
321 }
322
323 void
324 Session::timecode_duration (framecnt_t when, Timecode::Time& timecode) const
325 {
326         sample_to_timecode( when, timecode, false /* use_offset */, true /* use_subframes */ );
327 }
328
329 void
330 Session::timecode_duration_string (char* buf, framepos_t when) const
331 {
332         Timecode::Time timecode;
333
334         timecode_duration (when, timecode);
335         snprintf (buf, sizeof (buf), "%02" PRIu32 ":%02" PRIu32 ":%02" PRIu32 ":%02" PRIu32, timecode.hours, timecode.minutes, timecode.seconds, timecode.frames);
336 }
337
338 void
339 Session::timecode_time (Timecode::Time &t)
340
341 {
342         timecode_time (_transport_frame, t);
343 }
344
345 int
346 Session::jack_sync_callback (jack_transport_state_t state,
347                              jack_position_t* pos)
348 {
349         bool slave = synced_to_jack();
350
351         switch (state) {
352         case JackTransportStopped:
353                 if (slave && _transport_frame != pos->frame && post_transport_work() == 0) {
354                         request_locate (pos->frame, false);
355                         // cerr << "SYNC: stopped, locate to " << pos->frame << " from " << _transport_frame << endl;
356                         return false;
357                 } else {
358                         return true;
359                 }
360
361         case JackTransportStarting:
362                 // cerr << "SYNC: starting @ " << pos->frame << " a@ " << _transport_frame << " our work = " <<  post_transport_work() << " pos matches ? " << (_transport_frame == pos->frame) << endl;
363                 if (slave) {
364                         return _transport_frame == pos->frame && post_transport_work() == 0;
365                 } else {
366                         return true;
367                 }
368                 break;
369
370         case JackTransportRolling:
371                 // cerr << "SYNC: rolling slave = " << slave << endl;
372                 if (slave) {
373                         start_transport ();
374                 }
375                 break;
376
377         default:
378                 error << string_compose (_("Unknown JACK transport state %1 in sync callback"), state)
379                       << endmsg;
380         }
381
382         return true;
383 }
384
385 void
386 Session::jack_timebase_callback (jack_transport_state_t /*state*/,
387                                  pframes_t /*nframes*/,
388                                  jack_position_t* pos,
389                                  int /*new_position*/)
390 {
391         Timecode::BBT_Time bbt;
392
393         if (pos->frame != _transport_frame) {
394                 cerr << "ARDOUR says " << _transport_frame << " JACK says " << pos->frame << endl;
395         }
396
397         /* BBT info */
398
399         if (_tempo_map) {
400
401                 TempoMetric metric (_tempo_map->metric_at (_transport_frame));
402
403                 try {
404                         _tempo_map->bbt_time_rt (_transport_frame, bbt);
405
406                         pos->bar = bbt.bars;
407                         pos->beat = bbt.beats;
408                         pos->tick = bbt.ticks;
409                         
410                         // XXX still need to set bar_start_tick
411                         
412                         pos->beats_per_bar = metric.meter().divisions_per_bar();
413                         pos->beat_type = metric.meter().note_divisor();
414                         pos->ticks_per_beat = Timecode::BBT_Time::ticks_per_beat;
415                         pos->beats_per_minute = metric.tempo().beats_per_minute();
416                         
417                         pos->valid = jack_position_bits_t (pos->valid | JackPositionBBT);
418
419                 } catch (...) {
420                         /* no message */
421                 }
422         }
423
424 #ifdef HAVE_JACK_VIDEO_SUPPORT
425         //poke audio video ratio so Ardour can track Video Sync
426         pos->audio_frames_per_video_frame = frame_rate() / timecode_frames_per_second();
427         pos->valid = jack_position_bits_t (pos->valid | JackAudioVideoRatio);
428 #endif
429
430 #if 0
431         /* Timecode info */
432
433         pos->timecode_offset = config.get_timecode_offset();
434         t.timecode_frame_rate = timecode_frames_per_second();
435         pos->valid = jack_position_bits_t (pos->valid | JackPositionTimecode;
436
437         if (_transport_speed) {
438
439                 if (play_loop) {
440
441                         Location* location = _locations.auto_loop_location();
442
443                         if (location) {
444
445                                 t.transport_state = JackTransportLooping;
446                                 t.loop_start = location->start();
447                                 t.loop_end = location->end();
448                                 t.valid = jack_transport_bits_t (t.valid | JackTransportLoop);
449
450                         } else {
451
452                                 t.loop_start = 0;
453                                 t.loop_end = 0;
454                                 t.transport_state = JackTransportRolling;
455
456                         }
457
458                 } else {
459
460                         t.loop_start = 0;
461                         t.loop_end = 0;
462                         t.transport_state = JackTransportRolling;
463
464                 }
465
466         }
467 #endif
468 }
469
470 ARDOUR::framecnt_t
471 Session::convert_to_frames (AnyTime const & position)
472 {
473         double secs;
474
475         switch (position.type) {
476         case AnyTime::BBT:
477                 return _tempo_map->frame_time (position.bbt);
478                 break;
479
480         case AnyTime::Timecode:
481                 /* XXX need to handle negative values */
482                 secs = position.timecode.hours * 60 * 60;
483                 secs += position.timecode.minutes * 60;
484                 secs += position.timecode.seconds;
485                 secs += position.timecode.frames / timecode_frames_per_second();
486                 if (config.get_timecode_offset_negative()) {
487                         return (framecnt_t) floor (secs * frame_rate()) - config.get_timecode_offset();
488                 } else {
489                         return (framecnt_t) floor (secs * frame_rate()) + config.get_timecode_offset();
490                 }
491                 break;
492
493         case AnyTime::Seconds:
494                 return (framecnt_t) floor (position.seconds * frame_rate());
495                 break;
496
497         case AnyTime::Frames:
498                 return position.frames;
499                 break;
500         }
501
502         return position.frames;
503 }
504
505 ARDOUR::framecnt_t
506 Session::any_duration_to_frames (framepos_t position, AnyTime const & duration)
507 {
508         double secs;
509
510         switch (duration.type) {
511         case AnyTime::BBT:
512                 return (framecnt_t) ( _tempo_map->framepos_plus_bbt (position, duration.bbt) - position);
513                 break;
514
515         case AnyTime::Timecode:
516                 /* XXX need to handle negative values */
517                 secs = duration.timecode.hours * 60 * 60;
518                 secs += duration.timecode.minutes * 60;
519                 secs += duration.timecode.seconds;
520                 secs += duration.timecode.frames / timecode_frames_per_second();
521                 if (config.get_timecode_offset_negative()) {
522                         return (framecnt_t) floor (secs * frame_rate()) - config.get_timecode_offset();
523                 } else {
524                         return (framecnt_t) floor (secs * frame_rate()) + config.get_timecode_offset();
525                 }
526                 break;
527
528         case AnyTime::Seconds:
529                 return (framecnt_t) floor (duration.seconds * frame_rate());
530                 break;
531
532         case AnyTime::Frames:
533                 return duration.frames;
534                 break;
535         }
536
537         return duration.frames;
538 }