Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / gst / gstcaps.c
1 /* GStreamer
2  * Copyright (C) <2003> David A. Schleef <ds@schleef.org>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:gstcaps
22  * @short_description: Structure describing sets of media formats
23  * @see_also: #GstStructure
24  *
25  * Caps (capabilities) are lighweight refcounted objects describing media types.
26  * They are composed of an array of #GstStructure.
27  *
28  * Caps are exposed on #GstPadTemplate to describe all possible types a
29  * given pad can handle. They are also stored in the #GstRegistry along with
30  * a description of the #GstElement.
31  *
32  * Caps are exposed on the element pads using the gst_pad_get_caps() pad
33  * function. This function describes the possible types that the pad can
34  * handle or produce at runtime.
35  *
36  * Caps are also attached to buffers to describe to content of the data
37  * pointed to by the buffer with gst_buffer_set_caps(). Caps attached to
38  * a #GstBuffer allow for format negotiation upstream and downstream.
39  *
40  * A #GstCaps can be constructed with the following code fragment:
41  *
42  * <example>
43  *  <title>Creating caps</title>
44  *  <programlisting>
45  *  GstCaps *caps;
46  *  caps = gst_caps_new_simple ("video/x-raw-yuv",
47  *       "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC ('I', '4', '2', '0'),
48  *       "framerate", GST_TYPE_FRACTION, 25, 1,
49  *       "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1,
50  *       "width", G_TYPE_INT, 320,
51  *       "height", G_TYPE_INT, 240,
52  *       NULL);
53  *  </programlisting>
54  * </example>
55  *
56  * A #GstCaps is fixed when it has no properties with ranges or lists. Use
57  * gst_caps_is_fixed() to test for fixed caps. Only fixed caps can be
58  * set on a #GstPad or #GstBuffer.
59  *
60  * Various methods exist to work with the media types such as subtracting
61  * or intersecting.
62  *
63  * Last reviewed on 2007-02-13 (0.10.10)
64  */
65
66 #ifdef HAVE_CONFIG_H
67 #include "config.h"
68 #endif
69 #include <string.h>
70 #include <signal.h>
71
72 #include "gst_private.h"
73 #include <gst/gst.h>
74 #include <gobject/gvaluecollector.h>
75
76 #define DEBUG_REFCOUNT
77
78 #define IS_WRITABLE(caps) \
79   (GST_CAPS_REFCOUNT_VALUE (caps) == 1)
80
81 /* same as gst_caps_is_any () */
82 #define CAPS_IS_ANY(caps)                               \
83   (GST_CAPS_FLAGS(caps) & GST_CAPS_FLAGS_ANY)
84
85 /* same as gst_caps_is_empty () */
86 #define CAPS_IS_EMPTY(caps)                             \
87   (!CAPS_IS_ANY(caps) && CAPS_IS_EMPTY_SIMPLE(caps))
88
89 #define CAPS_IS_EMPTY_SIMPLE(caps)                                      \
90   (((caps)->structs == NULL) || ((caps)->structs->len == 0))
91
92 /* quick way to get a caps structure at an index without doing a type or array
93  * length check */
94 #define gst_caps_get_structure_unchecked(caps, index) \
95      ((GstStructure *)g_ptr_array_index ((caps)->structs, (index)))
96 /* quick way to append a structure without checking the args */
97 #define gst_caps_append_structure_unchecked(caps, structure) G_STMT_START{\
98   GstStructure *__s=structure;                                      \
99   gst_structure_set_parent_refcount (__s, &GST_MINI_OBJECT_REFCOUNT(caps));         \
100   g_ptr_array_add (caps->structs, __s);                             \
101 }G_STMT_END
102
103 /* lock to protect multiple invocations of static caps to caps conversion */
104 G_LOCK_DEFINE_STATIC (static_caps_lock);
105
106 static void gst_caps_transform_to_string (const GValue * src_value,
107     GValue * dest_value);
108 static gboolean gst_caps_from_string_inplace (GstCaps * caps,
109     const gchar * string);
110
111 GType _gst_caps_type = 0;
112
113 void
114 _gst_caps_initialize (void)
115 {
116   if (G_LIKELY (_gst_caps_type == 0)) {
117     _gst_caps_type = gst_mini_object_register ("GstCaps");
118
119     g_value_register_transform_func (_gst_caps_type,
120         G_TYPE_STRING, gst_caps_transform_to_string);
121   }
122 }
123
124 static GstCaps *
125 _gst_caps_copy (const GstCaps * caps)
126 {
127   GstCaps *newcaps;
128   GstStructure *structure;
129   guint i, n;
130
131   g_return_val_if_fail (GST_IS_CAPS (caps), NULL);
132
133   newcaps = gst_caps_new_empty ();
134   GST_CAPS_FLAGS (newcaps) = GST_CAPS_FLAGS (caps);
135   n = caps->structs->len;
136
137   for (i = 0; i < n; i++) {
138     structure = gst_caps_get_structure_unchecked (caps, i);
139     gst_caps_append_structure (newcaps, gst_structure_copy (structure));
140   }
141
142   return newcaps;
143 }
144
145 /* creation/deletion */
146 static void
147 _gst_caps_free (GstCaps * caps)
148 {
149   GstStructure *structure;
150   guint i, len;
151
152   /* The refcount must be 0, but since we're only called by gst_caps_unref,
153    * don't bother testing. */
154   len = caps->structs->len;
155   /* This can be used to get statistics about caps sizes */
156   /*GST_CAT_INFO (GST_CAT_CAPS, "caps size: %d", len); */
157   for (i = 0; i < len; i++) {
158     structure = (GstStructure *) gst_caps_get_structure_unchecked (caps, i);
159     gst_structure_set_parent_refcount (structure, NULL);
160     gst_structure_free (structure);
161   }
162   g_ptr_array_free (caps->structs, TRUE);
163
164 #ifdef DEBUG_REFCOUNT
165   GST_CAT_LOG (GST_CAT_CAPS, "freeing caps %p", caps);
166 #endif
167   g_slice_free1 (GST_MINI_OBJECT_SIZE (caps), caps);
168 }
169
170 static void
171 gst_caps_init (GstCaps * caps, gsize size)
172 {
173   gst_mini_object_init (GST_MINI_OBJECT_CAST (caps), _gst_caps_type, size);
174
175   caps->mini_object.copy = (GstMiniObjectCopyFunction) _gst_caps_copy;
176   caps->mini_object.dispose = NULL;
177   caps->mini_object.free = (GstMiniObjectFreeFunction) _gst_caps_free;
178
179   /* the 32 has been determined by logging caps sizes in _gst_caps_free
180    * but g_ptr_array uses 16 anyway if it expands once, so this does not help
181    * in practise
182    * caps->structs = g_ptr_array_sized_new (32);
183    */
184   caps->structs = g_ptr_array_new ();
185 }
186
187 /**
188  * gst_caps_new_empty:
189  *
190  * Creates a new #GstCaps that is empty.  That is, the returned
191  * #GstCaps contains no media formats.
192  * Caller is responsible for unreffing the returned caps.
193  *
194  * Returns: (transfer full): the new #GstCaps
195  */
196 GstCaps *
197 gst_caps_new_empty (void)
198 {
199   GstCaps *caps;
200
201   caps = g_slice_new (GstCaps);
202
203   gst_caps_init (caps, sizeof (GstCaps));
204
205 #ifdef DEBUG_REFCOUNT
206   GST_CAT_LOG (GST_CAT_CAPS, "created caps %p", caps);
207 #endif
208
209   return caps;
210 }
211
212 /**
213  * gst_caps_new_any:
214  *
215  * Creates a new #GstCaps that indicates that it is compatible with
216  * any media format.
217  *
218  * Returns: (transfer full): the new #GstCaps
219  */
220 GstCaps *
221 gst_caps_new_any (void)
222 {
223   GstCaps *caps = gst_caps_new_empty ();
224
225   GST_CAPS_FLAG_SET (caps, GST_CAPS_FLAGS_ANY);
226
227   return caps;
228 }
229
230 /**
231  * gst_caps_new_simple:
232  * @media_type: the media type of the structure
233  * @fieldname: first field to set
234  * @...: additional arguments
235  *
236  * Creates a new #GstCaps that contains one #GstStructure.  The
237  * structure is defined by the arguments, which have the same format
238  * as gst_structure_new().
239  * Caller is responsible for unreffing the returned caps.
240  *
241  * Returns: (transfer full): the new #GstCaps
242  */
243 GstCaps *
244 gst_caps_new_simple (const char *media_type, const char *fieldname, ...)
245 {
246   GstCaps *caps;
247   GstStructure *structure;
248   va_list var_args;
249
250   caps = gst_caps_new_empty ();
251
252   va_start (var_args, fieldname);
253   structure = gst_structure_new_valist (media_type, fieldname, var_args);
254   va_end (var_args);
255
256   gst_caps_append_structure_unchecked (caps, structure);
257
258   return caps;
259 }
260
261 /**
262  * gst_caps_new_full:
263  * @struct1: the first structure to add
264  * @...: additional structures to add
265  *
266  * Creates a new #GstCaps and adds all the structures listed as
267  * arguments.  The list must be NULL-terminated.  The structures
268  * are not copied; the returned #GstCaps owns the structures.
269  *
270  * Returns: (transfer full): the new #GstCaps
271  */
272 GstCaps *
273 gst_caps_new_full (GstStructure * struct1, ...)
274 {
275   GstCaps *caps;
276   va_list var_args;
277
278   va_start (var_args, struct1);
279   caps = gst_caps_new_full_valist (struct1, var_args);
280   va_end (var_args);
281
282   return caps;
283 }
284
285 /**
286  * gst_caps_new_full_valist:
287  * @structure: the first structure to add
288  * @var_args: additional structures to add
289  *
290  * Creates a new #GstCaps and adds all the structures listed as
291  * arguments.  The list must be NULL-terminated.  The structures
292  * are not copied; the returned #GstCaps owns the structures.
293  *
294  * Returns: (transfer full): the new #GstCaps
295  */
296 GstCaps *
297 gst_caps_new_full_valist (GstStructure * structure, va_list var_args)
298 {
299   GstCaps *caps;
300
301   caps = gst_caps_new_empty ();
302
303   while (structure) {
304     gst_caps_append_structure_unchecked (caps, structure);
305     structure = va_arg (var_args, GstStructure *);
306   }
307
308   return caps;
309 }
310
311 /**
312  * gst_caps_make_writable:
313  * @caps: (transfer full): the #GstCaps to make writable
314  *
315  * Returns a writable copy of @caps.
316  *
317  * If there is only one reference count on @caps, the caller must be the owner,
318  * and so this function will return the caps object unchanged. If on the other
319  * hand there is more than one reference on the object, a new caps object will
320  * be returned. The caller's reference on @caps will be removed, and instead the
321  * caller will own a reference to the returned object.
322  *
323  * In short, this function unrefs the caps in the argument and refs the caps
324  * that it returns. Don't access the argument after calling this function. See
325  * also: gst_caps_ref().
326  *
327  * Returns: (transfer full): the same #GstCaps object.
328  */
329 GstCaps *
330 gst_caps_make_writable (GstCaps * caps)
331 {
332   GstCaps *copy;
333
334   g_return_val_if_fail (caps != NULL, NULL);
335
336   /* we are the only instance reffing this caps */
337   if (IS_WRITABLE (caps))
338     return caps;
339
340   /* else copy */
341   GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "copy caps");
342   copy = _gst_caps_copy (caps);
343   gst_caps_unref (caps);
344
345   return copy;
346 }
347
348 GType
349 gst_static_caps_get_type (void)
350 {
351   static GType staticcaps_type = 0;
352
353   if (G_UNLIKELY (staticcaps_type == 0)) {
354     staticcaps_type = g_pointer_type_register_static ("GstStaticCaps");
355   }
356   return staticcaps_type;
357 }
358
359
360 /**
361  * gst_static_caps_get:
362  * @static_caps: the #GstStaticCaps to convert
363  *
364  * Converts a #GstStaticCaps to a #GstCaps.
365  *
366  * Returns: (transfer full): a pointer to the #GstCaps. Unref after usage.
367  *     Since the core holds an additional ref to the returned caps,
368  *     use gst_caps_make_writable() on the returned caps to modify it.
369  */
370 GstCaps *
371 gst_static_caps_get (GstStaticCaps * static_caps)
372 {
373   GstCaps *caps;
374
375   g_return_val_if_fail (static_caps != NULL, NULL);
376
377   caps = (GstCaps *) static_caps;
378
379   /* refcount is 0 when we need to convert */
380   if (G_UNLIKELY (GST_CAPS_REFCOUNT_VALUE (caps) == 0)) {
381     const char *string;
382     GstCaps temp;
383
384     G_LOCK (static_caps_lock);
385     /* check if other thread already updated */
386     if (G_UNLIKELY (GST_CAPS_REFCOUNT_VALUE (caps) > 0))
387       goto done;
388
389     string = static_caps->string;
390
391     if (G_UNLIKELY (string == NULL))
392       goto no_string;
393
394     GST_CAT_LOG (GST_CAT_CAPS, "creating %p", static_caps);
395
396     /* we construct the caps on the stack, then copy over the struct into our
397      * real caps, refcount last. We do this because we must leave the refcount
398      * of the result caps to 0 so that other threads don't run away with the
399      * caps while we are constructing it. */
400     gst_caps_init (&temp, sizeof (GstCaps));
401
402     /* convert to string */
403     if (G_UNLIKELY (!gst_caps_from_string_inplace (&temp, string)))
404       g_critical ("Could not convert static caps \"%s\"", string);
405
406     gst_caps_init (caps, sizeof (GstCaps));
407     /* now copy stuff over to the real caps. */
408     GST_CAPS_FLAGS (caps) = GST_CAPS_FLAGS (&temp);
409     caps->structs = temp.structs;
410
411     GST_CAT_LOG (GST_CAT_CAPS, "created %p", static_caps);
412   done:
413     G_UNLOCK (static_caps_lock);
414   }
415   /* ref the caps, makes it not writable */
416   gst_caps_ref (caps);
417
418   return caps;
419
420   /* ERRORS */
421 no_string:
422   {
423     G_UNLOCK (static_caps_lock);
424     g_warning ("static caps %p string is NULL", static_caps);
425     return NULL;
426   }
427 }
428
429 /* manipulation */
430
431 static GstStructure *
432 gst_caps_remove_and_get_structure (GstCaps * caps, guint idx)
433 {
434   /* don't use index_fast, gst_caps_do_simplify relies on the order */
435   GstStructure *s = g_ptr_array_remove_index (caps->structs, idx);
436
437   gst_structure_set_parent_refcount (s, NULL);
438   return s;
439 }
440
441 /**
442  * gst_caps_steal_structure:
443  * @caps: the #GstCaps to retrieve from
444  * @index: Index of the structure to retrieve
445  *
446  * Retrieves the stucture with the given index from the list of structures
447  * contained in @caps. The caller becomes the owner of the returned structure.
448  *
449  * Returns: (transfer full): a pointer to the #GstStructure corresponding
450  *     to @index.
451  *
452  * Since: 0.10.30
453  */
454 GstStructure *
455 gst_caps_steal_structure (GstCaps * caps, guint index)
456 {
457   g_return_val_if_fail (caps != NULL, NULL);
458   g_return_val_if_fail (IS_WRITABLE (caps), NULL);
459
460   if (G_UNLIKELY (index >= caps->structs->len))
461     return NULL;
462
463   return gst_caps_remove_and_get_structure (caps, index);
464 }
465
466 static gboolean
467 gst_structure_is_equal_foreach (GQuark field_id, const GValue * val2,
468     gpointer data)
469 {
470   GstStructure *struct1 = (GstStructure *) data;
471   const GValue *val1 = gst_structure_id_get_value (struct1, field_id);
472
473   if (G_UNLIKELY (val1 == NULL))
474     return FALSE;
475   if (gst_value_compare (val1, val2) == GST_VALUE_EQUAL) {
476     return TRUE;
477   }
478
479   return FALSE;
480 }
481
482 static gboolean
483 gst_caps_structure_is_subset_field (GQuark field_id, const GValue * value,
484     gpointer user_data)
485 {
486   GstStructure *subtract_from = user_data;
487   GValue subtraction = { 0, };
488   const GValue *other;
489
490   if (!(other = gst_structure_id_get_value (subtract_from, field_id)))
491     /* field is missing in one set */
492     return FALSE;
493
494   /* equal values are subset */
495   if (gst_value_compare (other, value) == GST_VALUE_EQUAL)
496     return TRUE;
497
498   /*
499    * 1 - [1,2] = empty
500    * -> !subset
501    *
502    * [1,2] - 1 = 2
503    *  -> 1 - [1,2] = empty
504    *  -> subset
505    *
506    * [1,3] - [1,2] = 3
507    * -> [1,2] - [1,3] = empty
508    * -> subset
509    *
510    * {1,2} - {1,3} = 2
511    * -> {1,3} - {1,2} = 3
512    * -> !subset
513    *
514    *  First caps subtraction needs to return a non-empty set, second
515    *  subtractions needs to give en empty set.
516    */
517   if (gst_value_subtract (&subtraction, other, value)) {
518     g_value_unset (&subtraction);
519     /* !empty result, swapping must be empty */
520     if (!gst_value_subtract (&subtraction, value, other))
521       return TRUE;
522
523     g_value_unset (&subtraction);
524   }
525   return FALSE;
526 }
527
528 static gboolean
529 gst_caps_structure_is_subset (const GstStructure * minuend,
530     const GstStructure * subtrahend)
531 {
532   if ((minuend->name != subtrahend->name) ||
533       (gst_structure_n_fields (minuend) !=
534           gst_structure_n_fields (subtrahend))) {
535     return FALSE;
536   }
537
538   return gst_structure_foreach ((GstStructure *) subtrahend,
539       gst_caps_structure_is_subset_field, (gpointer) minuend);
540 }
541
542 /**
543  * gst_caps_append:
544  * @caps1: the #GstCaps that will be appended to
545  * @caps2: (transfer full): the #GstCaps to append
546  *
547  * Appends the structures contained in @caps2 to @caps1. The structures in
548  * @caps2 are not copied -- they are transferred to @caps1, and then @caps2 is
549  * freed. If either caps is ANY, the resulting caps will be ANY.
550  */
551 void
552 gst_caps_append (GstCaps * caps1, GstCaps * caps2)
553 {
554   GstStructure *structure;
555   int i;
556
557   g_return_if_fail (GST_IS_CAPS (caps1));
558   g_return_if_fail (GST_IS_CAPS (caps2));
559   g_return_if_fail (IS_WRITABLE (caps1));
560   g_return_if_fail (IS_WRITABLE (caps2));
561
562   if (G_UNLIKELY (CAPS_IS_ANY (caps1) || CAPS_IS_ANY (caps2))) {
563     /* FIXME: this leaks */
564     GST_CAPS_FLAGS (caps1) |= GST_CAPS_FLAGS_ANY;
565     for (i = caps2->structs->len - 1; i >= 0; i--) {
566       structure = gst_caps_remove_and_get_structure (caps2, i);
567       gst_structure_free (structure);
568     }
569   } else {
570     for (i = caps2->structs->len; i; i--) {
571       structure = gst_caps_remove_and_get_structure (caps2, 0);
572       gst_caps_append_structure_unchecked (caps1, structure);
573     }
574   }
575   gst_caps_unref (caps2);       /* guaranteed to free it */
576 }
577
578 /**
579  * gst_caps_merge:
580  * @caps1: the #GstCaps that will take the new entries
581  * @caps2: (transfer full): the #GstCaps to merge in
582  *
583  * Appends the structures contained in @caps2 to @caps1 if they are not yet
584  * expressed by @caps1. The structures in @caps2 are not copied -- they are
585  * transferred to @caps1, and then @caps2 is freed.
586  * If either caps is ANY, the resulting caps will be ANY.
587  *
588  * Since: 0.10.10
589  */
590 void
591 gst_caps_merge (GstCaps * caps1, GstCaps * caps2)
592 {
593   GstStructure *structure;
594   int i;
595
596   g_return_if_fail (GST_IS_CAPS (caps1));
597   g_return_if_fail (GST_IS_CAPS (caps2));
598   g_return_if_fail (IS_WRITABLE (caps1));
599   g_return_if_fail (IS_WRITABLE (caps2));
600
601   if (G_UNLIKELY (CAPS_IS_ANY (caps1))) {
602     for (i = caps2->structs->len - 1; i >= 0; i--) {
603       structure = gst_caps_remove_and_get_structure (caps2, i);
604       gst_structure_free (structure);
605     }
606   } else if (G_UNLIKELY (CAPS_IS_ANY (caps2))) {
607     GST_CAPS_FLAGS (caps1) |= GST_CAPS_FLAGS_ANY;
608     for (i = caps1->structs->len - 1; i >= 0; i--) {
609       structure = gst_caps_remove_and_get_structure (caps1, i);
610       gst_structure_free (structure);
611     }
612   } else {
613     for (i = caps2->structs->len; i; i--) {
614       structure = gst_caps_remove_and_get_structure (caps2, 0);
615       gst_caps_merge_structure (caps1, structure);
616     }
617     /* this is too naive
618        GstCaps *com = gst_caps_intersect (caps1, caps2);
619        GstCaps *add = gst_caps_subtract (caps2, com);
620
621        GST_DEBUG ("common : %d", gst_caps_get_size (com));
622        GST_DEBUG ("adding : %d", gst_caps_get_size (add));
623        gst_caps_append (caps1, add);
624        gst_caps_unref (com);
625      */
626   }
627   gst_caps_unref (caps2);       /* guaranteed to free it */
628 }
629
630 /**
631  * gst_caps_append_structure:
632  * @caps: the #GstCaps that will be appended to
633  * @structure: (transfer full): the #GstStructure to append
634  *
635  * Appends @structure to @caps.  The structure is not copied; @caps
636  * becomes the owner of @structure.
637  */
638 void
639 gst_caps_append_structure (GstCaps * caps, GstStructure * structure)
640 {
641   g_return_if_fail (GST_IS_CAPS (caps));
642   g_return_if_fail (IS_WRITABLE (caps));
643
644   if (G_LIKELY (structure)) {
645     g_return_if_fail (structure->parent_refcount == NULL);
646     gst_caps_append_structure_unchecked (caps, structure);
647   }
648 }
649
650 /**
651  * gst_caps_remove_structure:
652  * @caps: the #GstCaps to remove from
653  * @idx: Index of the structure to remove
654  *
655  * removes the stucture with the given index from the list of structures
656  * contained in @caps.
657  */
658 void
659 gst_caps_remove_structure (GstCaps * caps, guint idx)
660 {
661   GstStructure *structure;
662
663   g_return_if_fail (caps != NULL);
664   g_return_if_fail (idx <= gst_caps_get_size (caps));
665   g_return_if_fail (IS_WRITABLE (caps));
666
667   structure = gst_caps_remove_and_get_structure (caps, idx);
668   gst_structure_free (structure);
669 }
670
671 /**
672  * gst_caps_merge_structure:
673  * @caps: the #GstCaps that will the the new structure
674  * @structure: (transfer full): the #GstStructure to merge
675  *
676  * Appends @structure to @caps if its not already expressed by @caps.  The
677  * structure is not copied; @caps becomes the owner of @structure.
678  */
679 void
680 gst_caps_merge_structure (GstCaps * caps, GstStructure * structure)
681 {
682   g_return_if_fail (GST_IS_CAPS (caps));
683   g_return_if_fail (IS_WRITABLE (caps));
684
685   if (G_LIKELY (structure)) {
686     GstStructure *structure1;
687     int i;
688     gboolean unique = TRUE;
689
690     g_return_if_fail (structure->parent_refcount == NULL);
691     /* check each structure */
692     for (i = caps->structs->len - 1; i >= 0; i--) {
693       structure1 = gst_caps_get_structure_unchecked (caps, i);
694       /* if structure is a subset of structure1, then skip it */
695       if (gst_caps_structure_is_subset (structure1, structure)) {
696         unique = FALSE;
697         break;
698       }
699     }
700     if (unique) {
701       gst_caps_append_structure_unchecked (caps, structure);
702     } else {
703       gst_structure_free (structure);
704     }
705   }
706 }
707
708 /**
709  * gst_caps_get_size:
710  * @caps: a #GstCaps
711  *
712  * Gets the number of structures contained in @caps.
713  *
714  * Returns: the number of structures that @caps contains
715  */
716 guint
717 gst_caps_get_size (const GstCaps * caps)
718 {
719   g_return_val_if_fail (GST_IS_CAPS (caps), 0);
720
721   return caps->structs->len;
722 }
723
724 /**
725  * gst_caps_get_structure:
726  * @caps: a #GstCaps
727  * @index: the index of the structure
728  *
729  * Finds the structure in @caps that has the index @index, and
730  * returns it.
731  *
732  * WARNING: This function takes a const GstCaps *, but returns a
733  * non-const GstStructure *.  This is for programming convenience --
734  * the caller should be aware that structures inside a constant
735  * #GstCaps should not be modified. However, if you know the caps
736  * are writable, either because you have just copied them or made
737  * them writable with gst_caps_make_writable(), you may modify the
738  * structure returned in the usual way, e.g. with functions like
739  * gst_structure_set().
740  *
741  * You do not need to free or unref the structure returned, it
742  * belongs to the #GstCaps.
743  *
744  * Returns: (transfer none): a pointer to the #GstStructure corresponding
745  *     to @index
746  */
747 GstStructure *
748 gst_caps_get_structure (const GstCaps * caps, guint index)
749 {
750   g_return_val_if_fail (GST_IS_CAPS (caps), NULL);
751   g_return_val_if_fail (index < caps->structs->len, NULL);
752
753   return gst_caps_get_structure_unchecked (caps, index);
754 }
755
756 /**
757  * gst_caps_copy_nth:
758  * @caps: the #GstCaps to copy
759  * @nth: the nth structure to copy
760  *
761  * Creates a new #GstCaps and appends a copy of the nth structure
762  * contained in @caps.
763  *
764  * Returns: (transfer full): the new #GstCaps
765  */
766 GstCaps *
767 gst_caps_copy_nth (const GstCaps * caps, guint nth)
768 {
769   GstCaps *newcaps;
770   GstStructure *structure;
771
772   g_return_val_if_fail (GST_IS_CAPS (caps), NULL);
773
774   newcaps = gst_caps_new_empty ();
775   GST_CAPS_FLAGS (newcaps) = GST_CAPS_FLAGS (caps);
776
777   if (G_LIKELY (caps->structs->len > nth)) {
778     structure = gst_caps_get_structure_unchecked (caps, nth);
779     gst_caps_append_structure_unchecked (newcaps,
780         gst_structure_copy (structure));
781   }
782
783   return newcaps;
784 }
785
786 /**
787  * gst_caps_truncate:
788  * @caps: the #GstCaps to truncate
789  *
790  * Destructively discard all but the first structure from @caps. Useful when
791  * fixating. @caps must be writable.
792  */
793 void
794 gst_caps_truncate (GstCaps * caps)
795 {
796   gint i;
797
798   g_return_if_fail (GST_IS_CAPS (caps));
799   g_return_if_fail (IS_WRITABLE (caps));
800
801   i = caps->structs->len - 1;
802
803   while (i > 0)
804     gst_caps_remove_structure (caps, i--);
805 }
806
807 /**
808  * gst_caps_set_value:
809  * @caps: a writable caps
810  * @field: name of the field to set
811  * @value: value to set the field to
812  *
813  * Sets the given @field on all structures of @caps to the given @value.
814  * This is a convenience function for calling gst_structure_set_value() on
815  * all structures of @caps.
816  *
817  * Since: 0.10.26
818  **/
819 void
820 gst_caps_set_value (GstCaps * caps, const char *field, const GValue * value)
821 {
822   guint i, len;
823
824   g_return_if_fail (GST_IS_CAPS (caps));
825   g_return_if_fail (IS_WRITABLE (caps));
826   g_return_if_fail (field != NULL);
827   g_return_if_fail (G_IS_VALUE (value));
828
829   len = caps->structs->len;
830   for (i = 0; i < len; i++) {
831     GstStructure *structure = gst_caps_get_structure_unchecked (caps, i);
832     gst_structure_set_value (structure, field, value);
833   }
834 }
835
836 /**
837  * gst_caps_set_simple_valist:
838  * @caps: the #GstCaps to set
839  * @field: first field to set
840  * @varargs: additional parameters
841  *
842  * Sets fields in a #GstCaps.  The arguments must be passed in the same
843  * manner as gst_structure_set(), and be NULL-terminated.
844  * <note>Prior to GStreamer version 0.10.26, this function failed when
845  * @caps was not simple. If your code needs to work with those versions 
846  * of GStreamer, you may only call this function when GST_CAPS_IS_SIMPLE()
847  * is %TRUE for @caps.</note>
848  */
849 void
850 gst_caps_set_simple_valist (GstCaps * caps, const char *field, va_list varargs)
851 {
852   GValue value = { 0, };
853
854   g_return_if_fail (GST_IS_CAPS (caps));
855   g_return_if_fail (IS_WRITABLE (caps));
856
857   while (field) {
858     GType type;
859     char *err;
860
861     type = va_arg (varargs, GType);
862
863     if (G_UNLIKELY (type == G_TYPE_DATE)) {
864       g_warning ("Don't use G_TYPE_DATE, use GST_TYPE_DATE instead\n");
865       type = GST_TYPE_DATE;
866     }
867 #if GLIB_CHECK_VERSION(2,23,3)
868     G_VALUE_COLLECT_INIT (&value, type, varargs, 0, &err);
869 #else
870     g_value_init (&value, type);
871     G_VALUE_COLLECT (&value, varargs, 0, &err);
872 #endif
873     if (G_UNLIKELY (err)) {
874       g_critical ("%s", err);
875       return;
876     }
877
878     gst_caps_set_value (caps, field, &value);
879
880     g_value_unset (&value);
881
882     field = va_arg (varargs, const gchar *);
883   }
884 }
885
886 /**
887  * gst_caps_set_simple:
888  * @caps: the #GstCaps to set
889  * @field: first field to set
890  * @...: additional parameters
891  *
892  * Sets fields in a #GstCaps.  The arguments must be passed in the same
893  * manner as gst_structure_set(), and be NULL-terminated.
894  * <note>Prior to GStreamer version 0.10.26, this function failed when
895  * @caps was not simple. If your code needs to work with those versions
896  * of GStreamer, you may only call this function when GST_CAPS_IS_SIMPLE()
897  * is %TRUE for @caps.</note>
898  */
899 void
900 gst_caps_set_simple (GstCaps * caps, const char *field, ...)
901 {
902   va_list var_args;
903
904   g_return_if_fail (GST_IS_CAPS (caps));
905   g_return_if_fail (IS_WRITABLE (caps));
906
907   va_start (var_args, field);
908   gst_caps_set_simple_valist (caps, field, var_args);
909   va_end (var_args);
910 }
911
912 /* tests */
913
914 /**
915  * gst_caps_is_any:
916  * @caps: the #GstCaps to test
917  *
918  * Determines if @caps represents any media format.
919  *
920  * Returns: TRUE if @caps represents any format.
921  */
922 gboolean
923 gst_caps_is_any (const GstCaps * caps)
924 {
925   g_return_val_if_fail (GST_IS_CAPS (caps), FALSE);
926
927   return (CAPS_IS_ANY (caps));
928 }
929
930 /**
931  * gst_caps_is_empty:
932  * @caps: the #GstCaps to test
933  *
934  * Determines if @caps represents no media formats.
935  *
936  * Returns: TRUE if @caps represents no formats.
937  */
938 gboolean
939 gst_caps_is_empty (const GstCaps * caps)
940 {
941   g_return_val_if_fail (GST_IS_CAPS (caps), FALSE);
942
943   if (CAPS_IS_ANY (caps))
944     return FALSE;
945
946   return CAPS_IS_EMPTY_SIMPLE (caps);
947 }
948
949 static gboolean
950 gst_caps_is_fixed_foreach (GQuark field_id, const GValue * value,
951     gpointer unused)
952 {
953   return gst_value_is_fixed (value);
954 }
955
956 /**
957  * gst_caps_is_fixed:
958  * @caps: the #GstCaps to test
959  *
960  * Fixed #GstCaps describe exactly one format, that is, they have exactly
961  * one structure, and each field in the structure describes a fixed type.
962  * Examples of non-fixed types are GST_TYPE_INT_RANGE and GST_TYPE_LIST.
963  *
964  * Returns: TRUE if @caps is fixed
965  */
966 gboolean
967 gst_caps_is_fixed (const GstCaps * caps)
968 {
969   GstStructure *structure;
970
971   g_return_val_if_fail (GST_IS_CAPS (caps), FALSE);
972
973   if (caps->structs->len != 1)
974     return FALSE;
975
976   structure = gst_caps_get_structure_unchecked (caps, 0);
977
978   return gst_structure_foreach (structure, gst_caps_is_fixed_foreach, NULL);
979 }
980
981 /**
982  * gst_caps_is_equal_fixed:
983  * @caps1: the #GstCaps to test
984  * @caps2: the #GstCaps to test
985  *
986  * Tests if two #GstCaps are equal.  This function only works on fixed
987  * #GstCaps.
988  *
989  * Returns: TRUE if the arguments represent the same format
990  */
991 gboolean
992 gst_caps_is_equal_fixed (const GstCaps * caps1, const GstCaps * caps2)
993 {
994   GstStructure *struct1, *struct2;
995
996   g_return_val_if_fail (gst_caps_is_fixed (caps1), FALSE);
997   g_return_val_if_fail (gst_caps_is_fixed (caps2), FALSE);
998
999   struct1 = gst_caps_get_structure_unchecked (caps1, 0);
1000   struct2 = gst_caps_get_structure_unchecked (caps2, 0);
1001
1002   if (struct1->name != struct2->name) {
1003     return FALSE;
1004   }
1005   if (struct1->fields->len != struct2->fields->len) {
1006     return FALSE;
1007   }
1008
1009   return gst_structure_foreach (struct1, gst_structure_is_equal_foreach,
1010       struct2);
1011 }
1012
1013 /**
1014  * gst_caps_is_always_compatible:
1015  * @caps1: the #GstCaps to test
1016  * @caps2: the #GstCaps to test
1017  *
1018  * A given #GstCaps structure is always compatible with another if
1019  * every media format that is in the first is also contained in the
1020  * second.  That is, @caps1 is a subset of @caps2.
1021  *
1022  * Returns: TRUE if @caps1 is a subset of @caps2.
1023  */
1024 gboolean
1025 gst_caps_is_always_compatible (const GstCaps * caps1, const GstCaps * caps2)
1026 {
1027   g_return_val_if_fail (GST_IS_CAPS (caps1), FALSE);
1028   g_return_val_if_fail (GST_IS_CAPS (caps2), FALSE);
1029
1030   return gst_caps_is_subset (caps1, caps2);
1031 }
1032
1033 /**
1034  * gst_caps_is_subset:
1035  * @subset: a #GstCaps
1036  * @superset: a potentially greater #GstCaps
1037  *
1038  * Checks if all caps represented by @subset are also represented by @superset.
1039  * <note>This function does not work reliably if optional properties for caps
1040  * are included on one caps and omitted on the other.</note>
1041  *
1042  * Returns: %TRUE if @subset is a subset of @superset
1043  */
1044 gboolean
1045 gst_caps_is_subset (const GstCaps * subset, const GstCaps * superset)
1046 {
1047   GstCaps *caps;
1048   gboolean ret;
1049
1050   g_return_val_if_fail (subset != NULL, FALSE);
1051   g_return_val_if_fail (superset != NULL, FALSE);
1052
1053   if (CAPS_IS_EMPTY (subset) || CAPS_IS_ANY (superset))
1054     return TRUE;
1055   if (CAPS_IS_ANY (subset) || CAPS_IS_EMPTY (superset))
1056     return FALSE;
1057
1058   caps = gst_caps_subtract (subset, superset);
1059   ret = CAPS_IS_EMPTY_SIMPLE (caps);
1060   gst_caps_unref (caps);
1061   return ret;
1062 }
1063
1064 /**
1065  * gst_caps_is_equal:
1066  * @caps1: a #GstCaps
1067  * @caps2: another #GstCaps
1068  *
1069  * Checks if the given caps represent the same set of caps.
1070  * <note>This function does not work reliably if optional properties for caps
1071  * are included on one caps and omitted on the other.</note>
1072  *
1073  * This function deals correctly with passing NULL for any of the caps.
1074  *
1075  * Returns: TRUE if both caps are equal.
1076  */
1077 gboolean
1078 gst_caps_is_equal (const GstCaps * caps1, const GstCaps * caps2)
1079 {
1080   /* FIXME 0.11: NULL pointers are no valid Caps but indicate an error
1081    * So there should be an assertion that caps1 and caps2 != NULL */
1082
1083   /* NULL <-> NULL is allowed here */
1084   if (G_UNLIKELY (caps1 == caps2))
1085     return TRUE;
1086
1087   /* one of them NULL => they are different (can't be both NULL because
1088    * we checked that above) */
1089   if (G_UNLIKELY (caps1 == NULL || caps2 == NULL))
1090     return FALSE;
1091
1092   if (G_UNLIKELY (gst_caps_is_fixed (caps1) && gst_caps_is_fixed (caps2)))
1093     return gst_caps_is_equal_fixed (caps1, caps2);
1094
1095   return gst_caps_is_subset (caps1, caps2) && gst_caps_is_subset (caps2, caps1);
1096 }
1097
1098 /* intersect operation */
1099
1100 typedef struct
1101 {
1102   GstStructure *dest;
1103   const GstStructure *intersect;
1104 }
1105 IntersectData;
1106
1107 static gboolean
1108 gst_caps_structure_intersect_field1 (GQuark id, const GValue * val1,
1109     gpointer data)
1110 {
1111   IntersectData *idata = (IntersectData *) data;
1112   const GValue *val2 = gst_structure_id_get_value (idata->intersect, id);
1113
1114   if (G_UNLIKELY (val2 == NULL)) {
1115     gst_structure_id_set_value (idata->dest, id, val1);
1116   } else {
1117     GValue dest_value = { 0 };
1118     if (gst_value_intersect (&dest_value, val1, val2)) {
1119       gst_structure_id_set_value (idata->dest, id, &dest_value);
1120       g_value_unset (&dest_value);
1121     } else {
1122       return FALSE;
1123     }
1124   }
1125   return TRUE;
1126 }
1127
1128 static gboolean
1129 gst_caps_structure_intersect_field2 (GQuark id, const GValue * val1,
1130     gpointer data)
1131 {
1132   IntersectData *idata = (IntersectData *) data;
1133   const GValue *val2 = gst_structure_id_get_value (idata->intersect, id);
1134
1135   if (G_UNLIKELY (val2 == NULL)) {
1136     gst_structure_id_set_value (idata->dest, id, val1);
1137   }
1138   return TRUE;
1139 }
1140
1141 static GstStructure *
1142 gst_caps_structure_intersect (const GstStructure * struct1,
1143     const GstStructure * struct2)
1144 {
1145   IntersectData data;
1146
1147   g_assert (struct1 != NULL);
1148   g_assert (struct2 != NULL);
1149
1150   if (G_UNLIKELY (struct1->name != struct2->name))
1151     return NULL;
1152
1153   /* copy fields from struct1 which we have not in struct2 to target
1154    * intersect if we have the field in both */
1155   data.dest = gst_structure_id_empty_new (struct1->name);
1156   data.intersect = struct2;
1157   if (G_UNLIKELY (!gst_structure_foreach ((GstStructure *) struct1,
1158               gst_caps_structure_intersect_field1, &data)))
1159     goto error;
1160
1161   /* copy fields from struct2 which we have not in struct1 to target */
1162   data.intersect = struct1;
1163   if (G_UNLIKELY (!gst_structure_foreach ((GstStructure *) struct2,
1164               gst_caps_structure_intersect_field2, &data)))
1165     goto error;
1166
1167   return data.dest;
1168
1169 error:
1170   gst_structure_free (data.dest);
1171   return NULL;
1172 }
1173
1174 static gboolean
1175 gst_caps_structure_can_intersect_field (GQuark id, const GValue * val1,
1176     gpointer data)
1177 {
1178   GstStructure *other = (GstStructure *) data;
1179   const GValue *val2 = gst_structure_id_get_value (other, id);
1180
1181   if (G_LIKELY (val2)) {
1182     if (!gst_value_can_intersect (val1, val2)) {
1183       return FALSE;
1184     } else {
1185       gint eq = gst_value_compare (val1, val2);
1186
1187       if (eq == GST_VALUE_UNORDERED) {
1188         /* we need to try interseting */
1189         GValue dest_value = { 0 };
1190         if (gst_value_intersect (&dest_value, val1, val2)) {
1191           g_value_unset (&dest_value);
1192         } else {
1193           return FALSE;
1194         }
1195       } else if (eq != GST_VALUE_EQUAL) {
1196         return FALSE;
1197       }
1198     }
1199   }
1200   return TRUE;
1201 }
1202
1203 static gboolean
1204 gst_caps_structure_can_intersect (const GstStructure * struct1,
1205     const GstStructure * struct2)
1206 {
1207   g_assert (struct1 != NULL);
1208   g_assert (struct2 != NULL);
1209
1210   if (G_UNLIKELY (struct1->name != struct2->name))
1211     return FALSE;
1212
1213   /* tries to intersect if we have the field in both */
1214   if (G_UNLIKELY (!gst_structure_foreach ((GstStructure *) struct1,
1215               gst_caps_structure_can_intersect_field, (gpointer) struct2)))
1216     return FALSE;
1217
1218   return TRUE;
1219 }
1220
1221 /**
1222  * gst_caps_can_intersect:
1223  * @caps1: a #GstCaps to intersect
1224  * @caps2: a #GstCaps to intersect
1225  *
1226  * Tries intersecting @caps1 and @caps2 and reports whether the result would not
1227  * be empty
1228  *
1229  * Returns: %TRUE if intersection would be not empty
1230  *
1231  * Since: 0.10.25
1232  */
1233 gboolean
1234 gst_caps_can_intersect (const GstCaps * caps1, const GstCaps * caps2)
1235 {
1236   guint64 i;                    /* index can be up to 2 * G_MAX_UINT */
1237   guint j, k, len1, len2;
1238   GstStructure *struct1;
1239   GstStructure *struct2;
1240
1241   g_return_val_if_fail (GST_IS_CAPS (caps1), FALSE);
1242   g_return_val_if_fail (GST_IS_CAPS (caps2), FALSE);
1243
1244   /* caps are exactly the same pointers */
1245   if (G_UNLIKELY (caps1 == caps2))
1246     return TRUE;
1247
1248   /* empty caps on either side, return empty */
1249   if (G_UNLIKELY (CAPS_IS_EMPTY (caps1) || CAPS_IS_EMPTY (caps2)))
1250     return FALSE;
1251
1252   /* one of the caps is any */
1253   if (G_UNLIKELY (CAPS_IS_ANY (caps1) || CAPS_IS_ANY (caps2)))
1254     return TRUE;
1255
1256   /* run zigzag on top line then right line, this preserves the caps order
1257    * much better than a simple loop.
1258    *
1259    * This algorithm zigzags over the caps structures as demonstrated in
1260    * the folowing matrix:
1261    *
1262    *          caps1                              0  1  2  3
1263    *       +-------------     total distance:  +-------------
1264    *       | 1  2  4  7                      0 | 0  1  2  3
1265    * caps2 | 3  5  8 10                      1 | 1  2  3  4
1266    *       | 6  9 11 12                      2 | 2  3  4  5
1267    *
1268    * First we iterate over the caps1 structures (top line) intersecting
1269    * the structures diagonally down, then we iterate over the caps2
1270    * structures. The result is that the intersections are ordered based on the
1271    * sum of the indexes in the list.
1272    */
1273   len1 = caps1->structs->len;
1274   len2 = caps2->structs->len;
1275   for (i = 0; i < len1 + len2 - 1; i++) {
1276     /* superset index goes from 0 to sgst_caps_structure_intersectuperset->structs->len-1 */
1277     j = MIN (i, len1 - 1);
1278     /* subset index stays 0 until i reaches superset->structs->len, then it
1279      * counts up from 1 to subset->structs->len - 1 */
1280     k = MAX (0, i - j);
1281
1282     /* now run the diagonal line, end condition is the left or bottom
1283      * border */
1284     while (k < len2) {
1285       struct1 = gst_caps_get_structure_unchecked (caps1, j);
1286       struct2 = gst_caps_get_structure_unchecked (caps2, k);
1287
1288       if (gst_caps_structure_can_intersect (struct1, struct2)) {
1289         return TRUE;
1290       }
1291       /* move down left */
1292       k++;
1293       if (G_UNLIKELY (j == 0))
1294         break;                  /* so we don't roll back to G_MAXUINT */
1295       j--;
1296     }
1297   }
1298   return FALSE;
1299 }
1300
1301 /**
1302  * gst_caps_intersect:
1303  * @caps1: a #GstCaps to intersect
1304  * @caps2: a #GstCaps to intersect
1305  *
1306  * Creates a new #GstCaps that contains all the formats that are common
1307  * to both @caps1 and @caps2.
1308  *
1309  * Returns: the new #GstCaps
1310  */
1311 GstCaps *
1312 gst_caps_intersect (const GstCaps * caps1, const GstCaps * caps2)
1313 {
1314   guint64 i;                    /* index can be up to 2 * G_MAX_UINT */
1315   guint j, k, len1, len2;
1316
1317   GstStructure *struct1;
1318   GstStructure *struct2;
1319   GstCaps *dest;
1320   GstStructure *istruct;
1321
1322   g_return_val_if_fail (GST_IS_CAPS (caps1), NULL);
1323   g_return_val_if_fail (GST_IS_CAPS (caps2), NULL);
1324
1325   /* caps are exactly the same pointers, just copy one caps */
1326   if (G_UNLIKELY (caps1 == caps2))
1327     return _gst_caps_copy (caps1);
1328
1329   /* empty caps on either side, return empty */
1330   if (G_UNLIKELY (CAPS_IS_EMPTY (caps1) || CAPS_IS_EMPTY (caps2)))
1331     return gst_caps_new_empty ();
1332
1333   /* one of the caps is any, just copy the other caps */
1334   if (G_UNLIKELY (CAPS_IS_ANY (caps1)))
1335     return _gst_caps_copy (caps2);
1336   if (G_UNLIKELY (CAPS_IS_ANY (caps2)))
1337     return _gst_caps_copy (caps1);
1338
1339   dest = gst_caps_new_empty ();
1340
1341   /* run zigzag on top line then right line, this preserves the caps order
1342    * much better than a simple loop.
1343    *
1344    * This algorithm zigzags over the caps structures as demonstrated in
1345    * the folowing matrix:
1346    *
1347    *          caps1
1348    *       +-------------
1349    *       | 1  2  4  7
1350    * caps2 | 3  5  8 10
1351    *       | 6  9 11 12
1352    *
1353    * First we iterate over the caps1 structures (top line) intersecting
1354    * the structures diagonally down, then we iterate over the caps2
1355    * structures.
1356    */
1357   len1 = caps1->structs->len;
1358   len2 = caps2->structs->len;
1359   for (i = 0; i < len1 + len2 - 1; i++) {
1360     /* caps1 index goes from 0 to caps1->structs->len-1 */
1361     j = MIN (i, len1 - 1);
1362     /* caps2 index stays 0 until i reaches caps1->structs->len, then it counts
1363      * up from 1 to caps2->structs->len - 1 */
1364     k = MAX (0, i - j);
1365
1366     /* now run the diagonal line, end condition is the left or bottom
1367      * border */
1368     while (k < len2) {
1369       struct1 = gst_caps_get_structure_unchecked (caps1, j);
1370       struct2 = gst_caps_get_structure_unchecked (caps2, k);
1371
1372       istruct = gst_caps_structure_intersect (struct1, struct2);
1373
1374       gst_caps_append_structure (dest, istruct);
1375       /* move down left */
1376       k++;
1377       if (G_UNLIKELY (j == 0))
1378         break;                  /* so we don't roll back to G_MAXUINT */
1379       j--;
1380     }
1381   }
1382   return dest;
1383 }
1384
1385 /* subtract operation */
1386
1387 typedef struct
1388 {
1389   const GstStructure *subtract_from;
1390   GSList *put_into;
1391 }
1392 SubtractionEntry;
1393
1394 static gboolean
1395 gst_caps_structure_subtract_field (GQuark field_id, const GValue * value,
1396     gpointer user_data)
1397 {
1398   SubtractionEntry *e = user_data;
1399   GValue subtraction = { 0, };
1400   const GValue *other;
1401   GstStructure *structure;
1402
1403   other = gst_structure_id_get_value (e->subtract_from, field_id);
1404   if (!other) {
1405     return FALSE;
1406   }
1407   if (!gst_value_subtract (&subtraction, other, value))
1408     return TRUE;
1409   if (gst_value_compare (&subtraction, other) == GST_VALUE_EQUAL) {
1410     g_value_unset (&subtraction);
1411     return FALSE;
1412   } else {
1413     structure = gst_structure_copy (e->subtract_from);
1414     gst_structure_id_set_value (structure, field_id, &subtraction);
1415     g_value_unset (&subtraction);
1416     e->put_into = g_slist_prepend (e->put_into, structure);
1417     return TRUE;
1418   }
1419 }
1420
1421 static gboolean
1422 gst_caps_structure_subtract (GSList ** into, const GstStructure * minuend,
1423     const GstStructure * subtrahend)
1424 {
1425   SubtractionEntry e;
1426   gboolean ret;
1427
1428   e.subtract_from = minuend;
1429   e.put_into = NULL;
1430
1431   ret = gst_structure_foreach ((GstStructure *) subtrahend,
1432       gst_caps_structure_subtract_field, &e);
1433   if (ret) {
1434     *into = e.put_into;
1435   } else {
1436     GSList *walk;
1437
1438     for (walk = e.put_into; walk; walk = g_slist_next (walk)) {
1439       gst_structure_free (walk->data);
1440     }
1441     g_slist_free (e.put_into);
1442   }
1443   return ret;
1444 }
1445
1446 /**
1447  * gst_caps_subtract:
1448  * @minuend: #GstCaps to substract from
1449  * @subtrahend: #GstCaps to substract
1450  *
1451  * Subtracts the @subtrahend from the @minuend.
1452  * <note>This function does not work reliably if optional properties for caps
1453  * are included on one caps and omitted on the other.</note>
1454  *
1455  * Returns: the resulting caps
1456  */
1457 GstCaps *
1458 gst_caps_subtract (const GstCaps * minuend, const GstCaps * subtrahend)
1459 {
1460   guint i, j, sublen;
1461   GstStructure *min;
1462   GstStructure *sub;
1463   GstCaps *dest = NULL, *src;
1464
1465   g_return_val_if_fail (minuend != NULL, NULL);
1466   g_return_val_if_fail (subtrahend != NULL, NULL);
1467
1468   if (CAPS_IS_EMPTY (minuend) || CAPS_IS_ANY (subtrahend)) {
1469     return gst_caps_new_empty ();
1470   }
1471   if (CAPS_IS_EMPTY_SIMPLE (subtrahend))
1472     return _gst_caps_copy (minuend);
1473
1474   /* FIXME: Do we want this here or above?
1475      The reason we need this is that there is no definition about what
1476      ANY means for specific types, so it's not possible to reduce ANY partially
1477      You can only remove everything or nothing and that is done above.
1478      Note: there's a test that checks this behaviour. */
1479   g_return_val_if_fail (!CAPS_IS_ANY (minuend), NULL);
1480   sublen = subtrahend->structs->len;
1481   g_assert (sublen > 0);
1482
1483   src = _gst_caps_copy (minuend);
1484   for (i = 0; i < sublen; i++) {
1485     guint srclen;
1486
1487     sub = gst_caps_get_structure_unchecked (subtrahend, i);
1488     if (dest) {
1489       gst_caps_unref (src);
1490       src = dest;
1491     }
1492     dest = gst_caps_new_empty ();
1493     srclen = src->structs->len;
1494     for (j = 0; j < srclen; j++) {
1495       min = gst_caps_get_structure_unchecked (src, j);
1496       if (gst_structure_get_name_id (min) == gst_structure_get_name_id (sub)) {
1497         GSList *list;
1498
1499         if (gst_caps_structure_subtract (&list, min, sub)) {
1500           GSList *walk;
1501
1502           for (walk = list; walk; walk = g_slist_next (walk)) {
1503             gst_caps_append_structure_unchecked (dest,
1504                 (GstStructure *) walk->data);
1505           }
1506           g_slist_free (list);
1507         } else {
1508           gst_caps_append_structure_unchecked (dest, gst_structure_copy (min));
1509         }
1510       } else {
1511         gst_caps_append_structure_unchecked (dest, gst_structure_copy (min));
1512       }
1513     }
1514     if (CAPS_IS_EMPTY_SIMPLE (dest)) {
1515       gst_caps_unref (src);
1516       return dest;
1517     }
1518   }
1519
1520   gst_caps_unref (src);
1521   gst_caps_do_simplify (dest);
1522   return dest;
1523 }
1524
1525 /* union operation */
1526
1527 #if 0
1528 static GstStructure *
1529 gst_caps_structure_union (const GstStructure * struct1,
1530     const GstStructure * struct2)
1531 {
1532   int i;
1533   GstStructure *dest;
1534   const GstStructureField *field1;
1535   const GstStructureField *field2;
1536   int ret;
1537
1538   /* FIXME this doesn't actually work */
1539
1540   if (struct1->name != struct2->name)
1541     return NULL;
1542
1543   dest = gst_structure_id_empty_new (struct1->name);
1544
1545   for (i = 0; i < struct1->fields->len; i++) {
1546     GValue dest_value = { 0 };
1547
1548     field1 = GST_STRUCTURE_FIELD (struct1, i);
1549     field2 = gst_structure_id_get_field (struct2, field1->name);
1550
1551     if (field2 == NULL) {
1552       continue;
1553     } else {
1554       if (gst_value_union (&dest_value, &field1->value, &field2->value)) {
1555         gst_structure_set_value (dest, g_quark_to_string (field1->name),
1556             &dest_value);
1557       } else {
1558         ret = gst_value_compare (&field1->value, &field2->value);
1559       }
1560     }
1561   }
1562
1563   return dest;
1564 }
1565 #endif
1566
1567 /**
1568  * gst_caps_union:
1569  * @caps1: a #GstCaps to union
1570  * @caps2: a #GstCaps to union
1571  *
1572  * Creates a new #GstCaps that contains all the formats that are in
1573  * either @caps1 and @caps2.
1574  *
1575  * Returns: the new #GstCaps
1576  */
1577 GstCaps *
1578 gst_caps_union (const GstCaps * caps1, const GstCaps * caps2)
1579 {
1580   GstCaps *dest1;
1581   GstCaps *dest2;
1582
1583   /* NULL pointers are no correct GstCaps */
1584   g_return_val_if_fail (caps1 != NULL, NULL);
1585   g_return_val_if_fail (caps2 != NULL, NULL);
1586
1587   if (CAPS_IS_EMPTY (caps1))
1588     return _gst_caps_copy (caps2);
1589
1590   if (CAPS_IS_EMPTY (caps2))
1591     return _gst_caps_copy (caps1);
1592
1593   if (CAPS_IS_ANY (caps1) || CAPS_IS_ANY (caps2))
1594     return gst_caps_new_any ();
1595
1596   dest1 = _gst_caps_copy (caps1);
1597   dest2 = _gst_caps_copy (caps2);
1598   gst_caps_append (dest1, dest2);
1599
1600   gst_caps_do_simplify (dest1);
1601   return dest1;
1602 }
1603
1604 /* normalize/simplify operations */
1605
1606 typedef struct _NormalizeForeach
1607 {
1608   GstCaps *caps;
1609   GstStructure *structure;
1610 }
1611 NormalizeForeach;
1612
1613 static gboolean
1614 gst_caps_normalize_foreach (GQuark field_id, const GValue * value, gpointer ptr)
1615 {
1616   NormalizeForeach *nf = (NormalizeForeach *) ptr;
1617   GValue val = { 0 };
1618   guint i;
1619
1620   if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
1621     guint len = gst_value_list_get_size (value);
1622     for (i = 1; i < len; i++) {
1623       const GValue *v = gst_value_list_get_value (value, i);
1624       GstStructure *structure = gst_structure_copy (nf->structure);
1625
1626       gst_structure_id_set_value (structure, field_id, v);
1627       gst_caps_append_structure_unchecked (nf->caps, structure);
1628     }
1629
1630     gst_value_init_and_copy (&val, gst_value_list_get_value (value, 0));
1631     gst_structure_id_set_value (nf->structure, field_id, &val);
1632     g_value_unset (&val);
1633
1634     return FALSE;
1635   }
1636   return TRUE;
1637 }
1638
1639 /**
1640  * gst_caps_normalize:
1641  * @caps: a #GstCaps to normalize
1642  *
1643  * Creates a new #GstCaps that represents the same set of formats as
1644  * @caps, but contains no lists.  Each list is expanded into separate
1645  * @GstStructures.
1646  *
1647  * Returns: the new #GstCaps
1648  */
1649 GstCaps *
1650 gst_caps_normalize (const GstCaps * caps)
1651 {
1652   NormalizeForeach nf;
1653   GstCaps *newcaps;
1654   guint i;
1655
1656   g_return_val_if_fail (GST_IS_CAPS (caps), NULL);
1657
1658   newcaps = _gst_caps_copy (caps);
1659   nf.caps = newcaps;
1660
1661   for (i = 0; i < gst_caps_get_size (newcaps); i++) {
1662     nf.structure = gst_caps_get_structure_unchecked (newcaps, i);
1663
1664     while (!gst_structure_foreach (nf.structure,
1665             gst_caps_normalize_foreach, &nf));
1666   }
1667
1668   return newcaps;
1669 }
1670
1671 static gint
1672 gst_caps_compare_structures (gconstpointer one, gconstpointer two)
1673 {
1674   gint ret;
1675   const GstStructure *struct1 = *((const GstStructure **) one);
1676   const GstStructure *struct2 = *((const GstStructure **) two);
1677
1678   /* FIXME: this orders alphabetically, but ordering the quarks might be faster
1679      So what's the best way? */
1680   ret = strcmp (gst_structure_get_name (struct1),
1681       gst_structure_get_name (struct2));
1682   if (ret)
1683     return ret;
1684
1685   return gst_structure_n_fields (struct2) - gst_structure_n_fields (struct1);
1686 }
1687
1688 typedef struct
1689 {
1690   GQuark name;
1691   GValue value;
1692   GstStructure *compare;
1693 }
1694 UnionField;
1695
1696 static gboolean
1697 gst_caps_structure_figure_out_union (GQuark field_id, const GValue * value,
1698     gpointer user_data)
1699 {
1700   UnionField *u = user_data;
1701   const GValue *val = gst_structure_id_get_value (u->compare, field_id);
1702
1703   if (!val) {
1704     if (u->name)
1705       g_value_unset (&u->value);
1706     return FALSE;
1707   }
1708   if (gst_value_compare (val, value) == GST_VALUE_EQUAL)
1709     return TRUE;
1710   if (u->name) {
1711     g_value_unset (&u->value);
1712     return FALSE;
1713   }
1714   u->name = field_id;
1715   gst_value_union (&u->value, val, value);
1716   return TRUE;
1717 }
1718
1719 static gboolean
1720 gst_caps_structure_simplify (GstStructure ** result,
1721     const GstStructure * simplify, GstStructure * compare)
1722 {
1723   GSList *list;
1724   UnionField field = { 0, {0,}, NULL };
1725
1726   /* try to subtract to get a real subset */
1727   if (gst_caps_structure_subtract (&list, simplify, compare)) {
1728     if (list == NULL) {         /* no result */
1729       *result = NULL;
1730       return TRUE;
1731     } else if (list->next == NULL) {    /* one result */
1732       *result = list->data;
1733       g_slist_free (list);
1734       return TRUE;
1735     } else {                    /* multiple results */
1736       g_slist_foreach (list, (GFunc) gst_structure_free, NULL);
1737       g_slist_free (list);
1738       list = NULL;
1739     }
1740   }
1741
1742   /* try to union both structs */
1743   field.compare = compare;
1744   if (gst_structure_foreach ((GstStructure *) simplify,
1745           gst_caps_structure_figure_out_union, &field)) {
1746     gboolean ret = FALSE;
1747
1748     /* now we know all of simplify's fields are the same in compare
1749      * but at most one field: field.name */
1750     if (G_IS_VALUE (&field.value)) {
1751       if (gst_structure_n_fields (simplify) == gst_structure_n_fields (compare)) {
1752         gst_structure_id_set_value (compare, field.name, &field.value);
1753         *result = NULL;
1754         ret = TRUE;
1755       }
1756       g_value_unset (&field.value);
1757     } else if (gst_structure_n_fields (simplify) <=
1758         gst_structure_n_fields (compare)) {
1759       /* compare is just more specific, will be optimized away later */
1760       /* FIXME: do this here? */
1761       GST_LOG ("found a case that will be optimized later.");
1762     } else {
1763       gchar *one = gst_structure_to_string (simplify);
1764       gchar *two = gst_structure_to_string (compare);
1765
1766       GST_ERROR
1767           ("caps mismatch: structures %s and %s claim to be possible to unify, but aren't",
1768           one, two);
1769       g_free (one);
1770       g_free (two);
1771     }
1772     return ret;
1773   }
1774
1775   return FALSE;
1776 }
1777
1778 static void
1779 gst_caps_switch_structures (GstCaps * caps, GstStructure * old,
1780     GstStructure * new, gint i)
1781 {
1782   gst_structure_set_parent_refcount (old, NULL);
1783   gst_structure_free (old);
1784   gst_structure_set_parent_refcount (new, &GST_CAPS_REFCOUNT (caps));
1785   g_ptr_array_index (caps->structs, i) = new;
1786 }
1787
1788 /**
1789  * gst_caps_do_simplify:
1790  * @caps: a #GstCaps to simplify
1791  *
1792  * Modifies the given @caps inplace into a representation that represents the
1793  * same set of formats, but in a simpler form.  Component structures that are
1794  * identical are merged.  Component structures that have values that can be
1795  * merged are also merged.
1796  *
1797  * Returns: TRUE, if the caps could be simplified
1798  */
1799 gboolean
1800 gst_caps_do_simplify (GstCaps * caps)
1801 {
1802   GstStructure *simplify, *compare, *result = NULL;
1803   gint i, j, start;
1804   gboolean changed = FALSE;
1805
1806   g_return_val_if_fail (caps != NULL, FALSE);
1807   g_return_val_if_fail (IS_WRITABLE (caps), FALSE);
1808
1809   if (gst_caps_get_size (caps) < 2)
1810     return FALSE;
1811
1812   g_ptr_array_sort (caps->structs, gst_caps_compare_structures);
1813
1814   start = caps->structs->len - 1;
1815   for (i = caps->structs->len - 1; i >= 0; i--) {
1816     simplify = gst_caps_get_structure_unchecked (caps, i);
1817     if (gst_structure_get_name_id (simplify) !=
1818         gst_structure_get_name_id (gst_caps_get_structure_unchecked (caps,
1819                 start)))
1820       start = i;
1821     for (j = start; j >= 0; j--) {
1822       if (j == i)
1823         continue;
1824       compare = gst_caps_get_structure_unchecked (caps, j);
1825       if (gst_structure_get_name_id (simplify) !=
1826           gst_structure_get_name_id (compare)) {
1827         break;
1828       }
1829       if (gst_caps_structure_simplify (&result, simplify, compare)) {
1830         if (result) {
1831           gst_caps_switch_structures (caps, simplify, result, i);
1832           simplify = result;
1833         } else {
1834           gst_caps_remove_structure (caps, i);
1835           start--;
1836           break;
1837         }
1838         changed = TRUE;
1839       }
1840     }
1841   }
1842
1843   if (!changed)
1844     return FALSE;
1845
1846   /* gst_caps_do_simplify (caps); */
1847   return TRUE;
1848 }
1849
1850 /* utility */
1851
1852 /**
1853  * gst_caps_replace:
1854  * @caps: (inout) (transfer full): a pointer to #GstCaps
1855  * @newcaps: a #GstCaps to replace *caps
1856  *
1857  * Replaces *caps with @newcaps.  Unrefs the #GstCaps in the location
1858  * pointed to by @caps, if applicable, then modifies @caps to point to
1859  * @newcaps. An additional ref on @newcaps is taken.
1860  *
1861  * This function does not take any locks so you might want to lock
1862  * the object owning @caps pointer.
1863  */
1864 void
1865 gst_caps_replace (GstCaps ** caps, GstCaps * newcaps)
1866 {
1867   GstCaps *oldcaps;
1868
1869   g_return_if_fail (caps != NULL);
1870
1871   oldcaps = *caps;
1872
1873   GST_CAT_TRACE (GST_CAT_REFCOUNTING, "%p, %p -> %p", caps, oldcaps, newcaps);
1874
1875   if (newcaps != oldcaps) {
1876     if (newcaps)
1877       gst_caps_ref (newcaps);
1878
1879     *caps = newcaps;
1880
1881     if (oldcaps)
1882       gst_caps_unref (oldcaps);
1883   }
1884 }
1885
1886 /**
1887  * gst_caps_to_string:
1888  * @caps: a #GstCaps
1889  *
1890  * Converts @caps to a string representation.  This string representation
1891  * can be converted back to a #GstCaps by gst_caps_from_string().
1892  *
1893  * For debugging purposes its easier to do something like this:
1894  * |[
1895  * GST_LOG ("caps are %" GST_PTR_FORMAT, caps);
1896  * ]|
1897  * This prints the caps in human readble form.
1898  *
1899  * Returns: (transfer full): a newly allocated string representing @caps.
1900  */
1901 gchar *
1902 gst_caps_to_string (const GstCaps * caps)
1903 {
1904   guint i, slen, clen;
1905   GString *s;
1906
1907   /* NOTE:  This function is potentially called by the debug system,
1908    * so any calls to gst_log() (and GST_DEBUG(), GST_LOG(), etc.)
1909    * should be careful to avoid recursion.  This includes any functions
1910    * called by gst_caps_to_string.  In particular, calls should
1911    * not use the GST_PTR_FORMAT extension.  */
1912
1913   if (caps == NULL) {
1914     return g_strdup ("NULL");
1915   }
1916   if (CAPS_IS_ANY (caps)) {
1917     return g_strdup ("ANY");
1918   }
1919   if (CAPS_IS_EMPTY_SIMPLE (caps)) {
1920     return g_strdup ("EMPTY");
1921   }
1922
1923   /* estimate a rough string length to avoid unnecessary reallocs in GString */
1924   slen = 0;
1925   clen = caps->structs->len;
1926   for (i = 0; i < clen; i++) {
1927     slen +=
1928         STRUCTURE_ESTIMATED_STRING_LEN (gst_caps_get_structure_unchecked (caps,
1929             i));
1930   }
1931
1932   s = g_string_sized_new (slen);
1933   for (i = 0; i < clen; i++) {
1934     GstStructure *structure;
1935
1936     if (i > 0) {
1937       /* ';' is now added by gst_structure_to_string */
1938       g_string_append_c (s, ' ');
1939     }
1940
1941     structure = gst_caps_get_structure_unchecked (caps, i);
1942     priv_gst_structure_append_to_gstring (structure, s);
1943   }
1944   if (s->len && s->str[s->len - 1] == ';') {
1945     /* remove latest ';' */
1946     s->str[--s->len] = '\0';
1947   }
1948   return g_string_free (s, FALSE);
1949 }
1950
1951 static gboolean
1952 gst_caps_from_string_inplace (GstCaps * caps, const gchar * string)
1953 {
1954   GstStructure *structure;
1955   gchar *s;
1956
1957   if (strcmp ("ANY", string) == 0) {
1958     GST_CAPS_FLAGS (caps) = GST_CAPS_FLAGS_ANY;
1959     return TRUE;
1960   }
1961   if (strcmp ("EMPTY", string) == 0) {
1962     return TRUE;
1963   }
1964
1965   structure = gst_structure_from_string (string, &s);
1966   if (structure == NULL) {
1967     return FALSE;
1968   }
1969   gst_caps_append_structure_unchecked (caps, structure);
1970
1971   do {
1972
1973     while (g_ascii_isspace (*s))
1974       s++;
1975     if (*s == '\0') {
1976       break;
1977     }
1978     structure = gst_structure_from_string (s, &s);
1979     if (structure == NULL) {
1980       return FALSE;
1981     }
1982     gst_caps_append_structure_unchecked (caps, structure);
1983
1984   } while (TRUE);
1985
1986   return TRUE;
1987 }
1988
1989 /**
1990  * gst_caps_from_string:
1991  * @string: a string to convert to #GstCaps
1992  *
1993  * Converts @caps from a string representation.
1994  *
1995  * Returns: (transfer full): a newly allocated #GstCaps
1996  */
1997 GstCaps *
1998 gst_caps_from_string (const gchar * string)
1999 {
2000   GstCaps *caps;
2001
2002   g_return_val_if_fail (string, FALSE);
2003
2004   caps = gst_caps_new_empty ();
2005   if (gst_caps_from_string_inplace (caps, string)) {
2006     return caps;
2007   } else {
2008     gst_caps_unref (caps);
2009     return NULL;
2010   }
2011 }
2012
2013 static void
2014 gst_caps_transform_to_string (const GValue * src_value, GValue * dest_value)
2015 {
2016   g_return_if_fail (G_IS_VALUE (src_value));
2017   g_return_if_fail (G_IS_VALUE (dest_value));
2018   g_return_if_fail (G_VALUE_HOLDS (src_value, GST_TYPE_CAPS));
2019   g_return_if_fail (G_VALUE_HOLDS (dest_value, G_TYPE_STRING)
2020       || G_VALUE_HOLDS (dest_value, G_TYPE_POINTER));
2021
2022   dest_value->data[0].v_pointer =
2023       gst_caps_to_string (src_value->data[0].v_pointer);
2024 }