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