3a4730501280d93e33d99bb6a6a5e32f05ba2526
[platform/upstream/gstreamer.git] / gst-libs / gst / rtsp / gstrtsprange.c
1 /* GStreamer
2  * Copyright (C) <2005,2006> Wim Taymans <wim@fluendo.com>
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  * Unless otherwise indicated, Source Code is licensed under MIT license.
21  * See further explanation attached in License Statement (distributed in the file
22  * LICENSE).
23  *
24  * Permission is hereby granted, free of charge, to any person obtaining a copy of
25  * this software and associated documentation files (the "Software"), to deal in
26  * the Software without restriction, including without limitation the rights to
27  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
28  * of the Software, and to permit persons to whom the Software is furnished to do
29  * so, subject to the following conditions:
30  *
31  * The above copyright notice and this permission notice shall be included in all
32  * copies or substantial portions of the Software.
33  *
34  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
35  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
36  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
37  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
38  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
39  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
40  * SOFTWARE.
41  */
42
43 /**
44  * SECTION:gstrtsprange
45  * @short_description: dealing with time ranges
46  *  
47  * Provides helper functions to deal with time ranges.
48  *  
49  * Last reviewed on 2007-07-25 (0.10.14)
50  */
51
52 #include <math.h>
53 #include <stdio.h>
54 #include <string.h>
55
56 #include "gstrtsprange.h"
57
58 static gdouble
59 gst_strtod (const gchar * dstr)
60 {
61   gchar s[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
62
63   /* canonicalise floating point string so we can handle float strings
64    * in the form "24.930" or "24,930" irrespective of the current locale.
65    * We should always be getting floats in 24.930 format with a floating point,
66    * but let's accept malformed ones as well, easy mistake to make after all */
67   g_strlcpy (s, dstr, sizeof (s));
68   g_strdelimit (s, ",", '.');
69   return g_ascii_strtod (s, NULL);
70 }
71
72 /* npt-time     =   "now" | npt-sec | npt-hhmmss
73  * npt-sec      =   1*DIGIT [ "." *DIGIT ]
74  * npt-hhmmss   =   npt-hh ":" npt-mm ":" npt-ss [ "." *DIGIT ]
75  * npt-hh       =   1*DIGIT     ; any positive number
76  * npt-mm       =   1*2DIGIT    ; 0-59
77  * npt-ss       =   1*2DIGIT    ; 0-59
78  */
79 static GstRTSPResult
80 parse_npt_time (const gchar * str, GstRTSPTime * time)
81 {
82   if (strncmp (str, "now", 3) == 0) {
83     time->type = GST_RTSP_TIME_NOW;
84   } else if (str[0] == '\0' || str[0] == '-') {
85     time->type = GST_RTSP_TIME_END;
86   } else if (strstr (str, ":")) {
87     gint hours, mins;
88
89     if (sscanf (str, "%2d:%2d:", &hours, &mins) != 2)
90       return GST_RTSP_EINVAL;
91
92     str = strchr (str, ':');
93     str = strchr (str + 1, ':');
94     if (str == NULL)
95       return GST_RTSP_EINVAL;
96
97     time->type = GST_RTSP_TIME_SECONDS;
98     time->seconds = ((hours * 60) + mins) * 60 + gst_strtod (str + 1);
99   } else {
100     time->type = GST_RTSP_TIME_SECONDS;
101     time->seconds = gst_strtod (str);
102   }
103   return GST_RTSP_OK;
104 }
105
106 /* npt-range    =   ( npt-time "-" [ npt-time ] ) | ( "-" npt-time )
107  */
108 static GstRTSPResult
109 parse_npt_range (const gchar * str, GstRTSPTimeRange * range)
110 {
111   GstRTSPResult res;
112   gchar *p;
113
114   range->unit = GST_RTSP_RANGE_NPT;
115
116   /* find '-' separator */
117   p = strstr (str, "-");
118   if (p == NULL)
119     return GST_RTSP_EINVAL;
120
121   if ((res = parse_npt_time (str, &range->min)) != GST_RTSP_OK)
122     goto done;
123
124   res = parse_npt_time (p + 1, &range->max);
125
126   /* a single - is not allowed */
127   if (range->min.type == GST_RTSP_TIME_END
128       && range->max.type == GST_RTSP_TIME_END)
129     return GST_RTSP_EINVAL;
130
131 done:
132   return res;
133 }
134
135 /*   utc-time     =   utc-date "T" utc-time "Z"
136  *   utc-date     =   8DIGIT                    ; < YYYYMMDD >
137  *   utc-time     =   6DIGIT [ "." fraction ]   ; < HHMMSS.fraction >
138  *
139  *   Example for November 8, 1996 at 14h37 and 20 and a quarter seconds
140  *   UTC:
141  *
142  *   19961108T143720.25Z
143  */
144 static GstRTSPResult
145 parse_utc_time (const gchar * str, GstRTSPTime * time, GstRTSPTime2 * time2,
146     const gchar * limit)
147 {
148
149   if (str[0] == '\0') {
150     time->type = GST_RTSP_TIME_END;
151     return GST_RTSP_OK;
152   } else {
153     gint year, month, day;
154     gint hours, mins;
155     gdouble secs;
156     gchar *T, *Z;
157
158     T = strchr (str, 'T');
159     if (T == NULL || T != str + 8)
160       return GST_RTSP_EINVAL;
161
162     Z = strchr (T + 1, 'Z');
163     if (Z == NULL)
164       return GST_RTSP_EINVAL;
165
166     time->type = GST_RTSP_TIME_UTC;
167
168     if (sscanf (str, "%4d%2d%2dT%2d%2d%lfZ", &year, &month, &day, &hours,
169             &mins, &secs) != 6)
170       return GST_RTSP_EINVAL;
171
172     time2->year = year;
173     time2->month = month;
174     time2->day = day;
175     time->seconds = ((hours * 60) + mins) * 60 + secs;
176   }
177   return GST_RTSP_OK;
178 }
179
180 /*   utc-range    =   "clock" "=" utc-time "-" [ utc-time ]
181  */
182 static GstRTSPResult
183 parse_utc_range (const gchar * str, GstRTSPTimeRange * range)
184 {
185   GstRTSPResult res;
186   gchar *p;
187
188   range->unit = GST_RTSP_RANGE_CLOCK;
189
190   /* find '-' separator, can't have a single - */
191   p = strstr (str, "-");
192   if (p == NULL || p == str)
193     return GST_RTSP_EINVAL;
194
195   if ((res = parse_utc_time (str, &range->min, &range->min2, p)) != GST_RTSP_OK)
196     goto done;
197
198   res = parse_utc_time (p + 1, &range->max, &range->max2, NULL);
199
200 done:
201   return res;
202 }
203
204 /* smpte-time   =   1*2DIGIT ":" 1*2DIGIT ":" 1*2DIGIT [ ":" 1*2DIGIT ]
205  *                     [ "." 1*2DIGIT ]
206  *  hours:minutes:seconds:frames.subframes
207 */
208 static GstRTSPResult
209 parse_smpte_time (const gchar * str, GstRTSPTime * time, GstRTSPTime2 * time2,
210     const gchar * limit)
211 {
212   gint hours, mins, secs;
213
214   if (str[0] == '\0') {
215     time->type = GST_RTSP_TIME_END;
216     return GST_RTSP_OK;
217   } else {
218     if (sscanf (str, "%2d:%2d:%2d", &hours, &mins, &secs) != 3)
219       return GST_RTSP_EINVAL;
220
221     time->type = GST_RTSP_TIME_FRAMES;
222     time->seconds = ((hours * 60) + mins) * 60 + secs;
223     str = strchr (str, ':');
224     str = strchr (str + 1, ':');
225     str = strchr (str + 1, ':');
226     if (str && (limit == NULL || str < limit))
227       time2->frames = gst_strtod (str + 1);
228   }
229   return GST_RTSP_OK;
230 }
231
232 /* smpte-range  =   smpte-type "=" smpte-time "-" [ smpte-time ]
233  */
234 static GstRTSPResult
235 parse_smpte_range (const gchar * str, GstRTSPTimeRange * range)
236 {
237   GstRTSPResult res;
238   gchar *p;
239
240   /* find '-' separator, can't have a single - */
241   p = strstr (str, "-");
242   if (p == NULL || p == str)
243     return GST_RTSP_EINVAL;
244
245   if ((res =
246           parse_smpte_time (str, &range->min, &range->min2, p)) != GST_RTSP_OK)
247     goto done;
248
249   res = parse_smpte_time (p + 1, &range->max, &range->max2, NULL);
250
251 done:
252   return res;
253 }
254
255 /**
256  * gst_rtsp_range_parse:
257  * @rangestr: a range string to parse
258  * @range: location to hold the #GstRTSPTimeRange result
259  *
260  * Parse @rangestr to a #GstRTSPTimeRange.
261  *
262  * Returns: #GST_RTSP_OK on success.
263  */
264 GstRTSPResult
265 gst_rtsp_range_parse (const gchar * rangestr, GstRTSPTimeRange ** range)
266 {
267   GstRTSPResult ret;
268   GstRTSPTimeRange *res;
269   gchar *p;
270
271   g_return_val_if_fail (rangestr != NULL, GST_RTSP_EINVAL);
272   g_return_val_if_fail (range != NULL, GST_RTSP_EINVAL);
273
274   res = g_new0 (GstRTSPTimeRange, 1);
275
276   p = (gchar *) rangestr;
277   /* first figure out the units of the range */
278   if (g_str_has_prefix (p, "npt=")) {
279     ret = parse_npt_range (p + 4, res);
280   } else if (g_str_has_prefix (p, "clock=")) {
281     ret = parse_utc_range (p + 6, res);
282   } else if (g_str_has_prefix (p, "smpte=")) {
283     res->unit = GST_RTSP_RANGE_SMPTE;
284     ret = parse_smpte_range (p + 6, res);
285   } else if (g_str_has_prefix (p, "smpte-30-drop=")) {
286     res->unit = GST_RTSP_RANGE_SMPTE_30_DROP;
287     ret = parse_smpte_range (p + 14, res);
288   } else if (g_str_has_prefix (p, "smpte-25=")) {
289     res->unit = GST_RTSP_RANGE_SMPTE_25;
290     ret = parse_smpte_range (p + 9, res);
291   } else
292     goto invalid;
293
294   if (ret != GST_RTSP_OK)
295     goto invalid;
296
297   *range = res;
298   return ret;
299
300   /* ERRORS */
301 invalid:
302   {
303     gst_rtsp_range_free (res);
304     return GST_RTSP_EINVAL;
305   }
306 }
307
308 static void
309 string_append_dtostr (GString * string, gdouble value, guint precision)
310 {
311   gchar dstrbuf[G_ASCII_DTOSTR_BUF_SIZE] = { 0, };
312   gchar *dot;
313   guint len;
314
315   precision++;
316
317   if (value != 0.0)
318     value += 4.9 * pow (10.0, precision * -1.0);
319
320   g_ascii_dtostr (dstrbuf, G_ASCII_DTOSTR_BUF_SIZE, value);
321
322   dot = strchr (dstrbuf, '.');
323
324   if (dot == NULL)
325     goto done;
326
327   for (; *dot != '.' && *dot != '0'; dot++);
328
329   if ((dot - dstrbuf) + precision < G_ASCII_DTOSTR_BUF_SIZE)
330     dot[precision] = 0;
331
332   len = strlen (dstrbuf);
333   while (dstrbuf[len - 1] == '0')
334     dstrbuf[--len] = 0;
335   if (dstrbuf[len - 1] == '.')
336     dstrbuf[--len] = 0;
337
338 done:
339
340   g_string_append (string, dstrbuf);
341 }
342
343 static gboolean
344 time_to_string (const GstRTSPTime * t1, const GstRTSPTime2 * t2,
345     GString * string)
346 {
347   gboolean res = TRUE;;
348
349   switch (t1->type) {
350     case GST_RTSP_TIME_SECONDS:
351       /* need to format floating point value strings as in C locale */
352       string_append_dtostr (string, t1->seconds +
353           (t1->seconds ? 0.00000000005 : 0), 9);
354       break;
355     case GST_RTSP_TIME_NOW:
356       g_string_append (string, "now");
357       break;
358     case GST_RTSP_TIME_END:
359       break;
360     case GST_RTSP_TIME_FRAMES:
361     {
362       gint64 sec = t1->seconds;
363
364       /* need to format floating point value strings as in C locale */
365       g_string_append_printf (string, "%d:%02d:%02d", (gint) sec / (60 * 60),
366           (gint) (sec % (60 * 60)) / 60, (gint) sec % 60);
367
368       if (t2->frames > 0.0) {
369         g_string_append_printf (string, ":%s", t2->frames < 10 ? "0" : "");
370         string_append_dtostr (string, t2->frames + 0.005, 2);
371       }
372       break;
373     }
374     case GST_RTSP_TIME_UTC:
375     {
376       gint64 sec = t1->seconds;
377       gint hours, minutes;
378       gdouble seconds;
379
380       hours = sec / (60 * 60);
381       sec -= hours * 60 * 60;
382       minutes = sec / 60;
383       sec = ((hours * 60) + minutes) * 60;
384       seconds = t1->seconds - sec;
385       if (seconds)
386         seconds += 0.00000000005;
387
388       g_string_append_printf (string, "%04d%02d%02dT%02d%02d%s",
389           t2->year, t2->month, t2->day, hours, minutes,
390           seconds < 10 ? "0" : "");
391       string_append_dtostr (string, seconds, 9);
392       g_string_append (string, "Z");
393       break;
394     }
395     default:
396       res = FALSE;
397       break;
398   }
399   return res;
400 }
401
402 static gboolean
403 range_to_string (const GstRTSPTimeRange * range, GString * string)
404 {
405   gboolean res;
406
407   if (!(res = time_to_string (&range->min, &range->min2, string)))
408     goto done;
409
410   g_string_append (string, "-");
411
412   if (!(res = time_to_string (&range->max, &range->max2, string)))
413     goto done;
414
415 done:
416   return res;
417 }
418
419 /**
420  * gst_rtsp_range_to_string:
421  * @range: a #GstRTSPTimeRange
422  *
423  * Convert @range into a string representation.
424  *
425  * Returns: The string representation of @range. g_free() after usage.
426  */
427 gchar *
428 gst_rtsp_range_to_string (const GstRTSPTimeRange * range)
429 {
430   GString *string;
431
432   g_return_val_if_fail (range != NULL, NULL);
433
434   switch (range->unit) {
435     case GST_RTSP_RANGE_NPT:
436       string = g_string_new ("npt=");
437       break;
438     case GST_RTSP_RANGE_SMPTE:
439     case GST_RTSP_RANGE_SMPTE_30_DROP:
440       string = g_string_new ("smpte=");
441       break;
442     case GST_RTSP_RANGE_SMPTE_25:
443       string = g_string_new ("smpte-25=");
444       break;
445     case GST_RTSP_RANGE_CLOCK:
446       string = g_string_new ("clock=");
447       break;
448     default:
449       goto not_implemented;
450   }
451
452   if (!range_to_string (range, string))
453     goto format_failed;
454
455   return g_string_free (string, FALSE);
456
457   /* ERRORS */
458 not_implemented:
459   {
460     g_warning ("time range unit not yet implemented");
461     return NULL;
462   }
463 format_failed:
464   {
465     g_string_free (string, TRUE);
466     return NULL;
467   }
468 }
469
470 /**
471  * gst_rtsp_range_free:
472  * @range: a #GstRTSPTimeRange
473  *
474  * Free the memory allocated by @range.
475  */
476 void
477 gst_rtsp_range_free (GstRTSPTimeRange * range)
478 {
479   g_return_if_fail (range != NULL);
480
481   g_free (range);
482 }
483
484 static GstClockTime
485 get_seconds (const GstRTSPTime * t)
486 {
487   if (t->seconds < G_MAXINT) {
488     gint num, denom;
489     /* Don't do direct multiply with GST_SECOND to avoid rounding
490      * errors.
491      * This only works for "small" numbers, because num is limited to 32-bit
492      */
493     gst_util_double_to_fraction (t->seconds, &num, &denom);
494     return gst_util_uint64_scale_int (GST_SECOND, num, denom);
495   } else {
496     return t->seconds * GST_SECOND;
497   }
498 }
499
500 static GstClockTime
501 get_frames (const GstRTSPTime2 * t, GstRTSPRangeUnit unit)
502 {
503   gint num, denom;
504
505   gst_util_double_to_fraction (t->frames, &num, &denom);
506
507   switch (unit) {
508     case GST_RTSP_RANGE_SMPTE_25:
509       denom *= 25;
510       break;
511     case GST_RTSP_RANGE_SMPTE:
512     case GST_RTSP_RANGE_SMPTE_30_DROP:
513     default:
514       num *= 1001;
515       denom *= 30003;
516       break;
517   }
518   return gst_util_uint64_scale_int (GST_SECOND, num, denom);
519 }
520
521 static GstClockTime
522 get_time (GstRTSPRangeUnit unit, const GstRTSPTime * t1,
523     const GstRTSPTime2 * t2)
524 {
525   GstClockTime res;
526
527   switch (t1->type) {
528     case GST_RTSP_TIME_SECONDS:
529     {
530       res = get_seconds (t1);
531       break;
532     }
533     case GST_RTSP_TIME_UTC:
534     {
535       GDateTime *dt, *bt;
536       GTimeSpan span;
537
538       /* make time base, we use 1900 */
539       bt = g_date_time_new_utc (1900, 1, 1, 0, 0, 0.0);
540       /* convert to GDateTime without the seconds */
541       dt = g_date_time_new_utc (t2->year, t2->month, t2->day, 0, 0, 0.0);
542       /* get amount of microseconds */
543       span = g_date_time_difference (dt, bt);
544       g_date_time_unref (bt);
545       g_date_time_unref (dt);
546       /* add seconds */
547       res = get_seconds (t1) + (span * 1000);
548       break;
549     }
550     case GST_RTSP_TIME_FRAMES:
551       res = get_seconds (t1);
552       res += get_frames (t2, unit);
553       break;
554     default:
555     case GST_RTSP_TIME_NOW:
556     case GST_RTSP_TIME_END:
557       res = GST_CLOCK_TIME_NONE;
558       break;
559   }
560   return res;
561 }
562
563 /**
564  * gst_rtsp_range_get_times:
565  * @range: a #GstRTSPTimeRange
566  * @min: result minimum #GstClockTime
567  * @max: result maximum #GstClockTime
568  *
569  * Retrieve the minimum and maximum values from @range converted to
570  * #GstClockTime in @min and @max.
571  *
572  * A value of %GST_CLOCK_TIME_NONE will be used to signal #GST_RTSP_TIME_NOW
573  * and #GST_RTSP_TIME_END for @min and @max respectively.
574  *
575  * UTC times will be converted to nanoseconds since 1900.
576  *
577  * Returns: %TRUE on success.
578  *
579  * Since: 1.1.1
580  */
581 gboolean
582 gst_rtsp_range_get_times (const GstRTSPTimeRange * range,
583     GstClockTime * min, GstClockTime * max)
584 {
585   g_return_val_if_fail (range != NULL, FALSE);
586
587   if (min)
588     *min = get_time (range->unit, &range->min, &range->min2);
589   if (max)
590     *max = get_time (range->unit, &range->max, &range->max2);
591
592   return TRUE;
593 }
594
595 static void
596 set_time (GstRTSPTime * time, GstRTSPTime2 * time2, GstRTSPRangeUnit unit,
597     GstClockTime clock_time)
598 {
599   memset (time, 0, sizeof (GstRTSPTime));
600   memset (time2, 0, sizeof (GstRTSPTime2));
601
602   if (clock_time == GST_CLOCK_TIME_NONE) {
603     time->type = GST_RTSP_TIME_END;
604     return;
605   }
606
607   switch (unit) {
608     case GST_RTSP_RANGE_SMPTE:
609     case GST_RTSP_RANGE_SMPTE_30_DROP:
610     {
611       time->seconds = (guint64) (clock_time / GST_SECOND);
612       time2->frames = 30003 * (clock_time % GST_SECOND) /
613           (gdouble) (1001 * GST_SECOND);
614       time->type = GST_RTSP_TIME_FRAMES;
615       g_assert (time2->frames < 30);
616       break;
617     }
618     case GST_RTSP_RANGE_SMPTE_25:
619     {
620       time->seconds = (guint64) (clock_time / GST_SECOND);
621       time2->frames = (25 * (clock_time % GST_SECOND)) / (gdouble) GST_SECOND;
622       time->type = GST_RTSP_TIME_FRAMES;
623       g_assert (time2->frames < 25);
624       break;
625     }
626     case GST_RTSP_RANGE_NPT:
627     {
628       time->seconds = (gdouble) clock_time / (gdouble) GST_SECOND;
629       time->type = GST_RTSP_TIME_SECONDS;
630       break;
631     }
632     case GST_RTSP_RANGE_CLOCK:
633     {
634       GDateTime *bt, *datetime;
635       GstClockTime subsecond = clock_time % GST_SECOND;
636
637       bt = g_date_time_new_utc (1900, 1, 1, 0, 0, 0.0);
638       datetime = g_date_time_add_seconds (bt, clock_time / GST_SECOND);
639
640       time2->year = g_date_time_get_year (datetime);
641       time2->month = g_date_time_get_month (datetime);
642       time2->day = g_date_time_get_day_of_month (datetime);
643
644       time->seconds = g_date_time_get_hour (datetime) * 60 * 60;
645       time->seconds += g_date_time_get_minute (datetime) * 60;
646       time->seconds += g_date_time_get_seconds (datetime);
647       time->seconds += (gdouble) subsecond / (gdouble) GST_SECOND;
648       time->type = GST_RTSP_TIME_UTC;
649
650       g_date_time_unref (bt);
651       g_date_time_unref (datetime);
652       break;
653     }
654   }
655
656   if (time->seconds < 0.000000001)
657     time->seconds = 0;
658   if (time2->frames < 0.000000001)
659     time2->frames = 0;
660 }
661
662 /**
663  * gst_rtsp_range_convert_units:
664  * @range: a #GstRTSPTimeRange
665  * @unit: the unit to convert the range into
666  *
667  * Converts the range in-place between different types of units.
668  * Ranges containing the special value #GST_RTSP_TIME_NOW can not be
669  * converted as these are only valid for #GST_RTSP_RANGE_NPT.
670  *
671  * Returns: %TRUE if the range could be converted
672  */
673
674 gboolean
675 gst_rtsp_range_convert_units (GstRTSPTimeRange * range, GstRTSPRangeUnit unit)
676 {
677   if (range->unit == unit)
678     return TRUE;
679
680   if (range->min.type == GST_RTSP_TIME_NOW ||
681       range->max.type == GST_RTSP_TIME_NOW)
682     return FALSE;
683
684   set_time (&range->min, &range->min2, unit,
685       get_time (range->unit, &range->min, &range->min2));
686   set_time (&range->max, &range->max2, unit,
687       get_time (range->unit, &range->max, &range->max2));
688
689   range->unit = unit;
690
691   return TRUE;
692 }