RealTimeSV.cpp
Go to the documentation of this file.
1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
2 
3 /*
4  Sonic Visualiser
5  An audio file viewer and annotation editor.
6  Centre for Digital Music, Queen Mary, University of London.
7 
8  This program is free software; you can redistribute it and/or
9  modify it under the terms of the GNU General Public License as
10  published by the Free Software Foundation; either version 2 of the
11  License, or (at your option) any later version. See the file
12  COPYING included with this distribution for more information.
13 */
14 
15 /*
16  This is a modified version of a source file from the
17  Rosegarden MIDI and audio sequencer and notation editor.
18  This file copyright 2000-2006 Chris Cannam.
19 */
20 
21 #include <iostream>
22 #include <limits.h>
23 
24 #include <cstdlib>
25 #include <sstream>
26 
27 #include "RealTime.h"
28 
29 #include "Debug.h"
30 
31 #include "Preferences.h"
32 
33 // A RealTime consists of two ints that must be at least 32 bits each.
34 // A signed 32-bit int can store values exceeding +/- 2 billion. This
35 // means we can safely use our lower int for nanoseconds, as there are
36 // 1 billion nanoseconds in a second and we need to handle double that
37 // because of the implementations of addition etc that we use.
38 //
39 // The maximum valid RealTime on a 32-bit system is somewhere around
40 // 68 years: 999999999 nanoseconds longer than the classic Unix epoch.
41 
42 #define ONE_BILLION 1000000000
43 
44 RealTime::RealTime(int s, int n) :
45  sec(s), nsec(n)
46 {
47  while (nsec <= -ONE_BILLION && sec > INT_MIN) { nsec += ONE_BILLION; --sec; }
48  while (nsec >= ONE_BILLION && sec < INT_MAX) { nsec -= ONE_BILLION; ++sec; }
49  while (nsec > 0 && sec < 0) { nsec -= ONE_BILLION; ++sec; }
50  while (nsec < 0 && sec > 0) { nsec += ONE_BILLION; --sec; }
51 }
52 
55 {
56  if (sec >= 0) {
57  return RealTime(int(sec), int((sec - int(sec)) * ONE_BILLION + 0.5));
58  } else {
59  return -fromSeconds(-sec);
60  }
61 }
62 
65 {
66  int64_t sec = msec / 1000;
67  if (sec > INT_MAX || sec < INT_MIN) {
68  cerr << "WARNING: millisecond value out of range for RealTime, "
69  << "returning zero instead: " << msec << endl;
70  return RealTime::zeroTime;
71  }
72 
73  return RealTime(int(sec), int(msec % 1000) * 1000000);
74 }
75 
78 {
79  int64_t sec = usec / 1000000;
80  if (sec > INT_MAX || sec < INT_MIN) {
81  cerr << "WARNING: microsecond value out of range for RealTime, "
82  << "returning zero instead: " << usec << endl;
83  return RealTime::zeroTime;
84  }
85 
86  return RealTime(int(sec), int(usec % 1000000) * 1000);
87 }
88 
90 RealTime::fromTimeval(const struct timeval &tv)
91 {
92  return RealTime(int(tv.tv_sec), int(tv.tv_usec * 1000));
93 }
94 
96 RealTime::fromXsdDuration(std::string xsdd)
97 {
98  RealTime t;
99 
100  int year = 0, month = 0, day = 0, hour = 0, minute = 0;
101  double second = 0.0;
102 
103  char *formerLoc = setlocale(LC_NUMERIC, "C"); // avoid strtod expecting ,-separator in DE
104 
105  int i = 0;
106 
107  const char *s = xsdd.c_str();
108  int len = int(xsdd.length());
109 
110  bool negative = false, afterT = false;
111 
112  while (i < len) {
113 
114  if (s[i] == '-') {
115  if (i == 0) negative = true;
116  ++i;
117  continue;
118  }
119 
120  double value = 0.0;
121  char *eptr = nullptr;
122 
123  if (isdigit(s[i]) || s[i] == '.') {
124  value = strtod(&s[i], &eptr);
125  i = int(eptr - s);
126  }
127 
128  if (i == len) break;
129 
130  switch (s[i]) {
131  case 'Y': year = int(value + 0.1); break;
132  case 'D': day = int(value + 0.1); break;
133  case 'H': hour = int(value + 0.1); break;
134  case 'M':
135  if (afterT) minute = int(value + 0.1);
136  else month = int(value + 0.1);
137  break;
138  case 'S':
139  second = value;
140  break;
141  case 'T': afterT = true; break;
142  };
143 
144  ++i;
145  }
146 
147  if (year > 0) {
148  cerr << "WARNING: This xsd:duration (\"" << xsdd << "\") contains a non-zero year.\nWith no origin and a limited data size, I will treat a year as exactly 31556952\nseconds and you should expect overflow and/or poor results." << endl;
149  t = t + RealTime(year * 31556952, 0);
150  }
151 
152  if (month > 0) {
153  cerr << "WARNING: This xsd:duration (\"" << xsdd << "\") contains a non-zero month.\nWith no origin and a limited data size, I will treat a month as exactly 2629746\nseconds and you should expect overflow and/or poor results." << endl;
154  t = t + RealTime(month * 2629746, 0);
155  }
156 
157  if (day > 0) {
158  t = t + RealTime(day * 86400, 0);
159  }
160 
161  if (hour > 0) {
162  t = t + RealTime(hour * 3600, 0);
163  }
164 
165  if (minute > 0) {
166  t = t + RealTime(minute * 60, 0);
167  }
168 
169  t = t + fromSeconds(second);
170 
171  setlocale(LC_NUMERIC, formerLoc);
172 
173  if (negative) {
174  return -t;
175  } else {
176  return t;
177  }
178 }
179 
180 double
182 {
183  double d = sec;
184  d += double(nsec) / double(ONE_BILLION);
185  return d;
186 }
187 
188 std::ostream &operator<<(std::ostream &out, const RealTime &rt)
189 {
190  if (rt < RealTime::zeroTime) {
191  out << "-";
192  } else {
193  out << " ";
194  }
195 
196  int s = (rt.sec < 0 ? -rt.sec : rt.sec);
197  int n = (rt.nsec < 0 ? -rt.nsec : rt.nsec);
198 
199  out << s << ".";
200 
201  int nn(n);
202  if (nn == 0) out << "00000000";
203  else while (nn < (ONE_BILLION / 10)) {
204  out << "0";
205  nn *= 10;
206  }
207 
208  out << n << "R";
209  return out;
210 }
211 
212 std::string
213 RealTime::toString(bool align) const
214 {
215  std::stringstream out;
216  out << *this;
217 
218  std::string s = out.str();
219 
220  if (!align && *this >= RealTime::zeroTime) {
221  // remove leading " "
222  s = s.substr(1, s.length() - 1);
223  }
224 
225  // remove trailing R
226  return s.substr(0, s.length() - 1);
227 }
228 
229 RealTime
230 RealTime::fromString(std::string s)
231 {
232  bool negative = false;
233  int section = 0;
234  std::string ssec, snsec;
235 
236  for (size_t i = 0; i < s.length(); ++i) {
237 
238  char c = s[i];
239  if (isspace(c)) continue;
240 
241  if (section == 0) {
242 
243  if (c == '-') negative = true;
244  else if (isdigit(c)) { section = 1; ssec += c; }
245  else if (c == '.') section = 2;
246  else break;
247 
248  } else if (section == 1) {
249 
250  if (c == '.') section = 2;
251  else if (isdigit(c)) ssec += c;
252  else break;
253 
254  } else if (section == 2) {
255 
256  if (isdigit(c)) snsec += c;
257  else break;
258  }
259  }
260 
261  while (snsec.length() < 8) snsec += '0';
262 
263  int sec = atoi(ssec.c_str());
264  int nsec = atoi(snsec.c_str());
265  if (negative) sec = -sec;
266 
267 // SVDEBUG << "RealTime::fromString: string " << s << " -> "
268 // << sec << " sec, " << nsec << " nsec" << endl;
269 
270  return RealTime(sec, nsec);
271 }
272 
273 std::string
274 RealTime::toText(bool fixedDp) const
275 {
276  if (*this < RealTime::zeroTime) return "-" + (-*this).toText(fixedDp);
277 
279  bool hms = true;
280  std::string frameDelimiter = ":";
281 
282  if (p) {
283  hms = p->getShowHMS();
284  int fps = 0;
285  switch (p->getTimeToTextMode()) {
287  break;
289  fps = 1000000;
290  frameDelimiter = ".";
291  break;
292  case Preferences::TimeToText24Frame: fps = 24; break;
293  case Preferences::TimeToText25Frame: fps = 25; break;
294  case Preferences::TimeToText30Frame: fps = 30; break;
295  case Preferences::TimeToText50Frame: fps = 50; break;
296  case Preferences::TimeToText60Frame: fps = 60; break;
297  }
298  if (fps != 0) {
299  return toFrameText(fps, hms, frameDelimiter);
300  }
301  }
302 
303  return toMSText(fixedDp, hms);
304 }
305 
306 static void
307 writeSecPart(std::stringstream &out, bool hms, int sec)
308 {
309  if (hms) {
310  if (sec >= 3600) {
311  out << (sec / 3600) << ":";
312  }
313 
314  if (sec >= 60) {
315  int minutes = (sec % 3600) / 60;
316  if (sec >= 3600 && minutes < 10) out << "0";
317  out << minutes << ":";
318  }
319 
320  if (sec >= 10) {
321  out << ((sec % 60) / 10);
322  }
323 
324  out << (sec % 10);
325 
326  } else {
327  out << sec;
328  }
329 }
330 
331 std::string
332 RealTime::toMSText(bool fixedDp, bool hms) const
333 {
334  if (*this < RealTime::zeroTime) return "-" + (-*this).toMSText(fixedDp, hms);
335 
336  std::stringstream out;
337 
338  writeSecPart(out, hms, sec);
339 
340  int ms = msec();
341 
342  if (ms != 0) {
343  out << ".";
344  out << (ms / 100);
345  ms = ms % 100;
346  if (ms != 0) {
347  out << (ms / 10);
348  ms = ms % 10;
349  } else if (fixedDp) {
350  out << "0";
351  }
352  if (ms != 0) {
353  out << ms;
354  } else if (fixedDp) {
355  out << "0";
356  }
357  } else if (fixedDp) {
358  out << ".000";
359  }
360 
361  std::string s = out.str();
362 
363  return s;
364 }
365 
366 std::string
367 RealTime::toFrameText(int fps, bool hms, std::string frameDelimiter) const
368 {
369  if (*this < RealTime::zeroTime) {
370  return "-" + (-*this).toFrameText(fps, hms);
371  }
372 
373  std::stringstream out;
374 
375  writeSecPart(out, hms, sec);
376 
377  // avoid rounding error if fps does not divide into ONE_BILLION
378  int64_t fbig = nsec;
379  fbig *= fps;
380  int f = int(fbig / ONE_BILLION);
381 
382  int div = 1;
383  int n = fps - 1;
384  while ((n = n / 10)) {
385  div *= 10;
386  }
387 
388  out << frameDelimiter;
389 
390 // cerr << "div = " << div << ", f = "<< f << endl;
391 
392  while (div) {
393  int d = (f / div) % 10;
394  out << d;
395  div /= 10;
396  }
397 
398  std::string s = out.str();
399 
400 // cerr << "converted " << toString() << " to " << s << endl;
401 
402  return s;
403 }
404 
405 std::string
407 {
408  if (*this < RealTime::zeroTime) return "-" + (-*this).toSecText();
409 
410  std::stringstream out;
411 
412  writeSecPart(out, true, sec);
413 
414  if (sec < 60) {
415  out << "s";
416  }
417 
418  std::string s = out.str();
419 
420  return s;
421 }
422 
423 std::string
425 {
426  std::string s = "PT" + toString(false) + "S";
427  return s;
428 }
429 
430 RealTime
432 {
433  double t = (double(nsec) / ONE_BILLION) * m;
434  t += sec * m;
435  return fromSeconds(t);
436 }
437 
438 RealTime
440 {
441  int secdiv = sec / d;
442  int secrem = sec % d;
443 
444  double nsecdiv = (double(nsec) + ONE_BILLION * double(secrem)) / d;
445 
446  return RealTime(secdiv, int(nsecdiv + 0.5));
447 }
448 
449 RealTime
450 RealTime::operator*(double m) const
451 {
452  double t = (double(nsec) / ONE_BILLION) * m;
453  t += sec * m;
454  return fromSeconds(t);
455 }
456 
457 RealTime
458 RealTime::operator/(double d) const
459 {
460  double t = (double(nsec) / ONE_BILLION) / d;
461  t += sec / d;
462  return fromSeconds(t);
463 }
464 
465 double
467 {
468  double lTotal = double(sec) * ONE_BILLION + double(nsec);
469  double rTotal = double(r.sec) * ONE_BILLION + double(r.nsec);
470 
471  if (rTotal == 0) return 0.0;
472  else return lTotal/rTotal;
473 }
474 
475 static RealTime
477 {
478  if (frame < 0) return -frame2RealTime_i(-frame, iSampleRate);
479 
480  int sec = int(frame / iSampleRate);
481  frame -= sec * iSampleRate;
482  int nsec = int((double(frame) / double(iSampleRate)) * ONE_BILLION + 0.5);
483  // Use ctor here instead of setting data members directly to
484  // ensure nsec > ONE_BILLION is handled properly. It's extremely
485  // unlikely, but not impossible.
486  return RealTime(sec, nsec);
487 }
488 
491 {
492  if (time < zeroTime) return -realTime2Frame(-time, sampleRate);
493  double s = time.sec + double(time.nsec) / 1000000000.0;
494  return sv_frame_t(s * sampleRate + 0.5);
495 }
496 
497 RealTime
499 {
500  if (sampleRate == double(int(sampleRate))) {
501  return frame2RealTime_i(frame, int(sampleRate));
502  }
503 
504  double sec = double(frame) / sampleRate;
505  return fromSeconds(sec);
506 }
507 
508 const RealTime RealTime::zeroTime(0,0);
509 
double sv_samplerate_t
Sample rate.
Definition: BaseTypes.h:51
bool getShowHMS() const
Definition: Preferences.h:102
#define ONE_BILLION
Definition: RealTimeSV.cpp:42
static RealTime fromTimeval(const struct timeval &)
Definition: RealTimeSV.cpp:90
static RealTime fromString(std::string)
Convert a string as obtained from toString back to a RealTime object.
Definition: RealTimeSV.cpp:230
int64_t sv_frame_t
Frame index, the unit of our time axis.
Definition: BaseTypes.h:31
static RealTime fromMilliseconds(int64_t msec)
Definition: RealTimeSV.cpp:64
static RealTime frame2RealTime(sv_frame_t frame, sv_samplerate_t sampleRate)
Convert a sample frame at the given sample rate into a RealTime.
Definition: RealTimeSV.cpp:498
static void writeSecPart(std::stringstream &out, bool hms, int sec)
Definition: RealTimeSV.cpp:307
static RealTime fromSeconds(double sec)
Definition: RealTimeSV.cpp:54
int nsec
Definition: RealTime.h:45
std::ostream & operator<<(std::ostream &out, const RealTime &rt)
Definition: RealTimeSV.cpp:188
std::string toXsdDuration() const
Return a string in xsd:duration format.
Definition: RealTimeSV.cpp:424
static Preferences * getInstance()
Definition: Preferences.cpp:31
std::string toString(bool align=false) const
Return a human-readable debug-type string to full precision (probably not a format to show to a user ...
Definition: RealTimeSV.cpp:213
std::string toMSText(bool fixedDp, bool hms) const
Return a user-readable string to the nearest millisecond.
Definition: RealTimeSV.cpp:332
double toDouble() const
Definition: RealTimeSV.cpp:181
RealTime operator/(int d) const
Definition: RealTimeSV.cpp:439
int sec
Definition: RealTime.h:44
RealTime()
Definition: RealTime.h:50
std::string toSecText() const
Return a user-readable string to the nearest second, in H:M:S form.
Definition: RealTimeSV.cpp:406
int msec() const
Definition: RealTime.h:48
static sv_frame_t realTime2Frame(const RealTime &r, sv_samplerate_t sampleRate)
Convert a RealTime into a sample frame at the given sample rate.
Definition: RealTimeSV.cpp:490
int usec() const
Definition: RealTime.h:47
std::string toFrameText(int fps, bool hms, std::string frameDelimiter=":") const
Return a user-readable string in which seconds are divided into frames (presumably at a lower frame r...
Definition: RealTimeSV.cpp:367
std::string toText(bool fixedDp=false) const
Return a user-readable string to the nearest millisecond, typically in a form like HH:MM:SS...
Definition: RealTimeSV.cpp:274
static RealTime fromMicroseconds(int64_t usec)
Definition: RealTimeSV.cpp:77
static const RealTime zeroTime
Definition: RealTime.h:204
static RealTime fromXsdDuration(std::string xsdd)
Definition: RealTimeSV.cpp:96
TimeToTextMode getTimeToTextMode() const
Definition: Preferences.h:100
static RealTime frame2RealTime_i(sv_frame_t frame, sv_frame_t iSampleRate)
Definition: RealTimeSV.cpp:476
RealTime represents time values to nanosecond precision with accurate arithmetic and frame-rate conve...
Definition: RealTime.h:42
RealTime operator*(int m) const
Definition: RealTimeSV.cpp:431