pbutils: don't assume LC_MESSAGES is always defined, also check for ENABLE_NLS
[platform/upstream/gstreamer.git] / gst-libs / gst / pbutils / encoding-target.c
1 /* GStreamer encoding profile registry
2  * Copyright (C) 2010 Edward Hervey <edward.hervey@collabora.co.uk>
3  *           (C) 2010 Nokia Corporation
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include <locale.h>
26 #include <string.h>
27 #include "encoding-target.h"
28
29 /*
30  * File format
31  *
32  * GKeyFile style.
33  *
34  * [_gstencodingtarget_]
35  * name : <name>
36  * category : <category>
37  * description : <description> #translatable
38  *
39  * [profile-<profile1name>]
40  * name : <name>
41  * description : <description> #optional
42  * format : <format>
43  * preset : <preset>
44  *
45  * [streamprofile-<id>]
46  * parent : <encodingprofile.name>[,<encodingprofile.name>..]
47  * type : <type> # "audio", "video", "text"
48  * format : <format>
49  * preset : <preset>
50  * restriction : <restriction>
51  * presence : <presence>
52  * pass : <pass>
53  * variableframerate : <variableframerate>
54  *  */
55
56 /*
57  * Location of profile files
58  *
59  * $GST_DATADIR/gstreamer-GST_MAJORMINOR/encoding-profile
60  * $HOME/gstreamer-GST_MAJORMINOR/encoding-profile
61  *
62  * Naming convention
63  *   $(target.category)/$(target.name).gep
64  *
65  * Naming restrictions:
66  *  lowercase ASCII letter for the first character
67  *  Same for all other characters + numerics + hyphens
68  */
69
70
71 #define GST_ENCODING_TARGET_HEADER "_gstencodingtarget_"
72 #define GST_ENCODING_TARGET_DIRECTORY "encoding-profiles"
73 #define GST_ENCODING_TARGET_SUFFIX ".gep"
74
75 struct _GstEncodingTarget
76 {
77   GstMiniObject parent;
78
79   gchar *name;
80   gchar *category;
81   gchar *description;
82   GList *profiles;
83
84   /*< private > */
85   gchar *keyfile;
86 };
87
88 G_DEFINE_TYPE (GstEncodingTarget, gst_encoding_target, GST_TYPE_MINI_OBJECT);
89
90 static void
91 gst_encoding_target_init (GstEncodingTarget * target)
92 {
93   /* Nothing to initialize */
94 }
95
96 static void
97 gst_encoding_target_finalize (GstEncodingTarget * target)
98 {
99   GST_DEBUG ("Finalizing");
100
101   if (target->name)
102     g_free (target->name);
103   if (target->category)
104     g_free (target->category);
105   if (target->description)
106     g_free (target->description);
107
108   g_list_foreach (target->profiles, (GFunc) gst_mini_object_unref, NULL);
109   g_list_free (target->profiles);
110 }
111
112 static void
113 gst_encoding_target_class_init (GstMiniObjectClass * klass)
114 {
115   klass->finalize =
116       (GstMiniObjectFinalizeFunction) gst_encoding_target_finalize;
117 }
118
119 /**
120  * gst_encoding_target_get_name:
121  * @target: a #GstEncodingTarget
122  *
123  * Since: 0.10.32
124  *
125  * Returns: (transfer none): The name of the @target.
126  */
127 const gchar *
128 gst_encoding_target_get_name (GstEncodingTarget * target)
129 {
130   return target->name;
131 }
132
133 /**
134  * gst_encoding_target_get_category:
135  * @target: a #GstEncodingTarget
136  *
137  * Since: 0.10.32
138  *
139  * Returns: (transfer none): The category of the @target. For example:
140  * #GST_ENCODING_CATEGORY_DEVICE.
141  */
142 const gchar *
143 gst_encoding_target_get_category (GstEncodingTarget * target)
144 {
145   return target->category;
146 }
147
148 /**
149  * gst_encoding_target_get_description:
150  * @target: a #GstEncodingTarget
151  *
152  * Since: 0.10.32
153  *
154  * Returns: (transfer none): The description of the @target.
155  */
156 const gchar *
157 gst_encoding_target_get_description (GstEncodingTarget * target)
158 {
159   return target->description;
160 }
161
162 /**
163  * gst_encoding_target_get_profiles:
164  * @target: a #GstEncodingTarget
165  *
166  * Since: 0.10.32
167  *
168  * Returns: (transfer none) (element-type Gst.EncodingProfile): A list of
169  * #GstEncodingProfile(s) this @target handles.
170  */
171 const GList *
172 gst_encoding_target_get_profiles (GstEncodingTarget * target)
173 {
174   return target->profiles;
175 }
176
177 /**
178  * gst_encoding_target_get_profile:
179  * @target: a #GstEncodingTarget
180  * @name: the name of the profile to retrieve
181  *
182  * Since: 0.10.32
183  *
184  * Returns: (transfer full): The matching #GstEncodingProfile, or %NULL.
185  */
186 GstEncodingProfile *
187 gst_encoding_target_get_profile (GstEncodingTarget * target, const gchar * name)
188 {
189   GList *tmp;
190
191   g_return_val_if_fail (GST_IS_ENCODING_TARGET (target), NULL);
192   g_return_val_if_fail (name != NULL, NULL);
193
194   for (tmp = target->profiles; tmp; tmp = tmp->next) {
195     GstEncodingProfile *tprof = (GstEncodingProfile *) tmp->data;
196
197     if (!g_strcmp0 (gst_encoding_profile_get_name (tprof), name)) {
198       gst_encoding_profile_ref (tprof);
199       return tprof;
200     }
201   }
202
203   return NULL;
204 }
205
206 static inline gboolean
207 validate_name (const gchar * name)
208 {
209   guint i, len;
210
211   len = strlen (name);
212   if (len == 0)
213     return FALSE;
214
215   /* First character can only be a lower case ASCII character */
216   if (!g_ascii_isalpha (name[0]) || !g_ascii_islower (name[0]))
217     return FALSE;
218
219   /* All following characters can only by:
220    * either a lower case ASCII character
221    * or an hyphen
222    * or a numeric */
223   for (i = 1; i < len; i++) {
224     /* if uppercase ASCII letter, return */
225     if (g_ascii_isupper (name[i]))
226       return FALSE;
227     /* if a digit, continue */
228     if (g_ascii_isdigit (name[i]))
229       continue;
230     /* if an hyphen, continue */
231     if (name[i] == '-')
232       continue;
233     /* remaining should only be ascii letters */
234     if (!g_ascii_isalpha (name[i]))
235       return FALSE;
236   }
237
238   return TRUE;
239 }
240
241 /**
242  * gst_encoding_target_new:
243  * @name: The name of the target.
244  * @category: (transfer none): The name of the category to which this @target
245  * belongs. For example: #GST_ENCODING_CATEGORY_DEVICE.
246  * @description: (transfer none): A description of #GstEncodingTarget in the
247  * current locale.
248  * @profiles: (transfer none) (element-type Gst.EncodingProfile): A #GList of
249  * #GstEncodingProfile.
250  *
251  * Creates a new #GstEncodingTarget.
252  *
253  * The name and category can only consist of lowercase ASCII letters for the
254  * first character, followed by either lowercase ASCII letters, digits or
255  * hyphens ('-').
256  *
257  * The @category <emphasis>should</emphasis> be one of the existing
258  * well-defined categories, like #GST_ENCODING_CATEGORY_DEVICE, but it
259  * <emphasis>can</emphasis> be a application or user specific category if
260  * needed.
261  *
262  * Since: 0.10.32
263  *
264  * Returns: (transfer full): The newly created #GstEncodingTarget or %NULL if
265  * there was an error.
266  */
267
268 GstEncodingTarget *
269 gst_encoding_target_new (const gchar * name, const gchar * category,
270     const gchar * description, const GList * profiles)
271 {
272   GstEncodingTarget *res;
273
274   g_return_val_if_fail (name != NULL, NULL);
275   g_return_val_if_fail (category != NULL, NULL);
276   g_return_val_if_fail (description != NULL, NULL);
277
278   /* Validate name */
279   if (!validate_name (name))
280     goto invalid_name;
281   if (!validate_name (category))
282     goto invalid_category;
283
284   res = (GstEncodingTarget *) gst_mini_object_new (GST_TYPE_ENCODING_TARGET);
285   res->name = g_strdup (name);
286   res->category = g_strdup (category);
287   res->description = g_strdup (description);
288
289   while (profiles) {
290     GstEncodingProfile *prof = (GstEncodingProfile *) profiles->data;
291
292     res->profiles =
293         g_list_append (res->profiles, gst_encoding_profile_ref (prof));
294     profiles = profiles->next;
295   }
296
297   return res;
298
299 invalid_name:
300   {
301     GST_ERROR ("Invalid name for encoding target : '%s'", name);
302     return NULL;
303   }
304
305 invalid_category:
306   {
307     GST_ERROR ("Invalid name for encoding category : '%s'", category);
308     return NULL;
309   }
310 }
311
312 /**
313  * gst_encoding_target_add_profile:
314  * @target: the #GstEncodingTarget to add a profile to
315  * @profile: (transfer full): the #GstEncodingProfile to add
316  *
317  * Adds the given @profile to the @target. Each added profile must have
318  * a unique name within the profile.
319  *
320  * The @target will steal a reference to the @profile. If you wish to use
321  * the profile after calling this method, you should increase its reference
322  * count.
323  *
324  * Since: 0.10.32
325  *
326  * Returns: %TRUE if the profile was added, else %FALSE.
327  **/
328
329 gboolean
330 gst_encoding_target_add_profile (GstEncodingTarget * target,
331     GstEncodingProfile * profile)
332 {
333   GList *tmp;
334
335   g_return_val_if_fail (GST_IS_ENCODING_TARGET (target), FALSE);
336   g_return_val_if_fail (GST_IS_ENCODING_PROFILE (profile), FALSE);
337
338   /* Make sure profile isn't already controlled by this target */
339   for (tmp = target->profiles; tmp; tmp = tmp->next) {
340     GstEncodingProfile *prof = (GstEncodingProfile *) tmp->data;
341
342     if (!g_strcmp0 (gst_encoding_profile_get_name (profile),
343             gst_encoding_profile_get_name (prof))) {
344       GST_WARNING ("Profile already present in target");
345       return FALSE;
346     }
347   }
348
349   target->profiles = g_list_append (target->profiles, profile);
350
351   return TRUE;
352 }
353
354 static gboolean
355 serialize_stream_profiles (GKeyFile * out, GstEncodingProfile * sprof,
356     const gchar * profilename, guint id)
357 {
358   gchar *sprofgroupname;
359   gchar *tmpc;
360   const GstCaps *format, *restriction;
361   const gchar *preset, *name, *description;
362
363   sprofgroupname = g_strdup_printf ("streamprofile-%s-%d", profilename, id);
364
365   /* Write the parent profile */
366   g_key_file_set_value (out, sprofgroupname, "parent", profilename);
367
368   g_key_file_set_value (out, sprofgroupname, "type",
369       gst_encoding_profile_get_type_nick (sprof));
370
371   format = gst_encoding_profile_get_format (sprof);
372   if (format) {
373     tmpc = gst_caps_to_string (format);
374     g_key_file_set_value (out, sprofgroupname, "format", tmpc);
375     g_free (tmpc);
376   }
377
378   name = gst_encoding_profile_get_name (sprof);
379   if (name)
380     g_key_file_set_string (out, sprofgroupname, "name", name);
381
382   description = gst_encoding_profile_get_description (sprof);
383   if (description)
384     g_key_file_set_string (out, sprofgroupname, "description", description);
385
386   preset = gst_encoding_profile_get_preset (sprof);
387   if (preset)
388     g_key_file_set_string (out, sprofgroupname, "preset", preset);
389
390   restriction = gst_encoding_profile_get_restriction (sprof);
391   if (restriction) {
392     tmpc = gst_caps_to_string (restriction);
393     g_key_file_set_value (out, sprofgroupname, "restriction", tmpc);
394     g_free (tmpc);
395   }
396   g_key_file_set_integer (out, sprofgroupname, "presence",
397       gst_encoding_profile_get_presence (sprof));
398
399   if (GST_IS_ENCODING_VIDEO_PROFILE (sprof)) {
400     GstEncodingVideoProfile *vp = (GstEncodingVideoProfile *) sprof;
401
402     g_key_file_set_integer (out, sprofgroupname, "pass",
403         gst_encoding_video_profile_get_pass (vp));
404     g_key_file_set_boolean (out, sprofgroupname, "variableframerate",
405         gst_encoding_video_profile_get_variableframerate (vp));
406   }
407
408   g_free (sprofgroupname);
409   return TRUE;
410 }
411
412 static gchar *
413 get_locale (void)
414 {
415   const char *loc = NULL;
416   gchar *ret;
417
418 #ifdef ENABLE_NLS
419 #if defined(LC_MESSAGES)
420   loc = setlocale (LC_MESSAGES, NULL);
421   GST_LOG ("LC_MESSAGES: %s", GST_STR_NULL (loc));
422 #elif defined(LC_ALL)
423   loc = setlocale (LC_ALL, NULL);
424   GST_LOG ("LC_ALL: %s", GST_STR_NULL (loc));
425 #else
426   GST_LOG ("Neither LC_ALL nor LC_MESSAGES defined");
427 #endif
428 #else /* !ENABLE_NLS */
429   GST_LOG ("i18n disabled");
430 #endif
431
432   if (loc == NULL || g_ascii_strncasecmp (loc, "en", 2) == 0)
433     return NULL;
434
435   /* en_GB.UTF-8 => en */
436   ret = g_ascii_strdown (loc, -1);
437   ret = g_strcanon (ret, "abcdefghijklmnopqrstuvwxyz", '\0');
438   GST_LOG ("using locale: %s", ret);
439   return ret;
440 }
441
442 /* Serialize the top-level profiles
443  * Note: They don't have to be containerprofiles */
444 static gboolean
445 serialize_encoding_profile (GKeyFile * out, GstEncodingProfile * prof)
446 {
447   gchar *profgroupname;
448   const GList *tmp;
449   guint i;
450   const gchar *profname, *profdesc, *profpreset, *proftype;
451   const GstCaps *profformat, *profrestriction;
452
453   profname = gst_encoding_profile_get_name (prof);
454   profdesc = gst_encoding_profile_get_description (prof);
455   profformat = gst_encoding_profile_get_format (prof);
456   profpreset = gst_encoding_profile_get_preset (prof);
457   proftype = gst_encoding_profile_get_type_nick (prof);
458   profrestriction = gst_encoding_profile_get_restriction (prof);
459
460   profgroupname = g_strdup_printf ("profile-%s", profname);
461
462   g_key_file_set_string (out, profgroupname, "name", profname);
463
464   g_key_file_set_value (out, profgroupname, "type",
465       gst_encoding_profile_get_type_nick (prof));
466
467   if (profdesc) {
468     gchar *locale;
469
470     locale = get_locale ();
471     if (locale != NULL) {
472       g_key_file_set_locale_string (out, profgroupname, "description",
473           locale, profdesc);
474       g_free (locale);
475     } else {
476       g_key_file_set_string (out, profgroupname, "description", profdesc);
477     }
478   }
479   if (profformat) {
480     gchar *tmpc = gst_caps_to_string (profformat);
481     g_key_file_set_string (out, profgroupname, "format", tmpc);
482     g_free (tmpc);
483   }
484   if (profpreset)
485     g_key_file_set_string (out, profgroupname, "preset", profpreset);
486
487   /* stream profiles */
488   if (GST_IS_ENCODING_CONTAINER_PROFILE (prof)) {
489     for (tmp =
490         gst_encoding_container_profile_get_profiles
491         (GST_ENCODING_CONTAINER_PROFILE (prof)), i = 0; tmp;
492         tmp = tmp->next, i++) {
493       GstEncodingProfile *sprof = (GstEncodingProfile *) tmp->data;
494
495       if (!serialize_stream_profiles (out, sprof, profname, i))
496         return FALSE;
497     }
498   }
499   g_free (profgroupname);
500   return TRUE;
501 }
502
503 static gboolean
504 serialize_target (GKeyFile * out, GstEncodingTarget * target)
505 {
506   GList *tmp;
507
508   g_key_file_set_string (out, GST_ENCODING_TARGET_HEADER, "name", target->name);
509   g_key_file_set_string (out, GST_ENCODING_TARGET_HEADER, "category",
510       target->category);
511   g_key_file_set_string (out, GST_ENCODING_TARGET_HEADER, "description",
512       target->description);
513
514   for (tmp = target->profiles; tmp; tmp = tmp->next) {
515     GstEncodingProfile *prof = (GstEncodingProfile *) tmp->data;
516     if (!serialize_encoding_profile (out, prof))
517       return FALSE;
518   }
519
520   return TRUE;
521 }
522
523 /**
524  * parse_encoding_profile:
525  * @in: a #GKeyFile
526  * @parentprofilename: the parent profile name (including 'profile-' or 'streamprofile-' header)
527  * @profilename: the profile name group to parse
528  * @nbgroups: the number of top-level groups
529  * @groups: the top-level groups
530  */
531 static GstEncodingProfile *
532 parse_encoding_profile (GKeyFile * in, gchar * parentprofilename,
533     gchar * profilename, gsize nbgroups, gchar ** groups)
534 {
535   GstEncodingProfile *sprof = NULL;
536   gchar **parent;
537   gchar *proftype, *format, *preset, *restriction, *pname, *description;
538   GstCaps *formatcaps = NULL;
539   GstCaps *restrictioncaps = NULL;
540   gboolean variableframerate;
541   gint pass, presence;
542   gsize i, nbencprofiles;
543
544   GST_DEBUG ("parentprofilename : %s , profilename : %s",
545       parentprofilename, profilename);
546
547   if (parentprofilename) {
548     gboolean found = FALSE;
549
550     parent =
551         g_key_file_get_string_list (in, profilename, "parent",
552         &nbencprofiles, NULL);
553     if (!parent || !nbencprofiles) {
554       return NULL;
555     }
556
557     /* Check if this streamprofile is used in <profilename> */
558     for (i = 0; i < nbencprofiles; i++) {
559       if (!g_strcmp0 (parent[i], parentprofilename)) {
560         found = TRUE;
561         break;
562       }
563     }
564     g_strfreev (parent);
565
566     if (!found) {
567       GST_DEBUG ("Stream profile '%s' isn't used in profile '%s'",
568           profilename, parentprofilename);
569       return NULL;
570     }
571   }
572
573   pname = g_key_file_get_value (in, profilename, "name", NULL);
574
575   /* First try to get localized description */
576   {
577     gchar *locale;
578
579     locale = get_locale ();
580     if (locale != NULL) {
581       /* will try to fall back to untranslated string if no translation found */
582       description = g_key_file_get_locale_string (in, profilename,
583           "description", locale, NULL);
584       g_free (locale);
585     } else {
586       description =
587           g_key_file_get_string (in, profilename, "description", NULL);
588     }
589   }
590
591   /* Note: a missing description is normal for non-container profiles */
592   if (description == NULL) {
593     GST_LOG ("Missing 'description' field for streamprofile %s", profilename);
594   }
595
596   /* Parse the remaining fields */
597   proftype = g_key_file_get_value (in, profilename, "type", NULL);
598   if (!proftype) {
599     GST_WARNING ("Missing 'type' field for streamprofile %s", profilename);
600     return NULL;
601   }
602
603   format = g_key_file_get_value (in, profilename, "format", NULL);
604   if (format) {
605     formatcaps = gst_caps_from_string (format);
606     g_free (format);
607   }
608
609   preset = g_key_file_get_value (in, profilename, "preset", NULL);
610
611   restriction = g_key_file_get_value (in, profilename, "restriction", NULL);
612   if (restriction) {
613     restrictioncaps = gst_caps_from_string (restriction);
614     g_free (restriction);
615   }
616
617   presence = g_key_file_get_integer (in, profilename, "presence", NULL);
618   pass = g_key_file_get_integer (in, profilename, "pass", NULL);
619   variableframerate =
620       g_key_file_get_boolean (in, profilename, "variableframerate", NULL);
621
622   /* Build the streamprofile ! */
623   if (!g_strcmp0 (proftype, "container")) {
624     GstEncodingProfile *pprof;
625
626     sprof =
627         (GstEncodingProfile *) gst_encoding_container_profile_new (pname,
628         description, formatcaps, preset);
629     /* Now look for the stream profiles */
630     for (i = 0; i < nbgroups; i++) {
631       if (!g_ascii_strncasecmp (groups[i], "streamprofile-", 13)) {
632         pprof = parse_encoding_profile (in, pname, groups[i], nbgroups, groups);
633         if (pprof) {
634           gst_encoding_container_profile_add_profile (
635               (GstEncodingContainerProfile *) sprof, pprof);
636         }
637       }
638     }
639   } else if (!g_strcmp0 (proftype, "video")) {
640     sprof =
641         (GstEncodingProfile *) gst_encoding_video_profile_new (formatcaps,
642         preset, restrictioncaps, presence);
643     gst_encoding_video_profile_set_variableframerate ((GstEncodingVideoProfile
644             *) sprof, variableframerate);
645     gst_encoding_video_profile_set_pass ((GstEncodingVideoProfile *) sprof,
646         pass);
647   } else if (!g_strcmp0 (proftype, "audio")) {
648     sprof =
649         (GstEncodingProfile *) gst_encoding_audio_profile_new (formatcaps,
650         preset, restrictioncaps, presence);
651   } else
652     GST_ERROR ("Unknown profile format '%s'", proftype);
653
654   if (restrictioncaps)
655     gst_caps_unref (restrictioncaps);
656   if (formatcaps)
657     gst_caps_unref (formatcaps);
658
659   if (pname)
660     g_free (pname);
661   if (description)
662     g_free (description);
663   if (preset)
664     g_free (preset);
665   if (proftype)
666     g_free (proftype);
667
668   return sprof;
669 }
670
671 static GstEncodingTarget *
672 parse_keyfile (GKeyFile * in, gchar * targetname, gchar * categoryname,
673     gchar * description)
674 {
675   GstEncodingTarget *res = NULL;
676   GstEncodingProfile *prof;
677   gchar **groups;
678   gsize i, nbgroups;
679
680   res = gst_encoding_target_new (targetname, categoryname, description, NULL);
681
682   /* Figure out the various profiles */
683   groups = g_key_file_get_groups (in, &nbgroups);
684   for (i = 0; i < nbgroups; i++) {
685     if (!g_ascii_strncasecmp (groups[i], "profile-", 8)) {
686       prof = parse_encoding_profile (in, NULL, groups[i], nbgroups, groups);
687       if (prof)
688         gst_encoding_target_add_profile (res, prof);
689     }
690   }
691
692   g_strfreev (groups);
693
694   if (targetname)
695     g_free (targetname);
696   if (categoryname)
697     g_free (categoryname);
698   if (description)
699     g_free (description);
700
701   return res;
702 }
703
704 static GKeyFile *
705 load_file_and_read_header (const gchar * path, gchar ** targetname,
706     gchar ** categoryname, gchar ** description, GError ** error)
707 {
708   GKeyFile *in;
709   gboolean res;
710
711   in = g_key_file_new ();
712
713   GST_DEBUG ("path:%s", path);
714
715   res =
716       g_key_file_load_from_file (in, path,
717       G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS, error);
718   if (!res || error != NULL)
719     goto load_error;
720
721   *targetname =
722       g_key_file_get_value (in, GST_ENCODING_TARGET_HEADER, "name", error);
723   if (!*targetname)
724     goto empty_name;
725
726   *categoryname =
727       g_key_file_get_value (in, GST_ENCODING_TARGET_HEADER, "category", NULL);
728   *description =
729       g_key_file_get_value (in, GST_ENCODING_TARGET_HEADER, "description",
730       NULL);
731
732   return in;
733
734 load_error:
735   {
736     GST_WARNING ("Unable to read GstEncodingTarget file %s: %s",
737         path, (*error)->message);
738     g_key_file_free (in);
739     return NULL;
740   }
741
742 empty_name:
743   {
744     GST_WARNING ("Wrong header in file %s: %s", path, (*error)->message);
745     g_key_file_free (in);
746     return NULL;
747   }
748 }
749
750 /**
751  * gst_encoding_target_load_from_file:
752  * @filepath: The file location to load the #GstEncodingTarget from
753  * @error: If an error occured, this field will be filled in.
754  *
755  * Opens the provided file and returns the contained #GstEncodingTarget.
756  *
757  * Since: 0.10.32
758  *
759  * Returns: (transfer full): The #GstEncodingTarget contained in the file, else
760  * %NULL
761  */
762
763 GstEncodingTarget *
764 gst_encoding_target_load_from_file (const gchar * filepath, GError ** error)
765 {
766   GKeyFile *in;
767   gchar *targetname, *categoryname, *description;
768   GstEncodingTarget *res = NULL;
769
770   in = load_file_and_read_header (filepath, &targetname, &categoryname,
771       &description, error);
772   if (!in)
773     goto beach;
774
775   res = parse_keyfile (in, targetname, categoryname, description);
776
777   g_key_file_free (in);
778
779 beach:
780   return res;
781 }
782
783 /*
784  * returned list contents must be freed
785  */
786 static GList *
787 get_matching_filenames (gchar * path, gchar * filename)
788 {
789   GList *res = NULL;
790   GDir *topdir;
791   const gchar *subdirname;
792
793   topdir = g_dir_open (path, 0, NULL);
794   if (G_UNLIKELY (topdir == NULL))
795     return NULL;
796
797   while ((subdirname = g_dir_read_name (topdir))) {
798     gchar *ltmp = g_build_filename (path, subdirname, NULL);
799
800     if (g_file_test (ltmp, G_FILE_TEST_IS_DIR)) {
801       gchar *tmp = g_build_filename (path, subdirname, filename, NULL);
802       /* Test to see if we have a file named like that in that directory */
803       if (g_file_test (tmp, G_FILE_TEST_EXISTS))
804         res = g_list_append (res, tmp);
805       else
806         g_free (tmp);
807     }
808     g_free (ltmp);
809   }
810
811   g_dir_close (topdir);
812
813   return res;
814 }
815
816 static GstEncodingTarget *
817 gst_encoding_target_subload (gchar * path, const gchar * category,
818     gchar * lfilename, GError ** error)
819 {
820   GstEncodingTarget *target = NULL;
821
822   if (category) {
823     gchar *filename;
824
825     filename = g_build_filename (path, category, lfilename, NULL);
826     target = gst_encoding_target_load_from_file (filename, error);
827     g_free (filename);
828   } else {
829     GList *tmp, *tries = get_matching_filenames (path, lfilename);
830
831     /* Try to find a file named %s.gstprofile in any subdirectories */
832     for (tmp = tries; tmp; tmp = tmp->next) {
833       target = gst_encoding_target_load_from_file ((gchar *) tmp->data, NULL);
834       if (target)
835         break;
836     }
837     g_list_foreach (tries, (GFunc) g_free, NULL);
838     if (tries)
839       g_list_free (tries);
840   }
841
842   return target;
843 }
844
845 /**
846  * gst_encoding_target_load:
847  * @name: the name of the #GstEncodingTarget to load.
848  * @category: (allow-none): the name of the target category, like
849  * #GST_ENCODING_CATEGORY_DEVICE. Can be %NULL
850  * @error: If an error occured, this field will be filled in.
851  *
852  * Searches for the #GstEncodingTarget with the given name, loads it
853  * and returns it.
854  *
855  * If the category name is specified only targets from that category will be
856  * searched for.
857  *
858  * Since: 0.10.32
859  *
860  * Returns: (transfer full): The #GstEncodingTarget if available, else %NULL.
861  */
862 GstEncodingTarget *
863 gst_encoding_target_load (const gchar * name, const gchar * category,
864     GError ** error)
865 {
866   gchar *lfilename, *tldir;
867   GstEncodingTarget *target = NULL;
868
869   g_return_val_if_fail (name != NULL, NULL);
870
871   if (!validate_name (name))
872     goto invalid_name;
873
874   if (category && !validate_name (category))
875     goto invalid_category;
876
877   lfilename = g_strdup_printf ("%s" GST_ENCODING_TARGET_SUFFIX, name);
878
879   /* Try from local profiles */
880   tldir =
881       g_build_filename (g_get_home_dir (), ".gstreamer-" GST_MAJORMINOR,
882       GST_ENCODING_TARGET_DIRECTORY, NULL);
883   target = gst_encoding_target_subload (tldir, category, lfilename, error);
884   g_free (tldir);
885
886   if (target == NULL) {
887     /* Try from system-wide profiles */
888     tldir =
889         g_build_filename (GST_DATADIR, "gstreamer-" GST_MAJORMINOR,
890         GST_ENCODING_TARGET_DIRECTORY, NULL);
891     target = gst_encoding_target_subload (tldir, category, lfilename, error);
892     g_free (tldir);
893   }
894
895   g_free (lfilename);
896
897   return target;
898
899 invalid_name:
900   {
901     GST_ERROR ("Invalid name for encoding target : '%s'", name);
902     return NULL;
903   }
904 invalid_category:
905   {
906     GST_ERROR ("Invalid name for encoding category : '%s'", category);
907     return NULL;
908   }
909 }
910
911 /**
912  * gst_encoding_target_save_to_file:
913  * @target: a #GstEncodingTarget
914  * @filepath: the location to store the @target at.
915  * @error: If an error occured, this field will be filled in.
916  *
917  * Saves the @target to the provided file location.
918  *
919  * Since: 0.10.32
920  *
921  * Returns: %TRUE if the target was correctly saved, else %FALSE.
922  **/
923
924 gboolean
925 gst_encoding_target_save_to_file (GstEncodingTarget * target,
926     const gchar * filepath, GError ** error)
927 {
928   GKeyFile *out;
929   gchar *data;
930   gsize data_size;
931
932   g_return_val_if_fail (GST_IS_ENCODING_TARGET (target), FALSE);
933   g_return_val_if_fail (filepath != NULL, FALSE);
934
935   /* FIXME : Check filepath is valid and writable
936    * FIXME : Strip out profiles already present in system target */
937
938   /* Get unique name... */
939
940   /* Create output GKeyFile */
941   out = g_key_file_new ();
942
943   if (!serialize_target (out, target))
944     goto serialize_failure;
945
946   if (!(data = g_key_file_to_data (out, &data_size, error)))
947     goto convert_failed;
948
949   if (!g_file_set_contents (filepath, data, data_size, error))
950     goto write_failed;
951
952   g_key_file_free (out);
953   g_free (data);
954
955   return TRUE;
956
957 serialize_failure:
958   {
959     GST_ERROR ("Failure serializing target");
960     g_key_file_free (out);
961     return FALSE;
962   }
963
964 convert_failed:
965   {
966     GST_ERROR ("Failure converting keyfile: %s", (*error)->message);
967     g_key_file_free (out);
968     g_free (data);
969     return FALSE;
970   }
971
972 write_failed:
973   {
974     GST_ERROR ("Unable to write file %s: %s", filepath, (*error)->message);
975     g_key_file_free (out);
976     g_free (data);
977     return FALSE;
978   }
979 }
980
981 /**
982  * gst_encoding_target_save:
983  * @target: a #GstEncodingTarget
984  * @error: If an error occured, this field will be filled in.
985  *
986  * Saves the @target to a default user-local directory.
987  *
988  * Since: 0.10.32
989  *
990  * Returns: %TRUE if the target was correctly saved, else %FALSE.
991  **/
992
993 gboolean
994 gst_encoding_target_save (GstEncodingTarget * target, GError ** error)
995 {
996   gchar *filename;
997   gchar *lfilename;
998   gboolean res;
999
1000   g_return_val_if_fail (GST_IS_ENCODING_TARGET (target), FALSE);
1001   g_return_val_if_fail (target->category != NULL, FALSE);
1002
1003   lfilename = g_strdup_printf ("%s" GST_ENCODING_TARGET_SUFFIX, target->name);
1004   filename =
1005       g_build_filename (g_get_home_dir (), ".gstreamer-" GST_MAJORMINOR,
1006       GST_ENCODING_TARGET_DIRECTORY, target->category, lfilename, NULL);
1007   g_free (lfilename);
1008
1009   res = gst_encoding_target_save_to_file (target, filename, error);
1010   g_free (filename);
1011
1012   return TRUE;
1013 }
1014
1015 static GList *
1016 get_categories (gchar * path)
1017 {
1018   GList *res = NULL;
1019   GDir *topdir;
1020   const gchar *subdirname;
1021
1022   topdir = g_dir_open (path, 0, NULL);
1023   if (G_UNLIKELY (topdir == NULL))
1024     return NULL;
1025
1026   while ((subdirname = g_dir_read_name (topdir))) {
1027     gchar *ltmp = g_build_filename (path, subdirname, NULL);
1028
1029     if (g_file_test (ltmp, G_FILE_TEST_IS_DIR)) {
1030       res = g_list_append (res, (gpointer) g_strdup (subdirname));
1031     }
1032     g_free (ltmp);
1033   }
1034
1035   g_dir_close (topdir);
1036
1037   return res;
1038 }
1039
1040 /**
1041  * gst_encoding_list_available_categories:
1042  *
1043  * Lists all #GstEncodingTarget categories present on disk.
1044  *
1045  * Returns: (transfer full) (element-type gchar*): A list
1046  * of #GstEncodingTarget categories.
1047  *
1048  * Since: 0.10.32
1049  */
1050 GList *
1051 gst_encoding_list_available_categories (void)
1052 {
1053   GList *res = NULL;
1054   GList *tmp1, *tmp2;
1055   gchar *topdir;
1056
1057   /* First try user-local categories */
1058   topdir = g_build_filename (g_get_home_dir (), ".gstreamer-" GST_MAJORMINOR,
1059       GST_ENCODING_TARGET_DIRECTORY, NULL);
1060   res = get_categories (topdir);
1061   g_free (topdir);
1062
1063   /* Extend with system-wide categories */
1064   topdir = g_build_filename (GST_DATADIR, "gstreamer-" GST_MAJORMINOR,
1065       GST_ENCODING_TARGET_DIRECTORY, NULL);
1066   tmp1 = get_categories (topdir);
1067   g_free (topdir);
1068
1069   for (tmp2 = tmp1; tmp2; tmp2 = tmp2->next) {
1070     gchar *name = (gchar *) tmp2->data;
1071     if (!g_list_find_custom (res, name, (GCompareFunc) g_strcmp0))
1072       res = g_list_append (res, (gpointer) name);
1073     else
1074       g_free (name);
1075   }
1076   g_free (tmp1);
1077
1078   return res;
1079 }
1080
1081 static inline GList *
1082 sub_get_all_targets (gchar * subdir)
1083 {
1084   GList *res = NULL;
1085   const gchar *filename;
1086   GDir *dir;
1087   GstEncodingTarget *target;
1088
1089   dir = g_dir_open (subdir, 0, NULL);
1090   if (G_UNLIKELY (dir == NULL))
1091     return NULL;
1092
1093   while ((filename = g_dir_read_name (dir))) {
1094     gchar *fullname;
1095
1096     /* Only try files ending with .gstprofile */
1097     if (!g_str_has_suffix (filename, GST_ENCODING_TARGET_SUFFIX))
1098       continue;
1099
1100     fullname = g_build_filename (subdir, filename, NULL);
1101     target = gst_encoding_target_load_from_file (fullname, NULL);
1102     if (target) {
1103       res = g_list_append (res, target);
1104     } else
1105       GST_WARNING ("Failed to get a target from %s", fullname);
1106     g_free (fullname);
1107   }
1108   g_dir_close (dir);
1109
1110   return res;
1111 }
1112
1113 static inline GList *
1114 get_all_targets (gchar * topdir, const gchar * categoryname)
1115 {
1116   GList *res = NULL;
1117
1118   if (categoryname) {
1119     gchar *subdir = g_build_filename (topdir, categoryname, NULL);
1120     /* Try to open the directory */
1121     res = sub_get_all_targets (subdir);
1122     g_free (subdir);
1123   } else {
1124     const gchar *subdirname;
1125     GDir *dir = g_dir_open (topdir, 0, NULL);
1126
1127     if (G_UNLIKELY (dir == NULL))
1128       return NULL;
1129
1130     while ((subdirname = g_dir_read_name (dir))) {
1131       gchar *ltmp = g_build_filename (topdir, subdirname, NULL);
1132
1133       if (g_file_test (ltmp, G_FILE_TEST_IS_DIR)) {
1134         res = g_list_concat (res, sub_get_all_targets (ltmp));
1135       }
1136       g_free (ltmp);
1137     }
1138     g_dir_close (dir);
1139   }
1140
1141   return res;
1142 }
1143
1144 static guint
1145 compare_targets (const GstEncodingTarget * ta, const GstEncodingTarget * tb)
1146 {
1147   if (!g_strcmp0 (ta->name, tb->name)
1148       && !g_strcmp0 (ta->category, tb->category))
1149     return -1;
1150
1151   return 0;
1152 }
1153
1154 /**
1155  * gst_encoding_list_all_targets:
1156  * @categoryname: (allow-none): The category, for ex: #GST_ENCODING_CATEGORY_DEVICE.
1157  * Can be %NULL.
1158  *
1159  * List all available #GstEncodingTarget for the specified category, or all categories
1160  * if @categoryname is %NULL.
1161  *
1162  * Returns: (transfer full) (element-type GstEncodingTarget): The list of #GstEncodingTarget
1163  *
1164  * Since: 0.10.32
1165  */
1166 GList *
1167 gst_encoding_list_all_targets (const gchar * categoryname)
1168 {
1169   GList *res;
1170   GList *tmp1, *tmp2;
1171   gchar *topdir;
1172
1173   /* Get user-locals */
1174   topdir = g_build_filename (g_get_home_dir (), ".gstreamer-" GST_MAJORMINOR,
1175       GST_ENCODING_TARGET_DIRECTORY, NULL);
1176   res = get_all_targets (topdir, categoryname);
1177   g_free (topdir);
1178
1179   /* Get system-wide */
1180   topdir = g_build_filename (GST_DATADIR, "gstreamer-" GST_MAJORMINOR,
1181       GST_ENCODING_TARGET_DIRECTORY, NULL);
1182   tmp1 = get_all_targets (topdir, categoryname);
1183   g_free (topdir);
1184
1185   /* Merge system-wide targets */
1186   /* FIXME : We should merge the system-wide profiles into the user-locals
1187    * instead of stopping at identical target names */
1188   for (tmp2 = tmp1; tmp2; tmp2 = tmp2->next) {
1189     GstEncodingTarget *target = (GstEncodingTarget *) tmp2->data;
1190     if (g_list_find_custom (res, target, (GCompareFunc) compare_targets))
1191       gst_encoding_target_unref (target);
1192     else
1193       res = g_list_append (res, target);
1194   }
1195   g_list_free (tmp1);
1196
1197   return res;
1198 }