1 /* GStreamer
2 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3 * 2000 Wim Taymans <wtay@chello.be>
4 * 2002 Thomas Vander Stichele <thomas@apestaart.org>
5 * 2004 Wim Taymans <wim@fluendo.com>
6 * 2015 Jan Schmidt <jan@centricular.com>
7 *
8 * gstutils.c: Utility functions
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
19 *
20 * You should have received a copy of the GNU Library General Public
21 * License along with this library; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
24 */
25
26 /**
27 * SECTION:gstutils
28 * @title: GstUtils
29 * @short_description: Various utility functions
30 *
31 */
32
33 /* FIXME 2.0: suppress warnings for deprecated API such as GValueArray
34 * with newer GLib versions (>= 2.31.0) */
35 #define GLIB_DISABLE_DEPRECATION_WARNINGS
36
37 #include "gst_private.h"
38 #include <stdio.h>
39 #include <string.h>
40
41 #include "gstghostpad.h"
42 #include "gstutils.h"
43 #include "gsterror.h"
44 #include "gstinfo.h"
45 #include "gstparse.h"
46 #include "gstvalue.h"
47 #include "gst-i18n-lib.h"
48 #include "glib-compat-private.h"
49 #include <math.h>
50
51 /**
52 * gst_util_dump_mem:
53 * @mem: (array length=size): a pointer to the memory to dump
54 * @size: the size of the memory block to dump
55 *
56 * Dumps the memory block into a hex representation. Useful for debugging.
57 */
58 void
gst_util_dump_mem(const guchar * mem,guint size)59 gst_util_dump_mem (const guchar * mem, guint size)
60 {
61 guint i, j;
62 GString *string = g_string_sized_new (50);
63 GString *chars = g_string_sized_new (18);
64
65 i = j = 0;
66 while (i < size) {
67 if (g_ascii_isprint (mem[i]))
68 g_string_append_c (chars, mem[i]);
69 else
70 g_string_append_c (chars, '.');
71
72 g_string_append_printf (string, "%02x ", mem[i]);
73
74 j++;
75 i++;
76
77 if (j == 16 || i == size) {
78 g_print ("%08x (%p): %-48.48s %-16.16s\n", i - j, mem + i - j,
79 string->str, chars->str);
80 g_string_set_size (string, 0);
81 g_string_set_size (chars, 0);
82 j = 0;
83 }
84 }
85 g_string_free (string, TRUE);
86 g_string_free (chars, TRUE);
87 }
88
89 /**
90 * gst_util_dump_buffer:
91 * @buf: a #GstBuffer whose memory to dump
92 *
93 * Dumps the buffer memory into a hex representation. Useful for debugging.
94 *
95 * Since: 1.14
96 */
97 void
gst_util_dump_buffer(GstBuffer * buf)98 gst_util_dump_buffer (GstBuffer * buf)
99 {
100 GstMapInfo map;
101
102 if (gst_buffer_map (buf, &map, GST_MAP_READ)) {
103 gst_util_dump_mem (map.data, map.size);
104 gst_buffer_unmap (buf, &map);
105 }
106 }
107
108 /**
109 * gst_util_set_value_from_string:
110 * @value: (out caller-allocates): the value to set
111 * @value_str: the string to get the value from
112 *
113 * Converts the string to the type of the value and
114 * sets the value with it.
115 *
116 * Note that this function is dangerous as it does not return any indication
117 * if the conversion worked or not.
118 */
119 void
gst_util_set_value_from_string(GValue * value,const gchar * value_str)120 gst_util_set_value_from_string (GValue * value, const gchar * value_str)
121 {
122 gboolean res;
123
124 g_return_if_fail (value != NULL);
125 g_return_if_fail (value_str != NULL);
126
127 GST_CAT_DEBUG (GST_CAT_PARAMS, "parsing '%s' to type %s", value_str,
128 g_type_name (G_VALUE_TYPE (value)));
129
130 res = gst_value_deserialize (value, value_str);
131 if (!res && G_VALUE_TYPE (value) == G_TYPE_BOOLEAN) {
132 /* backwards compat, all booleans that fail to parse are false */
133 g_value_set_boolean (value, FALSE);
134 res = TRUE;
135 }
136 g_return_if_fail (res);
137 }
138
139 /**
140 * gst_util_set_object_arg:
141 * @object: the object to set the argument of
142 * @name: the name of the argument to set
143 * @value: the string value to set
144 *
145 * Converts the string value to the type of the objects argument and
146 * sets the argument with it.
147 *
148 * Note that this function silently returns if @object has no property named
149 * @name or when @value cannot be converted to the type of the property.
150 */
151 void
gst_util_set_object_arg(GObject * object,const gchar * name,const gchar * value)152 gst_util_set_object_arg (GObject * object, const gchar * name,
153 const gchar * value)
154 {
155 GParamSpec *pspec;
156 GType value_type;
157 GValue v = { 0, };
158
159 g_return_if_fail (G_IS_OBJECT (object));
160 g_return_if_fail (name != NULL);
161 g_return_if_fail (value != NULL);
162
163 pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (object), name);
164 if (!pspec)
165 return;
166
167 value_type = pspec->value_type;
168
169 GST_DEBUG ("pspec->flags is %d, pspec->value_type is %s",
170 pspec->flags, g_type_name (value_type));
171
172 if (!(pspec->flags & G_PARAM_WRITABLE))
173 return;
174
175 g_value_init (&v, value_type);
176
177 /* special case for element <-> xml (de)serialisation */
178 if (value_type == GST_TYPE_STRUCTURE && strcmp (value, "NULL") == 0) {
179 g_value_set_boxed (&v, NULL);
180 goto done;
181 }
182
183 if (!gst_value_deserialize (&v, value))
184 return;
185
186 done:
187
188 g_object_set_property (object, pspec->name, &v);
189 g_value_unset (&v);
190 }
191
192 /**
193 * gst_util_set_object_array:
194 * @object: the object to set the array to
195 * @name: the name of the property to set
196 * @array: a #GValueArray containing the values
197 *
198 * Transfer a #GValueArray to %GST_TYPE_ARRAY and set this value on the
199 * specified property name. This allow language bindings to set GST_TYPE_ARRAY
200 * properties which are otherwise not an accessible type.
201 *
202 * Since: 1.12
203 */
204 gboolean
gst_util_set_object_array(GObject * object,const gchar * name,const GValueArray * array)205 gst_util_set_object_array (GObject * object, const gchar * name,
206 const GValueArray * array)
207 {
208 GValue v1 = G_VALUE_INIT, v2 = G_VALUE_INIT;
209 gboolean ret = FALSE;
210
211 g_value_init (&v1, G_TYPE_VALUE_ARRAY);
212 g_value_init (&v2, GST_TYPE_ARRAY);
213
214 g_value_set_static_boxed (&v1, array);
215
216 if (g_value_transform (&v1, &v2)) {
217 g_object_set_property (object, name, &v2);
218 ret = TRUE;
219 }
220
221 g_value_unset (&v1);
222 g_value_unset (&v2);
223
224 return ret;
225 }
226
227 /**
228 * gst_util_get_object_array:
229 * @object: the object to set the array to
230 * @name: the name of the property to set
231 * @array: (out): a return #GValueArray
232 *
233 * Get a property of type %GST_TYPE_ARRAY and transform it into a
234 * #GValueArray. This allow language bindings to get GST_TYPE_ARRAY
235 * properties which are otherwise not an accessible type.
236 *
237 * Since: 1.12
238 */
239 gboolean
gst_util_get_object_array(GObject * object,const gchar * name,GValueArray ** array)240 gst_util_get_object_array (GObject * object, const gchar * name,
241 GValueArray ** array)
242 {
243 GValue v1 = G_VALUE_INIT, v2 = G_VALUE_INIT;
244 gboolean ret = FALSE;
245
246 g_value_init (&v1, G_TYPE_VALUE_ARRAY);
247 g_value_init (&v2, GST_TYPE_ARRAY);
248
249 g_object_get_property (object, name, &v2);
250
251 if (g_value_transform (&v2, &v1)) {
252 *array = g_value_get_boxed (&v1);
253 ret = TRUE;
254 }
255
256 g_value_unset (&v2);
257
258 return ret;
259 }
260
261 /* work around error C2520: conversion from unsigned __int64 to double
262 * not implemented, use signed __int64
263 *
264 * These are implemented as functions because on some platforms a 64bit int to
265 * double conversion is not defined/implemented.
266 */
267
268 gdouble
gst_util_guint64_to_gdouble(guint64 value)269 gst_util_guint64_to_gdouble (guint64 value)
270 {
271 if (value & G_GINT64_CONSTANT (0x8000000000000000))
272 return (gdouble) ((gint64) value) + (gdouble) 18446744073709551616.;
273 else
274 return (gdouble) ((gint64) value);
275 }
276
277 guint64
gst_util_gdouble_to_guint64(gdouble value)278 gst_util_gdouble_to_guint64 (gdouble value)
279 {
280 if (value < (gdouble) 9223372036854775808.) /* 1 << 63 */
281 return ((guint64) ((gint64) value));
282
283 value -= (gdouble) 18446744073709551616.;
284 return ((guint64) ((gint64) value));
285 }
286
287 #ifndef HAVE_UINT128_T
288 /* convenience struct for getting high and low uint32 parts of
289 * a guint64 */
290 typedef union
291 {
292 guint64 ll;
293 struct
294 {
295 #if G_BYTE_ORDER == G_BIG_ENDIAN
296 guint32 high, low;
297 #else
298 guint32 low, high;
299 #endif
300 } l;
301 } GstUInt64;
302
303 #if defined (__x86_64__) && defined (__GNUC__)
304 static inline void
gst_util_uint64_mul_uint64(GstUInt64 * c1,GstUInt64 * c0,guint64 arg1,guint64 arg2)305 gst_util_uint64_mul_uint64 (GstUInt64 * c1, GstUInt64 * c0, guint64 arg1,
306 guint64 arg2)
307 {
308 __asm__ __volatile__ ("mulq %3":"=a" (c0->ll), "=d" (c1->ll)
309 :"a" (arg1), "g" (arg2)
310 );
311 }
312 #else /* defined (__x86_64__) */
313 /* multiply two 64-bit unsigned ints into a 128-bit unsigned int. the high
314 * and low 64 bits of the product are placed in c1 and c0 respectively.
315 * this operation cannot overflow. */
316 static inline void
gst_util_uint64_mul_uint64(GstUInt64 * c1,GstUInt64 * c0,guint64 arg1,guint64 arg2)317 gst_util_uint64_mul_uint64 (GstUInt64 * c1, GstUInt64 * c0, guint64 arg1,
318 guint64 arg2)
319 {
320 GstUInt64 a1, b0;
321 GstUInt64 v, n;
322
323 /* prepare input */
324 v.ll = arg1;
325 n.ll = arg2;
326
327 /* do 128 bits multiply
328 * nh nl
329 * * vh vl
330 * ----------
331 * a0 = vl * nl
332 * a1 = vl * nh
333 * b0 = vh * nl
334 * b1 = + vh * nh
335 * -------------------
336 * c1h c1l c0h c0l
337 *
338 * "a0" is optimized away, result is stored directly in c0. "b1" is
339 * optimized away, result is stored directly in c1.
340 */
341 c0->ll = (guint64) v.l.low * n.l.low;
342 a1.ll = (guint64) v.l.low * n.l.high;
343 b0.ll = (guint64) v.l.high * n.l.low;
344
345 /* add the high word of a0 to the low words of a1 and b0 using c1 as
346 * scrach space to capture the carry. the low word of the result becomes
347 * the final high word of c0 */
348 c1->ll = (guint64) c0->l.high + a1.l.low + b0.l.low;
349 c0->l.high = c1->l.low;
350
351 /* add the carry from the result above (found in the high word of c1) and
352 * the high words of a1 and b0 to b1, the result is c1. */
353 c1->ll = (guint64) v.l.high * n.l.high + c1->l.high + a1.l.high + b0.l.high;
354 }
355 #endif /* defined (__x86_64__) */
356
357 #if defined (__x86_64__) && defined (__GNUC__)
358 static inline guint64
gst_util_div128_64(GstUInt64 c1,GstUInt64 c0,guint64 denom)359 gst_util_div128_64 (GstUInt64 c1, GstUInt64 c0, guint64 denom)
360 {
361 guint64 res;
362
363 __asm__ __volatile__ ("divq %3":"=a" (res)
364 :"d" (c1.ll), "a" (c0.ll), "g" (denom)
365 );
366
367 return res;
368 }
369 #else
370 /* count leading zeros */
371 static inline guint
gst_util_clz(guint32 val)372 gst_util_clz (guint32 val)
373 {
374 guint s;
375
376 s = val | (val >> 1);
377 s |= (s >> 2);
378 s |= (s >> 4);
379 s |= (s >> 8);
380 s = ~(s | (s >> 16));
381 s = s - ((s >> 1) & 0x55555555);
382 s = (s & 0x33333333) + ((s >> 2) & 0x33333333);
383 s = (s + (s >> 4)) & 0x0f0f0f0f;
384 s += (s >> 8);
385 s = (s + (s >> 16)) & 0x3f;
386
387 return s;
388 }
389
390 /* based on Hacker's Delight p152 */
391 static inline guint64
gst_util_div128_64(GstUInt64 c1,GstUInt64 c0,guint64 denom)392 gst_util_div128_64 (GstUInt64 c1, GstUInt64 c0, guint64 denom)
393 {
394 GstUInt64 q1, q0, rhat;
395 GstUInt64 v, cmp1, cmp2;
396 guint s;
397
398 v.ll = denom;
399
400 /* count number of leading zeroes, we know they must be in the high
401 * part of denom since denom > G_MAXUINT32. */
402 s = gst_util_clz (v.l.high);
403
404 if (s > 0) {
405 /* normalize divisor and dividend */
406 v.ll <<= s;
407 c1.ll = (c1.ll << s) | (c0.l.high >> (32 - s));
408 c0.ll <<= s;
409 }
410
411 q1.ll = c1.ll / v.l.high;
412 rhat.ll = c1.ll - q1.ll * v.l.high;
413
414 cmp1.l.high = rhat.l.low;
415 cmp1.l.low = c0.l.high;
416 cmp2.ll = q1.ll * v.l.low;
417
418 while (q1.l.high || cmp2.ll > cmp1.ll) {
419 q1.ll--;
420 rhat.ll += v.l.high;
421 if (rhat.l.high)
422 break;
423 cmp1.l.high = rhat.l.low;
424 cmp2.ll -= v.l.low;
425 }
426 c1.l.high = c1.l.low;
427 c1.l.low = c0.l.high;
428 c1.ll -= q1.ll * v.ll;
429 q0.ll = c1.ll / v.l.high;
430 rhat.ll = c1.ll - q0.ll * v.l.high;
431
432 cmp1.l.high = rhat.l.low;
433 cmp1.l.low = c0.l.low;
434 cmp2.ll = q0.ll * v.l.low;
435
436 while (q0.l.high || cmp2.ll > cmp1.ll) {
437 q0.ll--;
438 rhat.ll += v.l.high;
439 if (rhat.l.high)
440 break;
441 cmp1.l.high = rhat.l.low;
442 cmp2.ll -= v.l.low;
443 }
444 q0.l.high += q1.l.low;
445
446 return q0.ll;
447 }
448 #endif /* defined (__GNUC__) */
449
450 /* This always gives the correct result because:
451 * a) val <= G_MAXUINT64-1
452 * b) (c0,c1) <= G_MAXUINT64 * (G_MAXUINT64-1)
453 * or
454 * (c0,c1) == G_MAXUINT64 * G_MAXUINT64 and denom < G_MAXUINT64
455 * (note: num==denom case is handled by short path)
456 * This means that (c0,c1) either has enough space for val
457 * or that the overall result will overflow anyway.
458 */
459
460 /* add correction with carry */
461 #define CORRECT(c0,c1,val) \
462 if (val) { \
463 if (G_MAXUINT64 - c0.ll < val) { \
464 if (G_UNLIKELY (c1.ll == G_MAXUINT64)) \
465 /* overflow */ \
466 return G_MAXUINT64; \
467 c1.ll++; \
468 } \
469 c0.ll += val; \
470 }
471
472 static guint64
gst_util_uint64_scale_uint64_unchecked(guint64 val,guint64 num,guint64 denom,guint64 correct)473 gst_util_uint64_scale_uint64_unchecked (guint64 val, guint64 num,
474 guint64 denom, guint64 correct)
475 {
476 GstUInt64 c1, c0;
477
478 /* compute 128-bit numerator product */
479 gst_util_uint64_mul_uint64 (&c1, &c0, val, num);
480
481 /* perform rounding correction */
482 CORRECT (c0, c1, correct);
483
484 /* high word as big as or bigger than denom --> overflow */
485 if (G_UNLIKELY (c1.ll >= denom))
486 return G_MAXUINT64;
487
488 /* compute quotient, fits in 64 bits */
489 return gst_util_div128_64 (c1, c0, denom);
490 }
491 #else
492
493 #define GST_MAXUINT128 ((__uint128_t) -1)
494 static guint64
gst_util_uint64_scale_uint64_unchecked(guint64 val,guint64 num,guint64 denom,guint64 correct)495 gst_util_uint64_scale_uint64_unchecked (guint64 val, guint64 num,
496 guint64 denom, guint64 correct)
497 {
498 __uint128_t tmp;
499
500 /* Calculate val * num */
501 tmp = ((__uint128_t) val) * ((__uint128_t) num);
502
503 /* overflow checks */
504 if (G_UNLIKELY (GST_MAXUINT128 - correct < tmp))
505 return G_MAXUINT64;
506
507 /* perform rounding correction */
508 tmp += correct;
509
510 /* Divide by denom */
511 tmp /= denom;
512
513 /* if larger than G_MAXUINT64 --> overflow */
514 if (G_UNLIKELY (tmp > G_MAXUINT64))
515 return G_MAXUINT64;
516
517 /* compute quotient, fits in 64 bits */
518 return (guint64) tmp;
519 }
520
521 #endif
522
523 #if !defined (__x86_64__) && !defined (HAVE_UINT128_T)
524 static inline void
gst_util_uint64_mul_uint32(GstUInt64 * c1,GstUInt64 * c0,guint64 arg1,guint32 arg2)525 gst_util_uint64_mul_uint32 (GstUInt64 * c1, GstUInt64 * c0, guint64 arg1,
526 guint32 arg2)
527 {
528 GstUInt64 a;
529
530 a.ll = arg1;
531
532 c0->ll = (guint64) a.l.low * arg2;
533 c1->ll = (guint64) a.l.high * arg2 + c0->l.high;
534 c0->l.high = 0;
535 }
536
537 /* divide a 96-bit unsigned int by a 32-bit unsigned int when we know the
538 * quotient fits into 64 bits. the high 64 bits and low 32 bits of the
539 * numerator are expected in c1 and c0 respectively. */
540 static inline guint64
gst_util_div96_32(guint64 c1,guint64 c0,guint32 denom)541 gst_util_div96_32 (guint64 c1, guint64 c0, guint32 denom)
542 {
543 c0 += (c1 % denom) << 32;
544 return ((c1 / denom) << 32) + (c0 / denom);
545 }
546
547 static inline guint64
gst_util_uint64_scale_uint32_unchecked(guint64 val,guint32 num,guint32 denom,guint32 correct)548 gst_util_uint64_scale_uint32_unchecked (guint64 val, guint32 num,
549 guint32 denom, guint32 correct)
550 {
551 GstUInt64 c1, c0;
552
553 /* compute 96-bit numerator product */
554 gst_util_uint64_mul_uint32 (&c1, &c0, val, num);
555
556 /* condition numerator based on rounding mode */
557 CORRECT (c0, c1, correct);
558
559 /* high 32 bits as big as or bigger than denom --> overflow */
560 if (G_UNLIKELY (c1.l.high >= denom))
561 return G_MAXUINT64;
562
563 /* compute quotient, fits in 64 bits */
564 return gst_util_div96_32 (c1.ll, c0.ll, denom);
565 }
566 #endif
567
568 /* the guts of the gst_util_uint64_scale() variants */
569 static guint64
_gst_util_uint64_scale(guint64 val,guint64 num,guint64 denom,guint64 correct)570 _gst_util_uint64_scale (guint64 val, guint64 num, guint64 denom,
571 guint64 correct)
572 {
573 g_return_val_if_fail (denom != 0, G_MAXUINT64);
574
575 if (G_UNLIKELY (num == 0))
576 return 0;
577
578 if (G_UNLIKELY (num == denom))
579 return val;
580
581 /* on 64bits we always use a full 128bits multiply/division */
582 #if !defined (__x86_64__) && !defined (HAVE_UINT128_T)
583 /* denom is low --> try to use 96 bit muldiv */
584 if (G_LIKELY (denom <= G_MAXUINT32)) {
585 /* num is low --> use 96 bit muldiv */
586 if (G_LIKELY (num <= G_MAXUINT32))
587 return gst_util_uint64_scale_uint32_unchecked (val, (guint32) num,
588 (guint32) denom, correct);
589
590 /* num is high but val is low --> swap and use 96-bit muldiv */
591 if (G_LIKELY (val <= G_MAXUINT32))
592 return gst_util_uint64_scale_uint32_unchecked (num, (guint32) val,
593 (guint32) denom, correct);
594 }
595 #endif /* !defined (__x86_64__) && !defined (HAVE_UINT128_T) */
596
597 /* val is high and num is high --> use 128-bit muldiv */
598 return gst_util_uint64_scale_uint64_unchecked (val, num, denom, correct);
599 }
600
601 /**
602 * gst_util_uint64_scale:
603 * @val: the number to scale
604 * @num: the numerator of the scale ratio
605 * @denom: the denominator of the scale ratio
606 *
607 * Scale @val by the rational number @num / @denom, avoiding overflows and
608 * underflows and without loss of precision.
609 *
610 * This function can potentially be very slow if val and num are both
611 * greater than G_MAXUINT32.
612 *
613 * Returns: @val * @num / @denom. In the case of an overflow, this
614 * function returns G_MAXUINT64. If the result is not exactly
615 * representable as an integer it is truncated. See also
616 * gst_util_uint64_scale_round(), gst_util_uint64_scale_ceil(),
617 * gst_util_uint64_scale_int(), gst_util_uint64_scale_int_round(),
618 * gst_util_uint64_scale_int_ceil().
619 */
620 guint64
gst_util_uint64_scale(guint64 val,guint64 num,guint64 denom)621 gst_util_uint64_scale (guint64 val, guint64 num, guint64 denom)
622 {
623 return _gst_util_uint64_scale (val, num, denom, 0);
624 }
625
626 /**
627 * gst_util_uint64_scale_round:
628 * @val: the number to scale
629 * @num: the numerator of the scale ratio
630 * @denom: the denominator of the scale ratio
631 *
632 * Scale @val by the rational number @num / @denom, avoiding overflows and
633 * underflows and without loss of precision.
634 *
635 * This function can potentially be very slow if val and num are both
636 * greater than G_MAXUINT32.
637 *
638 * Returns: @val * @num / @denom. In the case of an overflow, this
639 * function returns G_MAXUINT64. If the result is not exactly
640 * representable as an integer, it is rounded to the nearest integer
641 * (half-way cases are rounded up). See also gst_util_uint64_scale(),
642 * gst_util_uint64_scale_ceil(), gst_util_uint64_scale_int(),
643 * gst_util_uint64_scale_int_round(), gst_util_uint64_scale_int_ceil().
644 */
645 guint64
gst_util_uint64_scale_round(guint64 val,guint64 num,guint64 denom)646 gst_util_uint64_scale_round (guint64 val, guint64 num, guint64 denom)
647 {
648 return _gst_util_uint64_scale (val, num, denom, denom >> 1);
649 }
650
651 /**
652 * gst_util_uint64_scale_ceil:
653 * @val: the number to scale
654 * @num: the numerator of the scale ratio
655 * @denom: the denominator of the scale ratio
656 *
657 * Scale @val by the rational number @num / @denom, avoiding overflows and
658 * underflows and without loss of precision.
659 *
660 * This function can potentially be very slow if val and num are both
661 * greater than G_MAXUINT32.
662 *
663 * Returns: @val * @num / @denom. In the case of an overflow, this
664 * function returns G_MAXUINT64. If the result is not exactly
665 * representable as an integer, it is rounded up. See also
666 * gst_util_uint64_scale(), gst_util_uint64_scale_round(),
667 * gst_util_uint64_scale_int(), gst_util_uint64_scale_int_round(),
668 * gst_util_uint64_scale_int_ceil().
669 */
670 guint64
gst_util_uint64_scale_ceil(guint64 val,guint64 num,guint64 denom)671 gst_util_uint64_scale_ceil (guint64 val, guint64 num, guint64 denom)
672 {
673 return _gst_util_uint64_scale (val, num, denom, denom - 1);
674 }
675
676 /* the guts of the gst_util_uint64_scale_int() variants */
677 static guint64
_gst_util_uint64_scale_int(guint64 val,gint num,gint denom,gint correct)678 _gst_util_uint64_scale_int (guint64 val, gint num, gint denom, gint correct)
679 {
680 g_return_val_if_fail (denom > 0, G_MAXUINT64);
681 g_return_val_if_fail (num >= 0, G_MAXUINT64);
682
683 if (G_UNLIKELY (num == 0))
684 return 0;
685
686 if (G_UNLIKELY (num == denom))
687 return val;
688
689 if (val <= G_MAXUINT32) {
690 /* simple case. num and denom are not negative so casts are OK. when
691 * not truncating, the additions to the numerator cannot overflow
692 * because val*num <= G_MAXUINT32 * G_MAXINT32 < G_MAXUINT64 -
693 * G_MAXINT32, so there's room to add another gint32. */
694 val *= (guint64) num;
695 /* add rounding correction */
696 val += correct;
697
698 return val / (guint64) denom;
699 }
700 #if !defined (__x86_64__) && !defined (HAVE_UINT128_T)
701 /* num and denom are not negative so casts are OK */
702 return gst_util_uint64_scale_uint32_unchecked (val, (guint32) num,
703 (guint32) denom, (guint32) correct);
704 #else
705 /* always use full 128bits scale */
706 return gst_util_uint64_scale_uint64_unchecked (val, num, denom, correct);
707 #endif
708 }
709
710 /**
711 * gst_util_uint64_scale_int:
712 * @val: guint64 (such as a #GstClockTime) to scale.
713 * @num: numerator of the scale factor.
714 * @denom: denominator of the scale factor.
715 *
716 * Scale @val by the rational number @num / @denom, avoiding overflows and
717 * underflows and without loss of precision. @num must be non-negative and
718 * @denom must be positive.
719 *
720 * Returns: @val * @num / @denom. In the case of an overflow, this
721 * function returns G_MAXUINT64. If the result is not exactly
722 * representable as an integer, it is truncated. See also
723 * gst_util_uint64_scale_int_round(), gst_util_uint64_scale_int_ceil(),
724 * gst_util_uint64_scale(), gst_util_uint64_scale_round(),
725 * gst_util_uint64_scale_ceil().
726 */
727 guint64
gst_util_uint64_scale_int(guint64 val,gint num,gint denom)728 gst_util_uint64_scale_int (guint64 val, gint num, gint denom)
729 {
730 return _gst_util_uint64_scale_int (val, num, denom, 0);
731 }
732
733 /**
734 * gst_util_uint64_scale_int_round:
735 * @val: guint64 (such as a #GstClockTime) to scale.
736 * @num: numerator of the scale factor.
737 * @denom: denominator of the scale factor.
738 *
739 * Scale @val by the rational number @num / @denom, avoiding overflows and
740 * underflows and without loss of precision. @num must be non-negative and
741 * @denom must be positive.
742 *
743 * Returns: @val * @num / @denom. In the case of an overflow, this
744 * function returns G_MAXUINT64. If the result is not exactly
745 * representable as an integer, it is rounded to the nearest integer
746 * (half-way cases are rounded up). See also gst_util_uint64_scale_int(),
747 * gst_util_uint64_scale_int_ceil(), gst_util_uint64_scale(),
748 * gst_util_uint64_scale_round(), gst_util_uint64_scale_ceil().
749 */
750 guint64
gst_util_uint64_scale_int_round(guint64 val,gint num,gint denom)751 gst_util_uint64_scale_int_round (guint64 val, gint num, gint denom)
752 {
753 /* we can use a shift to divide by 2 because denom is required to be
754 * positive. */
755 return _gst_util_uint64_scale_int (val, num, denom, denom >> 1);
756 }
757
758 /**
759 * gst_util_uint64_scale_int_ceil:
760 * @val: guint64 (such as a #GstClockTime) to scale.
761 * @num: numerator of the scale factor.
762 * @denom: denominator of the scale factor.
763 *
764 * Scale @val by the rational number @num / @denom, avoiding overflows and
765 * underflows and without loss of precision. @num must be non-negative and
766 * @denom must be positive.
767 *
768 * Returns: @val * @num / @denom. In the case of an overflow, this
769 * function returns G_MAXUINT64. If the result is not exactly
770 * representable as an integer, it is rounded up. See also
771 * gst_util_uint64_scale_int(), gst_util_uint64_scale_int_round(),
772 * gst_util_uint64_scale(), gst_util_uint64_scale_round(),
773 * gst_util_uint64_scale_ceil().
774 */
775 guint64
gst_util_uint64_scale_int_ceil(guint64 val,gint num,gint denom)776 gst_util_uint64_scale_int_ceil (guint64 val, gint num, gint denom)
777 {
778 return _gst_util_uint64_scale_int (val, num, denom, denom - 1);
779 }
780
781 /**
782 * gst_util_seqnum_next:
783 *
784 * Return a constantly incrementing sequence number.
785 *
786 * This function is used internally to GStreamer to be able to determine which
787 * events and messages are "the same". For example, elements may set the seqnum
788 * on a segment-done message to be the same as that of the last seek event, to
789 * indicate that event and the message correspond to the same segment.
790 *
791 * This function never returns %GST_SEQNUM_INVALID (which is 0).
792 *
793 * Returns: A constantly incrementing 32-bit unsigned integer, which might
794 * overflow at some point. Use gst_util_seqnum_compare() to make sure
795 * you handle wraparound correctly.
796 */
797 guint32
gst_util_seqnum_next(void)798 gst_util_seqnum_next (void)
799 {
800 static gint counter = 1;
801 gint ret = g_atomic_int_add (&counter, 1);
802
803 /* Make sure we don't return 0 */
804 if (G_UNLIKELY (ret == GST_SEQNUM_INVALID))
805 ret = g_atomic_int_add (&counter, 1);
806
807 return ret;
808 }
809
810 /**
811 * gst_util_seqnum_compare:
812 * @s1: A sequence number.
813 * @s2: Another sequence number.
814 *
815 * Compare two sequence numbers, handling wraparound.
816 *
817 * The current implementation just returns (gint32)(@s1 - @s2).
818 *
819 * Returns: A negative number if @s1 is before @s2, 0 if they are equal, or a
820 * positive number if @s1 is after @s2.
821 */
822 gint32
gst_util_seqnum_compare(guint32 s1,guint32 s2)823 gst_util_seqnum_compare (guint32 s1, guint32 s2)
824 {
825 return (gint32) (s1 - s2);
826 }
827
828 /* -----------------------------------------------------
829 *
830 * The following code will be moved out of the main
831 * gstreamer library someday.
832 */
833
834 #include "gstpad.h"
835
836 /**
837 * gst_element_create_all_pads:
838 * @element: (transfer none): a #GstElement to create pads for
839 *
840 * Creates a pad for each pad template that is always available.
841 * This function is only useful during object initialization of
842 * subclasses of #GstElement.
843 */
844 void
gst_element_create_all_pads(GstElement * element)845 gst_element_create_all_pads (GstElement * element)
846 {
847 GList *padlist;
848
849 /* FIXME: lock element */
850
851 padlist =
852 gst_element_class_get_pad_template_list (GST_ELEMENT_CLASS
853 (G_OBJECT_GET_CLASS (element)));
854
855 while (padlist) {
856 GstPadTemplate *padtempl = (GstPadTemplate *) padlist->data;
857
858 if (padtempl->presence == GST_PAD_ALWAYS) {
859 GstPad *pad;
860
861 pad = gst_pad_new_from_template (padtempl, padtempl->name_template);
862
863 gst_element_add_pad (element, pad);
864 }
865 padlist = padlist->next;
866 }
867 }
868
869 /**
870 * gst_element_get_compatible_pad_template:
871 * @element: (transfer none): a #GstElement to get a compatible pad template for
872 * @compattempl: (transfer none): the #GstPadTemplate to find a compatible
873 * template for
874 *
875 * Retrieves a pad template from @element that is compatible with @compattempl.
876 * Pads from compatible templates can be linked together.
877 *
878 * Returns: (transfer none) (nullable): a compatible #GstPadTemplate,
879 * or %NULL if none was found. No unreferencing is necessary.
880 */
881 GstPadTemplate *
gst_element_get_compatible_pad_template(GstElement * element,GstPadTemplate * compattempl)882 gst_element_get_compatible_pad_template (GstElement * element,
883 GstPadTemplate * compattempl)
884 {
885 GstPadTemplate *newtempl = NULL;
886 GList *padlist;
887 GstElementClass *class;
888 gboolean compatible;
889
890 g_return_val_if_fail (element != NULL, NULL);
891 g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
892 g_return_val_if_fail (compattempl != NULL, NULL);
893
894 class = GST_ELEMENT_GET_CLASS (element);
895
896 padlist = gst_element_class_get_pad_template_list (class);
897
898 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
899 "Looking for a suitable pad template in %s out of %d templates...",
900 GST_ELEMENT_NAME (element), g_list_length (padlist));
901
902 while (padlist) {
903 GstPadTemplate *padtempl = (GstPadTemplate *) padlist->data;
904
905 /* Ignore name
906 * Ignore presence
907 * Check direction (must be opposite)
908 * Check caps
909 */
910 GST_CAT_LOG (GST_CAT_CAPS,
911 "checking pad template %s", padtempl->name_template);
912 if (padtempl->direction != compattempl->direction) {
913 GST_CAT_DEBUG (GST_CAT_CAPS,
914 "compatible direction: found %s pad template \"%s\"",
915 padtempl->direction == GST_PAD_SRC ? "src" : "sink",
916 padtempl->name_template);
917
918 GST_CAT_DEBUG (GST_CAT_CAPS,
919 "intersecting %" GST_PTR_FORMAT, GST_PAD_TEMPLATE_CAPS (compattempl));
920 GST_CAT_DEBUG (GST_CAT_CAPS,
921 "..and %" GST_PTR_FORMAT, GST_PAD_TEMPLATE_CAPS (padtempl));
922
923 compatible = gst_caps_can_intersect (GST_PAD_TEMPLATE_CAPS (compattempl),
924 GST_PAD_TEMPLATE_CAPS (padtempl));
925
926 GST_CAT_DEBUG (GST_CAT_CAPS, "caps are %scompatible",
927 (compatible ? "" : "not "));
928
929 if (compatible) {
930 newtempl = padtempl;
931 break;
932 }
933 }
934
935 padlist = g_list_next (padlist);
936 }
937 if (newtempl)
938 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
939 "Returning new pad template %p", newtempl);
940 else
941 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "No compatible pad template found");
942
943 return newtempl;
944 }
945
946 /**
947 * gst_element_get_pad_from_template:
948 * @element: (transfer none): a #GstElement.
949 * @templ: (transfer none): a #GstPadTemplate belonging to @element.
950 *
951 * Gets a pad from @element described by @templ. If the presence of @templ is
952 * #GST_PAD_REQUEST, requests a new pad. Can return %NULL for #GST_PAD_SOMETIMES
953 * templates.
954 *
955 * Returns: (transfer full) (nullable): the #GstPad, or %NULL if one
956 * could not be found or created.
957 */
958 static GstPad *
gst_element_get_pad_from_template(GstElement * element,GstPadTemplate * templ)959 gst_element_get_pad_from_template (GstElement * element, GstPadTemplate * templ)
960 {
961 GstPad *ret = NULL;
962 GstPadPresence presence;
963
964 /* If this function is ever exported, we need check the validity of `element'
965 * and `templ', and to make sure the template actually belongs to the
966 * element. */
967
968 presence = GST_PAD_TEMPLATE_PRESENCE (templ);
969
970 switch (presence) {
971 case GST_PAD_ALWAYS:
972 case GST_PAD_SOMETIMES:
973 ret = gst_element_get_static_pad (element, templ->name_template);
974 if (!ret && presence == GST_PAD_ALWAYS)
975 g_warning
976 ("Element %s has an ALWAYS template %s, but no pad of the same name",
977 GST_OBJECT_NAME (element), templ->name_template);
978 break;
979
980 case GST_PAD_REQUEST:
981 ret = gst_element_request_pad (element, templ, NULL, NULL);
982 break;
983 }
984
985 return ret;
986 }
987
988 /*
989 * gst_element_request_compatible_pad:
990 * @element: a #GstElement.
991 * @templ: the #GstPadTemplate to which the new pad should be able to link.
992 *
993 * Requests a pad from @element. The returned pad should be unlinked and
994 * compatible with @templ. Might return an existing pad, or request a new one.
995 *
996 * Returns: (nullable): a #GstPad, or %NULL if one could not be found
997 * or created.
998 */
999 static GstPad *
gst_element_request_compatible_pad(GstElement * element,GstPadTemplate * templ)1000 gst_element_request_compatible_pad (GstElement * element,
1001 GstPadTemplate * templ)
1002 {
1003 GstPadTemplate *templ_new;
1004 GstPad *pad = NULL;
1005
1006 g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
1007 g_return_val_if_fail (GST_IS_PAD_TEMPLATE (templ), NULL);
1008
1009 /* FIXME: should really loop through the templates, testing each for
1010 * compatibility and pad availability. */
1011 templ_new = gst_element_get_compatible_pad_template (element, templ);
1012 if (templ_new)
1013 pad = gst_element_get_pad_from_template (element, templ_new);
1014 /* This can happen for non-request pads. */
1015 if (pad && GST_PAD_PEER (pad)) {
1016 gst_object_unref (pad);
1017 pad = NULL;
1018 }
1019
1020 return pad;
1021 }
1022
1023 /*
1024 * Checks if the source pad and the sink pad can be linked.
1025 * Both @srcpad and @sinkpad must be unlinked and have a parent.
1026 */
1027 static gboolean
gst_pad_check_link(GstPad * srcpad,GstPad * sinkpad)1028 gst_pad_check_link (GstPad * srcpad, GstPad * sinkpad)
1029 {
1030 /* generic checks */
1031 g_return_val_if_fail (GST_IS_PAD (srcpad), FALSE);
1032 g_return_val_if_fail (GST_IS_PAD (sinkpad), FALSE);
1033
1034 GST_CAT_INFO (GST_CAT_PADS, "trying to link %s:%s and %s:%s",
1035 GST_DEBUG_PAD_NAME (srcpad), GST_DEBUG_PAD_NAME (sinkpad));
1036
1037 if (GST_PAD_PEER (srcpad) != NULL) {
1038 GST_CAT_INFO (GST_CAT_PADS, "Source pad %s:%s has a peer, failed",
1039 GST_DEBUG_PAD_NAME (srcpad));
1040 return FALSE;
1041 }
1042 if (GST_PAD_PEER (sinkpad) != NULL) {
1043 GST_CAT_INFO (GST_CAT_PADS, "Sink pad %s:%s has a peer, failed",
1044 GST_DEBUG_PAD_NAME (sinkpad));
1045 return FALSE;
1046 }
1047 if (!GST_PAD_IS_SRC (srcpad)) {
1048 GST_CAT_INFO (GST_CAT_PADS, "Src pad %s:%s is not source pad, failed",
1049 GST_DEBUG_PAD_NAME (srcpad));
1050 return FALSE;
1051 }
1052 if (!GST_PAD_IS_SINK (sinkpad)) {
1053 GST_CAT_INFO (GST_CAT_PADS, "Sink pad %s:%s is not sink pad, failed",
1054 GST_DEBUG_PAD_NAME (sinkpad));
1055 return FALSE;
1056 }
1057 if (GST_PAD_PARENT (srcpad) == NULL) {
1058 GST_CAT_INFO (GST_CAT_PADS, "Src pad %s:%s has no parent, failed",
1059 GST_DEBUG_PAD_NAME (srcpad));
1060 return FALSE;
1061 }
1062 if (GST_PAD_PARENT (sinkpad) == NULL) {
1063 GST_CAT_INFO (GST_CAT_PADS, "Sink pad %s:%s has no parent, failed",
1064 GST_DEBUG_PAD_NAME (srcpad));
1065 return FALSE;
1066 }
1067
1068 return TRUE;
1069 }
1070
1071 /**
1072 * gst_element_get_compatible_pad:
1073 * @element: (transfer none): a #GstElement in which the pad should be found.
1074 * @pad: (transfer none): the #GstPad to find a compatible one for.
1075 * @caps: (allow-none): the #GstCaps to use as a filter.
1076 *
1077 * Looks for an unlinked pad to which the given pad can link. It is not
1078 * guaranteed that linking the pads will work, though it should work in most
1079 * cases.
1080 *
1081 * This function will first attempt to find a compatible unlinked ALWAYS pad,
1082 * and if none can be found, it will request a compatible REQUEST pad by looking
1083 * at the templates of @element.
1084 *
1085 * Returns: (transfer full) (nullable): the #GstPad to which a link
1086 * can be made, or %NULL if one cannot be found. gst_object_unref()
1087 * after usage.
1088 */
1089 GstPad *
gst_element_get_compatible_pad(GstElement * element,GstPad * pad,GstCaps * caps)1090 gst_element_get_compatible_pad (GstElement * element, GstPad * pad,
1091 GstCaps * caps)
1092 {
1093 GstIterator *pads;
1094 GstPadTemplate *templ;
1095 GstCaps *templcaps;
1096 GstPad *foundpad = NULL;
1097 gboolean done;
1098 GValue padptr = { 0, };
1099
1100 g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
1101 g_return_val_if_fail (GST_IS_PAD (pad), NULL);
1102
1103 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1104 "finding pad in %s compatible with %s:%s",
1105 GST_ELEMENT_NAME (element), GST_DEBUG_PAD_NAME (pad));
1106
1107 g_return_val_if_fail (GST_PAD_PEER (pad) == NULL, NULL);
1108
1109 done = FALSE;
1110
1111 /* try to get an existing unlinked pad */
1112 if (GST_PAD_IS_SRC (pad)) {
1113 pads = gst_element_iterate_sink_pads (element);
1114 } else if (GST_PAD_IS_SINK (pad)) {
1115 pads = gst_element_iterate_src_pads (element);
1116 } else {
1117 pads = gst_element_iterate_pads (element);
1118 }
1119
1120 while (!done) {
1121 switch (gst_iterator_next (pads, &padptr)) {
1122 case GST_ITERATOR_OK:
1123 {
1124 GstPad *peer;
1125 GstPad *current;
1126 GstPad *srcpad;
1127 GstPad *sinkpad;
1128
1129 current = g_value_get_object (&padptr);
1130
1131 GST_CAT_LOG (GST_CAT_ELEMENT_PADS, "examining pad %s:%s",
1132 GST_DEBUG_PAD_NAME (current));
1133
1134 if (GST_PAD_IS_SRC (current)) {
1135 srcpad = current;
1136 sinkpad = pad;
1137 } else {
1138 srcpad = pad;
1139 sinkpad = current;
1140 }
1141 peer = gst_pad_get_peer (current);
1142
1143 if (peer == NULL && gst_pad_check_link (srcpad, sinkpad)) {
1144 GstCaps *temp, *intersection;
1145 gboolean compatible;
1146
1147 /* Now check if the two pads' caps are compatible */
1148 temp = gst_pad_query_caps (pad, NULL);
1149 if (caps) {
1150 intersection = gst_caps_intersect (temp, caps);
1151 gst_caps_unref (temp);
1152 } else {
1153 intersection = temp;
1154 }
1155
1156 temp = gst_pad_query_caps (current, NULL);
1157 compatible = gst_caps_can_intersect (temp, intersection);
1158 gst_caps_unref (temp);
1159 gst_caps_unref (intersection);
1160
1161 if (compatible) {
1162 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1163 "found existing unlinked compatible pad %s:%s",
1164 GST_DEBUG_PAD_NAME (current));
1165 gst_iterator_free (pads);
1166
1167 current = gst_object_ref (current);
1168 g_value_unset (&padptr);
1169
1170 return current;
1171 } else {
1172 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "incompatible pads");
1173 }
1174 } else {
1175 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1176 "already linked or cannot be linked (peer = %p)", peer);
1177 }
1178 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "unreffing pads");
1179
1180 g_value_reset (&padptr);
1181 if (peer)
1182 gst_object_unref (peer);
1183 break;
1184 }
1185 case GST_ITERATOR_DONE:
1186 done = TRUE;
1187 break;
1188 case GST_ITERATOR_RESYNC:
1189 gst_iterator_resync (pads);
1190 break;
1191 case GST_ITERATOR_ERROR:
1192 g_assert_not_reached ();
1193 break;
1194 }
1195 }
1196 g_value_unset (&padptr);
1197 gst_iterator_free (pads);
1198
1199 GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
1200 "Could not find a compatible unlinked always pad to link to %s:%s, now checking request pads",
1201 GST_DEBUG_PAD_NAME (pad));
1202
1203 /* try to create a new one */
1204 /* requesting is a little crazy, we need a template. Let's create one */
1205 templcaps = gst_pad_query_caps (pad, NULL);
1206 if (caps) {
1207 GstCaps *inter = gst_caps_intersect (templcaps, caps);
1208
1209 gst_caps_unref (templcaps);
1210 templcaps = inter;
1211 }
1212 templ = gst_pad_template_new ((gchar *) GST_PAD_NAME (pad),
1213 GST_PAD_DIRECTION (pad), GST_PAD_ALWAYS, templcaps);
1214 gst_caps_unref (templcaps);
1215
1216 foundpad = gst_element_request_compatible_pad (element, templ);
1217 gst_object_unref (templ);
1218
1219 if (foundpad) {
1220 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1221 "found existing request pad %s:%s", GST_DEBUG_PAD_NAME (foundpad));
1222 return foundpad;
1223 }
1224
1225 GST_CAT_INFO_OBJECT (GST_CAT_ELEMENT_PADS, element,
1226 "Could not find a compatible pad to link to %s:%s",
1227 GST_DEBUG_PAD_NAME (pad));
1228 return NULL;
1229 }
1230
1231 /**
1232 * gst_element_state_get_name:
1233 * @state: a #GstState to get the name of.
1234 *
1235 * Gets a string representing the given state.
1236 *
1237 * Returns: (transfer none): a string with the name of the state.
1238 */
1239 const gchar *
gst_element_state_get_name(GstState state)1240 gst_element_state_get_name (GstState state)
1241 {
1242 switch (state) {
1243 case GST_STATE_VOID_PENDING:
1244 return "VOID_PENDING";
1245 case GST_STATE_NULL:
1246 return "NULL";
1247 case GST_STATE_READY:
1248 return "READY";
1249 case GST_STATE_PLAYING:
1250 return "PLAYING";
1251 case GST_STATE_PAUSED:
1252 return "PAUSED";
1253 default:
1254 /* This is a memory leak */
1255 return g_strdup_printf ("UNKNOWN!(%d)", state);
1256 }
1257 }
1258
1259 /**
1260 * gst_element_state_change_return_get_name:
1261 * @state_ret: a #GstStateChangeReturn to get the name of.
1262 *
1263 * Gets a string representing the given state change result.
1264 *
1265 * Returns: (transfer none): a string with the name of the state
1266 * result.
1267 */
1268 const gchar *
gst_element_state_change_return_get_name(GstStateChangeReturn state_ret)1269 gst_element_state_change_return_get_name (GstStateChangeReturn state_ret)
1270 {
1271 switch (state_ret) {
1272 case GST_STATE_CHANGE_FAILURE:
1273 return "FAILURE";
1274 case GST_STATE_CHANGE_SUCCESS:
1275 return "SUCCESS";
1276 case GST_STATE_CHANGE_ASYNC:
1277 return "ASYNC";
1278 case GST_STATE_CHANGE_NO_PREROLL:
1279 return "NO PREROLL";
1280 default:
1281 /* This is a memory leak */
1282 return g_strdup_printf ("UNKNOWN!(%d)", state_ret);
1283 }
1284 }
1285
1286 /**
1287 * gst_state_change_get_name:
1288 * @transition: a #GstStateChange to get the name of.
1289 *
1290 * Gets a string representing the given state transition.
1291 *
1292 * Returns: (transfer none): a string with the name of the state
1293 * result.
1294 *
1295 * Since: 1.14
1296 */
1297 const gchar *
gst_state_change_get_name(GstStateChange transition)1298 gst_state_change_get_name (GstStateChange transition)
1299 {
1300 switch (transition) {
1301 case GST_STATE_CHANGE_NULL_TO_READY:
1302 return "NULL->READY";
1303 case GST_STATE_CHANGE_READY_TO_PAUSED:
1304 return "READY->PAUSED";
1305 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1306 return "PAUSED->PLAYING";
1307 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1308 return "PLAYING->PAUSED";
1309 case GST_STATE_CHANGE_PAUSED_TO_READY:
1310 return "PAUSED->READY";
1311 case GST_STATE_CHANGE_READY_TO_NULL:
1312 return "READY->NULL";
1313 case GST_STATE_CHANGE_NULL_TO_NULL:
1314 return "NULL->NULL";
1315 case GST_STATE_CHANGE_READY_TO_READY:
1316 return "READY->READY";
1317 case GST_STATE_CHANGE_PAUSED_TO_PAUSED:
1318 return "PAUSED->PAUSED";
1319 case GST_STATE_CHANGE_PLAYING_TO_PLAYING:
1320 return "PLAYING->PLAYING";
1321 }
1322
1323 return "Unknown state return";
1324 }
1325
1326
1327 static gboolean
gst_element_factory_can_accept_all_caps_in_direction(GstElementFactory * factory,const GstCaps * caps,GstPadDirection direction)1328 gst_element_factory_can_accept_all_caps_in_direction (GstElementFactory *
1329 factory, const GstCaps * caps, GstPadDirection direction)
1330 {
1331 GList *templates;
1332
1333 g_return_val_if_fail (factory != NULL, FALSE);
1334 g_return_val_if_fail (caps != NULL, FALSE);
1335
1336 templates = factory->staticpadtemplates;
1337
1338 while (templates) {
1339 GstStaticPadTemplate *template = (GstStaticPadTemplate *) templates->data;
1340
1341 if (template->direction == direction) {
1342 GstCaps *templcaps = gst_static_caps_get (&template->static_caps);
1343
1344 if (gst_caps_is_always_compatible (caps, templcaps)) {
1345 gst_caps_unref (templcaps);
1346 return TRUE;
1347 }
1348 gst_caps_unref (templcaps);
1349 }
1350 templates = g_list_next (templates);
1351 }
1352
1353 return FALSE;
1354 }
1355
1356 static gboolean
gst_element_factory_can_accept_any_caps_in_direction(GstElementFactory * factory,const GstCaps * caps,GstPadDirection direction)1357 gst_element_factory_can_accept_any_caps_in_direction (GstElementFactory *
1358 factory, const GstCaps * caps, GstPadDirection direction)
1359 {
1360 GList *templates;
1361
1362 g_return_val_if_fail (factory != NULL, FALSE);
1363 g_return_val_if_fail (caps != NULL, FALSE);
1364
1365 templates = factory->staticpadtemplates;
1366
1367 while (templates) {
1368 GstStaticPadTemplate *template = (GstStaticPadTemplate *) templates->data;
1369
1370 if (template->direction == direction) {
1371 GstCaps *templcaps = gst_static_caps_get (&template->static_caps);
1372
1373 if (gst_caps_can_intersect (caps, templcaps)) {
1374 gst_caps_unref (templcaps);
1375 return TRUE;
1376 }
1377 gst_caps_unref (templcaps);
1378 }
1379 templates = g_list_next (templates);
1380 }
1381
1382 return FALSE;
1383 }
1384
1385 /**
1386 * gst_element_factory_can_sink_all_caps:
1387 * @factory: factory to query
1388 * @caps: the caps to check
1389 *
1390 * Checks if the factory can sink all possible capabilities.
1391 *
1392 * Returns: %TRUE if the caps are fully compatible.
1393 */
1394 gboolean
gst_element_factory_can_sink_all_caps(GstElementFactory * factory,const GstCaps * caps)1395 gst_element_factory_can_sink_all_caps (GstElementFactory * factory,
1396 const GstCaps * caps)
1397 {
1398 return gst_element_factory_can_accept_all_caps_in_direction (factory, caps,
1399 GST_PAD_SINK);
1400 }
1401
1402 /**
1403 * gst_element_factory_can_src_all_caps:
1404 * @factory: factory to query
1405 * @caps: the caps to check
1406 *
1407 * Checks if the factory can src all possible capabilities.
1408 *
1409 * Returns: %TRUE if the caps are fully compatible.
1410 */
1411 gboolean
gst_element_factory_can_src_all_caps(GstElementFactory * factory,const GstCaps * caps)1412 gst_element_factory_can_src_all_caps (GstElementFactory * factory,
1413 const GstCaps * caps)
1414 {
1415 return gst_element_factory_can_accept_all_caps_in_direction (factory, caps,
1416 GST_PAD_SRC);
1417 }
1418
1419 /**
1420 * gst_element_factory_can_sink_any_caps:
1421 * @factory: factory to query
1422 * @caps: the caps to check
1423 *
1424 * Checks if the factory can sink any possible capability.
1425 *
1426 * Returns: %TRUE if the caps have a common subset.
1427 */
1428 gboolean
gst_element_factory_can_sink_any_caps(GstElementFactory * factory,const GstCaps * caps)1429 gst_element_factory_can_sink_any_caps (GstElementFactory * factory,
1430 const GstCaps * caps)
1431 {
1432 return gst_element_factory_can_accept_any_caps_in_direction (factory, caps,
1433 GST_PAD_SINK);
1434 }
1435
1436 /**
1437 * gst_element_factory_can_src_any_caps:
1438 * @factory: factory to query
1439 * @caps: the caps to check
1440 *
1441 * Checks if the factory can src any possible capability.
1442 *
1443 * Returns: %TRUE if the caps have a common subset.
1444 */
1445 gboolean
gst_element_factory_can_src_any_caps(GstElementFactory * factory,const GstCaps * caps)1446 gst_element_factory_can_src_any_caps (GstElementFactory * factory,
1447 const GstCaps * caps)
1448 {
1449 return gst_element_factory_can_accept_any_caps_in_direction (factory, caps,
1450 GST_PAD_SRC);
1451 }
1452
1453 /* if return val is true, *direct_child is a caller-owned ref on the direct
1454 * child of ancestor that is part of object's ancestry */
1455 static gboolean
object_has_ancestor(GstObject * object,GstObject * ancestor,GstObject ** direct_child)1456 object_has_ancestor (GstObject * object, GstObject * ancestor,
1457 GstObject ** direct_child)
1458 {
1459 GstObject *child, *parent;
1460
1461 if (direct_child)
1462 *direct_child = NULL;
1463
1464 child = gst_object_ref (object);
1465 parent = gst_object_get_parent (object);
1466
1467 while (parent) {
1468 if (ancestor == parent) {
1469 if (direct_child)
1470 *direct_child = child;
1471 else
1472 gst_object_unref (child);
1473 gst_object_unref (parent);
1474 return TRUE;
1475 }
1476
1477 gst_object_unref (child);
1478 child = parent;
1479 parent = gst_object_get_parent (parent);
1480 }
1481
1482 gst_object_unref (child);
1483
1484 return FALSE;
1485 }
1486
1487 /* caller owns return */
1488 static GstObject *
find_common_root(GstObject * o1,GstObject * o2)1489 find_common_root (GstObject * o1, GstObject * o2)
1490 {
1491 GstObject *top = o1;
1492 GstObject *kid1, *kid2;
1493 GstObject *root = NULL;
1494
1495 while (GST_OBJECT_PARENT (top))
1496 top = GST_OBJECT_PARENT (top);
1497
1498 /* the itsy-bitsy spider... */
1499
1500 if (!object_has_ancestor (o2, top, &kid2))
1501 return NULL;
1502
1503 root = gst_object_ref (top);
1504 while (TRUE) {
1505 if (!object_has_ancestor (o1, kid2, &kid1)) {
1506 gst_object_unref (kid2);
1507 return root;
1508 }
1509 gst_object_unref (root);
1510 root = kid2;
1511 if (!object_has_ancestor (o2, kid1, &kid2)) {
1512 gst_object_unref (kid1);
1513 return root;
1514 }
1515 gst_object_unref (root);
1516 root = kid1;
1517 }
1518 }
1519
1520 /* caller does not own return */
1521 static GstPad *
ghost_up(GstElement * e,GstPad * pad)1522 ghost_up (GstElement * e, GstPad * pad)
1523 {
1524 static gint ghost_pad_index = 0;
1525 GstPad *gpad;
1526 gchar *name;
1527 GstState current;
1528 GstState next;
1529 GstObject *parent = GST_OBJECT_PARENT (e);
1530
1531 name = g_strdup_printf ("ghost%d", ghost_pad_index++);
1532 gpad = gst_ghost_pad_new (name, pad);
1533 g_free (name);
1534
1535 GST_STATE_LOCK (parent);
1536 gst_element_get_state (GST_ELEMENT (parent), ¤t, &next, 0);
1537
1538 if (current > GST_STATE_READY || next >= GST_STATE_PAUSED)
1539 gst_pad_set_active (gpad, TRUE);
1540
1541 if (!gst_element_add_pad ((GstElement *) parent, gpad)) {
1542 g_warning ("Pad named %s already exists in element %s\n",
1543 GST_OBJECT_NAME (gpad), GST_OBJECT_NAME (parent));
1544 GST_STATE_UNLOCK (parent);
1545 return NULL;
1546 }
1547 GST_STATE_UNLOCK (parent);
1548
1549 return gpad;
1550 }
1551
1552 static void
remove_pad(gpointer ppad,gpointer unused)1553 remove_pad (gpointer ppad, gpointer unused)
1554 {
1555 GstPad *pad = ppad;
1556
1557 if (!gst_element_remove_pad ((GstElement *) GST_OBJECT_PARENT (pad), pad))
1558 g_warning ("Couldn't remove pad %s from element %s",
1559 GST_OBJECT_NAME (pad), GST_OBJECT_NAME (GST_OBJECT_PARENT (pad)));
1560 }
1561
1562 static gboolean
prepare_link_maybe_ghosting(GstPad ** src,GstPad ** sink,GSList ** pads_created)1563 prepare_link_maybe_ghosting (GstPad ** src, GstPad ** sink,
1564 GSList ** pads_created)
1565 {
1566 GstObject *root;
1567 GstObject *e1, *e2;
1568 GSList *pads_created_local = NULL;
1569
1570 g_assert (pads_created);
1571
1572 e1 = GST_OBJECT_PARENT (*src);
1573 e2 = GST_OBJECT_PARENT (*sink);
1574
1575 if (G_UNLIKELY (e1 == NULL)) {
1576 GST_WARNING ("Trying to ghost a pad that doesn't have a parent: %"
1577 GST_PTR_FORMAT, *src);
1578 return FALSE;
1579 }
1580 if (G_UNLIKELY (e2 == NULL)) {
1581 GST_WARNING ("Trying to ghost a pad that doesn't have a parent: %"
1582 GST_PTR_FORMAT, *sink);
1583 return FALSE;
1584 }
1585
1586 if (GST_OBJECT_PARENT (e1) == GST_OBJECT_PARENT (e2)) {
1587 GST_CAT_INFO (GST_CAT_PADS, "%s and %s in same bin, no need for ghost pads",
1588 GST_OBJECT_NAME (e1), GST_OBJECT_NAME (e2));
1589 return TRUE;
1590 }
1591
1592 GST_CAT_INFO (GST_CAT_PADS, "%s and %s not in same bin, making ghost pads",
1593 GST_OBJECT_NAME (e1), GST_OBJECT_NAME (e2));
1594
1595 /* we need to setup some ghost pads */
1596 root = find_common_root (e1, e2);
1597 if (!root) {
1598 if (GST_OBJECT_PARENT (e1) == NULL)
1599 g_warning ("Trying to link elements %s and %s that don't share a common "
1600 "ancestor: %s hasn't been added to a bin or pipeline, but %s is in %s",
1601 GST_ELEMENT_NAME (e1), GST_ELEMENT_NAME (e2),
1602 GST_ELEMENT_NAME (e1), GST_ELEMENT_NAME (e2),
1603 GST_ELEMENT_NAME (GST_OBJECT_PARENT (e2)));
1604 else if (GST_OBJECT_PARENT (e2) == NULL)
1605 g_warning ("Trying to link elements %s and %s that don't share a common "
1606 "ancestor: %s hasn't been added to a bin or pipeline, and %s is in %s",
1607 GST_ELEMENT_NAME (e1), GST_ELEMENT_NAME (e2),
1608 GST_ELEMENT_NAME (e2), GST_ELEMENT_NAME (e1),
1609 GST_ELEMENT_NAME (GST_OBJECT_PARENT (e1)));
1610 else
1611 g_warning ("Trying to link elements %s and %s that don't share a common "
1612 "ancestor: %s is in %s, and %s is in %s",
1613 GST_ELEMENT_NAME (e1), GST_ELEMENT_NAME (e2),
1614 GST_ELEMENT_NAME (e1), GST_ELEMENT_NAME (GST_OBJECT_PARENT (e1)),
1615 GST_ELEMENT_NAME (e2), GST_ELEMENT_NAME (GST_OBJECT_PARENT (e2)));
1616 return FALSE;
1617 }
1618
1619 while (GST_OBJECT_PARENT (e1) != root) {
1620 *src = ghost_up ((GstElement *) e1, *src);
1621 if (!*src)
1622 goto cleanup_fail;
1623 e1 = GST_OBJECT_PARENT (*src);
1624 pads_created_local = g_slist_prepend (pads_created_local, *src);
1625 }
1626 while (GST_OBJECT_PARENT (e2) != root) {
1627 *sink = ghost_up ((GstElement *) e2, *sink);
1628 if (!*sink)
1629 goto cleanup_fail;
1630 e2 = GST_OBJECT_PARENT (*sink);
1631 pads_created_local = g_slist_prepend (pads_created_local, *sink);
1632 }
1633
1634 gst_object_unref (root);
1635 *pads_created = g_slist_concat (*pads_created, pads_created_local);
1636 return TRUE;
1637
1638 cleanup_fail:
1639 gst_object_unref (root);
1640 g_slist_foreach (pads_created_local, remove_pad, NULL);
1641 g_slist_free (pads_created_local);
1642 return FALSE;
1643 }
1644
1645 static gboolean
pad_link_maybe_ghosting(GstPad * src,GstPad * sink,GstPadLinkCheck flags)1646 pad_link_maybe_ghosting (GstPad * src, GstPad * sink, GstPadLinkCheck flags)
1647 {
1648 GSList *pads_created = NULL;
1649 gboolean ret;
1650
1651 if (!prepare_link_maybe_ghosting (&src, &sink, &pads_created)) {
1652 ret = FALSE;
1653 } else {
1654 ret = (gst_pad_link_full (src, sink, flags) == GST_PAD_LINK_OK);
1655 }
1656
1657 if (!ret) {
1658 g_slist_foreach (pads_created, remove_pad, NULL);
1659 }
1660 g_slist_free (pads_created);
1661
1662 return ret;
1663 }
1664
1665 /**
1666 * gst_pad_link_maybe_ghosting_full:
1667 * @src: a #GstPad
1668 * @sink: a #GstPad
1669 * @flags: some #GstPadLinkCheck flags
1670 *
1671 * Links @src to @sink, creating any #GstGhostPad's in between as necessary.
1672 *
1673 * This is a convenience function to save having to create and add intermediate
1674 * #GstGhostPad's as required for linking across #GstBin boundaries.
1675 *
1676 * If @src or @sink pads don't have parent elements or do not share a common
1677 * ancestor, the link will fail.
1678 *
1679 * Calling gst_pad_link_maybe_ghosting_full() with
1680 * @flags == %GST_PAD_LINK_CHECK_DEFAULT is the recommended way of linking
1681 * pads with safety checks applied.
1682 *
1683 * Returns: whether the link succeeded.
1684 *
1685 * Since: 1.10
1686 */
1687 gboolean
gst_pad_link_maybe_ghosting_full(GstPad * src,GstPad * sink,GstPadLinkCheck flags)1688 gst_pad_link_maybe_ghosting_full (GstPad * src, GstPad * sink,
1689 GstPadLinkCheck flags)
1690 {
1691 g_return_val_if_fail (GST_IS_PAD (src), FALSE);
1692 g_return_val_if_fail (GST_IS_PAD (sink), FALSE);
1693
1694 return pad_link_maybe_ghosting (src, sink, flags);
1695 }
1696
1697 /**
1698 * gst_pad_link_maybe_ghosting:
1699 * @src: a #GstPad
1700 * @sink: a #GstPad
1701 *
1702 * Links @src to @sink, creating any #GstGhostPad's in between as necessary.
1703 *
1704 * This is a convenience function to save having to create and add intermediate
1705 * #GstGhostPad's as required for linking across #GstBin boundaries.
1706 *
1707 * If @src or @sink pads don't have parent elements or do not share a common
1708 * ancestor, the link will fail.
1709 *
1710 * Returns: whether the link succeeded.
1711 *
1712 * Since: 1.10
1713 */
1714 gboolean
gst_pad_link_maybe_ghosting(GstPad * src,GstPad * sink)1715 gst_pad_link_maybe_ghosting (GstPad * src, GstPad * sink)
1716 {
1717 g_return_val_if_fail (GST_IS_PAD (src), FALSE);
1718 g_return_val_if_fail (GST_IS_PAD (sink), FALSE);
1719
1720 return gst_pad_link_maybe_ghosting_full (src, sink,
1721 GST_PAD_LINK_CHECK_DEFAULT);
1722 }
1723
1724 static void
release_and_unref_pad(GstElement * element,GstPad * pad,gboolean requestpad)1725 release_and_unref_pad (GstElement * element, GstPad * pad, gboolean requestpad)
1726 {
1727 if (pad) {
1728 if (requestpad)
1729 gst_element_release_request_pad (element, pad);
1730 gst_object_unref (pad);
1731 }
1732 }
1733
1734 /**
1735 * gst_element_link_pads_full:
1736 * @src: a #GstElement containing the source pad.
1737 * @srcpadname: (allow-none): the name of the #GstPad in source element
1738 * or %NULL for any pad.
1739 * @dest: (transfer none): the #GstElement containing the destination pad.
1740 * @destpadname: (allow-none): the name of the #GstPad in destination element,
1741 * or %NULL for any pad.
1742 * @flags: the #GstPadLinkCheck to be performed when linking pads.
1743 *
1744 * Links the two named pads of the source and destination elements.
1745 * Side effect is that if one of the pads has no parent, it becomes a
1746 * child of the parent of the other element. If they have different
1747 * parents, the link fails.
1748 *
1749 * Calling gst_element_link_pads_full() with @flags == %GST_PAD_LINK_CHECK_DEFAULT
1750 * is the same as calling gst_element_link_pads() and the recommended way of
1751 * linking pads with safety checks applied.
1752 *
1753 * This is a convenience function for gst_pad_link_full().
1754 *
1755 * Returns: %TRUE if the pads could be linked, %FALSE otherwise.
1756 */
1757 gboolean
gst_element_link_pads_full(GstElement * src,const gchar * srcpadname,GstElement * dest,const gchar * destpadname,GstPadLinkCheck flags)1758 gst_element_link_pads_full (GstElement * src, const gchar * srcpadname,
1759 GstElement * dest, const gchar * destpadname, GstPadLinkCheck flags)
1760 {
1761 const GList *srcpads, *destpads, *srctempls, *desttempls, *l;
1762 GstPad *srcpad, *destpad;
1763 GstPadTemplate *srctempl, *desttempl;
1764 GstElementClass *srcclass, *destclass;
1765 gboolean srcrequest, destrequest;
1766
1767 /* checks */
1768 g_return_val_if_fail (GST_IS_ELEMENT (src), FALSE);
1769 g_return_val_if_fail (GST_IS_ELEMENT (dest), FALSE);
1770
1771 GST_CAT_INFO (GST_CAT_ELEMENT_PADS,
1772 "trying to link element %s:%s to element %s:%s", GST_ELEMENT_NAME (src),
1773 srcpadname ? srcpadname : "(any)", GST_ELEMENT_NAME (dest),
1774 destpadname ? destpadname : "(any)");
1775
1776 srcrequest = FALSE;
1777 destrequest = FALSE;
1778
1779 /* get a src pad */
1780 if (srcpadname) {
1781 /* name specified, look it up */
1782 if (!(srcpad = gst_element_get_static_pad (src, srcpadname))) {
1783 if ((srcpad = gst_element_get_request_pad (src, srcpadname)))
1784 srcrequest = TRUE;
1785 }
1786 if (!srcpad) {
1787 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no pad %s:%s",
1788 GST_ELEMENT_NAME (src), srcpadname);
1789 return FALSE;
1790 } else {
1791 if (!(GST_PAD_DIRECTION (srcpad) == GST_PAD_SRC)) {
1792 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is no src pad",
1793 GST_DEBUG_PAD_NAME (srcpad));
1794 release_and_unref_pad (src, srcpad, srcrequest);
1795 return FALSE;
1796 }
1797 if (GST_PAD_PEER (srcpad) != NULL) {
1798 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1799 "pad %s:%s is already linked to %s:%s", GST_DEBUG_PAD_NAME (srcpad),
1800 GST_DEBUG_PAD_NAME (GST_PAD_PEER (srcpad)));
1801 /* already linked request pads look like static pads, so the request pad
1802 * was never requested a second time above, so no need to release it */
1803 gst_object_unref (srcpad);
1804 return FALSE;
1805 }
1806 }
1807 srcpads = NULL;
1808 } else {
1809 /* no name given, get the first available pad */
1810 GST_OBJECT_LOCK (src);
1811 srcpads = GST_ELEMENT_PADS (src);
1812 srcpad = srcpads ? GST_PAD_CAST (srcpads->data) : NULL;
1813 if (srcpad)
1814 gst_object_ref (srcpad);
1815 GST_OBJECT_UNLOCK (src);
1816 }
1817
1818 /* get a destination pad */
1819 if (destpadname) {
1820 /* name specified, look it up */
1821 if (!(destpad = gst_element_get_static_pad (dest, destpadname))) {
1822 if ((destpad = gst_element_get_request_pad (dest, destpadname)))
1823 destrequest = TRUE;
1824 }
1825 if (!destpad) {
1826 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no pad %s:%s",
1827 GST_ELEMENT_NAME (dest), destpadname);
1828 release_and_unref_pad (src, srcpad, srcrequest);
1829 return FALSE;
1830 } else {
1831 if (!(GST_PAD_DIRECTION (destpad) == GST_PAD_SINK)) {
1832 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is no sink pad",
1833 GST_DEBUG_PAD_NAME (destpad));
1834 release_and_unref_pad (src, srcpad, srcrequest);
1835 release_and_unref_pad (dest, destpad, destrequest);
1836 return FALSE;
1837 }
1838 if (GST_PAD_PEER (destpad) != NULL) {
1839 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1840 "pad %s:%s is already linked to %s:%s",
1841 GST_DEBUG_PAD_NAME (destpad),
1842 GST_DEBUG_PAD_NAME (GST_PAD_PEER (destpad)));
1843 release_and_unref_pad (src, srcpad, srcrequest);
1844 /* already linked request pads look like static pads, so the request pad
1845 * was never requested a second time above, so no need to release it */
1846 gst_object_unref (destpad);
1847 return FALSE;
1848 }
1849 }
1850 destpads = NULL;
1851 } else {
1852 /* no name given, get the first available pad */
1853 GST_OBJECT_LOCK (dest);
1854 destpads = GST_ELEMENT_PADS (dest);
1855 destpad = destpads ? GST_PAD_CAST (destpads->data) : NULL;
1856 if (destpad)
1857 gst_object_ref (destpad);
1858 GST_OBJECT_UNLOCK (dest);
1859 }
1860
1861 if (srcpadname && destpadname) {
1862 gboolean result;
1863
1864 /* two explicitly specified pads */
1865 result = pad_link_maybe_ghosting (srcpad, destpad, flags);
1866
1867 if (result) {
1868 gst_object_unref (srcpad);
1869 gst_object_unref (destpad);
1870 } else {
1871 release_and_unref_pad (src, srcpad, srcrequest);
1872 release_and_unref_pad (dest, destpad, destrequest);
1873 }
1874 return result;
1875 }
1876
1877 if (srcpad) {
1878 /* loop through the allowed pads in the source, trying to find a
1879 * compatible destination pad */
1880 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1881 "looping through allowed src and dest pads");
1882 do {
1883 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "trying src pad %s:%s",
1884 GST_DEBUG_PAD_NAME (srcpad));
1885 if ((GST_PAD_DIRECTION (srcpad) == GST_PAD_SRC) &&
1886 (GST_PAD_PEER (srcpad) == NULL)) {
1887 gboolean temprequest = FALSE;
1888 GstPad *temp;
1889
1890 if (destpadname) {
1891 temp = destpad;
1892 gst_object_ref (temp);
1893 } else {
1894 temp = gst_element_get_compatible_pad (dest, srcpad, NULL);
1895 if (temp && GST_PAD_PAD_TEMPLATE (temp)
1896 && GST_PAD_TEMPLATE_PRESENCE (GST_PAD_PAD_TEMPLATE (temp)) ==
1897 GST_PAD_REQUEST) {
1898 temprequest = TRUE;
1899 }
1900 }
1901
1902 if (temp && pad_link_maybe_ghosting (srcpad, temp, flags)) {
1903 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "linked pad %s:%s to pad %s:%s",
1904 GST_DEBUG_PAD_NAME (srcpad), GST_DEBUG_PAD_NAME (temp));
1905 if (destpad)
1906 gst_object_unref (destpad);
1907 gst_object_unref (srcpad);
1908 gst_object_unref (temp);
1909 return TRUE;
1910 }
1911
1912 if (temp) {
1913 if (temprequest)
1914 gst_element_release_request_pad (dest, temp);
1915 gst_object_unref (temp);
1916 }
1917 }
1918 /* find a better way for this mess */
1919 if (srcpads) {
1920 srcpads = g_list_next (srcpads);
1921 if (srcpads) {
1922 gst_object_unref (srcpad);
1923 srcpad = GST_PAD_CAST (srcpads->data);
1924 gst_object_ref (srcpad);
1925 }
1926 }
1927 } while (srcpads);
1928 }
1929 if (srcpadname) {
1930 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no link possible from %s:%s to %s",
1931 GST_DEBUG_PAD_NAME (srcpad), GST_ELEMENT_NAME (dest));
1932 /* no need to release any request pad as both src- and destpadname must be
1933 * set to end up here, but this case has already been taken care of above */
1934 if (destpad)
1935 gst_object_unref (destpad);
1936 destpad = NULL;
1937 }
1938 if (srcpad) {
1939 release_and_unref_pad (src, srcpad, srcrequest);
1940 srcpad = NULL;
1941 }
1942
1943 if (destpad) {
1944 /* loop through the existing pads in the destination */
1945 do {
1946 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "trying dest pad %s:%s",
1947 GST_DEBUG_PAD_NAME (destpad));
1948 if ((GST_PAD_DIRECTION (destpad) == GST_PAD_SINK) &&
1949 (GST_PAD_PEER (destpad) == NULL)) {
1950 GstPad *temp = gst_element_get_compatible_pad (src, destpad, NULL);
1951 gboolean temprequest = FALSE;
1952
1953 if (temp && GST_PAD_PAD_TEMPLATE (temp)
1954 && GST_PAD_TEMPLATE_PRESENCE (GST_PAD_PAD_TEMPLATE (temp)) ==
1955 GST_PAD_REQUEST) {
1956 temprequest = TRUE;
1957 }
1958
1959 if (temp && pad_link_maybe_ghosting (temp, destpad, flags)) {
1960 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "linked pad %s:%s to pad %s:%s",
1961 GST_DEBUG_PAD_NAME (temp), GST_DEBUG_PAD_NAME (destpad));
1962 gst_object_unref (temp);
1963 gst_object_unref (destpad);
1964 return TRUE;
1965 }
1966
1967 release_and_unref_pad (src, temp, temprequest);
1968 }
1969 if (destpads) {
1970 destpads = g_list_next (destpads);
1971 if (destpads) {
1972 gst_object_unref (destpad);
1973 destpad = GST_PAD_CAST (destpads->data);
1974 gst_object_ref (destpad);
1975 }
1976 }
1977 } while (destpads);
1978 }
1979
1980 if (destpadname) {
1981 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no link possible from %s to %s:%s",
1982 GST_ELEMENT_NAME (src), GST_DEBUG_PAD_NAME (destpad));
1983 release_and_unref_pad (dest, destpad, destrequest);
1984 return FALSE;
1985 } else {
1986 /* no need to release any request pad as the case of unset destpatname and
1987 * destpad being a request pad has already been taken care of when looking
1988 * though the destination pads above */
1989 if (destpad) {
1990 gst_object_unref (destpad);
1991 }
1992 destpad = NULL;
1993 }
1994
1995 srcclass = GST_ELEMENT_GET_CLASS (src);
1996 destclass = GST_ELEMENT_GET_CLASS (dest);
1997
1998 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1999 "we might have request pads on both sides, checking...");
2000 srctempls = gst_element_class_get_pad_template_list (srcclass);
2001 desttempls = gst_element_class_get_pad_template_list (destclass);
2002
2003 if (srctempls && desttempls) {
2004 while (srctempls) {
2005 srctempl = (GstPadTemplate *) srctempls->data;
2006 if (srctempl->presence == GST_PAD_REQUEST) {
2007 for (l = desttempls; l; l = l->next) {
2008 desttempl = (GstPadTemplate *) l->data;
2009 if (desttempl->presence == GST_PAD_REQUEST &&
2010 desttempl->direction != srctempl->direction) {
2011 GstCaps *srccaps, *destcaps;
2012
2013 srccaps = gst_pad_template_get_caps (srctempl);
2014 destcaps = gst_pad_template_get_caps (desttempl);
2015 if (gst_caps_is_always_compatible (srccaps, destcaps)) {
2016 srcpad =
2017 gst_element_request_pad (src, srctempl,
2018 srctempl->name_template, NULL);
2019 destpad =
2020 gst_element_request_pad (dest, desttempl,
2021 desttempl->name_template, NULL);
2022 if (srcpad && destpad
2023 && pad_link_maybe_ghosting (srcpad, destpad, flags)) {
2024 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
2025 "linked pad %s:%s to pad %s:%s",
2026 GST_DEBUG_PAD_NAME (srcpad), GST_DEBUG_PAD_NAME (destpad));
2027 gst_object_unref (srcpad);
2028 gst_object_unref (destpad);
2029 gst_caps_unref (srccaps);
2030 gst_caps_unref (destcaps);
2031 return TRUE;
2032 }
2033 /* it failed, so we release the request pads */
2034 if (srcpad) {
2035 gst_element_release_request_pad (src, srcpad);
2036 gst_object_unref (srcpad);
2037 }
2038 if (destpad) {
2039 gst_element_release_request_pad (dest, destpad);
2040 gst_object_unref (destpad);
2041 }
2042 }
2043 gst_caps_unref (srccaps);
2044 gst_caps_unref (destcaps);
2045 }
2046 }
2047 }
2048 srctempls = srctempls->next;
2049 }
2050 }
2051
2052 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no link possible from %s to %s",
2053 GST_ELEMENT_NAME (src), GST_ELEMENT_NAME (dest));
2054 return FALSE;
2055 }
2056
2057 /**
2058 * gst_element_link_pads:
2059 * @src: a #GstElement containing the source pad.
2060 * @srcpadname: (allow-none): the name of the #GstPad in source element
2061 * or %NULL for any pad.
2062 * @dest: (transfer none): the #GstElement containing the destination pad.
2063 * @destpadname: (allow-none): the name of the #GstPad in destination element,
2064 * or %NULL for any pad.
2065 *
2066 * Links the two named pads of the source and destination elements.
2067 * Side effect is that if one of the pads has no parent, it becomes a
2068 * child of the parent of the other element. If they have different
2069 * parents, the link fails.
2070 *
2071 * Returns: %TRUE if the pads could be linked, %FALSE otherwise.
2072 */
2073 gboolean
gst_element_link_pads(GstElement * src,const gchar * srcpadname,GstElement * dest,const gchar * destpadname)2074 gst_element_link_pads (GstElement * src, const gchar * srcpadname,
2075 GstElement * dest, const gchar * destpadname)
2076 {
2077 return gst_element_link_pads_full (src, srcpadname, dest, destpadname,
2078 GST_PAD_LINK_CHECK_DEFAULT);
2079 }
2080
2081 /**
2082 * gst_element_link_pads_filtered:
2083 * @src: a #GstElement containing the source pad.
2084 * @srcpadname: (allow-none): the name of the #GstPad in source element
2085 * or %NULL for any pad.
2086 * @dest: (transfer none): the #GstElement containing the destination pad.
2087 * @destpadname: (allow-none): the name of the #GstPad in destination element
2088 * or %NULL for any pad.
2089 * @filter: (transfer none) (allow-none): the #GstCaps to filter the link,
2090 * or %NULL for no filter.
2091 *
2092 * Links the two named pads of the source and destination elements. Side effect
2093 * is that if one of the pads has no parent, it becomes a child of the parent of
2094 * the other element. If they have different parents, the link fails. If @caps
2095 * is not %NULL, makes sure that the caps of the link is a subset of @caps.
2096 *
2097 * Returns: %TRUE if the pads could be linked, %FALSE otherwise.
2098 */
2099 gboolean
gst_element_link_pads_filtered(GstElement * src,const gchar * srcpadname,GstElement * dest,const gchar * destpadname,GstCaps * filter)2100 gst_element_link_pads_filtered (GstElement * src, const gchar * srcpadname,
2101 GstElement * dest, const gchar * destpadname, GstCaps * filter)
2102 {
2103 /* checks */
2104 g_return_val_if_fail (GST_IS_ELEMENT (src), FALSE);
2105 g_return_val_if_fail (GST_IS_ELEMENT (dest), FALSE);
2106 g_return_val_if_fail (filter == NULL || GST_IS_CAPS (filter), FALSE);
2107
2108 if (filter) {
2109 GstElement *capsfilter;
2110 GstObject *parent;
2111 GstState state, pending;
2112 gboolean lr1, lr2;
2113
2114 capsfilter = gst_element_factory_make ("capsfilter", NULL);
2115 if (!capsfilter) {
2116 GST_ERROR ("Could not make a capsfilter");
2117 return FALSE;
2118 }
2119
2120 parent = gst_object_get_parent (GST_OBJECT (src));
2121 g_return_val_if_fail (GST_IS_BIN (parent), FALSE);
2122
2123 gst_element_get_state (GST_ELEMENT_CAST (parent), &state, &pending, 0);
2124
2125 if (!gst_bin_add (GST_BIN (parent), capsfilter)) {
2126 GST_ERROR ("Could not add capsfilter");
2127 gst_object_unref (parent);
2128 return FALSE;
2129 }
2130
2131 if (pending != GST_STATE_VOID_PENDING)
2132 state = pending;
2133
2134 gst_element_set_state (capsfilter, state);
2135
2136 gst_object_unref (parent);
2137
2138 g_object_set (capsfilter, "caps", filter, NULL);
2139
2140 lr1 = gst_element_link_pads (src, srcpadname, capsfilter, "sink");
2141 lr2 = gst_element_link_pads (capsfilter, "src", dest, destpadname);
2142 if (lr1 && lr2) {
2143 return TRUE;
2144 } else {
2145 if (!lr1) {
2146 GST_INFO ("Could not link pads: %s:%s - capsfilter:sink",
2147 GST_ELEMENT_NAME (src), srcpadname);
2148 } else {
2149 GST_INFO ("Could not link pads: capsfilter:src - %s:%s",
2150 GST_ELEMENT_NAME (dest), destpadname);
2151 }
2152 gst_element_set_state (capsfilter, GST_STATE_NULL);
2153 /* this will unlink and unref as appropriate */
2154 gst_bin_remove (GST_BIN (GST_OBJECT_PARENT (capsfilter)), capsfilter);
2155 return FALSE;
2156 }
2157 } else {
2158 if (gst_element_link_pads (src, srcpadname, dest, destpadname)) {
2159 return TRUE;
2160 } else {
2161 GST_INFO ("Could not link pads: %s:%s - %s:%s", GST_ELEMENT_NAME (src),
2162 srcpadname, GST_ELEMENT_NAME (dest), destpadname);
2163 return FALSE;
2164 }
2165 }
2166 }
2167
2168 /**
2169 * gst_element_link:
2170 * @src: (transfer none): a #GstElement containing the source pad.
2171 * @dest: (transfer none): the #GstElement containing the destination pad.
2172 *
2173 * Links @src to @dest. The link must be from source to
2174 * destination; the other direction will not be tried. The function looks for
2175 * existing pads that aren't linked yet. It will request new pads if necessary.
2176 * Such pads need to be released manually when unlinking.
2177 * If multiple links are possible, only one is established.
2178 *
2179 * Make sure you have added your elements to a bin or pipeline with
2180 * gst_bin_add() before trying to link them.
2181 *
2182 * Returns: %TRUE if the elements could be linked, %FALSE otherwise.
2183 */
2184 gboolean
gst_element_link(GstElement * src,GstElement * dest)2185 gst_element_link (GstElement * src, GstElement * dest)
2186 {
2187 return gst_element_link_pads (src, NULL, dest, NULL);
2188 }
2189
2190 /**
2191 * gst_element_link_many:
2192 * @element_1: (transfer none): the first #GstElement in the link chain.
2193 * @element_2: (transfer none): the second #GstElement in the link chain.
2194 * @...: the %NULL-terminated list of elements to link in order.
2195 *
2196 * Chain together a series of elements. Uses gst_element_link().
2197 * Make sure you have added your elements to a bin or pipeline with
2198 * gst_bin_add() before trying to link them.
2199 *
2200 * Returns: %TRUE on success, %FALSE otherwise.
2201 */
2202 gboolean
gst_element_link_many(GstElement * element_1,GstElement * element_2,...)2203 gst_element_link_many (GstElement * element_1, GstElement * element_2, ...)
2204 {
2205 gboolean res = TRUE;
2206 va_list args;
2207
2208 g_return_val_if_fail (GST_IS_ELEMENT (element_1), FALSE);
2209 g_return_val_if_fail (GST_IS_ELEMENT (element_2), FALSE);
2210
2211 va_start (args, element_2);
2212
2213 while (element_2) {
2214 if (!gst_element_link (element_1, element_2)) {
2215 res = FALSE;
2216 break;
2217 }
2218
2219 element_1 = element_2;
2220 element_2 = va_arg (args, GstElement *);
2221 }
2222
2223 va_end (args);
2224
2225 return res;
2226 }
2227
2228 /**
2229 * gst_element_link_filtered:
2230 * @src: a #GstElement containing the source pad.
2231 * @dest: (transfer none): the #GstElement containing the destination pad.
2232 * @filter: (transfer none) (allow-none): the #GstCaps to filter the link,
2233 * or %NULL for no filter.
2234 *
2235 * Links @src to @dest using the given caps as filtercaps.
2236 * The link must be from source to
2237 * destination; the other direction will not be tried. The function looks for
2238 * existing pads that aren't linked yet. It will request new pads if necessary.
2239 * If multiple links are possible, only one is established.
2240 *
2241 * Make sure you have added your elements to a bin or pipeline with
2242 * gst_bin_add() before trying to link them.
2243 *
2244 * Returns: %TRUE if the pads could be linked, %FALSE otherwise.
2245 */
2246 gboolean
gst_element_link_filtered(GstElement * src,GstElement * dest,GstCaps * filter)2247 gst_element_link_filtered (GstElement * src, GstElement * dest,
2248 GstCaps * filter)
2249 {
2250 return gst_element_link_pads_filtered (src, NULL, dest, NULL, filter);
2251 }
2252
2253 /**
2254 * gst_element_unlink_pads:
2255 * @src: a (transfer none): #GstElement containing the source pad.
2256 * @srcpadname: the name of the #GstPad in source element.
2257 * @dest: (transfer none): a #GstElement containing the destination pad.
2258 * @destpadname: the name of the #GstPad in destination element.
2259 *
2260 * Unlinks the two named pads of the source and destination elements.
2261 *
2262 * This is a convenience function for gst_pad_unlink().
2263 */
2264 void
gst_element_unlink_pads(GstElement * src,const gchar * srcpadname,GstElement * dest,const gchar * destpadname)2265 gst_element_unlink_pads (GstElement * src, const gchar * srcpadname,
2266 GstElement * dest, const gchar * destpadname)
2267 {
2268 GstPad *srcpad, *destpad;
2269 gboolean srcrequest, destrequest;
2270
2271 srcrequest = destrequest = FALSE;
2272
2273 g_return_if_fail (src != NULL);
2274 g_return_if_fail (GST_IS_ELEMENT (src));
2275 g_return_if_fail (srcpadname != NULL);
2276 g_return_if_fail (dest != NULL);
2277 g_return_if_fail (GST_IS_ELEMENT (dest));
2278 g_return_if_fail (destpadname != NULL);
2279
2280 /* obtain the pads requested */
2281 if (!(srcpad = gst_element_get_static_pad (src, srcpadname)))
2282 if ((srcpad = gst_element_get_request_pad (src, srcpadname)))
2283 srcrequest = TRUE;
2284 if (srcpad == NULL) {
2285 GST_WARNING_OBJECT (src, "source element has no pad \"%s\"", srcpadname);
2286 return;
2287 }
2288 if (!(destpad = gst_element_get_static_pad (dest, destpadname)))
2289 if ((destpad = gst_element_get_request_pad (dest, destpadname)))
2290 destrequest = TRUE;
2291 if (destpad == NULL) {
2292 GST_WARNING_OBJECT (dest, "destination element has no pad \"%s\"",
2293 destpadname);
2294 goto free_src;
2295 }
2296
2297 /* we're satisfied they can be unlinked, let's do it */
2298 gst_pad_unlink (srcpad, destpad);
2299
2300 if (destrequest)
2301 gst_element_release_request_pad (dest, destpad);
2302 gst_object_unref (destpad);
2303
2304 free_src:
2305 if (srcrequest)
2306 gst_element_release_request_pad (src, srcpad);
2307 gst_object_unref (srcpad);
2308 }
2309
2310 /**
2311 * gst_element_unlink_many:
2312 * @element_1: (transfer none): the first #GstElement in the link chain.
2313 * @element_2: (transfer none): the second #GstElement in the link chain.
2314 * @...: the %NULL-terminated list of elements to unlink in order.
2315 *
2316 * Unlinks a series of elements. Uses gst_element_unlink().
2317 */
2318 void
gst_element_unlink_many(GstElement * element_1,GstElement * element_2,...)2319 gst_element_unlink_many (GstElement * element_1, GstElement * element_2, ...)
2320 {
2321 va_list args;
2322
2323 g_return_if_fail (element_1 != NULL && element_2 != NULL);
2324 g_return_if_fail (GST_IS_ELEMENT (element_1) && GST_IS_ELEMENT (element_2));
2325
2326 va_start (args, element_2);
2327
2328 while (element_2) {
2329 gst_element_unlink (element_1, element_2);
2330
2331 element_1 = element_2;
2332 element_2 = va_arg (args, GstElement *);
2333 }
2334
2335 va_end (args);
2336 }
2337
2338 /**
2339 * gst_element_unlink:
2340 * @src: (transfer none): the source #GstElement to unlink.
2341 * @dest: (transfer none): the sink #GstElement to unlink.
2342 *
2343 * Unlinks all source pads of the source element with all sink pads
2344 * of the sink element to which they are linked.
2345 *
2346 * If the link has been made using gst_element_link(), it could have created an
2347 * requestpad, which has to be released using gst_element_release_request_pad().
2348 */
2349 void
gst_element_unlink(GstElement * src,GstElement * dest)2350 gst_element_unlink (GstElement * src, GstElement * dest)
2351 {
2352 GstIterator *pads;
2353 gboolean done = FALSE;
2354 GValue data = { 0, };
2355
2356 g_return_if_fail (GST_IS_ELEMENT (src));
2357 g_return_if_fail (GST_IS_ELEMENT (dest));
2358
2359 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "unlinking \"%s\" and \"%s\"",
2360 GST_ELEMENT_NAME (src), GST_ELEMENT_NAME (dest));
2361
2362 pads = gst_element_iterate_pads (src);
2363 while (!done) {
2364 switch (gst_iterator_next (pads, &data)) {
2365 case GST_ITERATOR_OK:
2366 {
2367 GstPad *pad = g_value_get_object (&data);
2368
2369 if (GST_PAD_IS_SRC (pad)) {
2370 GstPad *peerpad = gst_pad_get_peer (pad);
2371
2372 /* see if the pad is linked and is really a pad of dest */
2373 if (peerpad) {
2374 GstElement *peerelem;
2375
2376 peerelem = gst_pad_get_parent_element (peerpad);
2377
2378 if (peerelem == dest) {
2379 gst_pad_unlink (pad, peerpad);
2380 }
2381 if (peerelem)
2382 gst_object_unref (peerelem);
2383
2384 gst_object_unref (peerpad);
2385 }
2386 }
2387 g_value_reset (&data);
2388 break;
2389 }
2390 case GST_ITERATOR_RESYNC:
2391 gst_iterator_resync (pads);
2392 break;
2393 case GST_ITERATOR_DONE:
2394 done = TRUE;
2395 break;
2396 default:
2397 g_assert_not_reached ();
2398 break;
2399 }
2400 }
2401 g_value_unset (&data);
2402 gst_iterator_free (pads);
2403 }
2404
2405 /**
2406 * gst_element_query_position:
2407 * @element: a #GstElement to invoke the position query on.
2408 * @format: the #GstFormat requested
2409 * @cur: (out) (allow-none): a location in which to store the current
2410 * position, or %NULL.
2411 *
2412 * Queries an element (usually top-level pipeline or playbin element) for the
2413 * stream position in nanoseconds. This will be a value between 0 and the
2414 * stream duration (if the stream duration is known). This query will usually
2415 * only work once the pipeline is prerolled (i.e. reached PAUSED or PLAYING
2416 * state). The application will receive an ASYNC_DONE message on the pipeline
2417 * bus when that is the case.
2418 *
2419 * If one repeatedly calls this function one can also create a query and reuse
2420 * it in gst_element_query().
2421 *
2422 * Returns: %TRUE if the query could be performed.
2423 */
2424 gboolean
gst_element_query_position(GstElement * element,GstFormat format,gint64 * cur)2425 gst_element_query_position (GstElement * element, GstFormat format,
2426 gint64 * cur)
2427 {
2428 GstQuery *query;
2429 gboolean ret;
2430
2431 if (cur != NULL)
2432 *cur = GST_CLOCK_TIME_NONE;
2433
2434 g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
2435 g_return_val_if_fail (format != GST_FORMAT_UNDEFINED, FALSE);
2436
2437 query = gst_query_new_position (format);
2438 ret = gst_element_query (element, query);
2439
2440 if (ret)
2441 gst_query_parse_position (query, NULL, cur);
2442
2443 gst_query_unref (query);
2444
2445 return ret;
2446 }
2447
2448 /**
2449 * gst_element_query_duration:
2450 * @element: a #GstElement to invoke the duration query on.
2451 * @format: the #GstFormat requested
2452 * @duration: (out) (allow-none): A location in which to store the total duration, or %NULL.
2453 *
2454 * Queries an element (usually top-level pipeline or playbin element) for the
2455 * total stream duration in nanoseconds. This query will only work once the
2456 * pipeline is prerolled (i.e. reached PAUSED or PLAYING state). The application
2457 * will receive an ASYNC_DONE message on the pipeline bus when that is the case.
2458 *
2459 * If the duration changes for some reason, you will get a DURATION_CHANGED
2460 * message on the pipeline bus, in which case you should re-query the duration
2461 * using this function.
2462 *
2463 * Returns: %TRUE if the query could be performed.
2464 */
2465 gboolean
gst_element_query_duration(GstElement * element,GstFormat format,gint64 * duration)2466 gst_element_query_duration (GstElement * element, GstFormat format,
2467 gint64 * duration)
2468 {
2469 GstQuery *query;
2470 gboolean ret;
2471
2472 if (duration != NULL)
2473 *duration = GST_CLOCK_TIME_NONE;
2474
2475 g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
2476 g_return_val_if_fail (format != GST_FORMAT_UNDEFINED, FALSE);
2477
2478 query = gst_query_new_duration (format);
2479 ret = gst_element_query (element, query);
2480
2481 if (ret)
2482 gst_query_parse_duration (query, NULL, duration);
2483
2484 gst_query_unref (query);
2485
2486 return ret;
2487 }
2488
2489 /**
2490 * gst_element_query_convert:
2491 * @element: a #GstElement to invoke the convert query on.
2492 * @src_format: a #GstFormat to convert from.
2493 * @src_val: a value to convert.
2494 * @dest_format: the #GstFormat to convert to.
2495 * @dest_val: (out): a pointer to the result.
2496 *
2497 * Queries an element to convert @src_val in @src_format to @dest_format.
2498 *
2499 * Returns: %TRUE if the query could be performed.
2500 */
2501 gboolean
gst_element_query_convert(GstElement * element,GstFormat src_format,gint64 src_val,GstFormat dest_format,gint64 * dest_val)2502 gst_element_query_convert (GstElement * element, GstFormat src_format,
2503 gint64 src_val, GstFormat dest_format, gint64 * dest_val)
2504 {
2505 GstQuery *query;
2506 gboolean ret;
2507
2508 g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
2509 g_return_val_if_fail (dest_format != GST_FORMAT_UNDEFINED, FALSE);
2510 g_return_val_if_fail (dest_val != NULL, FALSE);
2511
2512 if (dest_format == src_format || src_val == -1) {
2513 *dest_val = src_val;
2514 return TRUE;
2515 }
2516
2517 query = gst_query_new_convert (src_format, src_val, dest_format);
2518 ret = gst_element_query (element, query);
2519
2520 if (ret)
2521 gst_query_parse_convert (query, NULL, NULL, NULL, dest_val);
2522
2523 gst_query_unref (query);
2524
2525 return ret;
2526 }
2527
2528 /**
2529 * gst_element_seek_simple:
2530 * @element: a #GstElement to seek on
2531 * @format: a #GstFormat to execute the seek in, such as #GST_FORMAT_TIME
2532 * @seek_flags: seek options; playback applications will usually want to use
2533 * GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT here
2534 * @seek_pos: position to seek to (relative to the start); if you are doing
2535 * a seek in #GST_FORMAT_TIME this value is in nanoseconds -
2536 * multiply with #GST_SECOND to convert seconds to nanoseconds or
2537 * with #GST_MSECOND to convert milliseconds to nanoseconds.
2538 *
2539 * Simple API to perform a seek on the given element, meaning it just seeks
2540 * to the given position relative to the start of the stream. For more complex
2541 * operations like segment seeks (e.g. for looping) or changing the playback
2542 * rate or seeking relative to the last configured playback segment you should
2543 * use gst_element_seek().
2544 *
2545 * In a completely prerolled PAUSED or PLAYING pipeline, seeking is always
2546 * guaranteed to return %TRUE on a seekable media type or %FALSE when the media
2547 * type is certainly not seekable (such as a live stream).
2548 *
2549 * Some elements allow for seeking in the READY state, in this
2550 * case they will store the seek event and execute it when they are put to
2551 * PAUSED. If the element supports seek in READY, it will always return %TRUE when
2552 * it receives the event in the READY state.
2553 *
2554 * Returns: %TRUE if the seek operation succeeded. Flushing seeks will trigger a
2555 * preroll, which will emit %GST_MESSAGE_ASYNC_DONE.
2556 */
2557 gboolean
gst_element_seek_simple(GstElement * element,GstFormat format,GstSeekFlags seek_flags,gint64 seek_pos)2558 gst_element_seek_simple (GstElement * element, GstFormat format,
2559 GstSeekFlags seek_flags, gint64 seek_pos)
2560 {
2561 g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
2562 g_return_val_if_fail (seek_pos >= 0, FALSE);
2563
2564 return gst_element_seek (element, 1.0, format, seek_flags,
2565 GST_SEEK_TYPE_SET, seek_pos, GST_SEEK_TYPE_SET, GST_CLOCK_TIME_NONE);
2566 }
2567
2568 /**
2569 * gst_pad_use_fixed_caps:
2570 * @pad: the pad to use
2571 *
2572 * A helper function you can use that sets the FIXED_CAPS flag
2573 * This way the default CAPS query will always return the negotiated caps
2574 * or in case the pad is not negotiated, the padtemplate caps.
2575 *
2576 * The negotiated caps are the caps of the last CAPS event that passed on the
2577 * pad. Use this function on a pad that, once it negotiated to a CAPS, cannot
2578 * be renegotiated to something else.
2579 */
2580 void
gst_pad_use_fixed_caps(GstPad * pad)2581 gst_pad_use_fixed_caps (GstPad * pad)
2582 {
2583 GST_OBJECT_FLAG_SET (pad, GST_PAD_FLAG_FIXED_CAPS);
2584 }
2585
2586 /**
2587 * gst_pad_get_parent_element:
2588 * @pad: a pad
2589 *
2590 * Gets the parent of @pad, cast to a #GstElement. If a @pad has no parent or
2591 * its parent is not an element, return %NULL.
2592 *
2593 * Returns: (transfer full) (nullable): the parent of the pad. The
2594 * caller has a reference on the parent, so unref when you're finished
2595 * with it.
2596 *
2597 * MT safe.
2598 */
2599 GstElement *
gst_pad_get_parent_element(GstPad * pad)2600 gst_pad_get_parent_element (GstPad * pad)
2601 {
2602 GstObject *p;
2603
2604 g_return_val_if_fail (GST_IS_PAD (pad), NULL);
2605
2606 p = gst_object_get_parent (GST_OBJECT_CAST (pad));
2607
2608 if (p && !GST_IS_ELEMENT (p)) {
2609 gst_object_unref (p);
2610 p = NULL;
2611 }
2612 return GST_ELEMENT_CAST (p);
2613 }
2614
2615 /**
2616 * gst_object_default_error:
2617 * @source: the #GstObject that initiated the error.
2618 * @error: (in): the GError.
2619 * @debug: (in) (allow-none): an additional debug information string, or %NULL
2620 *
2621 * A default error function that uses g_printerr() to display the error message
2622 * and the optional debug string..
2623 *
2624 * The default handler will simply print the error string using g_print.
2625 */
2626 void
gst_object_default_error(GstObject * source,const GError * error,const gchar * debug)2627 gst_object_default_error (GstObject * source, const GError * error,
2628 const gchar * debug)
2629 {
2630 gchar *name = gst_object_get_path_string (source);
2631
2632 g_printerr (_("ERROR: from element %s: %s\n"), name, error->message);
2633 if (debug)
2634 g_printerr (_("Additional debug info:\n%s\n"), debug);
2635
2636 g_free (name);
2637 }
2638
2639 /**
2640 * gst_bin_add_many: (skip)
2641 * @bin: a #GstBin
2642 * @element_1: (transfer floating): the #GstElement element to add to the bin
2643 * @...: additional elements to add to the bin
2644 *
2645 * Adds a %NULL-terminated list of elements to a bin. This function is
2646 * equivalent to calling gst_bin_add() for each member of the list. The return
2647 * value of each gst_bin_add() is ignored.
2648 */
2649 void
gst_bin_add_many(GstBin * bin,GstElement * element_1,...)2650 gst_bin_add_many (GstBin * bin, GstElement * element_1, ...)
2651 {
2652 va_list args;
2653
2654 g_return_if_fail (GST_IS_BIN (bin));
2655 g_return_if_fail (GST_IS_ELEMENT (element_1));
2656
2657 va_start (args, element_1);
2658
2659 while (element_1) {
2660 gst_bin_add (bin, element_1);
2661
2662 element_1 = va_arg (args, GstElement *);
2663 }
2664
2665 va_end (args);
2666 }
2667
2668 /**
2669 * gst_bin_remove_many: (skip)
2670 * @bin: a #GstBin
2671 * @element_1: (transfer none): the first #GstElement to remove from the bin
2672 * @...: (transfer none): %NULL-terminated list of elements to remove from the bin
2673 *
2674 * Remove a list of elements from a bin. This function is equivalent
2675 * to calling gst_bin_remove() with each member of the list.
2676 */
2677 void
gst_bin_remove_many(GstBin * bin,GstElement * element_1,...)2678 gst_bin_remove_many (GstBin * bin, GstElement * element_1, ...)
2679 {
2680 va_list args;
2681
2682 g_return_if_fail (GST_IS_BIN (bin));
2683 g_return_if_fail (GST_IS_ELEMENT (element_1));
2684
2685 va_start (args, element_1);
2686
2687 while (element_1) {
2688 gst_bin_remove (bin, element_1);
2689
2690 element_1 = va_arg (args, GstElement *);
2691 }
2692
2693 va_end (args);
2694 }
2695
2696 typedef struct
2697 {
2698 GstQuery *query;
2699 gboolean ret;
2700 } QueryAcceptCapsData;
2701
2702 static gboolean
query_accept_caps_func(GstPad * pad,QueryAcceptCapsData * data)2703 query_accept_caps_func (GstPad * pad, QueryAcceptCapsData * data)
2704 {
2705 if (G_LIKELY (gst_pad_peer_query (pad, data->query))) {
2706 gboolean result;
2707
2708 gst_query_parse_accept_caps_result (data->query, &result);
2709 data->ret &= result;
2710 }
2711 return FALSE;
2712 }
2713
2714 /**
2715 * gst_pad_proxy_query_accept_caps:
2716 * @pad: a #GstPad to proxy.
2717 * @query: an ACCEPT_CAPS #GstQuery.
2718 *
2719 * Checks if all internally linked pads of @pad accepts the caps in @query and
2720 * returns the intersection of the results.
2721 *
2722 * This function is useful as a default accept caps query function for an element
2723 * that can handle any stream format, but requires caps that are acceptable for
2724 * all opposite pads.
2725 *
2726 * Returns: %TRUE if @query could be executed
2727 */
2728 gboolean
gst_pad_proxy_query_accept_caps(GstPad * pad,GstQuery * query)2729 gst_pad_proxy_query_accept_caps (GstPad * pad, GstQuery * query)
2730 {
2731 QueryAcceptCapsData data;
2732
2733 g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2734 g_return_val_if_fail (GST_IS_QUERY (query), FALSE);
2735 g_return_val_if_fail (GST_QUERY_TYPE (query) == GST_QUERY_ACCEPT_CAPS, FALSE);
2736
2737 GST_CAT_DEBUG_OBJECT (GST_CAT_PADS, pad,
2738 "proxying accept caps query for %s:%s", GST_DEBUG_PAD_NAME (pad));
2739
2740 data.query = query;
2741 /* value to hold the return, by default it holds TRUE */
2742 /* FIXME: TRUE is wrong when there are no pads */
2743 data.ret = TRUE;
2744
2745 gst_pad_forward (pad, (GstPadForwardFunction) query_accept_caps_func, &data);
2746 gst_query_set_accept_caps_result (query, data.ret);
2747
2748 GST_CAT_DEBUG_OBJECT (GST_CAT_PADS, pad, "proxying accept caps query: %d",
2749 data.ret);
2750
2751 return data.ret;
2752 }
2753
2754 typedef struct
2755 {
2756 GstQuery *query;
2757 GstCaps *ret;
2758 } QueryCapsData;
2759
2760 static gboolean
query_caps_func(GstPad * pad,QueryCapsData * data)2761 query_caps_func (GstPad * pad, QueryCapsData * data)
2762 {
2763 gboolean empty = FALSE;
2764
2765 if (G_LIKELY (gst_pad_peer_query (pad, data->query))) {
2766 GstCaps *peercaps, *intersection;
2767
2768 gst_query_parse_caps_result (data->query, &peercaps);
2769 GST_DEBUG_OBJECT (pad, "intersect with result %" GST_PTR_FORMAT, peercaps);
2770 intersection = gst_caps_intersect (data->ret, peercaps);
2771 GST_DEBUG_OBJECT (pad, "intersected %" GST_PTR_FORMAT, intersection);
2772
2773 gst_caps_unref (data->ret);
2774 data->ret = intersection;
2775
2776 /* stop when empty */
2777 empty = gst_caps_is_empty (intersection);
2778 }
2779 return empty;
2780 }
2781
2782 /**
2783 * gst_pad_proxy_query_caps:
2784 * @pad: a #GstPad to proxy.
2785 * @query: a CAPS #GstQuery.
2786 *
2787 * Calls gst_pad_query_caps() for all internally linked pads of @pad and returns
2788 * the intersection of the results.
2789 *
2790 * This function is useful as a default caps query function for an element
2791 * that can handle any stream format, but requires all its pads to have
2792 * the same caps. Two such elements are tee and adder.
2793 *
2794 * Returns: %TRUE if @query could be executed
2795 */
2796 gboolean
gst_pad_proxy_query_caps(GstPad * pad,GstQuery * query)2797 gst_pad_proxy_query_caps (GstPad * pad, GstQuery * query)
2798 {
2799 GstCaps *filter, *templ, *result;
2800 QueryCapsData data;
2801
2802 g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2803 g_return_val_if_fail (GST_IS_QUERY (query), FALSE);
2804 g_return_val_if_fail (GST_QUERY_TYPE (query) == GST_QUERY_CAPS, FALSE);
2805
2806 GST_CAT_DEBUG_OBJECT (GST_CAT_PADS, pad, "proxying caps query for %s:%s",
2807 GST_DEBUG_PAD_NAME (pad));
2808
2809 data.query = query;
2810
2811 /* value to hold the return, by default it holds the filter or ANY */
2812 gst_query_parse_caps (query, &filter);
2813 data.ret = filter ? gst_caps_ref (filter) : gst_caps_new_any ();
2814
2815 gst_pad_forward (pad, (GstPadForwardFunction) query_caps_func, &data);
2816
2817 templ = gst_pad_get_pad_template_caps (pad);
2818 result = gst_caps_intersect (data.ret, templ);
2819 gst_caps_unref (data.ret);
2820 gst_caps_unref (templ);
2821
2822 gst_query_set_caps_result (query, result);
2823 gst_caps_unref (result);
2824
2825 /* FIXME: return something depending on the processing */
2826 return TRUE;
2827 }
2828
2829 /**
2830 * gst_pad_query_position:
2831 * @pad: a #GstPad to invoke the position query on.
2832 * @format: the #GstFormat requested
2833 * @cur: (out) (allow-none): A location in which to store the current position, or %NULL.
2834 *
2835 * Queries a pad for the stream position.
2836 *
2837 * Returns: %TRUE if the query could be performed.
2838 */
2839 gboolean
gst_pad_query_position(GstPad * pad,GstFormat format,gint64 * cur)2840 gst_pad_query_position (GstPad * pad, GstFormat format, gint64 * cur)
2841 {
2842 GstQuery *query;
2843 gboolean ret;
2844
2845 if (cur != NULL)
2846 *cur = GST_CLOCK_TIME_NONE;
2847
2848 g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2849 g_return_val_if_fail (format != GST_FORMAT_UNDEFINED, FALSE);
2850
2851 query = gst_query_new_position (format);
2852 if ((ret = gst_pad_query (pad, query)))
2853 gst_query_parse_position (query, NULL, cur);
2854 gst_query_unref (query);
2855
2856 return ret;
2857 }
2858
2859 /**
2860 * gst_pad_peer_query_position:
2861 * @pad: a #GstPad on whose peer to invoke the position query on.
2862 * Must be a sink pad.
2863 * @format: the #GstFormat requested
2864 * @cur: (out) (allow-none): a location in which to store the current
2865 * position, or %NULL.
2866 *
2867 * Queries the peer of a given sink pad for the stream position.
2868 *
2869 * Returns: %TRUE if the query could be performed.
2870 */
2871 gboolean
gst_pad_peer_query_position(GstPad * pad,GstFormat format,gint64 * cur)2872 gst_pad_peer_query_position (GstPad * pad, GstFormat format, gint64 * cur)
2873 {
2874 GstQuery *query;
2875 gboolean ret = FALSE;
2876
2877 if (cur != NULL)
2878 *cur = GST_CLOCK_TIME_NONE;
2879
2880 g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2881 g_return_val_if_fail (format != GST_FORMAT_UNDEFINED, FALSE);
2882
2883 query = gst_query_new_position (format);
2884 if ((ret = gst_pad_peer_query (pad, query)))
2885 gst_query_parse_position (query, NULL, cur);
2886 gst_query_unref (query);
2887
2888 return ret;
2889 }
2890
2891 /**
2892 * gst_pad_query_duration:
2893 * @pad: a #GstPad to invoke the duration query on.
2894 * @format: the #GstFormat requested
2895 * @duration: (out) (allow-none): a location in which to store the total
2896 * duration, or %NULL.
2897 *
2898 * Queries a pad for the total stream duration.
2899 *
2900 * Returns: %TRUE if the query could be performed.
2901 */
2902 gboolean
gst_pad_query_duration(GstPad * pad,GstFormat format,gint64 * duration)2903 gst_pad_query_duration (GstPad * pad, GstFormat format, gint64 * duration)
2904 {
2905 GstQuery *query;
2906 gboolean ret;
2907
2908 if (duration != NULL)
2909 *duration = GST_CLOCK_TIME_NONE;
2910
2911 g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2912 g_return_val_if_fail (format != GST_FORMAT_UNDEFINED, FALSE);
2913
2914 query = gst_query_new_duration (format);
2915 if ((ret = gst_pad_query (pad, query)))
2916 gst_query_parse_duration (query, NULL, duration);
2917 gst_query_unref (query);
2918
2919 return ret;
2920 }
2921
2922 /**
2923 * gst_pad_peer_query_duration:
2924 * @pad: a #GstPad on whose peer pad to invoke the duration query on.
2925 * Must be a sink pad.
2926 * @format: the #GstFormat requested
2927 * @duration: (out) (allow-none): a location in which to store the total
2928 * duration, or %NULL.
2929 *
2930 * Queries the peer pad of a given sink pad for the total stream duration.
2931 *
2932 * Returns: %TRUE if the query could be performed.
2933 */
2934 gboolean
gst_pad_peer_query_duration(GstPad * pad,GstFormat format,gint64 * duration)2935 gst_pad_peer_query_duration (GstPad * pad, GstFormat format, gint64 * duration)
2936 {
2937 GstQuery *query;
2938 gboolean ret = FALSE;
2939
2940 if (duration != NULL)
2941 *duration = GST_CLOCK_TIME_NONE;
2942
2943 g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2944 g_return_val_if_fail (GST_PAD_IS_SINK (pad), FALSE);
2945 g_return_val_if_fail (format != GST_FORMAT_UNDEFINED, FALSE);
2946
2947 query = gst_query_new_duration (format);
2948 if ((ret = gst_pad_peer_query (pad, query)))
2949 gst_query_parse_duration (query, NULL, duration);
2950 gst_query_unref (query);
2951
2952 return ret;
2953 }
2954
2955 /**
2956 * gst_pad_query_convert:
2957 * @pad: a #GstPad to invoke the convert query on.
2958 * @src_format: a #GstFormat to convert from.
2959 * @src_val: a value to convert.
2960 * @dest_format: the #GstFormat to convert to.
2961 * @dest_val: (out): a pointer to the result.
2962 *
2963 * Queries a pad to convert @src_val in @src_format to @dest_format.
2964 *
2965 * Returns: %TRUE if the query could be performed.
2966 */
2967 gboolean
gst_pad_query_convert(GstPad * pad,GstFormat src_format,gint64 src_val,GstFormat dest_format,gint64 * dest_val)2968 gst_pad_query_convert (GstPad * pad, GstFormat src_format, gint64 src_val,
2969 GstFormat dest_format, gint64 * dest_val)
2970 {
2971 GstQuery *query;
2972 gboolean ret;
2973
2974 g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2975 g_return_val_if_fail (dest_format != GST_FORMAT_UNDEFINED, FALSE);
2976 g_return_val_if_fail (dest_val != NULL, FALSE);
2977
2978 if (dest_format == src_format || src_val == -1) {
2979 *dest_val = src_val;
2980 return TRUE;
2981 }
2982
2983 query = gst_query_new_convert (src_format, src_val, dest_format);
2984 if ((ret = gst_pad_query (pad, query)))
2985 gst_query_parse_convert (query, NULL, NULL, NULL, dest_val);
2986 gst_query_unref (query);
2987
2988 return ret;
2989 }
2990
2991 /**
2992 * gst_pad_peer_query_convert:
2993 * @pad: a #GstPad, on whose peer pad to invoke the convert query on.
2994 * Must be a sink pad.
2995 * @src_format: a #GstFormat to convert from.
2996 * @src_val: a value to convert.
2997 * @dest_format: the #GstFormat to convert to.
2998 * @dest_val: (out): a pointer to the result.
2999 *
3000 * Queries the peer pad of a given sink pad to convert @src_val in @src_format
3001 * to @dest_format.
3002 *
3003 * Returns: %TRUE if the query could be performed.
3004 */
3005 gboolean
gst_pad_peer_query_convert(GstPad * pad,GstFormat src_format,gint64 src_val,GstFormat dest_format,gint64 * dest_val)3006 gst_pad_peer_query_convert (GstPad * pad, GstFormat src_format, gint64 src_val,
3007 GstFormat dest_format, gint64 * dest_val)
3008 {
3009 GstQuery *query;
3010 gboolean ret = FALSE;
3011
3012 g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
3013 g_return_val_if_fail (GST_PAD_IS_SINK (pad), FALSE);
3014 g_return_val_if_fail (dest_format != GST_FORMAT_UNDEFINED, FALSE);
3015 g_return_val_if_fail (dest_val != NULL, FALSE);
3016
3017 query = gst_query_new_convert (src_format, src_val, dest_format);
3018 if ((ret = gst_pad_peer_query (pad, query)))
3019 gst_query_parse_convert (query, NULL, NULL, NULL, dest_val);
3020 gst_query_unref (query);
3021
3022 return ret;
3023 }
3024
3025 /**
3026 * gst_pad_query_caps:
3027 * @pad: a #GstPad to get the capabilities of.
3028 * @filter: (allow-none): suggested #GstCaps, or %NULL
3029 *
3030 * Gets the capabilities this pad can produce or consume.
3031 * Note that this method doesn't necessarily return the caps set by sending a
3032 * gst_event_new_caps() - use gst_pad_get_current_caps() for that instead.
3033 * gst_pad_query_caps returns all possible caps a pad can operate with, using
3034 * the pad's CAPS query function, If the query fails, this function will return
3035 * @filter, if not %NULL, otherwise ANY.
3036 *
3037 * When called on sinkpads @filter contains the caps that
3038 * upstream could produce in the order preferred by upstream. When
3039 * called on srcpads @filter contains the caps accepted by
3040 * downstream in the preferred order. @filter might be %NULL but
3041 * if it is not %NULL the returned caps will be a subset of @filter.
3042 *
3043 * Note that this function does not return writable #GstCaps, use
3044 * gst_caps_make_writable() before modifying the caps.
3045 *
3046 * Returns: (transfer full): the caps of the pad with incremented ref-count.
3047 */
3048 GstCaps *
gst_pad_query_caps(GstPad * pad,GstCaps * filter)3049 gst_pad_query_caps (GstPad * pad, GstCaps * filter)
3050 {
3051 GstCaps *result = NULL;
3052 GstQuery *query;
3053
3054 g_return_val_if_fail (GST_IS_PAD (pad), NULL);
3055 g_return_val_if_fail (filter == NULL || GST_IS_CAPS (filter), NULL);
3056
3057 GST_CAT_DEBUG_OBJECT (GST_CAT_CAPS, pad,
3058 "get pad caps with filter %" GST_PTR_FORMAT, filter);
3059
3060 query = gst_query_new_caps (filter);
3061 if (gst_pad_query (pad, query)) {
3062 gst_query_parse_caps_result (query, &result);
3063 gst_caps_ref (result);
3064 GST_CAT_DEBUG_OBJECT (GST_CAT_CAPS, pad,
3065 "query returned %" GST_PTR_FORMAT, result);
3066 } else if (filter) {
3067 result = gst_caps_ref (filter);
3068 } else {
3069 result = gst_caps_new_any ();
3070 }
3071 gst_query_unref (query);
3072
3073 return result;
3074 }
3075
3076 /**
3077 * gst_pad_peer_query_caps:
3078 * @pad: a #GstPad to get the capabilities of.
3079 * @filter: (allow-none): a #GstCaps filter, or %NULL.
3080 *
3081 * Gets the capabilities of the peer connected to this pad. Similar to
3082 * gst_pad_query_caps().
3083 *
3084 * When called on srcpads @filter contains the caps that
3085 * upstream could produce in the order preferred by upstream. When
3086 * called on sinkpads @filter contains the caps accepted by
3087 * downstream in the preferred order. @filter might be %NULL but
3088 * if it is not %NULL the returned caps will be a subset of @filter.
3089 *
3090 * Returns: (transfer full): the caps of the peer pad with incremented
3091 * ref-count. When there is no peer pad, this function returns @filter or,
3092 * when @filter is %NULL, ANY caps.
3093 */
3094 GstCaps *
gst_pad_peer_query_caps(GstPad * pad,GstCaps * filter)3095 gst_pad_peer_query_caps (GstPad * pad, GstCaps * filter)
3096 {
3097 GstCaps *result = NULL;
3098 GstQuery *query;
3099
3100 g_return_val_if_fail (GST_IS_PAD (pad), NULL);
3101 g_return_val_if_fail (filter == NULL || GST_IS_CAPS (filter), NULL);
3102
3103 GST_CAT_DEBUG_OBJECT (GST_CAT_CAPS, pad,
3104 "get pad peer caps with filter %" GST_PTR_FORMAT, filter);
3105
3106 query = gst_query_new_caps (filter);
3107 if (gst_pad_peer_query (pad, query)) {
3108 gst_query_parse_caps_result (query, &result);
3109 gst_caps_ref (result);
3110 GST_CAT_DEBUG_OBJECT (GST_CAT_CAPS, pad,
3111 "peer query returned %" GST_PTR_FORMAT, result);
3112 } else if (filter) {
3113 result = gst_caps_ref (filter);
3114 } else {
3115 result = gst_caps_new_any ();
3116 }
3117 gst_query_unref (query);
3118
3119 return result;
3120 }
3121
3122 /**
3123 * gst_pad_query_accept_caps:
3124 * @pad: a #GstPad to check
3125 * @caps: a #GstCaps to check on the pad
3126 *
3127 * Check if the given pad accepts the caps.
3128 *
3129 * Returns: %TRUE if the pad can accept the caps.
3130 */
3131 gboolean
gst_pad_query_accept_caps(GstPad * pad,GstCaps * caps)3132 gst_pad_query_accept_caps (GstPad * pad, GstCaps * caps)
3133 {
3134 gboolean res = TRUE;
3135 GstQuery *query;
3136
3137 g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
3138 g_return_val_if_fail (GST_IS_CAPS (caps), FALSE);
3139
3140 GST_CAT_DEBUG_OBJECT (GST_CAT_CAPS, pad, "accept caps of %"
3141 GST_PTR_FORMAT, caps);
3142
3143 query = gst_query_new_accept_caps (caps);
3144 if (gst_pad_query (pad, query)) {
3145 gst_query_parse_accept_caps_result (query, &res);
3146 GST_DEBUG_OBJECT (pad, "query returned %d", res);
3147 }
3148 gst_query_unref (query);
3149
3150 return res;
3151 }
3152
3153 /**
3154 * gst_pad_peer_query_accept_caps:
3155 * @pad: a #GstPad to check the peer of
3156 * @caps: a #GstCaps to check on the pad
3157 *
3158 * Check if the peer of @pad accepts @caps. If @pad has no peer, this function
3159 * returns %TRUE.
3160 *
3161 * Returns: %TRUE if the peer of @pad can accept the caps or @pad has no peer.
3162 */
3163 gboolean
gst_pad_peer_query_accept_caps(GstPad * pad,GstCaps * caps)3164 gst_pad_peer_query_accept_caps (GstPad * pad, GstCaps * caps)
3165 {
3166 gboolean res = TRUE;
3167 GstQuery *query;
3168
3169 g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
3170 g_return_val_if_fail (GST_IS_CAPS (caps), FALSE);
3171
3172 query = gst_query_new_accept_caps (caps);
3173 if (gst_pad_peer_query (pad, query)) {
3174 gst_query_parse_accept_caps_result (query, &res);
3175 GST_DEBUG_OBJECT (pad, "query returned %d", res);
3176 }
3177 gst_query_unref (query);
3178
3179 return res;
3180 }
3181
3182 static GstPad *
element_find_unlinked_pad(GstElement * element,GstPadDirection direction)3183 element_find_unlinked_pad (GstElement * element, GstPadDirection direction)
3184 {
3185 GstIterator *iter;
3186 GstPad *unlinked_pad = NULL;
3187 gboolean done;
3188 GValue data = { 0, };
3189
3190 switch (direction) {
3191 case GST_PAD_SRC:
3192 iter = gst_element_iterate_src_pads (element);
3193 break;
3194 case GST_PAD_SINK:
3195 iter = gst_element_iterate_sink_pads (element);
3196 break;
3197 default:
3198 g_return_val_if_reached (NULL);
3199 }
3200
3201 done = FALSE;
3202 while (!done) {
3203 switch (gst_iterator_next (iter, &data)) {
3204 case GST_ITERATOR_OK:{
3205 GstPad *peer;
3206 GstPad *pad = g_value_get_object (&data);
3207
3208 GST_CAT_LOG (GST_CAT_ELEMENT_PADS, "examining pad %s:%s",
3209 GST_DEBUG_PAD_NAME (pad));
3210
3211 peer = gst_pad_get_peer (pad);
3212 if (peer == NULL) {
3213 unlinked_pad = gst_object_ref (pad);
3214 done = TRUE;
3215 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
3216 "found existing unlinked pad %s:%s",
3217 GST_DEBUG_PAD_NAME (unlinked_pad));
3218 } else {
3219 gst_object_unref (peer);
3220 }
3221 g_value_reset (&data);
3222 break;
3223 }
3224 case GST_ITERATOR_DONE:
3225 done = TRUE;
3226 break;
3227 case GST_ITERATOR_RESYNC:
3228 gst_iterator_resync (iter);
3229 break;
3230 case GST_ITERATOR_ERROR:
3231 g_return_val_if_reached (NULL);
3232 break;
3233 }
3234 }
3235 g_value_unset (&data);
3236 gst_iterator_free (iter);
3237
3238 return unlinked_pad;
3239 }
3240
3241 /**
3242 * gst_bin_find_unlinked_pad:
3243 * @bin: bin in which to look for elements with unlinked pads
3244 * @direction: whether to look for an unlinked source or sink pad
3245 *
3246 * Recursively looks for elements with an unlinked pad of the given
3247 * direction within the specified bin and returns an unlinked pad
3248 * if one is found, or %NULL otherwise. If a pad is found, the caller
3249 * owns a reference to it and should use gst_object_unref() on the
3250 * pad when it is not needed any longer.
3251 *
3252 * Returns: (transfer full) (nullable): unlinked pad of the given
3253 * direction, %NULL.
3254 */
3255 GstPad *
gst_bin_find_unlinked_pad(GstBin * bin,GstPadDirection direction)3256 gst_bin_find_unlinked_pad (GstBin * bin, GstPadDirection direction)
3257 {
3258 GstIterator *iter;
3259 gboolean done;
3260 GstPad *pad = NULL;
3261 GValue data = { 0, };
3262
3263 g_return_val_if_fail (GST_IS_BIN (bin), NULL);
3264 g_return_val_if_fail (direction != GST_PAD_UNKNOWN, NULL);
3265
3266 done = FALSE;
3267 iter = gst_bin_iterate_recurse (bin);
3268 while (!done) {
3269 switch (gst_iterator_next (iter, &data)) {
3270 case GST_ITERATOR_OK:{
3271 GstElement *element = g_value_get_object (&data);
3272
3273 pad = element_find_unlinked_pad (element, direction);
3274 if (pad != NULL)
3275 done = TRUE;
3276 g_value_reset (&data);
3277 break;
3278 }
3279 case GST_ITERATOR_DONE:
3280 done = TRUE;
3281 break;
3282 case GST_ITERATOR_RESYNC:
3283 gst_iterator_resync (iter);
3284 break;
3285 case GST_ITERATOR_ERROR:
3286 g_return_val_if_reached (NULL);
3287 break;
3288 }
3289 }
3290 g_value_unset (&data);
3291 gst_iterator_free (iter);
3292
3293 return pad;
3294 }
3295
3296 static void
gst_bin_sync_children_states_foreach(const GValue * value,gpointer user_data)3297 gst_bin_sync_children_states_foreach (const GValue * value, gpointer user_data)
3298 {
3299 gboolean *success = user_data;
3300 GstElement *element = g_value_get_object (value);
3301
3302 if (gst_element_is_locked_state (element)) {
3303 *success = TRUE;
3304 } else {
3305 *success = *success && gst_element_sync_state_with_parent (element);
3306
3307 if (GST_IS_BIN (element))
3308 *success = *success
3309 && gst_bin_sync_children_states (GST_BIN_CAST (element));
3310 }
3311 }
3312
3313 /**
3314 * gst_bin_sync_children_states:
3315 * @bin: a #GstBin
3316 *
3317 * Synchronizes the state of every child of @bin with the state
3318 * of @bin. See also gst_element_sync_state_with_parent().
3319 *
3320 * Returns: %TRUE if syncing the state was successful for all children,
3321 * otherwise %FALSE.
3322 *
3323 * Since: 1.6
3324 */
3325 gboolean
gst_bin_sync_children_states(GstBin * bin)3326 gst_bin_sync_children_states (GstBin * bin)
3327 {
3328 GstIterator *it;
3329 GstIteratorResult res = GST_ITERATOR_OK;
3330 gboolean success = TRUE;
3331
3332 it = gst_bin_iterate_sorted (bin);
3333
3334 do {
3335 if (res == GST_ITERATOR_RESYNC) {
3336 success = TRUE;
3337 gst_iterator_resync (it);
3338 }
3339 res =
3340 gst_iterator_foreach (it, gst_bin_sync_children_states_foreach,
3341 &success);
3342 } while (res == GST_ITERATOR_RESYNC);
3343 gst_iterator_free (it);
3344
3345 return success;
3346 }
3347
3348 /**
3349 * gst_parse_bin_from_description:
3350 * @bin_description: command line describing the bin
3351 * @ghost_unlinked_pads: whether to automatically create ghost pads
3352 * for unlinked source or sink pads within the bin
3353 * @err: where to store the error message in case of an error, or %NULL
3354 *
3355 * This is a convenience wrapper around gst_parse_launch() to create a
3356 * #GstBin from a gst-launch-style pipeline description. See
3357 * gst_parse_launch() and the gst-launch man page for details about the
3358 * syntax. Ghost pads on the bin for unlinked source or sink pads
3359 * within the bin can automatically be created (but only a maximum of
3360 * one ghost pad for each direction will be created; if you expect
3361 * multiple unlinked source pads or multiple unlinked sink pads
3362 * and want them all ghosted, you will have to create the ghost pads
3363 * yourself).
3364 *
3365 * Returns: (transfer floating) (type Gst.Bin) (nullable): a
3366 * newly-created bin, or %NULL if an error occurred.
3367 */
3368 GstElement *
gst_parse_bin_from_description(const gchar * bin_description,gboolean ghost_unlinked_pads,GError ** err)3369 gst_parse_bin_from_description (const gchar * bin_description,
3370 gboolean ghost_unlinked_pads, GError ** err)
3371 {
3372 return gst_parse_bin_from_description_full (bin_description,
3373 ghost_unlinked_pads, NULL, GST_PARSE_FLAG_NONE, err);
3374 }
3375
3376 /**
3377 * gst_parse_bin_from_description_full:
3378 * @bin_description: command line describing the bin
3379 * @ghost_unlinked_pads: whether to automatically create ghost pads
3380 * for unlinked source or sink pads within the bin
3381 * @context: (transfer none) (allow-none): a parse context allocated with
3382 * gst_parse_context_new(), or %NULL
3383 * @flags: parsing options, or #GST_PARSE_FLAG_NONE
3384 * @err: where to store the error message in case of an error, or %NULL
3385 *
3386 * This is a convenience wrapper around gst_parse_launch() to create a
3387 * #GstBin from a gst-launch-style pipeline description. See
3388 * gst_parse_launch() and the gst-launch man page for details about the
3389 * syntax. Ghost pads on the bin for unlinked source or sink pads
3390 * within the bin can automatically be created (but only a maximum of
3391 * one ghost pad for each direction will be created; if you expect
3392 * multiple unlinked source pads or multiple unlinked sink pads
3393 * and want them all ghosted, you will have to create the ghost pads
3394 * yourself).
3395 *
3396 * Returns: (transfer floating) (type Gst.Element) (nullable): a newly-created
3397 * element, which is guaranteed to be a bin unless
3398 * GST_FLAG_NO_SINGLE_ELEMENT_BINS was passed, or %NULL if an error
3399 * occurred.
3400 */
3401 GstElement *
gst_parse_bin_from_description_full(const gchar * bin_description,gboolean ghost_unlinked_pads,GstParseContext * context,GstParseFlags flags,GError ** err)3402 gst_parse_bin_from_description_full (const gchar * bin_description,
3403 gboolean ghost_unlinked_pads, GstParseContext * context,
3404 GstParseFlags flags, GError ** err)
3405 {
3406 #ifndef GST_DISABLE_PARSE
3407 GstPad *pad = NULL;
3408 GstElement *element;
3409 GstBin *bin;
3410 gchar *desc;
3411
3412 g_return_val_if_fail (bin_description != NULL, NULL);
3413 g_return_val_if_fail (err == NULL || *err == NULL, NULL);
3414
3415 GST_DEBUG ("Making bin from description '%s'", bin_description);
3416
3417 /* parse the pipeline to a bin */
3418 if (flags & GST_PARSE_FLAG_NO_SINGLE_ELEMENT_BINS) {
3419 element = gst_parse_launch_full (bin_description, context, flags, err);
3420 } else {
3421 desc = g_strdup_printf ("bin.( %s )", bin_description);
3422 element = gst_parse_launch_full (desc, context, flags, err);
3423 g_free (desc);
3424 }
3425
3426 if (element == NULL || (err && *err != NULL)) {
3427 if (element)
3428 gst_object_unref (element);
3429 return NULL;
3430 }
3431
3432 if (GST_IS_BIN (element)) {
3433 bin = GST_BIN (element);
3434 } else {
3435 return element;
3436 }
3437
3438 /* find pads and ghost them if necessary */
3439 if (ghost_unlinked_pads) {
3440 if ((pad = gst_bin_find_unlinked_pad (bin, GST_PAD_SRC))) {
3441 gst_element_add_pad (GST_ELEMENT (bin), gst_ghost_pad_new ("src", pad));
3442 gst_object_unref (pad);
3443 }
3444 if ((pad = gst_bin_find_unlinked_pad (bin, GST_PAD_SINK))) {
3445 gst_element_add_pad (GST_ELEMENT (bin), gst_ghost_pad_new ("sink", pad));
3446 gst_object_unref (pad);
3447 }
3448 }
3449
3450 return GST_ELEMENT (bin);
3451 #else
3452 gchar *msg;
3453
3454 GST_WARNING ("Disabled API called");
3455
3456 msg = gst_error_get_message (GST_CORE_ERROR, GST_CORE_ERROR_DISABLED);
3457 g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_DISABLED, "%s", msg);
3458 g_free (msg);
3459
3460 return NULL;
3461 #endif
3462 }
3463
3464 /**
3465 * gst_util_get_timestamp:
3466 *
3467 * Get a timestamp as GstClockTime to be used for interval measurements.
3468 * The timestamp should not be interpreted in any other way.
3469 *
3470 * Returns: the timestamp
3471 */
3472 GstClockTime
gst_util_get_timestamp(void)3473 gst_util_get_timestamp (void)
3474 {
3475 #if defined (HAVE_POSIX_TIMERS) && defined(HAVE_MONOTONIC_CLOCK) &&\
3476 defined (HAVE_CLOCK_GETTIME)
3477 struct timespec now;
3478
3479 clock_gettime (CLOCK_MONOTONIC, &now);
3480 return GST_TIMESPEC_TO_TIME (now);
3481 #else
3482 return g_get_monotonic_time () * 1000;
3483 #endif
3484 }
3485
3486 /**
3487 * gst_util_array_binary_search:
3488 * @array: the sorted input array
3489 * @num_elements: number of elements in the array
3490 * @element_size: size of every element in bytes
3491 * @search_func: (scope call): function to compare two elements, @search_data will always be passed as second argument
3492 * @mode: search mode that should be used
3493 * @search_data: element that should be found
3494 * @user_data: (closure): data to pass to @search_func
3495 *
3496 * Searches inside @array for @search_data by using the comparison function
3497 * @search_func. @array must be sorted ascending.
3498 *
3499 * As @search_data is always passed as second argument to @search_func it's
3500 * not required that @search_data has the same type as the array elements.
3501 *
3502 * The complexity of this search function is O(log (num_elements)).
3503 *
3504 * Returns: (transfer none) (nullable): The address of the found
3505 * element or %NULL if nothing was found
3506 */
3507 gpointer
gst_util_array_binary_search(gpointer array,guint num_elements,gsize element_size,GCompareDataFunc search_func,GstSearchMode mode,gconstpointer search_data,gpointer user_data)3508 gst_util_array_binary_search (gpointer array, guint num_elements,
3509 gsize element_size, GCompareDataFunc search_func, GstSearchMode mode,
3510 gconstpointer search_data, gpointer user_data)
3511 {
3512 glong left = 0, right = num_elements - 1, m;
3513 gint ret;
3514 guint8 *data = (guint8 *) array;
3515
3516 g_return_val_if_fail (array != NULL, NULL);
3517 g_return_val_if_fail (element_size > 0, NULL);
3518 g_return_val_if_fail (search_func != NULL, NULL);
3519
3520 /* 0. No elements => return NULL */
3521 if (num_elements == 0)
3522 return NULL;
3523
3524 /* 1. If search_data is before the 0th element return the 0th element */
3525 ret = search_func (data, search_data, user_data);
3526 if ((ret >= 0 && mode == GST_SEARCH_MODE_AFTER) || ret == 0)
3527 return data;
3528 else if (ret > 0)
3529 return NULL;
3530
3531 /* 2. If search_data is after the last element return the last element */
3532 ret =
3533 search_func (data + (num_elements - 1) * element_size, search_data,
3534 user_data);
3535 if ((ret <= 0 && mode == GST_SEARCH_MODE_BEFORE) || ret == 0)
3536 return data + (num_elements - 1) * element_size;
3537 else if (ret < 0)
3538 return NULL;
3539
3540 /* 3. else binary search */
3541 while (TRUE) {
3542 m = left + (right - left) / 2;
3543
3544 ret = search_func (data + m * element_size, search_data, user_data);
3545
3546 if (ret == 0) {
3547 return data + m * element_size;
3548 } else if (ret < 0) {
3549 left = m + 1;
3550 } else {
3551 right = m - 1;
3552 }
3553
3554 /* No exact match found */
3555 if (right < left) {
3556 if (mode == GST_SEARCH_MODE_EXACT) {
3557 return NULL;
3558 } else if (mode == GST_SEARCH_MODE_AFTER) {
3559 if (ret < 0)
3560 return (m < num_elements) ? data + (m + 1) * element_size : NULL;
3561 else
3562 return data + m * element_size;
3563 } else {
3564 if (ret < 0)
3565 return data + m * element_size;
3566 else
3567 return (m > 0) ? data + (m - 1) * element_size : NULL;
3568 }
3569 }
3570 }
3571 }
3572
3573 /* Finds the greatest common divisor.
3574 * Returns 1 if none other found.
3575 * This is Euclid's algorithm. */
3576
3577 /**
3578 * gst_util_greatest_common_divisor:
3579 * @a: First value as #gint
3580 * @b: Second value as #gint
3581 *
3582 * Calculates the greatest common divisor of @a
3583 * and @b.
3584 *
3585 * Returns: Greatest common divisor of @a and @b
3586 */
3587 gint
gst_util_greatest_common_divisor(gint a,gint b)3588 gst_util_greatest_common_divisor (gint a, gint b)
3589 {
3590 while (b != 0) {
3591 int temp = a;
3592
3593 a = b;
3594 b = temp % b;
3595 }
3596
3597 return ABS (a);
3598 }
3599
3600 /**
3601 * gst_util_greatest_common_divisor_int64:
3602 * @a: First value as #gint64
3603 * @b: Second value as #gint64
3604 *
3605 * Calculates the greatest common divisor of @a
3606 * and @b.
3607 *
3608 * Returns: Greatest common divisor of @a and @b
3609 */
3610 gint64
gst_util_greatest_common_divisor_int64(gint64 a,gint64 b)3611 gst_util_greatest_common_divisor_int64 (gint64 a, gint64 b)
3612 {
3613 while (b != 0) {
3614 gint64 temp = a;
3615
3616 a = b;
3617 b = temp % b;
3618 }
3619
3620 return ABS (a);
3621 }
3622
3623
3624 /**
3625 * gst_util_fraction_to_double:
3626 * @src_n: Fraction numerator as #gint
3627 * @src_d: Fraction denominator #gint
3628 * @dest: (out): pointer to a #gdouble for the result
3629 *
3630 * Transforms a fraction to a #gdouble.
3631 */
3632 void
gst_util_fraction_to_double(gint src_n,gint src_d,gdouble * dest)3633 gst_util_fraction_to_double (gint src_n, gint src_d, gdouble * dest)
3634 {
3635 g_return_if_fail (dest != NULL);
3636 g_return_if_fail (src_d != 0);
3637
3638 *dest = ((gdouble) src_n) / ((gdouble) src_d);
3639 }
3640
3641 #define MAX_TERMS 30
3642 #define MIN_DIVISOR 1.0e-10
3643 #define MAX_ERROR 1.0e-20
3644
3645 /* use continued fractions to transform a double into a fraction,
3646 * see http://mathforum.org/dr.math/faq/faq.fractions.html#decfrac.
3647 * This algorithm takes care of overflows.
3648 */
3649
3650 /**
3651 * gst_util_double_to_fraction:
3652 * @src: #gdouble to transform
3653 * @dest_n: (out): pointer to a #gint to hold the result numerator
3654 * @dest_d: (out): pointer to a #gint to hold the result denominator
3655 *
3656 * Transforms a #gdouble to a fraction and simplifies
3657 * the result.
3658 */
3659 void
gst_util_double_to_fraction(gdouble src,gint * dest_n,gint * dest_d)3660 gst_util_double_to_fraction (gdouble src, gint * dest_n, gint * dest_d)
3661 {
3662
3663 gdouble V, F; /* double being converted */
3664 gint N, D; /* will contain the result */
3665 gint A; /* current term in continued fraction */
3666 gint64 N1, D1; /* numerator, denominator of last approx */
3667 gint64 N2, D2; /* numerator, denominator of previous approx */
3668 gint i;
3669 gint gcd;
3670 gboolean negative = FALSE;
3671
3672 g_return_if_fail (dest_n != NULL);
3673 g_return_if_fail (dest_d != NULL);
3674
3675 /* initialize fraction being converted */
3676 F = src;
3677 if (F < 0.0) {
3678 F = -F;
3679 negative = TRUE;
3680 }
3681
3682 V = F;
3683 /* initialize fractions with 1/0, 0/1 */
3684 N1 = 1;
3685 D1 = 0;
3686 N2 = 0;
3687 D2 = 1;
3688 N = 1;
3689 D = 1;
3690
3691 for (i = 0; i < MAX_TERMS; i++) {
3692 /* get next term */
3693 A = (gint) F; /* no floor() needed, F is always >= 0 */
3694 /* get new divisor */
3695 F = F - A;
3696
3697 /* calculate new fraction in temp */
3698 N2 = N1 * A + N2;
3699 D2 = D1 * A + D2;
3700
3701 /* guard against overflow */
3702 if (N2 > G_MAXINT || D2 > G_MAXINT) {
3703 break;
3704 }
3705
3706 N = N2;
3707 D = D2;
3708
3709 /* save last two fractions */
3710 N2 = N1;
3711 D2 = D1;
3712 N1 = N;
3713 D1 = D;
3714
3715 /* quit if dividing by zero or close enough to target */
3716 if (F < MIN_DIVISOR || fabs (V - ((gdouble) N) / D) < MAX_ERROR) {
3717 break;
3718 }
3719
3720 /* Take reciprocal */
3721 F = 1 / F;
3722 }
3723 /* fix for overflow */
3724 if (D == 0) {
3725 N = G_MAXINT;
3726 D = 1;
3727 }
3728 /* fix for negative */
3729 if (negative)
3730 N = -N;
3731
3732 /* simplify */
3733 gcd = gst_util_greatest_common_divisor (N, D);
3734 if (gcd) {
3735 N /= gcd;
3736 D /= gcd;
3737 }
3738
3739 /* set results */
3740 *dest_n = N;
3741 *dest_d = D;
3742 }
3743
3744 /**
3745 * gst_util_fraction_multiply:
3746 * @a_n: Numerator of first value
3747 * @a_d: Denominator of first value
3748 * @b_n: Numerator of second value
3749 * @b_d: Denominator of second value
3750 * @res_n: (out): Pointer to #gint to hold the result numerator
3751 * @res_d: (out): Pointer to #gint to hold the result denominator
3752 *
3753 * Multiplies the fractions @a_n/@a_d and @b_n/@b_d and stores
3754 * the result in @res_n and @res_d.
3755 *
3756 * Returns: %FALSE on overflow, %TRUE otherwise.
3757 */
3758 gboolean
gst_util_fraction_multiply(gint a_n,gint a_d,gint b_n,gint b_d,gint * res_n,gint * res_d)3759 gst_util_fraction_multiply (gint a_n, gint a_d, gint b_n, gint b_d,
3760 gint * res_n, gint * res_d)
3761 {
3762 gint gcd;
3763
3764 g_return_val_if_fail (res_n != NULL, FALSE);
3765 g_return_val_if_fail (res_d != NULL, FALSE);
3766 g_return_val_if_fail (a_d != 0, FALSE);
3767 g_return_val_if_fail (b_d != 0, FALSE);
3768
3769 /* early out if either is 0, as its gcd would be 0 */
3770 if (a_n == 0 || b_n == 0) {
3771 *res_n = 0;
3772 *res_d = 1;
3773 return TRUE;
3774 }
3775
3776 gcd = gst_util_greatest_common_divisor (a_n, a_d);
3777 a_n /= gcd;
3778 a_d /= gcd;
3779
3780 gcd = gst_util_greatest_common_divisor (b_n, b_d);
3781 b_n /= gcd;
3782 b_d /= gcd;
3783
3784 gcd = gst_util_greatest_common_divisor (a_n, b_d);
3785 a_n /= gcd;
3786 b_d /= gcd;
3787
3788 gcd = gst_util_greatest_common_divisor (a_d, b_n);
3789 a_d /= gcd;
3790 b_n /= gcd;
3791
3792 /* This would result in overflow */
3793 if (a_n != 0 && G_MAXINT / ABS (a_n) < ABS (b_n))
3794 return FALSE;
3795 if (G_MAXINT / ABS (a_d) < ABS (b_d))
3796 return FALSE;
3797
3798 *res_n = a_n * b_n;
3799 *res_d = a_d * b_d;
3800
3801 gcd = gst_util_greatest_common_divisor (*res_n, *res_d);
3802 *res_n /= gcd;
3803 *res_d /= gcd;
3804
3805 return TRUE;
3806 }
3807
3808 /**
3809 * gst_util_fraction_add:
3810 * @a_n: Numerator of first value
3811 * @a_d: Denominator of first value
3812 * @b_n: Numerator of second value
3813 * @b_d: Denominator of second value
3814 * @res_n: (out): Pointer to #gint to hold the result numerator
3815 * @res_d: (out): Pointer to #gint to hold the result denominator
3816 *
3817 * Adds the fractions @a_n/@a_d and @b_n/@b_d and stores
3818 * the result in @res_n and @res_d.
3819 *
3820 * Returns: %FALSE on overflow, %TRUE otherwise.
3821 */
3822 gboolean
gst_util_fraction_add(gint a_n,gint a_d,gint b_n,gint b_d,gint * res_n,gint * res_d)3823 gst_util_fraction_add (gint a_n, gint a_d, gint b_n, gint b_d, gint * res_n,
3824 gint * res_d)
3825 {
3826 gint gcd;
3827
3828 g_return_val_if_fail (res_n != NULL, FALSE);
3829 g_return_val_if_fail (res_d != NULL, FALSE);
3830 g_return_val_if_fail (a_d != 0, FALSE);
3831 g_return_val_if_fail (b_d != 0, FALSE);
3832
3833 gcd = gst_util_greatest_common_divisor (a_n, a_d);
3834 a_n /= gcd;
3835 a_d /= gcd;
3836
3837 gcd = gst_util_greatest_common_divisor (b_n, b_d);
3838 b_n /= gcd;
3839 b_d /= gcd;
3840
3841 if (a_n == 0) {
3842 *res_n = b_n;
3843 *res_d = b_d;
3844 return TRUE;
3845 }
3846 if (b_n == 0) {
3847 *res_n = a_n;
3848 *res_d = a_d;
3849 return TRUE;
3850 }
3851
3852 /* This would result in overflow */
3853 if (G_MAXINT / ABS (a_n) < ABS (b_n))
3854 return FALSE;
3855 if (G_MAXINT / ABS (a_d) < ABS (b_d))
3856 return FALSE;
3857
3858 *res_n = (a_n * b_d) + (a_d * b_n);
3859 *res_d = a_d * b_d;
3860
3861 gcd = gst_util_greatest_common_divisor (*res_n, *res_d);
3862 if (gcd) {
3863 *res_n /= gcd;
3864 *res_d /= gcd;
3865 } else {
3866 /* res_n == 0 */
3867 *res_d = 1;
3868 }
3869
3870 return TRUE;
3871 }
3872
3873 /**
3874 * gst_util_fraction_compare:
3875 * @a_n: Numerator of first value
3876 * @a_d: Denominator of first value
3877 * @b_n: Numerator of second value
3878 * @b_d: Denominator of second value
3879 *
3880 * Compares the fractions @a_n/@a_d and @b_n/@b_d and returns
3881 * -1 if a < b, 0 if a = b and 1 if a > b.
3882 *
3883 * Returns: -1 if a < b; 0 if a = b; 1 if a > b.
3884 */
3885 gint
gst_util_fraction_compare(gint a_n,gint a_d,gint b_n,gint b_d)3886 gst_util_fraction_compare (gint a_n, gint a_d, gint b_n, gint b_d)
3887 {
3888 gint64 new_num_1;
3889 gint64 new_num_2;
3890 gint gcd;
3891
3892 g_return_val_if_fail (a_d != 0 && b_d != 0, 0);
3893
3894 /* Simplify */
3895 gcd = gst_util_greatest_common_divisor (a_n, a_d);
3896 a_n /= gcd;
3897 a_d /= gcd;
3898
3899 gcd = gst_util_greatest_common_divisor (b_n, b_d);
3900 b_n /= gcd;
3901 b_d /= gcd;
3902
3903 /* fractions are reduced when set, so we can quickly see if they're equal */
3904 if (a_n == b_n && a_d == b_d)
3905 return 0;
3906
3907 /* extend to 64 bits */
3908 new_num_1 = ((gint64) a_n) * b_d;
3909 new_num_2 = ((gint64) b_n) * a_d;
3910 if (new_num_1 < new_num_2)
3911 return -1;
3912 if (new_num_1 > new_num_2)
3913 return 1;
3914
3915 /* Should not happen because a_d and b_d are not 0 */
3916 g_return_val_if_reached (0);
3917 }
3918
3919 static gchar *
gst_pad_create_stream_id_internal(GstPad * pad,GstElement * parent,const gchar * stream_id)3920 gst_pad_create_stream_id_internal (GstPad * pad, GstElement * parent,
3921 const gchar * stream_id)
3922 {
3923 GstEvent *upstream_event;
3924 gchar *upstream_stream_id = NULL, *new_stream_id;
3925 GstPad *sinkpad;
3926
3927 g_return_val_if_fail (GST_IS_PAD (pad), NULL);
3928 g_return_val_if_fail (GST_PAD_IS_SRC (pad), NULL);
3929 g_return_val_if_fail (GST_IS_ELEMENT (parent), NULL);
3930
3931 g_return_val_if_fail (parent->numsinkpads <= 1, NULL);
3932
3933 /* If the element has multiple source pads it must
3934 * provide a stream-id for every source pad, otherwise
3935 * all source pads will have the same and are not
3936 * distinguishable */
3937 g_return_val_if_fail (parent->numsrcpads <= 1 || stream_id, NULL);
3938
3939 /* First try to get the upstream stream-start stream-id from the sinkpad.
3940 * This will only work for non-source elements */
3941 sinkpad = gst_element_get_static_pad (parent, "sink");
3942 if (sinkpad) {
3943 upstream_event =
3944 gst_pad_get_sticky_event (sinkpad, GST_EVENT_STREAM_START, 0);
3945 if (upstream_event) {
3946 const gchar *tmp;
3947
3948 gst_event_parse_stream_start (upstream_event, &tmp);
3949 if (tmp)
3950 upstream_stream_id = g_strdup (tmp);
3951 gst_event_unref (upstream_event);
3952 }
3953 gst_object_unref (sinkpad);
3954 }
3955
3956 /* The only case where we don't have an upstream start-start event
3957 * here is for source elements */
3958 if (!upstream_stream_id) {
3959 GstQuery *query;
3960 gchar *uri = NULL;
3961
3962 /* Try to generate one from the URI query and
3963 * if it fails take a random number instead */
3964 query = gst_query_new_uri ();
3965 if (gst_element_query (parent, query)) {
3966 gst_query_parse_uri (query, &uri);
3967 }
3968
3969 if (uri) {
3970 GChecksum *cs;
3971
3972 /* And then generate an SHA256 sum of the URI */
3973 cs = g_checksum_new (G_CHECKSUM_SHA256);
3974 g_checksum_update (cs, (const guchar *) uri, strlen (uri));
3975 g_free (uri);
3976 upstream_stream_id = g_strdup (g_checksum_get_string (cs));
3977 g_checksum_free (cs);
3978 } else {
3979 /* Just get some random number if the URI query fails */
3980 GST_FIXME_OBJECT (pad, "Creating random stream-id, consider "
3981 "implementing a deterministic way of creating a stream-id");
3982 upstream_stream_id =
3983 g_strdup_printf ("%08x%08x%08x%08x", g_random_int (), g_random_int (),
3984 g_random_int (), g_random_int ());
3985 }
3986
3987 gst_query_unref (query);
3988 }
3989
3990 if (stream_id) {
3991 new_stream_id = g_strconcat (upstream_stream_id, "/", stream_id, NULL);
3992 } else {
3993 new_stream_id = g_strdup (upstream_stream_id);
3994 }
3995
3996 g_free (upstream_stream_id);
3997
3998 return new_stream_id;
3999 }
4000
4001 /**
4002 * gst_pad_create_stream_id_printf_valist:
4003 * @pad: A source #GstPad
4004 * @parent: Parent #GstElement of @pad
4005 * @stream_id: (allow-none): The stream-id
4006 * @var_args: parameters for the @stream_id format string
4007 *
4008 * Creates a stream-id for the source #GstPad @pad by combining the
4009 * upstream information with the optional @stream_id of the stream
4010 * of @pad. @pad must have a parent #GstElement and which must have zero
4011 * or one sinkpad. @stream_id can only be %NULL if the parent element
4012 * of @pad has only a single source pad.
4013 *
4014 * This function generates an unique stream-id by getting the upstream
4015 * stream-start event stream ID and appending @stream_id to it. If the
4016 * element has no sinkpad it will generate an upstream stream-id by
4017 * doing an URI query on the element and in the worst case just uses
4018 * a random number. Source elements that don't implement the URI
4019 * handler interface should ideally generate a unique, deterministic
4020 * stream-id manually instead.
4021 *
4022 * Returns: A stream-id for @pad. g_free() after usage.
4023 */
4024 gchar *
gst_pad_create_stream_id_printf_valist(GstPad * pad,GstElement * parent,const gchar * stream_id,va_list var_args)4025 gst_pad_create_stream_id_printf_valist (GstPad * pad, GstElement * parent,
4026 const gchar * stream_id, va_list var_args)
4027 {
4028 gchar *expanded = NULL, *new_stream_id;
4029
4030 if (stream_id)
4031 expanded = g_strdup_vprintf (stream_id, var_args);
4032
4033 new_stream_id = gst_pad_create_stream_id_internal (pad, parent, expanded);
4034
4035 g_free (expanded);
4036
4037 return new_stream_id;
4038 }
4039
4040 /**
4041 * gst_pad_create_stream_id_printf:
4042 * @pad: A source #GstPad
4043 * @parent: Parent #GstElement of @pad
4044 * @stream_id: (allow-none): The stream-id
4045 * @...: parameters for the @stream_id format string
4046 *
4047 * Creates a stream-id for the source #GstPad @pad by combining the
4048 * upstream information with the optional @stream_id of the stream
4049 * of @pad. @pad must have a parent #GstElement and which must have zero
4050 * or one sinkpad. @stream_id can only be %NULL if the parent element
4051 * of @pad has only a single source pad.
4052 *
4053 * This function generates an unique stream-id by getting the upstream
4054 * stream-start event stream ID and appending @stream_id to it. If the
4055 * element has no sinkpad it will generate an upstream stream-id by
4056 * doing an URI query on the element and in the worst case just uses
4057 * a random number. Source elements that don't implement the URI
4058 * handler interface should ideally generate a unique, deterministic
4059 * stream-id manually instead.
4060 *
4061 * Returns: A stream-id for @pad. g_free() after usage.
4062 */
4063 gchar *
gst_pad_create_stream_id_printf(GstPad * pad,GstElement * parent,const gchar * stream_id,...)4064 gst_pad_create_stream_id_printf (GstPad * pad, GstElement * parent,
4065 const gchar * stream_id, ...)
4066 {
4067 va_list var_args;
4068 gchar *new_stream_id;
4069
4070 va_start (var_args, stream_id);
4071 new_stream_id =
4072 gst_pad_create_stream_id_printf_valist (pad, parent, stream_id, var_args);
4073 va_end (var_args);
4074
4075 return new_stream_id;
4076 }
4077
4078 /**
4079 * gst_pad_create_stream_id:
4080 * @pad: A source #GstPad
4081 * @parent: Parent #GstElement of @pad
4082 * @stream_id: (allow-none): The stream-id
4083 *
4084 * Creates a stream-id for the source #GstPad @pad by combining the
4085 * upstream information with the optional @stream_id of the stream
4086 * of @pad. @pad must have a parent #GstElement and which must have zero
4087 * or one sinkpad. @stream_id can only be %NULL if the parent element
4088 * of @pad has only a single source pad.
4089 *
4090 * This function generates an unique stream-id by getting the upstream
4091 * stream-start event stream ID and appending @stream_id to it. If the
4092 * element has no sinkpad it will generate an upstream stream-id by
4093 * doing an URI query on the element and in the worst case just uses
4094 * a random number. Source elements that don't implement the URI
4095 * handler interface should ideally generate a unique, deterministic
4096 * stream-id manually instead.
4097 *
4098 * Since stream IDs are sorted alphabetically, any numbers in the
4099 * stream ID should be printed with a fixed number of characters,
4100 * preceded by 0's, such as by using the format \%03u instead of \%u.
4101 *
4102 * Returns: A stream-id for @pad. g_free() after usage.
4103 */
4104 gchar *
gst_pad_create_stream_id(GstPad * pad,GstElement * parent,const gchar * stream_id)4105 gst_pad_create_stream_id (GstPad * pad, GstElement * parent,
4106 const gchar * stream_id)
4107 {
4108 return gst_pad_create_stream_id_internal (pad, parent, stream_id);
4109 }
4110
4111 /**
4112 * gst_pad_get_stream_id:
4113 * @pad: A source #GstPad
4114 *
4115 * Returns the current stream-id for the @pad, or %NULL if none has been
4116 * set yet, i.e. the pad has not received a stream-start event yet.
4117 *
4118 * This is a convenience wrapper around gst_pad_get_sticky_event() and
4119 * gst_event_parse_stream_start().
4120 *
4121 * The returned stream-id string should be treated as an opaque string, its
4122 * contents should not be interpreted.
4123 *
4124 * Returns: (nullable): a newly-allocated copy of the stream-id for
4125 * @pad, or %NULL. g_free() the returned string when no longer
4126 * needed.
4127 *
4128 * Since: 1.2
4129 */
4130 gchar *
gst_pad_get_stream_id(GstPad * pad)4131 gst_pad_get_stream_id (GstPad * pad)
4132 {
4133 const gchar *stream_id = NULL;
4134 GstEvent *event;
4135 gchar *ret = NULL;
4136
4137 g_return_val_if_fail (GST_IS_PAD (pad), NULL);
4138
4139 event = gst_pad_get_sticky_event (pad, GST_EVENT_STREAM_START, 0);
4140 if (event != NULL) {
4141 gst_event_parse_stream_start (event, &stream_id);
4142 ret = g_strdup (stream_id);
4143 gst_event_unref (event);
4144 GST_LOG_OBJECT (pad, "pad has stream-id '%s'", ret);
4145 } else {
4146 GST_DEBUG_OBJECT (pad, "pad has not received a stream-start event yet");
4147 }
4148
4149 return ret;
4150 }
4151
4152 /**
4153 * gst_pad_get_stream:
4154 * @pad: A source #GstPad
4155 *
4156 * Returns the current #GstStream for the @pad, or %NULL if none has been
4157 * set yet, i.e. the pad has not received a stream-start event yet.
4158 *
4159 * This is a convenience wrapper around gst_pad_get_sticky_event() and
4160 * gst_event_parse_stream().
4161 *
4162 * Returns: (nullable) (transfer full): the current #GstStream for @pad, or %NULL.
4163 * unref the returned stream when no longer needed.
4164 *
4165 * Since: 1.10
4166 */
4167 GstStream *
gst_pad_get_stream(GstPad * pad)4168 gst_pad_get_stream (GstPad * pad)
4169 {
4170 GstStream *stream = NULL;
4171 GstEvent *event;
4172
4173 g_return_val_if_fail (GST_IS_PAD (pad), NULL);
4174
4175 event = gst_pad_get_sticky_event (pad, GST_EVENT_STREAM_START, 0);
4176 if (event != NULL) {
4177 gst_event_parse_stream (event, &stream);
4178 gst_event_unref (event);
4179 GST_LOG_OBJECT (pad, "pad has stream object %p", stream);
4180 } else {
4181 GST_DEBUG_OBJECT (pad, "pad has not received a stream-start event yet");
4182 }
4183
4184 return stream;
4185 }
4186
4187 /**
4188 * gst_util_group_id_next:
4189 *
4190 * Return a constantly incrementing group id.
4191 *
4192 * This function is used to generate a new group-id for the
4193 * stream-start event.
4194 *
4195 * This function never returns %GST_GROUP_ID_INVALID (which is 0)
4196 *
4197 * Returns: A constantly incrementing unsigned integer, which might
4198 * overflow back to 0 at some point.
4199 */
4200 guint
gst_util_group_id_next(void)4201 gst_util_group_id_next (void)
4202 {
4203 static gint counter = 1;
4204 gint ret = g_atomic_int_add (&counter, 1);
4205
4206 /* Make sure we don't return GST_GROUP_ID_INVALID */
4207 if (G_UNLIKELY (ret == GST_GROUP_ID_INVALID))
4208 ret = g_atomic_int_add (&counter, 1);
4209
4210 return ret;
4211 }
4212
4213 /* Compute log2 of the passed 64-bit number by finding the highest set bit */
4214 static guint
gst_log2(GstClockTime in)4215 gst_log2 (GstClockTime in)
4216 {
4217 const guint64 b[] =
4218 { 0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000LL };
4219 const guint64 S[] = { 1, 2, 4, 8, 16, 32 };
4220 int i;
4221
4222 guint count = 0;
4223 for (i = 5; i >= 0; i--) {
4224 if (in & b[i]) {
4225 in >>= S[i];
4226 count |= S[i];
4227 }
4228 }
4229
4230 return count;
4231 }
4232
4233 /**
4234 * gst_calculate_linear_regression: (skip)
4235 * @xy: Pairs of (x,y) values
4236 * @temp: Temporary scratch space used by the function
4237 * @n: number of (x,y) pairs
4238 * @m_num: (out): numerator of calculated slope
4239 * @m_denom: (out): denominator of calculated slope
4240 * @b: (out): Offset at Y-axis
4241 * @xbase: (out): Offset at X-axis
4242 * @r_squared: (out): R-squared
4243 *
4244 * Calculates the linear regression of the values @xy and places the
4245 * result in @m_num, @m_denom, @b and @xbase, representing the function
4246 * y(x) = m_num/m_denom * (x - xbase) + b
4247 * that has the least-square distance from all points @x and @y.
4248 *
4249 * @r_squared will contain the remaining error.
4250 *
4251 * If @temp is not %NULL, it will be used as temporary space for the function,
4252 * in which case the function works without any allocation at all. If @temp is
4253 * %NULL, an allocation will take place. @temp should have at least the same
4254 * amount of memory allocated as @xy, i.e. 2*n*sizeof(GstClockTime).
4255 *
4256 * > This function assumes (x,y) values with reasonable large differences
4257 * > between them. It will not calculate the exact results if the differences
4258 * > between neighbouring values are too small due to not being able to
4259 * > represent sub-integer values during the calculations.
4260 *
4261 * Returns: %TRUE if the linear regression was successfully calculated
4262 *
4263 * Since: 1.12
4264 */
4265 /* http://mathworld.wolfram.com/LeastSquaresFitting.html
4266 * with SLAVE_LOCK
4267 */
4268 gboolean
gst_calculate_linear_regression(const GstClockTime * xy,GstClockTime * temp,guint n,GstClockTime * m_num,GstClockTime * m_denom,GstClockTime * b,GstClockTime * xbase,gdouble * r_squared)4269 gst_calculate_linear_regression (const GstClockTime * xy,
4270 GstClockTime * temp, guint n,
4271 GstClockTime * m_num, GstClockTime * m_denom,
4272 GstClockTime * b, GstClockTime * xbase, gdouble * r_squared)
4273 {
4274 const GstClockTime *x, *y;
4275 GstClockTime *newx, *newy;
4276 GstClockTime xmin, ymin, xbar, ybar, xbar4, ybar4;
4277 GstClockTime xmax, ymax;
4278 GstClockTimeDiff sxx, sxy, syy;
4279 gint i, j;
4280 gint pshift = 0;
4281 gint max_bits;
4282
4283 g_return_val_if_fail (xy != NULL, FALSE);
4284 g_return_val_if_fail (m_num != NULL, FALSE);
4285 g_return_val_if_fail (m_denom != NULL, FALSE);
4286 g_return_val_if_fail (b != NULL, FALSE);
4287 g_return_val_if_fail (xbase != NULL, FALSE);
4288 g_return_val_if_fail (r_squared != NULL, FALSE);
4289
4290 x = xy;
4291 y = xy + 1;
4292
4293 xbar = ybar = sxx = syy = sxy = 0;
4294
4295 xmin = ymin = G_MAXUINT64;
4296 xmax = ymax = 0;
4297 for (i = j = 0; i < n; i++, j += 2) {
4298 xmin = MIN (xmin, x[j]);
4299 ymin = MIN (ymin, y[j]);
4300
4301 xmax = MAX (xmax, x[j]);
4302 ymax = MAX (ymax, y[j]);
4303 }
4304
4305 if (temp == NULL) {
4306 /* Allocate up to 1kb on the stack, otherwise heap */
4307 newx = n > 64 ? g_new (GstClockTime, 2 * n) : g_newa (GstClockTime, 2 * n);
4308 newy = newx + 1;
4309 } else {
4310 newx = temp;
4311 newy = temp + 1;
4312 }
4313
4314 /* strip off unnecessary bits of precision */
4315 for (i = j = 0; i < n; i++, j += 2) {
4316 newx[j] = x[j] - xmin;
4317 newy[j] = y[j] - ymin;
4318 }
4319
4320 #ifdef DEBUGGING_ENABLED
4321 GST_CAT_DEBUG (GST_CAT_CLOCK, "reduced numbers:");
4322 for (i = j = 0; i < n; i++, j += 2)
4323 GST_CAT_DEBUG (GST_CAT_CLOCK,
4324 " %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT, newx[j], newy[j]);
4325 #endif
4326
4327 /* have to do this precisely otherwise the results are pretty much useless.
4328 * should guarantee that none of these accumulators can overflow */
4329
4330 /* quantities on the order of 1e10 to 1e13 -> 30-35 bits;
4331 * window size a max of 2^10, so
4332 this addition could end up around 2^45 or so -- ample headroom */
4333 for (i = j = 0; i < n; i++, j += 2) {
4334 /* Just in case assumptions about headroom prove false, let's check */
4335 if ((newx[j] > 0 && G_MAXUINT64 - xbar <= newx[j]) ||
4336 (newy[j] > 0 && G_MAXUINT64 - ybar <= newy[j])) {
4337 GST_CAT_WARNING (GST_CAT_CLOCK,
4338 "Regression overflowed in clock slaving! xbar %"
4339 G_GUINT64_FORMAT " newx[j] %" G_GUINT64_FORMAT " ybar %"
4340 G_GUINT64_FORMAT " newy[j] %" G_GUINT64_FORMAT, xbar, newx[j], ybar,
4341 newy[j]);
4342 if (temp == NULL && n > 64)
4343 g_free (newx);
4344 return FALSE;
4345 }
4346
4347 xbar += newx[j];
4348 ybar += newy[j];
4349 }
4350 xbar /= n;
4351 ybar /= n;
4352
4353 /* multiplying directly would give quantities on the order of 1e20-1e26 ->
4354 * 60 bits to 70 bits times the window size that's 80 which is too much.
4355 * Instead we (1) subtract off the xbar*ybar in the loop instead of after,
4356 * to avoid accumulation; (2) shift off some estimated number of bits from
4357 * each multiplicand to limit the expected ceiling. For strange
4358 * distributions of input values, things can still overflow, in which
4359 * case we drop precision and retry - at most a few times, in practice rarely
4360 */
4361
4362 /* Guess how many bits we might need for the usual distribution of input,
4363 * with a fallback loop that drops precision if things go pear-shaped */
4364 max_bits = gst_log2 (MAX (xmax - xmin, ymax - ymin)) * 7 / 8 + gst_log2 (n);
4365 if (max_bits > 64)
4366 pshift = max_bits - 64;
4367
4368 i = 0;
4369 do {
4370 #ifdef DEBUGGING_ENABLED
4371 GST_CAT_DEBUG (GST_CAT_CLOCK,
4372 "Restarting regression with precision shift %u", pshift);
4373 #endif
4374
4375 xbar4 = xbar >> pshift;
4376 ybar4 = ybar >> pshift;
4377 sxx = syy = sxy = 0;
4378 for (i = j = 0; i < n; i++, j += 2) {
4379 GstClockTime newx4, newy4;
4380 GstClockTimeDiff tmp;
4381
4382 newx4 = newx[j] >> pshift;
4383 newy4 = newy[j] >> pshift;
4384
4385 tmp = (newx4 + xbar4) * (newx4 - xbar4);
4386 if (G_UNLIKELY (tmp > 0 && sxx > 0 && (G_MAXINT64 - sxx <= tmp))) {
4387 do {
4388 /* Drop some precision and restart */
4389 pshift++;
4390 sxx /= 4;
4391 tmp /= 4;
4392 } while (G_MAXINT64 - sxx <= tmp);
4393 break;
4394 } else if (G_UNLIKELY (tmp < 0 && sxx < 0 && (G_MININT64 - sxx >= tmp))) {
4395 do {
4396 /* Drop some precision and restart */
4397 pshift++;
4398 sxx /= 4;
4399 tmp /= 4;
4400 } while (G_MININT64 - sxx >= tmp);
4401 break;
4402 }
4403 sxx += tmp;
4404
4405 tmp = newy4 * newy4 - ybar4 * ybar4;
4406 if (G_UNLIKELY (tmp > 0 && syy > 0 && (G_MAXINT64 - syy <= tmp))) {
4407 do {
4408 pshift++;
4409 syy /= 4;
4410 tmp /= 4;
4411 } while (G_MAXINT64 - syy <= tmp);
4412 break;
4413 } else if (G_UNLIKELY (tmp < 0 && syy < 0 && (G_MININT64 - syy >= tmp))) {
4414 do {
4415 pshift++;
4416 syy /= 4;
4417 tmp /= 4;
4418 } while (G_MININT64 - syy >= tmp);
4419 break;
4420 }
4421 syy += tmp;
4422
4423 tmp = newx4 * newy4 - xbar4 * ybar4;
4424 if (G_UNLIKELY (tmp > 0 && sxy > 0 && (G_MAXINT64 - sxy <= tmp))) {
4425 do {
4426 pshift++;
4427 sxy /= 4;
4428 tmp /= 4;
4429 } while (G_MAXINT64 - sxy <= tmp);
4430 break;
4431 } else if (G_UNLIKELY (tmp < 0 && sxy < 0 && (G_MININT64 - sxy >= tmp))) {
4432 do {
4433 pshift++;
4434 sxy /= 4;
4435 tmp /= 4;
4436 } while (G_MININT64 - sxy >= tmp);
4437 break;
4438 }
4439 sxy += tmp;
4440 }
4441 } while (i < n);
4442
4443 if (G_UNLIKELY (sxx == 0))
4444 goto invalid;
4445
4446 *m_num = sxy;
4447 *m_denom = sxx;
4448 *b = (ymin + ybar) - gst_util_uint64_scale_round (xbar, *m_num, *m_denom);
4449 /* Report base starting from the most recent observation */
4450 *xbase = xmax;
4451 *b += gst_util_uint64_scale_round (xmax - xmin, *m_num, *m_denom);
4452
4453 *r_squared = ((double) sxy * (double) sxy) / ((double) sxx * (double) syy);
4454
4455 #ifdef DEBUGGING_ENABLED
4456 GST_CAT_DEBUG (GST_CAT_CLOCK, " m = %g", ((double) *m_num) / *m_denom);
4457 GST_CAT_DEBUG (GST_CAT_CLOCK, " b = %" G_GUINT64_FORMAT, *b);
4458 GST_CAT_DEBUG (GST_CAT_CLOCK, " xbase = %" G_GUINT64_FORMAT, *xbase);
4459 GST_CAT_DEBUG (GST_CAT_CLOCK, " r2 = %g", *r_squared);
4460 #endif
4461
4462 if (temp == NULL && n > 64)
4463 g_free (newx);
4464
4465 return TRUE;
4466
4467 invalid:
4468 {
4469 GST_CAT_DEBUG (GST_CAT_CLOCK, "sxx == 0, regression failed");
4470 if (temp == NULL && n > 64)
4471 g_free (newx);
4472 return FALSE;
4473 }
4474 }
4475