94ae2621d621104b8998c0ec4e7179d64e80b1f5
[platform/upstream/gstreamer.git] / gst / gstdatetime.c
1 /* GStreamer
2  * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include "gst_private.h"
25 #include "glib-compat-private.h"
26 #include "gstdatetime.h"
27 #include "gstvalue.h"
28 #include <glib.h>
29 #include <math.h>
30 #include <stdio.h>
31
32 /**
33  * SECTION:gstdatetime
34  * @title: GstDateTime
35  * @short_description: A date, time and timezone structure
36  *
37  * Struct to store date, time and timezone information altogether.
38  * #GstDateTime is refcounted and immutable.
39  *
40  * Date information is handled using the proleptic Gregorian calendar.
41  *
42  * Provides basic creation functions and accessor functions to its fields.
43  */
44
45 typedef enum
46 {
47   GST_DATE_TIME_FIELDS_INVALID = 0,
48   GST_DATE_TIME_FIELDS_Y,       /* have year                */
49   GST_DATE_TIME_FIELDS_YM,      /* have year and month      */
50   GST_DATE_TIME_FIELDS_YMD,     /* have year, month and day */
51   GST_DATE_TIME_FIELDS_YMD_HM,
52   GST_DATE_TIME_FIELDS_YMD_HMS
53       /* Note: if we ever add more granularity here, e.g. for microsecs,
54        * the compare function will need updating */
55 } GstDateTimeFields;
56
57 struct _GstDateTime
58 {
59   GstMiniObject mini_object;
60
61   GDateTime *datetime;
62
63   GstDateTimeFields fields;
64 };
65
66 GST_DEFINE_MINI_OBJECT_TYPE (GstDateTime, gst_date_time);
67
68 static void gst_date_time_free (GstDateTime * datetime);
69
70 /**
71  * gst_date_time_new_from_g_date_time:
72  * @dt: (transfer full): the #GDateTime. The new #GstDateTime takes ownership.
73  *
74  * Creates a new #GstDateTime from a #GDateTime object.
75  *
76  * Free-function: gst_date_time_unref
77  *
78  * Returns: (transfer full): a newly created #GstDateTime, or %NULL on error
79  */
80 GstDateTime *
81 gst_date_time_new_from_g_date_time (GDateTime * dt)
82 {
83   GstDateTime *gst_dt;
84
85   if (!dt)
86     return NULL;
87
88   gst_dt = g_slice_new (GstDateTime);
89
90   gst_mini_object_init (GST_MINI_OBJECT_CAST (gst_dt), 0, GST_TYPE_DATE_TIME,
91       NULL, NULL, (GstMiniObjectFreeFunction) gst_date_time_free);
92
93   gst_dt->datetime = dt;
94   gst_dt->fields = GST_DATE_TIME_FIELDS_YMD_HMS;
95   return gst_dt;
96 }
97
98 /**
99  * gst_date_time_to_g_date_time:
100  * @datetime: GstDateTime.
101  *
102  * Creates a new #GDateTime from a fully defined #GstDateTime object.
103  *
104  * Free-function: g_date_time_unref
105  *
106  * Returns: (transfer full): a newly created #GDateTime, or %NULL on error
107  */
108 GDateTime *
109 gst_date_time_to_g_date_time (GstDateTime * datetime)
110 {
111   g_return_val_if_fail (datetime != NULL, NULL);
112
113   if (datetime->fields != GST_DATE_TIME_FIELDS_YMD_HMS)
114     return NULL;
115
116   return g_date_time_add (datetime->datetime, 0);
117 }
118
119 /**
120  * gst_date_time_has_year:
121  * @datetime: a #GstDateTime
122  *
123  * Returns: %TRUE if @datetime<!-- -->'s year field is set (which should always
124  *     be the case), otherwise %FALSE
125  */
126 gboolean
127 gst_date_time_has_year (const GstDateTime * datetime)
128 {
129   g_return_val_if_fail (datetime != NULL, FALSE);
130
131   return (datetime->fields >= GST_DATE_TIME_FIELDS_Y);
132 }
133
134 /**
135  * gst_date_time_has_month:
136  * @datetime: a #GstDateTime
137  *
138  * Returns: %TRUE if @datetime<!-- -->'s month field is set, otherwise %FALSE
139  */
140 gboolean
141 gst_date_time_has_month (const GstDateTime * datetime)
142 {
143   g_return_val_if_fail (datetime != NULL, FALSE);
144
145   return (datetime->fields >= GST_DATE_TIME_FIELDS_YM);
146 }
147
148 /**
149  * gst_date_time_has_day:
150  * @datetime: a #GstDateTime
151  *
152  * Returns: %TRUE if @datetime<!-- -->'s day field is set, otherwise %FALSE
153  */
154 gboolean
155 gst_date_time_has_day (const GstDateTime * datetime)
156 {
157   g_return_val_if_fail (datetime != NULL, FALSE);
158
159   return (datetime->fields >= GST_DATE_TIME_FIELDS_YMD);
160 }
161
162 /**
163  * gst_date_time_has_time:
164  * @datetime: a #GstDateTime
165  *
166  * Returns: %TRUE if @datetime<!-- -->'s hour and minute fields are set,
167  *     otherwise %FALSE
168  */
169 gboolean
170 gst_date_time_has_time (const GstDateTime * datetime)
171 {
172   g_return_val_if_fail (datetime != NULL, FALSE);
173
174   return (datetime->fields >= GST_DATE_TIME_FIELDS_YMD_HM);
175 }
176
177 /**
178  * gst_date_time_has_second:
179  * @datetime: a #GstDateTime
180  *
181  * Returns: %TRUE if @datetime<!-- -->'s second field is set, otherwise %FALSE
182  */
183 gboolean
184 gst_date_time_has_second (const GstDateTime * datetime)
185 {
186   g_return_val_if_fail (datetime != NULL, FALSE);
187
188   return (datetime->fields >= GST_DATE_TIME_FIELDS_YMD_HMS);
189 }
190
191 /**
192  * gst_date_time_get_year:
193  * @datetime: a #GstDateTime
194  *
195  * Returns the year of this #GstDateTime
196  * Call gst_date_time_has_year before, to avoid warnings.
197  *
198  * Return value: The year of this #GstDateTime
199  */
200 gint
201 gst_date_time_get_year (const GstDateTime * datetime)
202 {
203   g_return_val_if_fail (datetime != NULL, 0);
204
205   return g_date_time_get_year (datetime->datetime);
206 }
207
208 /**
209  * gst_date_time_get_month:
210  * @datetime: a #GstDateTime
211  *
212  * Returns the month of this #GstDateTime. January is 1, February is 2, etc..
213  * Call gst_date_time_has_month before, to avoid warnings.
214  *
215  * Return value: The month of this #GstDateTime
216  */
217 gint
218 gst_date_time_get_month (const GstDateTime * datetime)
219 {
220   g_return_val_if_fail (datetime != NULL, 0);
221   g_return_val_if_fail (gst_date_time_has_month (datetime), 0);
222
223   return g_date_time_get_month (datetime->datetime);
224 }
225
226 /**
227  * gst_date_time_get_day:
228  * @datetime: a #GstDateTime
229  *
230  * Returns the day of the month of this #GstDateTime.
231  * Call gst_date_time_has_day before, to avoid warnings.
232  *
233  * Return value: The day of this #GstDateTime
234  */
235 gint
236 gst_date_time_get_day (const GstDateTime * datetime)
237 {
238   g_return_val_if_fail (datetime != NULL, 0);
239   g_return_val_if_fail (gst_date_time_has_day (datetime), 0);
240
241   return g_date_time_get_day_of_month (datetime->datetime);
242 }
243
244 /**
245  * gst_date_time_get_hour:
246  * @datetime: a #GstDateTime
247  *
248  * Retrieves the hour of the day represented by @datetime in the gregorian
249  * calendar. The return is in the range of 0 to 23.
250  * Call gst_date_time_has_haur before, to avoid warnings.
251  *
252  * Return value: the hour of the day
253  */
254 gint
255 gst_date_time_get_hour (const GstDateTime * datetime)
256 {
257   g_return_val_if_fail (datetime != NULL, 0);
258   g_return_val_if_fail (gst_date_time_has_time (datetime), 0);
259
260   return g_date_time_get_hour (datetime->datetime);
261 }
262
263 /**
264  * gst_date_time_get_minute:
265  * @datetime: a #GstDateTime
266  *
267  * Retrieves the minute of the hour represented by @datetime in the gregorian
268  * calendar.
269  * Call gst_date_time_has_minute before, to avoid warnings.
270  *
271  * Return value: the minute of the hour
272  */
273 gint
274 gst_date_time_get_minute (const GstDateTime * datetime)
275 {
276   g_return_val_if_fail (datetime != NULL, 0);
277   g_return_val_if_fail (gst_date_time_has_time (datetime), 0);
278
279   return g_date_time_get_minute (datetime->datetime);
280 }
281
282 /**
283  * gst_date_time_get_second:
284  * @datetime: a #GstDateTime
285  *
286  * Retrieves the second of the minute represented by @datetime in the gregorian
287  * calendar.
288  * Call gst_date_time_has_second before, to avoid warnings.
289  *
290  * Return value: the second represented by @datetime
291  */
292 gint
293 gst_date_time_get_second (const GstDateTime * datetime)
294 {
295   g_return_val_if_fail (datetime != NULL, 0);
296   g_return_val_if_fail (gst_date_time_has_second (datetime), 0);
297
298   return g_date_time_get_second (datetime->datetime);
299 }
300
301 /**
302  * gst_date_time_get_microsecond:
303  * @datetime: a #GstDateTime
304  *
305  * Retrieves the fractional part of the seconds in microseconds represented by
306  * @datetime in the gregorian calendar.
307  *
308  * Return value: the microsecond of the second
309  */
310 gint
311 gst_date_time_get_microsecond (const GstDateTime * datetime)
312 {
313   g_return_val_if_fail (datetime != NULL, 0);
314   g_return_val_if_fail (gst_date_time_has_second (datetime), 0);
315
316   return g_date_time_get_microsecond (datetime->datetime);
317 }
318
319 /**
320  * gst_date_time_get_time_zone_offset:
321  * @datetime: a #GstDateTime
322  *
323  * Retrieves the offset from UTC in hours that the timezone specified
324  * by @datetime represents. Timezones ahead (to the east) of UTC have positive
325  * values, timezones before (to the west) of UTC have negative values.
326  * If @datetime represents UTC time, then the offset is zero.
327  *
328  * Return value: the offset from UTC in hours
329  */
330 gfloat
331 gst_date_time_get_time_zone_offset (const GstDateTime * datetime)
332 {
333   g_return_val_if_fail (datetime != NULL, 0.0);
334   g_return_val_if_fail (gst_date_time_has_time (datetime), 0.0);
335
336   return (g_date_time_get_utc_offset (datetime->datetime) /
337       G_USEC_PER_SEC) / 3600.0;
338 }
339
340 /**
341  * gst_date_time_new_y:
342  * @year: the gregorian year
343  *
344  * Creates a new #GstDateTime using the date and times in the gregorian calendar
345  * in the local timezone.
346  *
347  * @year should be from 1 to 9999.
348  *
349  * Free-function: gst_date_time_unref
350  *
351  * Return value: (transfer full): the newly created #GstDateTime
352  */
353 GstDateTime *
354 gst_date_time_new_y (gint year)
355 {
356   return gst_date_time_new (0.0, year, -1, -1, -1, -1, -1);
357 }
358
359 /**
360  * gst_date_time_new_ym:
361  * @year: the gregorian year
362  * @month: the gregorian month
363  *
364  * Creates a new #GstDateTime using the date and times in the gregorian calendar
365  * in the local timezone.
366  *
367  * @year should be from 1 to 9999, @month should be from 1 to 12.
368  *
369  * If value is -1 then all over value will be ignored. For example
370  * if @month == -1, then #GstDateTime will created only for @year.
371  *
372  * Free-function: gst_date_time_unref
373  *
374  * Return value: (transfer full): the newly created #GstDateTime
375  */
376 GstDateTime *
377 gst_date_time_new_ym (gint year, gint month)
378 {
379   return gst_date_time_new (0.0, year, month, -1, -1, -1, -1);
380 }
381
382 /**
383  * gst_date_time_new_ymd:
384  * @year: the gregorian year
385  * @month: the gregorian month
386  * @day: the day of the gregorian month
387  *
388  * Creates a new #GstDateTime using the date and times in the gregorian calendar
389  * in the local timezone.
390  *
391  * @year should be from 1 to 9999, @month should be from 1 to 12, @day from
392  * 1 to 31.
393  *
394  * If value is -1 then all over value will be ignored. For example
395  * if @month == -1, then #GstDateTime will created only for @year. If
396  * @day == -1, then #GstDateTime will created for @year and @month and
397  * so on.
398  *
399  * Free-function: gst_date_time_unref
400  *
401  * Return value: (transfer full): the newly created #GstDateTime
402  */
403 GstDateTime *
404 gst_date_time_new_ymd (gint year, gint month, gint day)
405 {
406   return gst_date_time_new (0.0, year, month, day, -1, -1, -1);
407 }
408
409 /**
410  * gst_date_time_new_from_unix_epoch_local_time:
411  * @secs: seconds from the Unix epoch
412  *
413  * Creates a new #GstDateTime using the time since Jan 1, 1970 specified by
414  * @secs. The #GstDateTime is in the local timezone.
415  *
416  * Free-function: gst_date_time_unref
417  *
418  * Return value: (transfer full): the newly created #GstDateTime
419  */
420 GstDateTime *
421 gst_date_time_new_from_unix_epoch_local_time (gint64 secs)
422 {
423   GDateTime *datetime;
424
425   datetime = g_date_time_new_from_unix_local (secs);
426   return gst_date_time_new_from_g_date_time (datetime);
427 }
428
429 /**
430  * gst_date_time_new_from_unix_epoch_utc:
431  * @secs: seconds from the Unix epoch
432  *
433  * Creates a new #GstDateTime using the time since Jan 1, 1970 specified by
434  * @secs. The #GstDateTime is in the UTC timezone.
435  *
436  * Free-function: gst_date_time_unref
437  *
438  * Return value: (transfer full): the newly created #GstDateTime
439  */
440 GstDateTime *
441 gst_date_time_new_from_unix_epoch_utc (gint64 secs)
442 {
443   GstDateTime *datetime;
444   datetime =
445       gst_date_time_new_from_g_date_time (g_date_time_new_from_unix_utc (secs));
446   return datetime;
447 }
448
449 static GstDateTimeFields
450 gst_date_time_check_fields (gint * year, gint * month, gint * day,
451     gint * hour, gint * minute, gdouble * seconds)
452 {
453   if (*month == -1) {
454     *month = *day = 1;
455     *hour = *minute = *seconds = 0;
456     return GST_DATE_TIME_FIELDS_Y;
457   } else if (*day == -1) {
458     *day = 1;
459     *hour = *minute = *seconds = 0;
460     return GST_DATE_TIME_FIELDS_YM;
461   } else if (*hour == -1) {
462     *hour = *minute = *seconds = 0;
463     return GST_DATE_TIME_FIELDS_YMD;
464   } else if (*seconds == -1) {
465     *seconds = 0;
466     return GST_DATE_TIME_FIELDS_YMD_HM;
467   } else
468     return GST_DATE_TIME_FIELDS_YMD_HMS;
469 }
470
471 /**
472  * gst_date_time_new_local_time:
473  * @year: the gregorian year
474  * @month: the gregorian month, or -1
475  * @day: the day of the gregorian month, or -1
476  * @hour: the hour of the day, or -1
477  * @minute: the minute of the hour, or -1
478  * @seconds: the second of the minute, or -1
479  *
480  * Creates a new #GstDateTime using the date and times in the gregorian calendar
481  * in the local timezone.
482  *
483  * @year should be from 1 to 9999, @month should be from 1 to 12, @day from
484  * 1 to 31, @hour from 0 to 23, @minutes and @seconds from 0 to 59.
485  *
486  * If @month is -1, then the #GstDateTime created will only contain @year,
487  * and all other fields will be considered not set.
488  *
489  * If @day is -1, then the #GstDateTime created will only contain @year and
490  * @month and all other fields will be considered not set.
491  *
492  * If @hour is -1, then the #GstDateTime created will only contain @year and
493  * @month and @day, and the time fields will be considered not set. In this
494  * case @minute and @seconds should also be -1.
495  *
496  * Free-function: gst_date_time_unref
497  *
498  * Return value: (transfer full): the newly created #GstDateTime
499  */
500 GstDateTime *
501 gst_date_time_new_local_time (gint year, gint month, gint day, gint hour,
502     gint minute, gdouble seconds)
503 {
504   GstDateTimeFields fields;
505   GstDateTime *datetime;
506
507   g_return_val_if_fail (year > 0 && year <= 9999, NULL);
508   g_return_val_if_fail ((month > 0 && month <= 12) || month == -1, NULL);
509   g_return_val_if_fail ((day > 0 && day <= 31) || day == -1, NULL);
510   g_return_val_if_fail ((hour >= 0 && hour < 24) || hour == -1, NULL);
511   g_return_val_if_fail ((minute >= 0 && minute < 60) || minute == -1, NULL);
512   g_return_val_if_fail ((seconds >= 0 && seconds < 60) || seconds == -1, NULL);
513
514   fields = gst_date_time_check_fields (&year, &month, &day,
515       &hour, &minute, &seconds);
516
517   datetime = gst_date_time_new_from_g_date_time (g_date_time_new_local (year,
518           month, day, hour, minute, seconds));
519
520   datetime->fields = fields;
521   return datetime;
522 }
523
524 /**
525  * gst_date_time_new_now_local_time:
526  *
527  * Creates a new #GstDateTime representing the current date and time.
528  *
529  * Free-function: gst_date_time_unref
530  *
531  * Return value: (transfer full): the newly created #GstDateTime which should
532  *     be freed with gst_date_time_unref().
533  */
534 GstDateTime *
535 gst_date_time_new_now_local_time (void)
536 {
537   return gst_date_time_new_from_g_date_time (g_date_time_new_now_local ());
538 }
539
540 /**
541  * gst_date_time_new_now_utc:
542  *
543  * Creates a new #GstDateTime that represents the current instant at Universal
544  * coordinated time.
545  *
546  * Free-function: gst_date_time_unref
547  *
548  * Return value: (transfer full): the newly created #GstDateTime which should
549  *   be freed with gst_date_time_unref().
550  */
551 GstDateTime *
552 gst_date_time_new_now_utc (void)
553 {
554   return gst_date_time_new_from_g_date_time (g_date_time_new_now_utc ());
555 }
556
557 gint
558 __gst_date_time_compare (const GstDateTime * dt1, const GstDateTime * dt2)
559 {
560   gint64 diff;
561
562   /* we assume here that GST_DATE_TIME_FIELDS_YMD_HMS is the highest
563    * resolution, and ignore microsecond differences on purpose for now */
564   if (dt1->fields != dt2->fields)
565     return GST_VALUE_UNORDERED;
566
567   /* This will round down to nearest second, which is what we want. We're
568    * not comparing microseconds on purpose here, since we're not
569    * serialising them when doing new_utc_now() + to_string() */
570   diff =
571       g_date_time_to_unix (dt1->datetime) - g_date_time_to_unix (dt2->datetime);
572   if (diff < 0)
573     return GST_VALUE_LESS_THAN;
574   else if (diff > 0)
575     return GST_VALUE_GREATER_THAN;
576   else
577     return GST_VALUE_EQUAL;
578 }
579
580 /**
581  * gst_date_time_new:
582  * @tzoffset: Offset from UTC in hours.
583  * @year: the gregorian year
584  * @month: the gregorian month
585  * @day: the day of the gregorian month
586  * @hour: the hour of the day
587  * @minute: the minute of the hour
588  * @seconds: the second of the minute
589  *
590  * Creates a new #GstDateTime using the date and times in the gregorian calendar
591  * in the supplied timezone.
592  *
593  * @year should be from 1 to 9999, @month should be from 1 to 12, @day from
594  * 1 to 31, @hour from 0 to 23, @minutes and @seconds from 0 to 59.
595  *
596  * Note that @tzoffset is a float and was chosen so for being able to handle
597  * some fractional timezones, while it still keeps the readability of
598  * representing it in hours for most timezones.
599  *
600  * If value is -1 then all over value will be ignored. For example
601  * if @month == -1, then #GstDateTime will created only for @year. If
602  * @day == -1, then #GstDateTime will created for @year and @month and
603  * so on.
604  *
605  * Free-function: gst_date_time_unref
606  *
607  * Return value: (transfer full): the newly created #GstDateTime
608  */
609 GstDateTime *
610 gst_date_time_new (gfloat tzoffset, gint year, gint month, gint day, gint hour,
611     gint minute, gdouble seconds)
612 {
613   GstDateTimeFields fields;
614   gchar buf[6];
615   GTimeZone *tz;
616   GDateTime *dt;
617   GstDateTime *datetime;
618   gint tzhour, tzminute;
619
620   g_return_val_if_fail (year > 0 && year <= 9999, NULL);
621   g_return_val_if_fail ((month > 0 && month <= 12) || month == -1, NULL);
622   g_return_val_if_fail ((day > 0 && day <= 31) || day == -1, NULL);
623   g_return_val_if_fail ((hour >= 0 && hour < 24) || hour == -1, NULL);
624   g_return_val_if_fail ((minute >= 0 && minute < 60) || minute == -1, NULL);
625   g_return_val_if_fail ((seconds >= 0 && seconds < 60) || seconds == -1, NULL);
626   g_return_val_if_fail (tzoffset >= -12.0 && tzoffset <= 12.0, NULL);
627   g_return_val_if_fail ((hour >= 0 && minute >= 0) ||
628       (hour == -1 && minute == -1 && seconds == -1 && tzoffset == 0.0), NULL);
629
630   tzhour = (gint) ABS (tzoffset);
631   tzminute = (gint) ((ABS (tzoffset) - tzhour) * 60);
632
633   g_snprintf (buf, 6, "%c%02d%02d", tzoffset >= 0 ? '+' : '-', tzhour,
634       tzminute);
635
636   tz = g_time_zone_new (buf);
637
638   fields = gst_date_time_check_fields (&year, &month, &day,
639       &hour, &minute, &seconds);
640
641   dt = g_date_time_new (tz, year, month, day, hour, minute, seconds);
642   g_time_zone_unref (tz);
643
644   datetime = gst_date_time_new_from_g_date_time (dt);
645   datetime->fields = fields;
646
647   return datetime;
648 }
649
650 gchar *
651 __gst_date_time_serialize (GstDateTime * datetime, gboolean serialize_usecs)
652 {
653   GString *s;
654   gfloat gmt_offset;
655   guint msecs;
656
657   /* we always have at least the year */
658   s = g_string_new (NULL);
659   g_string_append_printf (s, "%04u", gst_date_time_get_year (datetime));
660
661   if (datetime->fields == GST_DATE_TIME_FIELDS_Y)
662     goto done;
663
664   /* add month */
665   g_string_append_printf (s, "-%02u", gst_date_time_get_month (datetime));
666
667   if (datetime->fields == GST_DATE_TIME_FIELDS_YM)
668     goto done;
669
670   /* add day of month */
671   g_string_append_printf (s, "-%02u", gst_date_time_get_day (datetime));
672
673   if (datetime->fields == GST_DATE_TIME_FIELDS_YMD)
674     goto done;
675
676   /* add time */
677   g_string_append_printf (s, "T%02u:%02u", gst_date_time_get_hour (datetime),
678       gst_date_time_get_minute (datetime));
679
680   if (datetime->fields == GST_DATE_TIME_FIELDS_YMD_HM)
681     goto add_timezone;
682
683   /* add seconds */
684   g_string_append_printf (s, ":%02u", gst_date_time_get_second (datetime));
685
686   /* add microseconds */
687   if (serialize_usecs) {
688     msecs = gst_date_time_get_microsecond (datetime);
689     if (msecs != 0) {
690       g_string_append_printf (s, ".%06u", msecs);
691       /* trim trailing 0s */
692       while (s->str[s->len - 1] == '0')
693         g_string_truncate (s, s->len - 1);
694     }
695   }
696
697   /* add timezone */
698
699 add_timezone:
700
701   gmt_offset = gst_date_time_get_time_zone_offset (datetime);
702   if (gmt_offset == 0) {
703     g_string_append_c (s, 'Z');
704   } else {
705     guint tzhour, tzminute;
706
707     tzhour = (guint) ABS (gmt_offset);
708     tzminute = (guint) ((ABS (gmt_offset) - tzhour) * 60);
709
710     g_string_append_c (s, (gmt_offset >= 0) ? '+' : '-');
711     g_string_append_printf (s, "%02u%02u", tzhour, tzminute);
712   }
713
714 done:
715
716   return g_string_free (s, FALSE);
717 }
718
719 /**
720  * gst_date_time_to_iso8601_string:
721  * @datetime: GstDateTime.
722  *
723  * Create a minimal string compatible with ISO-8601. Possible output formats
724  * are (for example): 2012, 2012-06, 2012-06-23, 2012-06-23T23:30Z,
725  * 2012-06-23T23:30+0100, 2012-06-23T23:30:59Z, 2012-06-23T23:30:59+0100
726  *
727  * Returns: a newly allocated string formatted according to ISO 8601 and
728  *     only including the datetime fields that are valid, or %NULL in case
729  *     there was an error. The string should be freed with g_free().
730  */
731 gchar *
732 gst_date_time_to_iso8601_string (GstDateTime * datetime)
733 {
734   g_return_val_if_fail (datetime != NULL, NULL);
735
736   if (datetime->fields == GST_DATE_TIME_FIELDS_INVALID)
737     return NULL;
738
739   return __gst_date_time_serialize (datetime, FALSE);
740 }
741
742 /**
743  * gst_date_time_new_from_iso8601_string:
744  * @string: ISO 8601-formatted datetime string.
745  *
746  * Tries to parse common variants of ISO-8601 datetime strings into a
747  * #GstDateTime.
748  *
749  * Free-function: gst_date_time_unref
750  *
751  * Returns: (transfer full): a newly created #GstDateTime, or %NULL on error
752  */
753 GstDateTime *
754 gst_date_time_new_from_iso8601_string (const gchar * string)
755 {
756   gint year = -1, month = -1, day = -1, hour = -1, minute = -1;
757   gdouble second = -1.0;
758   gfloat tzoffset = 0.0;
759   guint64 usecs;
760   gint len, ret;
761
762   g_return_val_if_fail (string != NULL, NULL);
763
764   GST_DEBUG ("Parsing '%s' into a datetime", string);
765
766   len = strlen (string);
767
768   if (len < 4 || !g_ascii_isdigit (string[0]) || !g_ascii_isdigit (string[1])
769       || !g_ascii_isdigit (string[2]) || !g_ascii_isdigit (string[3]))
770     return NULL;
771
772   ret = sscanf (string, "%04d-%02d-%02d", &year, &month, &day);
773
774   if (ret == 0)
775     return NULL;
776
777   if (ret == 3 && day <= 0) {
778     ret = 2;
779     day = -1;
780   }
781
782   if (ret >= 2 && month <= 0) {
783     ret = 1;
784     month = day = -1;
785   }
786
787   if (ret >= 1 && year <= 0)
788     return NULL;
789
790   else if (ret >= 1 && len < 16)
791     /* YMD is 10 chars. XMD + HM will be 16 chars. if it is less,
792      * it make no sense to continue. We will stay with YMD. */
793     goto ymd;
794
795   string += 10;
796   /* Exit if there is no expeceted value on this stage */
797   if (!(*string == 'T' || *string == '-' || *string == ' '))
798     goto ymd;
799
800   /* if hour or minute fails, then we will use onlly ymd. */
801   hour = g_ascii_strtoull (string + 1, (gchar **) & string, 10);
802   if (hour > 24 || *string != ':')
803     goto ymd;
804
805   /* minute */
806   minute = g_ascii_strtoull (string + 1, (gchar **) & string, 10);
807   if (minute > 59)
808     goto ymd;
809
810   /* second */
811   if (*string == ':') {
812     second = g_ascii_strtoull (string + 1, (gchar **) & string, 10);
813     /* if we fail here, we still can reuse hour and minute. We
814      * will still attempt to parse any timezone information */
815     if (second > 59) {
816       second = -1.0;
817     } else {
818       /* microseconds */
819       if (*string == '.' || *string == ',') {
820         const gchar *usec_start = string + 1;
821         guint digits;
822
823         usecs = g_ascii_strtoull (string + 1, (gchar **) & string, 10);
824         if (usecs != G_MAXUINT64 && string > usec_start) {
825           digits = (guint) (string - usec_start);
826           second += (gdouble) usecs / pow (10.0, digits);
827         }
828       }
829     }
830   }
831
832   if (*string == 'Z')
833     goto ymd_hms;
834   else {
835     /* reuse some code from gst-plugins-base/gst-libs/gst/tag/gstxmptag.c */
836     gint gmt_offset_hour = -1, gmt_offset_min = -1, gmt_offset = -1;
837     gchar *plus_pos = NULL;
838     gchar *neg_pos = NULL;
839     gchar *pos = NULL;
840
841     GST_LOG ("Checking for timezone information");
842
843     /* check if there is timezone info */
844     plus_pos = strrchr (string, '+');
845     neg_pos = strrchr (string, '-');
846     if (plus_pos)
847       pos = plus_pos + 1;
848     else if (neg_pos)
849       pos = neg_pos + 1;
850
851     if (pos) {
852       gint ret_tz;
853       if (pos[2] == ':')
854         ret_tz = sscanf (pos, "%d:%d", &gmt_offset_hour, &gmt_offset_min);
855       else
856         ret_tz = sscanf (pos, "%02d%02d", &gmt_offset_hour, &gmt_offset_min);
857
858       GST_DEBUG ("Parsing timezone: %s", pos);
859
860       if (ret_tz == 2) {
861         gmt_offset = gmt_offset_hour * 60 + gmt_offset_min;
862         if (neg_pos != NULL && neg_pos + 1 == pos)
863           gmt_offset *= -1;
864
865         tzoffset = gmt_offset / 60.0;
866
867         GST_LOG ("Timezone offset: %f (%d minutes)", tzoffset, gmt_offset);
868       } else
869         GST_WARNING ("Failed to parse timezone information");
870     }
871   }
872
873 ymd_hms:
874   return gst_date_time_new (tzoffset, year, month, day, hour, minute, second);
875 ymd:
876   return gst_date_time_new_ymd (year, month, day);
877 }
878
879 static void
880 gst_date_time_free (GstDateTime * datetime)
881 {
882   g_date_time_unref (datetime->datetime);
883   g_slice_free (GstDateTime, datetime);
884 }
885
886 /**
887  * gst_date_time_ref:
888  * @datetime: a #GstDateTime
889  *
890  * Atomically increments the reference count of @datetime by one.
891  *
892  * Return value: (transfer full): the reference @datetime
893  */
894 GstDateTime *
895 gst_date_time_ref (GstDateTime * datetime)
896 {
897   return (GstDateTime *) gst_mini_object_ref (GST_MINI_OBJECT_CAST (datetime));
898 }
899
900 /**
901  * gst_date_time_unref:
902  * @datetime: (transfer full): a #GstDateTime
903  *
904  * Atomically decrements the reference count of @datetime by one.  When the
905  * reference count reaches zero, the structure is freed.
906  */
907 void
908 gst_date_time_unref (GstDateTime * datetime)
909 {
910   gst_mini_object_unref (GST_MINI_OBJECT_CAST (datetime));
911 }