preset: don't return empty preset lists
[platform/upstream/gstreamer.git] / gst / gstpreset.c
1 /* GStreamer
2  * Copyright (C) 2006 Stefan Kost <ensonic@users.sf.net>
3  *
4  * gstpreset.c: helper interface for element presets
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21 /**
22  * SECTION:gstpreset
23  * @short_description: helper interface for element presets
24  *
25  * This interface offers methods to query and manipulate parameter preset sets.
26  * A preset is a bunch of property settings, together with meta data and a name.
27  * The name of a preset serves as key for subsequent method calls to manipulate
28  * single presets.
29  * All instances of one type will share the list of presets. The list is created
30  * on demand, if presets are not used, the list is not created.
31  *
32  * The interface comes with a default implementation that serves most plugins.
33  * Wrapper plugins will override most methods to implement support for the
34  * native preset format of those wrapped plugins.
35  * One method that is useful to be overridden is gst_preset_get_property_names().
36  * With that one can control which properties are saved and in which order.
37  * When implementing support for read-only presets, one should set the vmethods
38  * for gst_preset_save_preset() and gst_preset_delete_preset() to %NULL.
39  * Applications can use gst_preset_is_editable() to check for that.
40  *
41  * The default implementation supports presets located in a system directory, 
42  * application specific directory and in the users home directory. When getting
43  * a list of presets individual presets are read and overlaid in 1) system, 
44  * 2) application and 3) user order. Whenever an earlier entry is newer, the
45  * later entries will be updated. 
46  * 
47  */
48 /* FIXME:
49  * - non racyness
50  *   - we need to avoid two instances writing the preset file
51  *     -> flock(fileno()), http://www.ecst.csuchico.edu/~beej/guide/ipc/flock.html
52  *     -> open exclusive
53  *     -> better save the new file to a tempfile and then rename?
54  *   - we like to know when any other instance makes changes to the keyfile
55  *     - then ui can be updated
56  *     - and we make sure that we don't lose edits
57  *   -> its the same problem actually, once for inside a process, once system-
58  *      wide
59  *     - can we use a lock inside a names shared memory segment?
60  *
61  * - should there be a 'preset-list' property to get the preset list
62  *   (and to connect a notify:: to to listen for changes)
63  *   we could use gnome_vfs_monitor_add() to monitor the user preset_file.
64  *
65  * - should there be a 'preset-name' property so that we can set a preset via
66  *   gst-launch, or should we handle this with special syntax in gst-launch:
67  *   gst-launch element preset:<preset-name> property=value ...
68  *   - this would allow to have preset-bundles too (a preset on bins that
69  *     specifies presets for children
70  */
71
72 #include "gst_private.h"
73
74 #include "gstpreset.h"
75 #include "gstchildproxy.h"
76 #include "gstinfo.h"
77 #include "gstvalue.h"
78
79 #ifdef HAVE_UNISTD_H
80 #include <unistd.h>
81 #endif
82 #include <glib/gstdio.h>
83
84 #ifdef G_OS_WIN32
85 #define WIN32_LEAN_AND_MEAN
86 #include <windows.h>
87
88 extern HMODULE _priv_gst_dll_handle;
89 #endif
90
91 #define GST_CAT_DEFAULT preset_debug
92 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
93
94 /* defines for keyfile usage, this group contains the element type name and
95  * version these presets belong to. */
96 #define PRESET_HEADER "_presets_"
97
98 /* keys of the preset header section */
99 #define PRESET_HEADER_ELEMENT_NAME "element-name"
100 #define PRESET_HEADER_VERSION "version"
101
102 static GQuark preset_user_path_quark = 0;
103 static GQuark preset_app_path_quark = 0;
104 static GQuark preset_system_path_quark = 0;
105 static GQuark preset_quark = 0;
106
107 /* the application can set a custom path that is checked in addition to standard
108  * system and user dirs. This helps to develop new presets first local to the
109  * application.
110  */
111 static gchar *preset_app_dir = NULL;
112
113 /* default iface implementation */
114
115 static gboolean gst_preset_default_save_presets_file (GstPreset * preset);
116
117 /*
118  * preset_get_paths:
119  * @preset: a #GObject that implements #GstPreset
120  * @preset_user_path: (out) (allow-none): location for path or %NULL
121  * @preset_app_path: (out) (allow-none): location for path or %NULL
122  * @preset_system_path: (out) (allow-none): location for path or %NULL
123  *
124  * Fetch the preset_path for user local, application specific and system wide
125  * settings. Don't free after use.
126  *
127  * Returns: %FALSE if no paths could be found.
128  */
129 static gboolean
130 preset_get_paths (GstPreset * preset, const gchar ** preset_user_path,
131     const gchar ** preset_app_path, const gchar ** preset_system_path)
132 {
133   GType type = G_TYPE_FROM_INSTANCE (preset);
134   gchar *preset_path;
135   const gchar *element_name;
136
137   /* we use the element name when we must construct the paths */
138   element_name = G_OBJECT_TYPE_NAME (preset);
139   GST_INFO_OBJECT (preset, "element_name: '%s'", element_name);
140
141   if (preset_user_path) {
142     /* preset user path requested, see if we have it cached in the qdata */
143     if (!(preset_path = g_type_get_qdata (type, preset_user_path_quark))) {
144       gchar *preset_dir;
145
146       /* user presets go in  user's XDG data directory. */
147       preset_dir = g_build_filename (g_get_user_data_dir (),
148           "gstreamer-" GST_API_VERSION, "presets", NULL);
149       GST_INFO_OBJECT (preset, "user_preset_dir: '%s'", preset_dir);
150       preset_path =
151           g_strdup_printf ("%s" G_DIR_SEPARATOR_S "%s.prs", preset_dir,
152           element_name);
153       GST_INFO_OBJECT (preset, "user_preset_path: '%s'", preset_path);
154       /* create dirs */
155       g_mkdir_with_parents (preset_dir, 0755);
156       g_free (preset_dir);
157
158       /* cache the preset path to the type */
159       g_type_set_qdata (type, preset_user_path_quark, preset_path);
160     }
161     *preset_user_path = preset_path;
162   }
163
164   if (preset_app_path) {
165     if (preset_app_dir) {
166       if (!(preset_path = g_type_get_qdata (type, preset_system_path_quark))) {
167         preset_path = g_strdup_printf ("%s" G_DIR_SEPARATOR_S "%s.prs",
168             preset_app_dir, element_name);
169         GST_INFO_OBJECT (preset, "application_preset_path: '%s'", preset_path);
170
171         /* cache the preset path to the type */
172         g_type_set_qdata (type, preset_app_path_quark, preset_path);
173       }
174       *preset_app_path = preset_path;
175     } else {
176       *preset_app_path = NULL;
177     }
178   }
179
180   if (preset_system_path) {
181     /* preset system path requested, see if we have it cached in the qdata */
182     if (!(preset_path = g_type_get_qdata (type, preset_system_path_quark))) {
183       gchar *preset_dir;
184
185       /* system presets in '$GST_DATADIR/gstreamer-1.0/presets/GstAudioPanorama.prs' */
186 #ifdef G_OS_WIN32
187       gchar *basedir =
188           g_win32_get_package_installation_directory_of_module
189           (_priv_gst_dll_handle);
190       preset_dir =
191           g_build_filename (basedir, "share", "gstreamer-" GST_API_VERSION,
192           "presets", NULL);
193       g_free (basedir);
194 #else
195       preset_dir = g_build_filename (GST_DATADIR, "gstreamer-" GST_API_VERSION,
196           "presets", NULL);
197 #endif
198       GST_INFO_OBJECT (preset, "system_preset_dir: '%s'", preset_dir);
199       preset_path = g_strdup_printf ("%s" G_DIR_SEPARATOR_S "%s.prs",
200           preset_dir, element_name);
201       GST_INFO_OBJECT (preset, "system_preset_path: '%s'", preset_path);
202       /* create dirs */
203       g_mkdir_with_parents (preset_dir, 0755);
204       g_free (preset_dir);
205
206       /* cache the preset path to the type */
207       g_type_set_qdata (type, preset_system_path_quark, preset_path);
208     }
209     *preset_system_path = preset_path;
210   }
211   return TRUE;
212 }
213
214 static gboolean
215 preset_skip_property (GParamSpec * property)
216 {
217   if (((property->flags & G_PARAM_READWRITE) != G_PARAM_READWRITE) ||
218       (property->flags & G_PARAM_CONSTRUCT_ONLY))
219     return TRUE;
220   /* FIXME: skip GST_PARAM_NOT_PRESETABLE, see #522205 */
221   return FALSE;
222 }
223
224 static guint64
225 preset_parse_version (const gchar * str_version)
226 {
227   guint major, minor, micro, nano;
228   gint num;
229
230   major = minor = micro = nano = 0;
231
232   /* parse version (e.g. 0.10.15.1) to guint64 */
233   num = sscanf (str_version, "%u.%u.%u.%u", &major, &minor, &micro, &nano);
234   /* make sure we have at least "major.minor" */
235   if (num > 1) {
236     guint64 version;
237
238     version = ((((major << 8 | minor) << 8) | micro) << 8) | nano;
239     GST_DEBUG ("version %s -> %" G_GUINT64_FORMAT, str_version, version);
240     return version;
241   }
242   return G_GUINT64_CONSTANT (0);
243 }
244
245 static GKeyFile *
246 preset_open_and_parse_header (GstPreset * preset, const gchar * preset_path,
247     guint64 * preset_version)
248 {
249   GKeyFile *in;
250   GError *error = NULL;
251   gboolean res;
252   const gchar *element_name;
253   gchar *name;
254
255   in = g_key_file_new ();
256
257   res = g_key_file_load_from_file (in, preset_path,
258       G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS, &error);
259   if (!res || error != NULL)
260     goto load_error;
261
262   /* element type name and preset name must match or we are dealing with a wrong
263    * preset file */
264   element_name = G_OBJECT_TYPE_NAME (preset);
265   name =
266       g_key_file_get_value (in, PRESET_HEADER, PRESET_HEADER_ELEMENT_NAME,
267       NULL);
268
269   if (!name || strcmp (name, element_name))
270     goto wrong_name;
271
272   g_free (name);
273
274   /* get the version now so that the caller can check it */
275   if (preset_version) {
276     gchar *str =
277         g_key_file_get_value (in, PRESET_HEADER, PRESET_HEADER_VERSION, NULL);
278     *preset_version = preset_parse_version (str);
279     g_free (str);
280   }
281
282   return in;
283
284   /* ERRORS */
285 load_error:
286   {
287     GST_WARNING_OBJECT (preset, "Unable to read preset file %s: %s",
288         preset_path, error->message);
289     g_error_free (error);
290     g_key_file_free (in);
291     return NULL;
292   }
293 wrong_name:
294   {
295     GST_WARNING_OBJECT (preset,
296         "Wrong element name in preset file %s. Expected %s, got %s",
297         preset_path, element_name, GST_STR_NULL (name));
298     g_free (name);
299     g_key_file_free (in);
300     return NULL;
301   }
302 }
303
304 static void
305 preset_merge (GKeyFile * system, GKeyFile * user)
306 {
307   gchar *str;
308   gchar **groups, **keys;
309   gsize i, j, num_groups, num_keys;
310
311   /* copy file comment if there is any */
312   if ((str = g_key_file_get_comment (user, NULL, NULL, NULL))) {
313     g_key_file_set_comment (system, NULL, NULL, str, NULL);
314     g_free (str);
315   }
316
317   /* get groups in user and copy into system */
318   groups = g_key_file_get_groups (user, &num_groups);
319   for (i = 0; i < num_groups; i++) {
320     /* copy group comment if there is any */
321     if ((str = g_key_file_get_comment (user, groups[i], NULL, NULL))) {
322       g_key_file_set_comment (system, groups[i], NULL, str, NULL);
323       g_free (str);
324     }
325
326     /* ignore private groups */
327     if (groups[i][0] == '_')
328       continue;
329
330     /* if group already exists in system, remove and re-add keys from user */
331     if (g_key_file_has_group (system, groups[i])) {
332       g_key_file_remove_group (system, groups[i], NULL);
333     }
334
335     keys = g_key_file_get_keys (user, groups[i], &num_keys, NULL);
336     for (j = 0; j < num_keys; j++) {
337       /* copy key comment if there is any */
338       if ((str = g_key_file_get_comment (user, groups[i], keys[j], NULL))) {
339         g_key_file_set_comment (system, groups[i], keys[j], str, NULL);
340         g_free (str);
341       }
342       str = g_key_file_get_value (user, groups[i], keys[j], NULL);
343       g_key_file_set_value (system, groups[i], keys[j], str);
344       g_free (str);
345     }
346     g_strfreev (keys);
347   }
348   g_strfreev (groups);
349 }
350
351 /* reads the user and system presets files and merges them together. This
352  * function caches the GKeyFile on the element type. If there is no existing
353  * preset file, a new in-memory GKeyFile will be created. */
354 static GKeyFile *
355 preset_get_keyfile (GstPreset * preset)
356 {
357   GKeyFile *presets;
358   GType type = G_TYPE_FROM_INSTANCE (preset);
359
360   /* first see if the have a cached version for the type */
361   if (!(presets = g_type_get_qdata (type, preset_quark))) {
362     const gchar *preset_user_path, *preset_app_path, *preset_system_path;
363     guint64 version_system = G_GUINT64_CONSTANT (0);
364     guint64 version_app = G_GUINT64_CONSTANT (0);
365     guint64 version_user = G_GUINT64_CONSTANT (0);
366     guint64 version = G_GUINT64_CONSTANT (0);
367     gboolean merged = FALSE;
368     GKeyFile *in_user, *in_app = NULL, *in_system;
369
370     preset_get_paths (preset, &preset_user_path, &preset_app_path,
371         &preset_system_path);
372
373     /* try to load the user, app and system presets, we do this to get the
374      * versions of all files. */
375     in_user = preset_open_and_parse_header (preset, preset_user_path,
376         &version_user);
377     if (preset_app_path) {
378       in_app = preset_open_and_parse_header (preset, preset_app_path,
379           &version_app);
380     }
381     in_system = preset_open_and_parse_header (preset, preset_system_path,
382         &version_system);
383
384     /* compare version to check for merge */
385     if (in_system) {
386       presets = in_system;
387       version = version_system;
388     }
389     if (in_app) {
390       /* if system version is higher, merge */
391       if (version > version_app) {
392         preset_merge (presets, in_app);
393         g_key_file_free (in_app);
394       } else {
395         if (presets)
396           g_key_file_free (presets);
397         presets = in_app;
398         version = version_system;
399       }
400     }
401     if (in_user) {
402       /* if system or app version is higher, merge */
403       if (version > version_user) {
404         preset_merge (presets, in_user);
405         g_key_file_free (in_user);
406         merged = TRUE;
407       } else {
408         if (presets)
409           g_key_file_free (presets);
410         presets = in_user;
411       }
412     }
413
414     if (!presets) {
415       /* we did not load a user, app or system presets file, create a new one */
416       presets = g_key_file_new ();
417       g_key_file_set_string (presets, PRESET_HEADER, PRESET_HEADER_ELEMENT_NAME,
418           G_OBJECT_TYPE_NAME (preset));
419     }
420
421     /* attach the preset to the type */
422     g_type_set_qdata (type, preset_quark, (gpointer) presets);
423
424     if (merged) {
425       gst_preset_default_save_presets_file (preset);
426     }
427   }
428   return presets;
429 }
430
431 /* get a list of all supported preset names for an element */
432 static gchar **
433 gst_preset_default_get_preset_names (GstPreset * preset)
434 {
435   GKeyFile *presets;
436   gsize i, num_groups;
437   gchar **groups;
438
439   /* get the presets from the type */
440   if (!(presets = preset_get_keyfile (preset)))
441     goto no_presets;
442
443   /* get the groups, which are also the preset names */
444   if (!(groups = g_key_file_get_groups (presets, &num_groups)))
445     goto no_groups;
446
447   /* remove all private group names starting with '_' from the array */
448   for (i = 0; i < num_groups; i++) {
449     if (groups[i][0] == '_') {
450       /* free private group */
451       g_free (groups[i]);
452       /* move last element of list down */
453       num_groups--;
454       /* move last element into removed element */
455       groups[i] = groups[num_groups];
456       groups[num_groups] = NULL;
457     }
458   }
459   if (!num_groups) {
460     GST_INFO_OBJECT (preset, "Empty preset file");
461     g_strfreev (groups);
462     return NULL;
463   }
464
465   /* sort the array now */
466   g_qsort_with_data (groups, num_groups, sizeof (gchar *),
467       (GCompareDataFunc) strcmp, NULL);
468
469   return groups;
470
471   /* ERRORS */
472 no_presets:
473   {
474     GST_WARNING_OBJECT (preset, "Could not load presets");
475     return NULL;
476   }
477 no_groups:
478   {
479     GST_WARNING_OBJECT (preset, "Could not find preset groups");
480     return NULL;
481   }
482 }
483
484 /* get a list of all property names that are used for presets */
485 static gchar **
486 gst_preset_default_get_property_names (GstPreset * preset)
487 {
488   GParamSpec **props;
489   guint i, j = 0, n_props;
490   GObjectClass *gclass;
491   gboolean is_child_proxy;
492   gchar **result = NULL;
493
494   gclass = G_OBJECT_CLASS (GST_ELEMENT_GET_CLASS (preset));
495   is_child_proxy = GST_IS_CHILD_PROXY (preset);
496
497   /* get a list of object properties */
498   props = g_object_class_list_properties (gclass, &n_props);
499   if (props) {
500     /* allocate array big enough to hold the worst case, including a terminating
501      * NULL pointer. */
502     result = g_new (gchar *, n_props + 1);
503
504     /* now filter out the properties that we can use for presets */
505     GST_DEBUG_OBJECT (preset, "  filtering properties: %u", n_props);
506     for (i = 0; i < n_props; i++) {
507       if (preset_skip_property (props[i]))
508         continue;
509       GST_DEBUG_OBJECT (preset, "    using: %s", props[i]->name);
510       result[j++] = g_strdup (props[i]->name);
511     }
512     g_free (props);
513   }
514
515   if (is_child_proxy) {
516     guint c, n_children;
517     GObject *child;
518
519     n_children = gst_child_proxy_get_children_count ((GstChildProxy *) preset);
520     for (c = 0; c < n_children; c++) {
521       child = gst_child_proxy_get_child_by_index ((GstChildProxy *) preset, c);
522       gclass = G_OBJECT_CLASS (GST_ELEMENT_GET_CLASS (child));
523
524       props = g_object_class_list_properties (gclass, &n_props);
525       if (props) {
526         /* resize property name array */
527         result = g_renew (gchar *, result, j + n_props + 1);
528
529         /* now filter out the properties that we can use for presets */
530         GST_DEBUG_OBJECT (preset, "  filtering properties: %u", n_props);
531         for (i = 0; i < n_props; i++) {
532           if (preset_skip_property (props[i]))
533             continue;
534           GST_DEBUG_OBJECT (preset, "    using: %s::%s",
535               GST_OBJECT_NAME (child), props[i]->name);
536           result[j++] = g_strdup_printf ("%s::%s", GST_OBJECT_NAME (child),
537               props[i]->name);
538         }
539         g_free (props);
540       }
541
542       g_object_unref (child);
543     }
544   }
545   if (!result) {
546     GST_INFO_OBJECT (preset, "object has no properties");
547   } else {
548     result[j] = NULL;
549   }
550   return result;
551 }
552
553 /* load the presets of @name for the instance @preset. Returns %FALSE if something
554  * failed. */
555 static gboolean
556 gst_preset_default_load_preset (GstPreset * preset, const gchar * name)
557 {
558   GKeyFile *presets;
559   gchar **props;
560   guint i;
561   GObjectClass *gclass;
562   gboolean is_child_proxy;
563
564   /* get the presets from the type */
565   if (!(presets = preset_get_keyfile (preset)))
566     goto no_presets;
567
568   /* get the preset name */
569   if (!g_key_file_has_group (presets, name))
570     goto no_group;
571
572   GST_DEBUG_OBJECT (preset, "loading preset : '%s'", name);
573
574   /* get the properties that we can configure in this element */
575   if (!(props = gst_preset_get_property_names (preset)))
576     goto no_properties;
577
578   gclass = G_OBJECT_CLASS (GST_ELEMENT_GET_CLASS (preset));
579   is_child_proxy = GST_IS_CHILD_PROXY (preset);
580
581   /* for each of the property names, find the preset parameter and try to
582    * configure the property with its value */
583   for (i = 0; props[i]; i++) {
584     gchar *str;
585     GValue gvalue = { 0, };
586     GParamSpec *property = NULL;
587
588     /* check if we have a settings for this element property */
589     if (!(str = g_key_file_get_value (presets, name, props[i], NULL))) {
590       /* the element has a property but the parameter is not in the keyfile */
591       GST_WARNING_OBJECT (preset, "parameter '%s' not in preset", props[i]);
592       continue;
593     }
594
595     GST_DEBUG_OBJECT (preset, "setting value '%s' for property '%s'", str,
596         props[i]);
597
598     if (is_child_proxy) {
599       gst_child_proxy_lookup ((GstChildProxy *) preset, props[i], NULL,
600           &property);
601     } else {
602       property = g_object_class_find_property (gclass, props[i]);
603     }
604     if (!property) {
605       /* the parameter was in the keyfile, the element said it supported it but
606        * then the property was not found in the element. This should not happen. */
607       GST_WARNING_OBJECT (preset, "property '%s' not in object", props[i]);
608       g_free (str);
609       continue;
610     }
611
612     /* try to deserialize the property value from the keyfile and set it as
613      * the object property */
614     g_value_init (&gvalue, property->value_type);
615     if (gst_value_deserialize (&gvalue, str)) {
616       if (is_child_proxy) {
617         gst_child_proxy_set_property ((GstChildProxy *) preset, props[i],
618             &gvalue);
619       } else {
620         g_object_set_property ((GObject *) preset, props[i], &gvalue);
621       }
622     } else {
623       GST_WARNING_OBJECT (preset,
624           "deserialization of value '%s' for property '%s' failed", str,
625           props[i]);
626     }
627     g_value_unset (&gvalue);
628     g_free (str);
629   }
630   g_strfreev (props);
631
632   return TRUE;
633
634   /* ERRORS */
635 no_presets:
636   {
637     GST_WARNING_OBJECT (preset, "no presets");
638     return FALSE;
639   }
640 no_group:
641   {
642     GST_WARNING_OBJECT (preset, "no preset named '%s'", name);
643     return FALSE;
644   }
645 no_properties:
646   {
647     GST_INFO_OBJECT (preset, "no properties");
648     return FALSE;
649   }
650 }
651
652 /* save the presets file. A copy of the existing presets file is stored in a
653  * .bak file */
654 static gboolean
655 gst_preset_default_save_presets_file (GstPreset * preset)
656 {
657   GKeyFile *presets;
658   const gchar *preset_path;
659   GError *error = NULL;
660   gchar *bak_file_name;
661   gboolean backup = TRUE;
662   gchar *data;
663   gsize data_size;
664
665   preset_get_paths (preset, &preset_path, NULL, NULL);
666
667   /* get the presets from the type */
668   if (!(presets = preset_get_keyfile (preset)))
669     goto no_presets;
670
671   GST_DEBUG_OBJECT (preset, "saving preset file: '%s'", preset_path);
672
673   /* create backup if possible */
674   bak_file_name = g_strdup_printf ("%s.bak", preset_path);
675   if (g_file_test (bak_file_name, G_FILE_TEST_EXISTS)) {
676     if (g_unlink (bak_file_name)) {
677       backup = FALSE;
678       GST_INFO_OBJECT (preset, "cannot remove old backup file : %s",
679           bak_file_name);
680     }
681   }
682   if (backup) {
683     if (g_rename (preset_path, bak_file_name)) {
684       GST_INFO_OBJECT (preset, "cannot backup file : %s -> %s", preset_path,
685           bak_file_name);
686     }
687   }
688   g_free (bak_file_name);
689
690   /* update gstreamer version */
691   g_key_file_set_string (presets, PRESET_HEADER, PRESET_HEADER_VERSION,
692       PACKAGE_VERSION);
693
694   /* get new contents, wee need this to save it */
695   if (!(data = g_key_file_to_data (presets, &data_size, &error)))
696     goto convert_failed;
697
698   /* write presets */
699   if (!g_file_set_contents (preset_path, data, data_size, &error))
700     goto write_failed;
701
702   g_free (data);
703
704   return TRUE;
705
706   /* ERRORS */
707 no_presets:
708   {
709     GST_WARNING_OBJECT (preset,
710         "no presets, trying to unlink possibly existing preset file: '%s'",
711         preset_path);
712     g_unlink (preset_path);
713     return FALSE;
714   }
715 convert_failed:
716   {
717     GST_WARNING_OBJECT (preset, "can not get the keyfile contents: %s",
718         error->message);
719     g_error_free (error);
720     g_free (data);
721     return FALSE;
722   }
723 write_failed:
724   {
725     GST_WARNING_OBJECT (preset, "Unable to store preset file %s: %s",
726         preset_path, error->message);
727     g_error_free (error);
728     g_free (data);
729     return FALSE;
730   }
731 }
732
733 /* save the preset with the given name */
734 static gboolean
735 gst_preset_default_save_preset (GstPreset * preset, const gchar * name)
736 {
737   GKeyFile *presets;
738   gchar **props;
739   guint i;
740   GObjectClass *gclass;
741   gboolean is_child_proxy;
742
743   GST_INFO_OBJECT (preset, "saving new preset: %s", name);
744
745   /* get the presets from the type */
746   if (!(presets = preset_get_keyfile (preset)))
747     goto no_presets;
748
749   /* take copies of current gobject properties from preset */
750   if (!(props = gst_preset_get_property_names (preset)))
751     goto no_properties;
752
753   gclass = G_OBJECT_CLASS (GST_ELEMENT_GET_CLASS (preset));
754   is_child_proxy = GST_IS_CHILD_PROXY (preset);
755
756   /* loop over the object properties and store the property value in the
757    * keyfile */
758   for (i = 0; props[i]; i++) {
759     GValue gvalue = { 0, };
760     gchar *str;
761     GParamSpec *property = NULL;
762
763     if (is_child_proxy) {
764       gst_child_proxy_lookup ((GstChildProxy *) preset, props[i], NULL,
765           &property);
766     } else {
767       property = g_object_class_find_property (gclass, props[i]);
768     }
769     if (!property) {
770       /* the element said it supported the property but then it does not have
771        * that property. This should not happen. */
772       GST_WARNING_OBJECT (preset, "property '%s' not in object", props[i]);
773       continue;
774     }
775
776     g_value_init (&gvalue, property->value_type);
777     if (is_child_proxy) {
778       gst_child_proxy_get_property ((GstChildProxy *) preset, props[i],
779           &gvalue);
780     } else {
781       g_object_get_property ((GObject *) preset, props[i], &gvalue);
782     }
783
784     if ((str = gst_value_serialize (&gvalue))) {
785       g_key_file_set_string (presets, name, props[i], (gpointer) str);
786       g_free (str);
787     } else {
788       GST_WARNING_OBJECT (preset, "serialization for property '%s' failed",
789           props[i]);
790     }
791     g_value_unset (&gvalue);
792   }
793   GST_INFO_OBJECT (preset, "  saved");
794   g_strfreev (props);
795
796   /* save updated version */
797   return gst_preset_default_save_presets_file (preset);
798
799   /* ERRORS */
800 no_presets:
801   {
802     GST_WARNING_OBJECT (preset, "no presets");
803     return FALSE;
804   }
805 no_properties:
806   {
807     GST_INFO_OBJECT (preset, "no properties");
808     return FALSE;
809   }
810 }
811
812 /* copies all keys and comments from one group to another, deleting the old
813  * group. */
814 static gboolean
815 gst_preset_default_rename_preset (GstPreset * preset, const gchar * old_name,
816     const gchar * new_name)
817 {
818   GKeyFile *presets;
819   gchar *str;
820   gchar **keys;
821   gsize i, num_keys;
822
823   /* get the presets from the type */
824   if (!(presets = preset_get_keyfile (preset)))
825     goto no_presets;
826
827   if (!g_key_file_has_group (presets, old_name))
828     goto no_group;
829
830   /* copy group comment if there is any */
831   if ((str = g_key_file_get_comment (presets, old_name, NULL, NULL))) {
832     g_key_file_set_comment (presets, new_name, NULL, str, NULL);
833     g_free (str);
834   }
835
836   /* get all keys from the old group and copy them in the new group */
837   keys = g_key_file_get_keys (presets, old_name, &num_keys, NULL);
838   for (i = 0; i < num_keys; i++) {
839     /* copy key comment if there is any */
840     if ((str = g_key_file_get_comment (presets, old_name, keys[i], NULL))) {
841       g_key_file_set_comment (presets, new_name, keys[i], str, NULL);
842       g_free (str);
843     }
844     /* copy key value */
845     str = g_key_file_get_value (presets, old_name, keys[i], NULL);
846     g_key_file_set_value (presets, new_name, keys[i], str);
847     g_free (str);
848   }
849   g_strfreev (keys);
850
851   /* remove old group */
852   g_key_file_remove_group (presets, old_name, NULL);
853
854   /* save updated version */
855   return gst_preset_default_save_presets_file (preset);
856
857   /* ERRORS */
858 no_presets:
859   {
860     GST_WARNING_OBJECT (preset, "no presets");
861     return FALSE;
862   }
863 no_group:
864   {
865     GST_WARNING_OBJECT (preset, "no preset named %s", old_name);
866     return FALSE;
867   }
868 }
869
870 /* delete a group from the keyfile */
871 static gboolean
872 gst_preset_default_delete_preset (GstPreset * preset, const gchar * name)
873 {
874   GKeyFile *presets;
875
876   /* get the presets from the type */
877   if (!(presets = preset_get_keyfile (preset)))
878     goto no_presets;
879
880   /* get the group */
881   if (!g_key_file_has_group (presets, name))
882     goto no_group;
883
884   /* remove the group */
885   g_key_file_remove_group (presets, name, NULL);
886
887   /* save updated version */
888   return gst_preset_default_save_presets_file (preset);
889
890   /* ERRORS */
891 no_presets:
892   {
893     GST_WARNING_OBJECT (preset, "no presets");
894     return FALSE;
895   }
896 no_group:
897   {
898     GST_WARNING_OBJECT (preset, "no preset named %s", name);
899     return FALSE;
900   }
901 }
902
903 static gboolean
904 gst_preset_default_set_meta (GstPreset * preset, const gchar * name,
905     const gchar * tag, const gchar * value)
906 {
907   GKeyFile *presets;
908   gchar *key;
909
910   /* get the presets from the type */
911   if (!(presets = preset_get_keyfile (preset)))
912     goto no_presets;
913
914   key = g_strdup_printf ("_meta/%s", tag);
915   if (value && *value) {
916     g_key_file_set_value (presets, name, key, value);
917   } else {
918     g_key_file_remove_key (presets, name, key, NULL);
919   }
920   g_free (key);
921
922   /* save updated keyfile */
923   return gst_preset_default_save_presets_file (preset);
924
925   /* ERRORS */
926 no_presets:
927   {
928     GST_WARNING_OBJECT (preset, "no presets");
929     return FALSE;
930   }
931 }
932
933 /* the caller must free @value after usage */
934 static gboolean
935 gst_preset_default_get_meta (GstPreset * preset, const gchar * name,
936     const gchar * tag, gchar ** value)
937 {
938   GKeyFile *presets;
939   gchar *key;
940
941   /* get the presets from the type */
942   if (!(presets = preset_get_keyfile (preset)))
943     goto no_presets;
944
945   key = g_strdup_printf ("_meta/%s", tag);
946   *value = g_key_file_get_value (presets, name, key, NULL);
947   g_free (key);
948
949   return TRUE;
950
951   /* ERRORS */
952 no_presets:
953   {
954     GST_WARNING_OBJECT (preset, "no presets");
955     *value = NULL;
956     return FALSE;
957   }
958 }
959
960 /* wrapper */
961
962 /**
963  * gst_preset_get_preset_names:
964  * @preset: a #GObject that implements #GstPreset
965  *
966  * Get a copy of preset names as a %NULL terminated string array.
967  *
968  * Returns: (transfer full) (array zero-terminated=1) (element-type gchar*):
969  *     list with names, use g_strfreev() after usage.
970  */
971 gchar **
972 gst_preset_get_preset_names (GstPreset * preset)
973 {
974   g_return_val_if_fail (GST_IS_PRESET (preset), NULL);
975
976   return (GST_PRESET_GET_INTERFACE (preset)->get_preset_names (preset));
977 }
978
979 /**
980  * gst_preset_get_property_names:
981  * @preset: a #GObject that implements #GstPreset
982  *
983  * Get a the names of the GObject properties that can be used for presets.
984  *
985  * Returns: (transfer full) (array zero-terminated=1) (element-type gchar*): an
986  *   array of property names which should be freed with g_strfreev() after use.
987  */
988 gchar **
989 gst_preset_get_property_names (GstPreset * preset)
990 {
991   g_return_val_if_fail (GST_IS_PRESET (preset), NULL);
992
993   return (GST_PRESET_GET_INTERFACE (preset)->get_property_names (preset));
994 }
995
996 /**
997  * gst_preset_load_preset:
998  * @preset: a #GObject that implements #GstPreset
999  * @name: preset name to load
1000  *
1001  * Load the given preset.
1002  *
1003  * Returns: %TRUE for success, %FALSE if e.g. there is no preset with that @name
1004  */
1005 gboolean
1006 gst_preset_load_preset (GstPreset * preset, const gchar * name)
1007 {
1008   g_return_val_if_fail (GST_IS_PRESET (preset), FALSE);
1009   g_return_val_if_fail (name, FALSE);
1010
1011   return (GST_PRESET_GET_INTERFACE (preset)->load_preset (preset, name));
1012 }
1013
1014 /**
1015  * gst_preset_save_preset:
1016  * @preset: a #GObject that implements #GstPreset
1017  * @name: preset name to save
1018  *
1019  * Save the current object settings as a preset under the given name. If there
1020  * is already a preset by this @name it will be overwritten.
1021  *
1022  * Returns: %TRUE for success, %FALSE
1023  */
1024 gboolean
1025 gst_preset_save_preset (GstPreset * preset, const gchar * name)
1026 {
1027   g_return_val_if_fail (GST_IS_PRESET (preset), FALSE);
1028   g_return_val_if_fail (name, FALSE);
1029
1030   return (GST_PRESET_GET_INTERFACE (preset)->save_preset (preset, name));
1031 }
1032
1033 /**
1034  * gst_preset_rename_preset:
1035  * @preset: a #GObject that implements #GstPreset
1036  * @old_name: current preset name
1037  * @new_name: new preset name
1038  *
1039  * Renames a preset. If there is already a preset by the @new_name it will be
1040  * overwritten.
1041  *
1042  * Returns: %TRUE for success, %FALSE if e.g. there is no preset with @old_name
1043  */
1044 gboolean
1045 gst_preset_rename_preset (GstPreset * preset, const gchar * old_name,
1046     const gchar * new_name)
1047 {
1048   g_return_val_if_fail (GST_IS_PRESET (preset), FALSE);
1049   g_return_val_if_fail (old_name, FALSE);
1050   g_return_val_if_fail (new_name, FALSE);
1051
1052   return (GST_PRESET_GET_INTERFACE (preset)->rename_preset (preset, old_name,
1053           new_name));
1054 }
1055
1056 /**
1057  * gst_preset_delete_preset:
1058  * @preset: a #GObject that implements #GstPreset
1059  * @name: preset name to remove
1060  *
1061  * Delete the given preset.
1062  *
1063  * Returns: %TRUE for success, %FALSE if e.g. there is no preset with that @name
1064  */
1065 gboolean
1066 gst_preset_delete_preset (GstPreset * preset, const gchar * name)
1067 {
1068   g_return_val_if_fail (GST_IS_PRESET (preset), FALSE);
1069   g_return_val_if_fail (name, FALSE);
1070
1071   return (GST_PRESET_GET_INTERFACE (preset)->delete_preset (preset, name));
1072 }
1073
1074 /**
1075  * gst_preset_set_meta:
1076  * @preset: a #GObject that implements #GstPreset
1077  * @name: preset name
1078  * @tag: meta data item name
1079  * @value: (allow-none): new value
1080  *
1081  * Sets a new @value for an existing meta data item or adds a new item. Meta
1082  * data @tag names can be something like e.g. "comment". Supplying %NULL for the
1083  * @value will unset an existing value.
1084  *
1085  * Returns: %TRUE for success, %FALSE if e.g. there is no preset with that @name
1086  */
1087 gboolean
1088 gst_preset_set_meta (GstPreset * preset, const gchar * name, const gchar * tag,
1089     const gchar * value)
1090 {
1091   g_return_val_if_fail (GST_IS_PRESET (preset), FALSE);
1092   g_return_val_if_fail (name, FALSE);
1093   g_return_val_if_fail (tag, FALSE);
1094
1095   return GST_PRESET_GET_INTERFACE (preset)->set_meta (preset, name, tag, value);
1096 }
1097
1098 /**
1099  * gst_preset_get_meta:
1100  * @preset: a #GObject that implements #GstPreset
1101  * @name: preset name
1102  * @tag: meta data item name
1103  * @value: (out callee-allocates): value
1104  *
1105  * Gets the @value for an existing meta data @tag. Meta data @tag names can be
1106  * something like e.g. "comment". Returned values need to be released when done.
1107  *
1108  * Returns: %TRUE for success, %FALSE if e.g. there is no preset with that @name
1109  * or no value for the given @tag
1110  */
1111 gboolean
1112 gst_preset_get_meta (GstPreset * preset, const gchar * name, const gchar * tag,
1113     gchar ** value)
1114 {
1115   g_return_val_if_fail (GST_IS_PRESET (preset), FALSE);
1116   g_return_val_if_fail (name, FALSE);
1117   g_return_val_if_fail (tag, FALSE);
1118   g_return_val_if_fail (value, FALSE);
1119
1120   return GST_PRESET_GET_INTERFACE (preset)->get_meta (preset, name, tag, value);
1121 }
1122
1123 /**
1124  * gst_preset_set_app_dir:
1125  * @app_dir: the application specific preset dir
1126  *
1127  * Sets an extra directory as an absolute path that should be considered when
1128  * looking for presets. Any presets in the application dir will shadow the 
1129  * system presets.
1130  *
1131  * Returns: %TRUE for success, %FALSE if the dir already has been set
1132  */
1133 gboolean
1134 gst_preset_set_app_dir (const gchar * app_dir)
1135 {
1136   g_return_val_if_fail (app_dir, FALSE);
1137
1138   if (!preset_app_dir) {
1139     preset_app_dir = g_strdup (app_dir);
1140     return TRUE;
1141   }
1142   return FALSE;
1143 }
1144
1145 /**
1146  * gst_preset_get_app_dir:
1147  *
1148  * Gets the directory for application specific presets if set by the
1149  * application.
1150  *
1151  * Returns: (nullable): the directory or %NULL, don't free or modify
1152  * the string
1153  */
1154 const gchar *
1155 gst_preset_get_app_dir (void)
1156 {
1157   return preset_app_dir;
1158 }
1159
1160 /**
1161  * gst_preset_is_editable:
1162  * @preset: a #GObject that implements #GstPreset
1163  *
1164  * Check if one can add new presets, change existing ones and remove presets.
1165  *
1166  * Returns: %TRUE if presets are editable or %FALSE if they are static
1167  *
1168  * Since: 1.6
1169  */
1170 gboolean
1171 gst_preset_is_editable (GstPreset * preset)
1172 {
1173   GstPresetInterface *iface = GST_PRESET_GET_INTERFACE (preset);
1174
1175   return iface->save_preset && iface->delete_preset;
1176 }
1177
1178 /* class internals */
1179
1180 static void
1181 gst_preset_class_init (GstPresetInterface * iface)
1182 {
1183   iface->get_preset_names = gst_preset_default_get_preset_names;
1184   iface->get_property_names = gst_preset_default_get_property_names;
1185
1186   iface->load_preset = gst_preset_default_load_preset;
1187   iface->save_preset = gst_preset_default_save_preset;
1188   iface->rename_preset = gst_preset_default_rename_preset;
1189   iface->delete_preset = gst_preset_default_delete_preset;
1190
1191   iface->set_meta = gst_preset_default_set_meta;
1192   iface->get_meta = gst_preset_default_get_meta;
1193 }
1194
1195 static void
1196 gst_preset_base_init (gpointer g_class)
1197 {
1198   static gboolean initialized = FALSE;
1199
1200   if (!initialized) {
1201     /* init default implementation */
1202     GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "preset",
1203         GST_DEBUG_FG_WHITE | GST_DEBUG_BG_BLACK, "preset interface");
1204
1205     /* create quarks for use with g_type_{g,s}et_qdata() */
1206     preset_quark = g_quark_from_static_string ("GstPreset::presets");
1207     preset_user_path_quark =
1208         g_quark_from_static_string ("GstPreset::user_path");
1209     preset_app_path_quark = g_quark_from_static_string ("GstPreset::app_path");
1210     preset_system_path_quark =
1211         g_quark_from_static_string ("GstPreset::system_path");
1212
1213 #if 0
1214     /* create interface properties, each element would need to override this
1215      *   g_object_class_override_property(gobject_class, PROP_PRESET_NAME, "preset-name");
1216      * and in _set_property() do
1217      *   case PROP_PRESET_NAME: {
1218      *     gchar *name = g_value_get_string (value);
1219      *     if (name)
1220      *       gst_preset_load_preset(preset, name);
1221      *   } break;
1222      */
1223     g_object_interface_install_property (g_class,
1224         g_param_spec_string ("preset-name",
1225             "preset-name property",
1226             "load given preset", NULL, G_PARAM_WRITABLE));
1227 #endif
1228
1229     initialized = TRUE;
1230   }
1231 }
1232
1233 GType
1234 gst_preset_get_type (void)
1235 {
1236   static volatile gsize type = 0;
1237
1238   if (g_once_init_enter (&type)) {
1239     GType _type;
1240     const GTypeInfo info = {
1241       sizeof (GstPresetInterface),
1242       (GBaseInitFunc) gst_preset_base_init,     /* base_init */
1243       NULL,                     /* base_finalize */
1244       (GClassInitFunc) gst_preset_class_init,   /* class_init */
1245       NULL,                     /* class_finalize */
1246       NULL,                     /* class_data */
1247       0,
1248       0,                        /* n_preallocs */
1249       NULL                      /* instance_init */
1250     };
1251     _type = g_type_register_static (G_TYPE_INTERFACE, "GstPreset", &info, 0);
1252     g_once_init_leave (&type, _type);
1253   }
1254   return type;
1255 }