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 
RealTime(int s,int n)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 
53 RealTime
fromSeconds(double sec)54 RealTime::fromSeconds(double sec)
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 
63 RealTime
fromMilliseconds(int64_t msec)64 RealTime::fromMilliseconds(int64_t msec)
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 
76 RealTime
fromMicroseconds(int64_t usec)77 RealTime::fromMicroseconds(int64_t usec)
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 
89 RealTime
fromTimeval(const struct timeval & tv)90 RealTime::fromTimeval(const struct timeval &tv)
91 {
92     return RealTime(int(tv.tv_sec), int(tv.tv_usec * 1000));
93 }
94 
95 RealTime
fromXsdDuration(std::string xsdd)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
toDouble() const181 RealTime::toDouble() const
182 {
183     double d = sec;
184     d += double(nsec) / double(ONE_BILLION);
185     return d;
186 }
187 
operator <<(std::ostream & out,const RealTime & rt)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
toString(bool align) const213 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
fromString(std::string s)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
toText(bool fixedDp) const274 RealTime::toText(bool fixedDp) const
275 {
276     if (*this < RealTime::zeroTime) return "-" + (-*this).toText(fixedDp);
277 
278     Preferences *p = Preferences::getInstance();
279     bool hms = true;
280     std::string frameDelimiter = ":";
281 
282     if (p) {
283         hms = p->getShowHMS();
284         int fps = 0;
285         switch (p->getTimeToTextMode()) {
286         case Preferences::TimeToTextMs:
287             break;
288         case Preferences::TimeToTextUs:
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
writeSecPart(std::stringstream & out,bool hms,int sec)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
toMSText(bool fixedDp,bool hms) const332 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
toFrameText(int fps,bool hms,std::string frameDelimiter) const367 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
toSecText() const406 RealTime::toSecText() const
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
toXsdDuration() const424 RealTime::toXsdDuration() const
425 {
426     std::string s = "PT" + toString(false) + "S";
427     return s;
428 }
429 
430 RealTime
operator *(int m) const431 RealTime::operator*(int m) const
432 {
433     double t = (double(nsec) / ONE_BILLION) * m;
434     t += sec * m;
435     return fromSeconds(t);
436 }
437 
438 RealTime
operator /(int d) const439 RealTime::operator/(int d) const
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
operator *(double m) const450 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
operator /(double d) const458 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
operator /(const RealTime & r) const466 RealTime::operator/(const RealTime &r) const
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
frame2RealTime_i(sv_frame_t frame,sv_frame_t iSampleRate)476 frame2RealTime_i(sv_frame_t frame, sv_frame_t iSampleRate)
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 
489 sv_frame_t
realTime2Frame(const RealTime & time,sv_samplerate_t sampleRate)490 RealTime::realTime2Frame(const RealTime &time, sv_samplerate_t sampleRate)
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
frame2RealTime(sv_frame_t frame,sv_samplerate_t sampleRate)498 RealTime::frame2RealTime(sv_frame_t frame, sv_samplerate_t sampleRate)
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 
510