Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_Time.cpp 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. namespace TimeHelpers
  24. {
  25. #if 0
  26. static std::tm millisToLocal (int64 millis) noexcept
  27. {
  28. #if JUCE_WINDOWS && JUCE_MINGW
  29. time_t now = (time_t) (millis / 1000);
  30. return *localtime (&now);
  31. #elif JUCE_WINDOWS
  32. std::tm result;
  33. millis /= 1000;
  34. if (_localtime64_s (&result, &millis) != 0)
  35. zerostruct (result);
  36. return result;
  37. #else
  38. std::tm result;
  39. time_t now = (time_t) (millis / 1000);
  40. if (localtime_r (&now, &result) == nullptr)
  41. zerostruct (result);
  42. return result;
  43. #endif
  44. }
  45. static std::tm millisToUTC (int64 millis) noexcept
  46. {
  47. #if JUCE_WINDOWS && JUCE_MINGW
  48. time_t now = (time_t) (millis / 1000);
  49. return *gmtime (&now);
  50. #elif JUCE_WINDOWS
  51. std::tm result;
  52. millis /= 1000;
  53. if (_gmtime64_s (&result, &millis) != 0)
  54. zerostruct (result);
  55. return result;
  56. #else
  57. std::tm result;
  58. time_t now = (time_t) (millis / 1000);
  59. if (gmtime_r (&now, &result) == nullptr)
  60. zerostruct (result);
  61. return result;
  62. #endif
  63. }
  64. static int getUTCOffsetSeconds (const int64 millis) noexcept
  65. {
  66. std::tm utc = millisToUTC (millis);
  67. utc.tm_isdst = -1; // Treat this UTC time as local to find the offset
  68. return (int) ((millis / 1000) - (int64) mktime (&utc));
  69. }
  70. static int extendedModulo (const int64 value, const int modulo) noexcept
  71. {
  72. return (int) (value >= 0 ? (value % modulo)
  73. : (value - ((value / modulo) + 1) * modulo));
  74. }
  75. static inline String formatString (const String& format, const std::tm* const tm)
  76. {
  77. #if JUCE_ANDROID
  78. typedef CharPointer_UTF8 StringType;
  79. #elif JUCE_WINDOWS
  80. typedef CharPointer_UTF16 StringType;
  81. #else
  82. typedef CharPointer_UTF32 StringType;
  83. #endif
  84. #ifdef JUCE_MSVC
  85. if (tm->tm_year < -1900 || tm->tm_year > 8099)
  86. return String(); // Visual Studio's library can only handle 0 -> 9999 AD
  87. #endif
  88. for (size_t bufferSize = 256; ; bufferSize += 256)
  89. {
  90. HeapBlock<StringType::CharType> buffer (bufferSize);
  91. const size_t numChars =
  92. #if JUCE_ANDROID
  93. strftime (buffer, bufferSize - 1, format.toUTF8(), tm);
  94. #elif JUCE_WINDOWS
  95. wcsftime (buffer, bufferSize - 1, format.toWideCharPointer(), tm);
  96. #else
  97. wcsftime (buffer, bufferSize - 1, format.toUTF32(), tm);
  98. #endif
  99. if (numChars > 0 || format.isEmpty())
  100. return String (StringType (buffer),
  101. StringType (buffer) + (int) numChars);
  102. }
  103. }
  104. //==============================================================================
  105. static inline bool isLeapYear (int year) noexcept
  106. {
  107. return (year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0));
  108. }
  109. static inline int daysFromJan1 (int year, int month) noexcept
  110. {
  111. const short dayOfYear[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334,
  112. 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
  113. return dayOfYear [(isLeapYear (year) ? 12 : 0) + month];
  114. }
  115. static inline int64 daysFromYear0 (int year) noexcept
  116. {
  117. --year;
  118. return 365 * year + (year / 400) - (year / 100) + (year / 4);
  119. }
  120. static inline int64 daysFrom1970 (int year) noexcept
  121. {
  122. return daysFromYear0 (year) - daysFromYear0 (1970);
  123. }
  124. static inline int64 daysFrom1970 (int year, int month) noexcept
  125. {
  126. if (month > 11)
  127. {
  128. year += month / 12;
  129. month %= 12;
  130. }
  131. else if (month < 0)
  132. {
  133. const int numYears = (11 - month) / 12;
  134. year -= numYears;
  135. month += 12 * numYears;
  136. }
  137. return daysFrom1970 (year) + daysFromJan1 (year, month);
  138. }
  139. // There's no posix function that does a UTC version of mktime,
  140. // so annoyingly we need to implement this manually..
  141. static inline int64 mktime_utc (const std::tm& t) noexcept
  142. {
  143. return 24 * 3600 * (daysFrom1970 (t.tm_year + 1900, t.tm_mon) + (t.tm_mday - 1))
  144. + 3600 * t.tm_hour
  145. + 60 * t.tm_min
  146. + t.tm_sec;
  147. }
  148. #endif
  149. static uint32 lastMSCounterValue = 0;
  150. }
  151. //==============================================================================
  152. Time::Time() noexcept : millisSinceEpoch (0)
  153. {
  154. }
  155. Time::Time (const Time& other) noexcept : millisSinceEpoch (other.millisSinceEpoch)
  156. {
  157. }
  158. Time::Time (const int64 ms) noexcept : millisSinceEpoch (ms)
  159. {
  160. }
  161. #if 0
  162. Time::Time (const int year,
  163. const int month,
  164. const int day,
  165. const int hours,
  166. const int minutes,
  167. const int seconds,
  168. const int milliseconds,
  169. const bool useLocalTime) noexcept
  170. {
  171. std::tm t;
  172. t.tm_year = year - 1900;
  173. t.tm_mon = month;
  174. t.tm_mday = day;
  175. t.tm_hour = hours;
  176. t.tm_min = minutes;
  177. t.tm_sec = seconds;
  178. t.tm_isdst = -1;
  179. millisSinceEpoch = 1000 * (useLocalTime ? (int64) mktime (&t)
  180. : TimeHelpers::mktime_utc (t))
  181. + milliseconds;
  182. }
  183. #endif
  184. Time::~Time() noexcept
  185. {
  186. }
  187. Time& Time::operator= (const Time& other) noexcept
  188. {
  189. millisSinceEpoch = other.millisSinceEpoch;
  190. return *this;
  191. }
  192. //==============================================================================
  193. int64 Time::currentTimeMillis() noexcept
  194. {
  195. struct timeval tv;
  196. gettimeofday (&tv, nullptr);
  197. return ((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000;
  198. }
  199. #if 0
  200. Time JUCE_CALLTYPE Time::getCurrentTime() noexcept
  201. {
  202. return Time (currentTimeMillis());
  203. }
  204. #endif
  205. //==============================================================================
  206. static uint32 juce_millisecondsSinceStartup() noexcept
  207. {
  208. #ifdef CARLA_OS_WIN
  209. return (uint32) timeGetTime();
  210. #else
  211. timespec t;
  212. clock_gettime (CLOCK_MONOTONIC, &t);
  213. return (uint32) (t.tv_sec * 1000 + t.tv_nsec / 1000000);
  214. #endif
  215. }
  216. uint32 Time::getMillisecondCounter() noexcept
  217. {
  218. const uint32 now = juce_millisecondsSinceStartup();
  219. if (now < TimeHelpers::lastMSCounterValue)
  220. {
  221. // in multi-threaded apps this might be called concurrently, so
  222. // make sure that our last counter value only increases and doesn't
  223. // go backwards..
  224. if (now < TimeHelpers::lastMSCounterValue - 1000)
  225. TimeHelpers::lastMSCounterValue = now;
  226. }
  227. else
  228. {
  229. TimeHelpers::lastMSCounterValue = now;
  230. }
  231. return now;
  232. }
  233. uint32 Time::getApproximateMillisecondCounter() noexcept
  234. {
  235. if (TimeHelpers::lastMSCounterValue == 0)
  236. getMillisecondCounter();
  237. return TimeHelpers::lastMSCounterValue;
  238. }
  239. #if 0
  240. void Time::waitForMillisecondCounter (const uint32 targetTime) noexcept
  241. {
  242. for (;;)
  243. {
  244. const uint32 now = getMillisecondCounter();
  245. if (now >= targetTime)
  246. break;
  247. const int toWait = (int) (targetTime - now);
  248. if (toWait > 2)
  249. {
  250. Thread::sleep (jmin (20, toWait >> 1));
  251. }
  252. else
  253. {
  254. // xxx should consider using mutex_pause on the mac as it apparently
  255. // makes it seem less like a spinlock and avoids lowering the thread pri.
  256. for (int i = 10; --i >= 0;)
  257. Thread::yield();
  258. }
  259. }
  260. }
  261. //==============================================================================
  262. double Time::highResolutionTicksToSeconds (const int64 ticks) noexcept
  263. {
  264. return ticks / (double) getHighResolutionTicksPerSecond();
  265. }
  266. int64 Time::secondsToHighResolutionTicks (const double seconds) noexcept
  267. {
  268. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  269. }
  270. //==============================================================================
  271. String Time::toString (const bool includeDate,
  272. const bool includeTime,
  273. const bool includeSeconds,
  274. const bool use24HourClock) const noexcept
  275. {
  276. String result;
  277. if (includeDate)
  278. {
  279. result << getDayOfMonth() << ' '
  280. << getMonthName (true) << ' '
  281. << getYear();
  282. if (includeTime)
  283. result << ' ';
  284. }
  285. if (includeTime)
  286. {
  287. const int mins = getMinutes();
  288. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  289. << (mins < 10 ? ":0" : ":") << mins;
  290. if (includeSeconds)
  291. {
  292. const int secs = getSeconds();
  293. result << (secs < 10 ? ":0" : ":") << secs;
  294. }
  295. if (! use24HourClock)
  296. result << (isAfternoon() ? "pm" : "am");
  297. }
  298. return result.trimEnd();
  299. }
  300. String Time::formatted (const String& format) const
  301. {
  302. std::tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  303. return TimeHelpers::formatString (format, &t);
  304. }
  305. //==============================================================================
  306. int Time::getYear() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900; }
  307. int Time::getMonth() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon; }
  308. int Time::getDayOfYear() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_yday; }
  309. int Time::getDayOfMonth() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday; }
  310. int Time::getDayOfWeek() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday; }
  311. int Time::getHours() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour; }
  312. int Time::getMinutes() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min; }
  313. int Time::getSeconds() const noexcept { return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60); }
  314. int Time::getMilliseconds() const noexcept { return TimeHelpers::extendedModulo (millisSinceEpoch, 1000); }
  315. int Time::getHoursInAmPmFormat() const noexcept
  316. {
  317. const int hours = getHours();
  318. if (hours == 0) return 12;
  319. if (hours <= 12) return hours;
  320. return hours - 12;
  321. }
  322. bool Time::isAfternoon() const noexcept
  323. {
  324. return getHours() >= 12;
  325. }
  326. bool Time::isDaylightSavingTime() const noexcept
  327. {
  328. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  329. }
  330. String Time::getTimeZone() const noexcept
  331. {
  332. String zone[2];
  333. #if JUCE_WINDOWS
  334. #if JUCE_MSVC || JUCE_CLANG
  335. _tzset();
  336. for (int i = 0; i < 2; ++i)
  337. {
  338. char name[128] = { 0 };
  339. size_t length;
  340. _get_tzname (&length, name, 127, i);
  341. zone[i] = name;
  342. }
  343. #else
  344. #warning "Can't find a replacement for tzset on mingw - ideas welcome!"
  345. #endif
  346. #else
  347. tzset();
  348. const char** const zonePtr = (const char**) tzname;
  349. zone[0] = zonePtr[0];
  350. zone[1] = zonePtr[1];
  351. #endif
  352. if (isDaylightSavingTime())
  353. {
  354. zone[0] = zone[1];
  355. if (zone[0].length() > 3
  356. && zone[0].containsIgnoreCase ("daylight")
  357. && zone[0].contains ("GMT"))
  358. zone[0] = "BST";
  359. }
  360. return zone[0].substring (0, 3);
  361. }
  362. int Time::getUTCOffsetSeconds() const noexcept
  363. {
  364. return TimeHelpers::getUTCOffsetSeconds (millisSinceEpoch);
  365. }
  366. String Time::getUTCOffsetString (bool includeSemiColon) const
  367. {
  368. if (int seconds = getUTCOffsetSeconds())
  369. {
  370. const int minutes = seconds / 60;
  371. return String::formatted (includeSemiColon ? "%+03d:%02d"
  372. : "%+03d%02d",
  373. minutes / 60,
  374. minutes % 60);
  375. }
  376. return "Z";
  377. }
  378. String Time::toISO8601 (bool includeDividerCharacters) const
  379. {
  380. return String::formatted (includeDividerCharacters ? "%04d-%02d-%02dT%02d:%02d:%06.03f"
  381. : "%04d%02d%02dT%02d%02d%06.03f",
  382. getYear(),
  383. getMonth() + 1,
  384. getDayOfMonth(),
  385. getHours(),
  386. getMinutes(),
  387. getSeconds() + getMilliseconds() / 1000.0)
  388. + getUTCOffsetString (includeDividerCharacters);
  389. }
  390. static int parseFixedSizeIntAndSkip (String::CharPointerType& t, int numChars, char charToSkip) noexcept
  391. {
  392. int n = 0;
  393. for (int i = numChars; --i >= 0;)
  394. {
  395. const int digit = (int) (*t - '0');
  396. if (! isPositiveAndBelow (digit, 10))
  397. return -1;
  398. ++t;
  399. n = n * 10 + digit;
  400. }
  401. if (charToSkip != 0 && *t == (juce_wchar) charToSkip)
  402. ++t;
  403. return n;
  404. }
  405. Time Time::fromISO8601 (StringRef iso) noexcept
  406. {
  407. String::CharPointerType t = iso.text;
  408. const int year = parseFixedSizeIntAndSkip (t, 4, '-');
  409. if (year < 0)
  410. return Time();
  411. const int month = parseFixedSizeIntAndSkip (t, 2, '-');
  412. if (month < 0)
  413. return Time();
  414. const int day = parseFixedSizeIntAndSkip (t, 2, 0);
  415. if (day < 0)
  416. return Time();
  417. int hours = 0, minutes = 0, milliseconds = 0;
  418. if (*t == 'T')
  419. {
  420. ++t;
  421. hours = parseFixedSizeIntAndSkip (t, 2, ':');
  422. if (hours < 0)
  423. return Time();
  424. minutes = parseFixedSizeIntAndSkip (t, 2, ':');
  425. if (minutes < 0)
  426. return Time();
  427. milliseconds = (int) (1000.0 * CharacterFunctions::readDoubleValue (t));
  428. }
  429. const juce_wchar nextChar = t.getAndAdvance();
  430. if (nextChar == '-' || nextChar == '+')
  431. {
  432. const int offsetHours = parseFixedSizeIntAndSkip (t, 2, ':');
  433. if (offsetHours < 0)
  434. return Time();
  435. const int offsetMinutes = parseFixedSizeIntAndSkip (t, 2, 0);
  436. if (offsetMinutes < 0)
  437. return Time();
  438. const int offsetMs = (offsetHours * 60 + offsetMinutes) * 60 * 1000;
  439. milliseconds += nextChar == '-' ? offsetMs : -offsetMs; // NB: this seems backwards but is correct!
  440. }
  441. else if (nextChar != 0 && nextChar != 'Z')
  442. {
  443. return Time();
  444. }
  445. return Time (year, month - 1, day, hours, minutes, 0, milliseconds, false);
  446. }
  447. String Time::getMonthName (const bool threeLetterVersion) const
  448. {
  449. return getMonthName (getMonth(), threeLetterVersion);
  450. }
  451. String Time::getWeekdayName (const bool threeLetterVersion) const
  452. {
  453. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  454. }
  455. static const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  456. static const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  457. String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  458. {
  459. monthNumber %= 12;
  460. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  461. : longMonthNames [monthNumber]);
  462. }
  463. String Time::getWeekdayName (int day, const bool threeLetterVersion)
  464. {
  465. static const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  466. static const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  467. day %= 7;
  468. return TRANS (threeLetterVersion ? shortDayNames [day]
  469. : longDayNames [day]);
  470. }
  471. //==============================================================================
  472. Time& Time::operator+= (RelativeTime delta) noexcept { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  473. Time& Time::operator-= (RelativeTime delta) noexcept { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  474. Time operator+ (Time time, RelativeTime delta) noexcept { Time t (time); return t += delta; }
  475. Time operator- (Time time, RelativeTime delta) noexcept { Time t (time); return t -= delta; }
  476. Time operator+ (RelativeTime delta, Time time) noexcept { Time t (time); return t += delta; }
  477. const RelativeTime operator- (Time time1, Time time2) noexcept { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); }
  478. bool operator== (Time time1, Time time2) noexcept { return time1.toMilliseconds() == time2.toMilliseconds(); }
  479. bool operator!= (Time time1, Time time2) noexcept { return time1.toMilliseconds() != time2.toMilliseconds(); }
  480. bool operator< (Time time1, Time time2) noexcept { return time1.toMilliseconds() < time2.toMilliseconds(); }
  481. bool operator> (Time time1, Time time2) noexcept { return time1.toMilliseconds() > time2.toMilliseconds(); }
  482. bool operator<= (Time time1, Time time2) noexcept { return time1.toMilliseconds() <= time2.toMilliseconds(); }
  483. bool operator>= (Time time1, Time time2) noexcept { return time1.toMilliseconds() >= time2.toMilliseconds(); }
  484. static int getMonthNumberForCompileDate (const String& m) noexcept
  485. {
  486. for (int i = 0; i < 12; ++i)
  487. if (m.equalsIgnoreCase (shortMonthNames[i]))
  488. return i;
  489. // If you hit this because your compiler has an unusual __DATE__
  490. // format, let us know so we can add support for it!
  491. jassertfalse;
  492. return 0;
  493. }
  494. Time Time::getCompilationDate()
  495. {
  496. StringArray dateTokens, timeTokens;
  497. dateTokens.addTokens (__DATE__, true);
  498. dateTokens.removeEmptyStrings (true);
  499. timeTokens.addTokens (__TIME__, ":", StringRef());
  500. return Time (dateTokens[2].getIntValue(),
  501. getMonthNumberForCompileDate (dateTokens[0]),
  502. dateTokens[1].getIntValue(),
  503. timeTokens[0].getIntValue(),
  504. timeTokens[1].getIntValue());
  505. }
  506. #endif