pbutils: save localised strings properly when writing encoding targets to a file
[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 = setlocale (LC_MESSAGES, NULL);
416   gchar *ret;
417
418   if (loc == NULL || g_ascii_strncasecmp (loc, "en", 2) == 0)
419     return NULL;
420
421   /* en_GB.UTF-8 => en */
422   ret = g_ascii_strdown (loc, -1);
423   ret = g_strcanon (ret, "abcdefghijklmnopqrstuvwxyz", '\0');
424   GST_LOG ("using locale: %s", ret);
425   return ret;
426 }
427
428 /* Serialize the top-level profiles
429  * Note: They don't have to be containerprofiles */
430 static gboolean
431 serialize_encoding_profile (GKeyFile * out, GstEncodingProfile * prof)
432 {
433   gchar *profgroupname;
434   const GList *tmp;
435   guint i;
436   const gchar *profname, *profdesc, *profpreset, *proftype;
437   const GstCaps *profformat, *profrestriction;
438
439   profname = gst_encoding_profile_get_name (prof);
440   profdesc = gst_encoding_profile_get_description (prof);
441   profformat = gst_encoding_profile_get_format (prof);
442   profpreset = gst_encoding_profile_get_preset (prof);
443   proftype = gst_encoding_profile_get_type_nick (prof);
444   profrestriction = gst_encoding_profile_get_restriction (prof);
445
446   profgroupname = g_strdup_printf ("profile-%s", profname);
447
448   g_key_file_set_string (out, profgroupname, "name", profname);
449
450   g_key_file_set_value (out, profgroupname, "type",
451       gst_encoding_profile_get_type_nick (prof));
452
453   if (profdesc) {
454     gchar *locale;
455
456     locale = get_locale ();
457     if (locale != NULL) {
458       g_key_file_set_locale_string (out, profgroupname, "description",
459           locale, profdesc);
460       g_free (locale);
461     } else {
462       g_key_file_set_string (out, profgroupname, "description", profdesc);
463     }
464   }
465   if (profformat) {
466     gchar *tmpc = gst_caps_to_string (profformat);
467     g_key_file_set_string (out, profgroupname, "format", tmpc);
468     g_free (tmpc);
469   }
470   if (profpreset)
471     g_key_file_set_string (out, profgroupname, "preset", profpreset);
472
473   /* stream profiles */
474   if (GST_IS_ENCODING_CONTAINER_PROFILE (prof)) {
475     for (tmp =
476         gst_encoding_container_profile_get_profiles
477         (GST_ENCODING_CONTAINER_PROFILE (prof)), i = 0; tmp;
478         tmp = tmp->next, i++) {
479       GstEncodingProfile *sprof = (GstEncodingProfile *) tmp->data;
480
481       if (!serialize_stream_profiles (out, sprof, profname, i))
482         return FALSE;
483     }
484   }
485   g_free (profgroupname);
486   return TRUE;
487 }
488
489 static gboolean
490 serialize_target (GKeyFile * out, GstEncodingTarget * target)
491 {
492   GList *tmp;
493
494   g_key_file_set_string (out, GST_ENCODING_TARGET_HEADER, "name", target->name);
495   g_key_file_set_string (out, GST_ENCODING_TARGET_HEADER, "category",
496       target->category);
497   g_key_file_set_string (out, GST_ENCODING_TARGET_HEADER, "description",
498       target->description);
499
500   for (tmp = target->profiles; tmp; tmp = tmp->next) {
501     GstEncodingProfile *prof = (GstEncodingProfile *) tmp->data;
502     if (!serialize_encoding_profile (out, prof))
503       return FALSE;
504   }
505
506   return TRUE;
507 }
508
509 /**
510  * parse_encoding_profile:
511  * @in: a #GKeyFile
512  * @parentprofilename: the parent profile name (including 'profile-' or 'streamprofile-' header)
513  * @profilename: the profile name group to parse
514  * @nbgroups: the number of top-level groups
515  * @groups: the top-level groups
516  */
517 static GstEncodingProfile *
518 parse_encoding_profile (GKeyFile * in, gchar * parentprofilename,
519     gchar * profilename, gsize nbgroups, gchar ** groups)
520 {
521   GstEncodingProfile *sprof = NULL;
522   gchar **parent;
523   gchar *proftype, *format, *preset, *restriction, *pname, *description;
524   GstCaps *formatcaps = NULL;
525   GstCaps *restrictioncaps = NULL;
526   gboolean variableframerate;
527   gint pass, presence;
528   gsize i, nbencprofiles;
529
530   GST_DEBUG ("parentprofilename : %s , profilename : %s",
531       parentprofilename, profilename);
532
533   if (parentprofilename) {
534     gboolean found = FALSE;
535
536     parent =
537         g_key_file_get_string_list (in, profilename, "parent",
538         &nbencprofiles, NULL);
539     if (!parent || !nbencprofiles) {
540       return NULL;
541     }
542
543     /* Check if this streamprofile is used in <profilename> */
544     for (i = 0; i < nbencprofiles; i++) {
545       if (!g_strcmp0 (parent[i], parentprofilename)) {
546         found = TRUE;
547         break;
548       }
549     }
550     g_strfreev (parent);
551
552     if (!found) {
553       GST_DEBUG ("Stream profile '%s' isn't used in profile '%s'",
554           profilename, parentprofilename);
555       return NULL;
556     }
557   }
558
559   pname = g_key_file_get_value (in, profilename, "name", NULL);
560
561   /* First try to get localized description */
562   {
563     gchar *locale;
564
565     locale = get_locale ();
566     if (locale != NULL) {
567       /* will try to fall back to untranslated string if no translation found */
568       description = g_key_file_get_locale_string (in, profilename,
569           "description", locale, NULL);
570       g_free (locale);
571     } else {
572       description =
573           g_key_file_get_string (in, profilename, "description", NULL);
574     }
575   }
576
577   /* Note: a missing description is normal for non-container profiles */
578   if (description == NULL) {
579     GST_LOG ("Missing 'description' field for streamprofile %s", profilename);
580   }
581
582   /* Parse the remaining fields */
583   proftype = g_key_file_get_value (in, profilename, "type", NULL);
584   if (!proftype) {
585     GST_WARNING ("Missing 'type' field for streamprofile %s", profilename);
586     return NULL;
587   }
588
589   format = g_key_file_get_value (in, profilename, "format", NULL);
590   if (format) {
591     formatcaps = gst_caps_from_string (format);
592     g_free (format);
593   }
594
595   preset = g_key_file_get_value (in, profilename, "preset", NULL);
596
597   restriction = g_key_file_get_value (in, profilename, "restriction", NULL);
598   if (restriction) {
599     restrictioncaps = gst_caps_from_string (restriction);
600     g_free (restriction);
601   }
602
603   presence = g_key_file_get_integer (in, profilename, "presence", NULL);
604   pass = g_key_file_get_integer (in, profilename, "pass", NULL);
605   variableframerate =
606       g_key_file_get_boolean (in, profilename, "variableframerate", NULL);
607
608   /* Build the streamprofile ! */
609   if (!g_strcmp0 (proftype, "container")) {
610     GstEncodingProfile *pprof;
611
612     sprof =
613         (GstEncodingProfile *) gst_encoding_container_profile_new (pname,
614         description, formatcaps, preset);
615     /* Now look for the stream profiles */
616     for (i = 0; i < nbgroups; i++) {
617       if (!g_ascii_strncasecmp (groups[i], "streamprofile-", 13)) {
618         pprof = parse_encoding_profile (in, pname, groups[i], nbgroups, groups);
619         if (pprof) {
620           gst_encoding_container_profile_add_profile (
621               (GstEncodingContainerProfile *) sprof, pprof);
622         }
623       }
624     }
625   } else if (!g_strcmp0 (proftype, "video")) {
626     sprof =
627         (GstEncodingProfile *) gst_encoding_video_profile_new (formatcaps,
628         preset, restrictioncaps, presence);
629     gst_encoding_video_profile_set_variableframerate ((GstEncodingVideoProfile
630             *) sprof, variableframerate);
631     gst_encoding_video_profile_set_pass ((GstEncodingVideoProfile *) sprof,
632         pass);
633   } else if (!g_strcmp0 (proftype, "audio")) {
634     sprof =
635         (GstEncodingProfile *) gst_encoding_audio_profile_new (formatcaps,
636         preset, restrictioncaps, presence);
637   } else
638     GST_ERROR ("Unknown profile format '%s'", proftype);
639
640   if (restrictioncaps)
641     gst_caps_unref (restrictioncaps);
642   if (formatcaps)
643     gst_caps_unref (formatcaps);
644
645   if (pname)
646     g_free (pname);
647   if (description)
648     g_free (description);
649   if (preset)
650     g_free (preset);
651   if (proftype)
652     g_free (proftype);
653
654   return sprof;
655 }
656
657 static GstEncodingTarget *
658 parse_keyfile (GKeyFile * in, gchar * targetname, gchar * categoryname,
659     gchar * description)
660 {
661   GstEncodingTarget *res = NULL;
662   GstEncodingProfile *prof;
663   gchar **groups;
664   gsize i, nbgroups;
665
666   res = gst_encoding_target_new (targetname, categoryname, description, NULL);
667
668   /* Figure out the various profiles */
669   groups = g_key_file_get_groups (in, &nbgroups);
670   for (i = 0; i < nbgroups; i++) {
671     if (!g_ascii_strncasecmp (groups[i], "profile-", 8)) {
672       prof = parse_encoding_profile (in, NULL, groups[i], nbgroups, groups);
673       if (prof)
674         gst_encoding_target_add_profile (res, prof);
675     }
676   }
677
678   g_strfreev (groups);
679
680   if (targetname)
681     g_free (targetname);
682   if (categoryname)
683     g_free (categoryname);
684   if (description)
685     g_free (description);
686
687   return res;
688 }
689
690 static GKeyFile *
691 load_file_and_read_header (const gchar * path, gchar ** targetname,
692     gchar ** categoryname, gchar ** description, GError ** error)
693 {
694   GKeyFile *in;
695   gboolean res;
696
697   in = g_key_file_new ();
698
699   GST_DEBUG ("path:%s", path);
700
701   res =
702       g_key_file_load_from_file (in, path,
703       G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS, error);
704   if (!res || error != NULL)
705     goto load_error;
706
707   *targetname =
708       g_key_file_get_value (in, GST_ENCODING_TARGET_HEADER, "name", error);
709   if (!*targetname)
710     goto empty_name;
711
712   *categoryname =
713       g_key_file_get_value (in, GST_ENCODING_TARGET_HEADER, "category", NULL);
714   *description =
715       g_key_file_get_value (in, GST_ENCODING_TARGET_HEADER, "description",
716       NULL);
717
718   return in;
719
720 load_error:
721   {
722     GST_WARNING ("Unable to read GstEncodingTarget file %s: %s",
723         path, (*error)->message);
724     g_key_file_free (in);
725     return NULL;
726   }
727
728 empty_name:
729   {
730     GST_WARNING ("Wrong header in file %s: %s", path, (*error)->message);
731     g_key_file_free (in);
732     return NULL;
733   }
734 }
735
736 /**
737  * gst_encoding_target_load_from_file:
738  * @filepath: The file location to load the #GstEncodingTarget from
739  * @error: If an error occured, this field will be filled in.
740  *
741  * Opens the provided file and returns the contained #GstEncodingTarget.
742  *
743  * Since: 0.10.32
744  *
745  * Returns: (transfer full): The #GstEncodingTarget contained in the file, else
746  * %NULL
747  */
748
749 GstEncodingTarget *
750 gst_encoding_target_load_from_file (const gchar * filepath, GError ** error)
751 {
752   GKeyFile *in;
753   gchar *targetname, *categoryname, *description;
754   GstEncodingTarget *res = NULL;
755
756   in = load_file_and_read_header (filepath, &targetname, &categoryname,
757       &description, error);
758   if (!in)
759     goto beach;
760
761   res = parse_keyfile (in, targetname, categoryname, description);
762
763   g_key_file_free (in);
764
765 beach:
766   return res;
767 }
768
769 /*
770  * returned list contents must be freed
771  */
772 static GList *
773 get_matching_filenames (gchar * path, gchar * filename)
774 {
775   GList *res = NULL;
776   GDir *topdir;
777   const gchar *subdirname;
778
779   topdir = g_dir_open (path, 0, NULL);
780   if (G_UNLIKELY (topdir == NULL))
781     return NULL;
782
783   while ((subdirname = g_dir_read_name (topdir))) {
784     gchar *ltmp = g_build_filename (path, subdirname, NULL);
785
786     if (g_file_test (ltmp, G_FILE_TEST_IS_DIR)) {
787       gchar *tmp = g_build_filename (path, subdirname, filename, NULL);
788       /* Test to see if we have a file named like that in that directory */
789       if (g_file_test (tmp, G_FILE_TEST_EXISTS))
790         res = g_list_append (res, tmp);
791       else
792         g_free (tmp);
793     }
794     g_free (ltmp);
795   }
796
797   g_dir_close (topdir);
798
799   return res;
800 }
801
802 static GstEncodingTarget *
803 gst_encoding_target_subload (gchar * path, const gchar * category,
804     gchar * lfilename, GError ** error)
805 {
806   GstEncodingTarget *target = NULL;
807
808   if (category) {
809     gchar *filename;
810
811     filename = g_build_filename (path, category, lfilename, NULL);
812     target = gst_encoding_target_load_from_file (filename, error);
813     g_free (filename);
814   } else {
815     GList *tmp, *tries = get_matching_filenames (path, lfilename);
816
817     /* Try to find a file named %s.gstprofile in any subdirectories */
818     for (tmp = tries; tmp; tmp = tmp->next) {
819       target = gst_encoding_target_load_from_file ((gchar *) tmp->data, NULL);
820       if (target)
821         break;
822     }
823     g_list_foreach (tries, (GFunc) g_free, NULL);
824     if (tries)
825       g_list_free (tries);
826   }
827
828   return target;
829 }
830
831 /**
832  * gst_encoding_target_load:
833  * @name: the name of the #GstEncodingTarget to load.
834  * @category: (allow-none): the name of the target category, like
835  * #GST_ENCODING_CATEGORY_DEVICE. Can be %NULL
836  * @error: If an error occured, this field will be filled in.
837  *
838  * Searches for the #GstEncodingTarget with the given name, loads it
839  * and returns it.
840  *
841  * If the category name is specified only targets from that category will be
842  * searched for.
843  *
844  * Since: 0.10.32
845  *
846  * Returns: (transfer full): The #GstEncodingTarget if available, else %NULL.
847  */
848 GstEncodingTarget *
849 gst_encoding_target_load (const gchar * name, const gchar * category,
850     GError ** error)
851 {
852   gchar *lfilename, *tldir;
853   GstEncodingTarget *target = NULL;
854
855   g_return_val_if_fail (name != NULL, NULL);
856
857   if (!validate_name (name))
858     goto invalid_name;
859
860   if (category && !validate_name (category))
861     goto invalid_category;
862
863   lfilename = g_strdup_printf ("%s" GST_ENCODING_TARGET_SUFFIX, name);
864
865   /* Try from local profiles */
866   tldir =
867       g_build_filename (g_get_home_dir (), ".gstreamer-" GST_MAJORMINOR,
868       GST_ENCODING_TARGET_DIRECTORY, NULL);
869   target = gst_encoding_target_subload (tldir, category, lfilename, error);
870   g_free (tldir);
871
872   if (target == NULL) {
873     /* Try from system-wide profiles */
874     tldir =
875         g_build_filename (GST_DATADIR, "gstreamer-" GST_MAJORMINOR,
876         GST_ENCODING_TARGET_DIRECTORY, NULL);
877     target = gst_encoding_target_subload (tldir, category, lfilename, error);
878     g_free (tldir);
879   }
880
881   g_free (lfilename);
882
883   return target;
884
885 invalid_name:
886   {
887     GST_ERROR ("Invalid name for encoding target : '%s'", name);
888     return NULL;
889   }
890 invalid_category:
891   {
892     GST_ERROR ("Invalid name for encoding category : '%s'", category);
893     return NULL;
894   }
895 }
896
897 /**
898  * gst_encoding_target_save_to_file:
899  * @target: a #GstEncodingTarget
900  * @filepath: the location to store the @target at.
901  * @error: If an error occured, this field will be filled in.
902  *
903  * Saves the @target to the provided file location.
904  *
905  * Since: 0.10.32
906  *
907  * Returns: %TRUE if the target was correctly saved, else %FALSE.
908  **/
909
910 gboolean
911 gst_encoding_target_save_to_file (GstEncodingTarget * target,
912     const gchar * filepath, GError ** error)
913 {
914   GKeyFile *out;
915   gchar *data;
916   gsize data_size;
917
918   g_return_val_if_fail (GST_IS_ENCODING_TARGET (target), FALSE);
919   g_return_val_if_fail (filepath != NULL, FALSE);
920
921   /* FIXME : Check filepath is valid and writable
922    * FIXME : Strip out profiles already present in system target */
923
924   /* Get unique name... */
925
926   /* Create output GKeyFile */
927   out = g_key_file_new ();
928
929   if (!serialize_target (out, target))
930     goto serialize_failure;
931
932   if (!(data = g_key_file_to_data (out, &data_size, error)))
933     goto convert_failed;
934
935   if (!g_file_set_contents (filepath, data, data_size, error))
936     goto write_failed;
937
938   g_key_file_free (out);
939   g_free (data);
940
941   return TRUE;
942
943 serialize_failure:
944   {
945     GST_ERROR ("Failure serializing target");
946     g_key_file_free (out);
947     return FALSE;
948   }
949
950 convert_failed:
951   {
952     GST_ERROR ("Failure converting keyfile: %s", (*error)->message);
953     g_key_file_free (out);
954     g_free (data);
955     return FALSE;
956   }
957
958 write_failed:
959   {
960     GST_ERROR ("Unable to write file %s: %s", filepath, (*error)->message);
961     g_key_file_free (out);
962     g_free (data);
963     return FALSE;
964   }
965 }
966
967 /**
968  * gst_encoding_target_save:
969  * @target: a #GstEncodingTarget
970  * @error: If an error occured, this field will be filled in.
971  *
972  * Saves the @target to a default user-local directory.
973  *
974  * Since: 0.10.32
975  *
976  * Returns: %TRUE if the target was correctly saved, else %FALSE.
977  **/
978
979 gboolean
980 gst_encoding_target_save (GstEncodingTarget * target, GError ** error)
981 {
982   gchar *filename;
983   gchar *lfilename;
984   gboolean res;
985
986   g_return_val_if_fail (GST_IS_ENCODING_TARGET (target), FALSE);
987   g_return_val_if_fail (target->category != NULL, FALSE);
988
989   lfilename = g_strdup_printf ("%s" GST_ENCODING_TARGET_SUFFIX, target->name);
990   filename =
991       g_build_filename (g_get_home_dir (), ".gstreamer-" GST_MAJORMINOR,
992       GST_ENCODING_TARGET_DIRECTORY, target->category, lfilename, NULL);
993   g_free (lfilename);
994
995   res = gst_encoding_target_save_to_file (target, filename, error);
996   g_free (filename);
997
998   return TRUE;
999 }
1000
1001 static GList *
1002 get_categories (gchar * path)
1003 {
1004   GList *res = NULL;
1005   GDir *topdir;
1006   const gchar *subdirname;
1007
1008   topdir = g_dir_open (path, 0, NULL);
1009   if (G_UNLIKELY (topdir == NULL))
1010     return NULL;
1011
1012   while ((subdirname = g_dir_read_name (topdir))) {
1013     gchar *ltmp = g_build_filename (path, subdirname, NULL);
1014
1015     if (g_file_test (ltmp, G_FILE_TEST_IS_DIR)) {
1016       res = g_list_append (res, (gpointer) g_strdup (subdirname));
1017     }
1018     g_free (ltmp);
1019   }
1020
1021   g_dir_close (topdir);
1022
1023   return res;
1024 }
1025
1026 /**
1027  * gst_encoding_list_available_categories:
1028  *
1029  * Lists all #GstEncodingTarget categories present on disk.
1030  *
1031  * Returns: (transfer full) (element-type gchar*): A list
1032  * of #GstEncodingTarget categories.
1033  *
1034  * Since: 0.10.32
1035  */
1036 GList *
1037 gst_encoding_list_available_categories (void)
1038 {
1039   GList *res = NULL;
1040   GList *tmp1, *tmp2;
1041   gchar *topdir;
1042
1043   /* First try user-local categories */
1044   topdir = g_build_filename (g_get_home_dir (), ".gstreamer-" GST_MAJORMINOR,
1045       GST_ENCODING_TARGET_DIRECTORY, NULL);
1046   res = get_categories (topdir);
1047   g_free (topdir);
1048
1049   /* Extend with system-wide categories */
1050   topdir = g_build_filename (GST_DATADIR, "gstreamer-" GST_MAJORMINOR,
1051       GST_ENCODING_TARGET_DIRECTORY, NULL);
1052   tmp1 = get_categories (topdir);
1053   g_free (topdir);
1054
1055   for (tmp2 = tmp1; tmp2; tmp2 = tmp2->next) {
1056     gchar *name = (gchar *) tmp2->data;
1057     if (!g_list_find_custom (res, name, (GCompareFunc) g_strcmp0))
1058       res = g_list_append (res, (gpointer) name);
1059     else
1060       g_free (name);
1061   }
1062   g_free (tmp1);
1063
1064   return res;
1065 }
1066
1067 static inline GList *
1068 sub_get_all_targets (gchar * subdir)
1069 {
1070   GList *res = NULL;
1071   const gchar *filename;
1072   GDir *dir;
1073   GstEncodingTarget *target;
1074
1075   dir = g_dir_open (subdir, 0, NULL);
1076   if (G_UNLIKELY (dir == NULL))
1077     return NULL;
1078
1079   while ((filename = g_dir_read_name (dir))) {
1080     gchar *fullname;
1081
1082     /* Only try files ending with .gstprofile */
1083     if (!g_str_has_suffix (filename, GST_ENCODING_TARGET_SUFFIX))
1084       continue;
1085
1086     fullname = g_build_filename (subdir, filename, NULL);
1087     target = gst_encoding_target_load_from_file (fullname, NULL);
1088     if (target) {
1089       res = g_list_append (res, target);
1090     } else
1091       GST_WARNING ("Failed to get a target from %s", fullname);
1092     g_free (fullname);
1093   }
1094   g_dir_close (dir);
1095
1096   return res;
1097 }
1098
1099 static inline GList *
1100 get_all_targets (gchar * topdir, const gchar * categoryname)
1101 {
1102   GList *res = NULL;
1103
1104   if (categoryname) {
1105     gchar *subdir = g_build_filename (topdir, categoryname, NULL);
1106     /* Try to open the directory */
1107     res = sub_get_all_targets (subdir);
1108     g_free (subdir);
1109   } else {
1110     const gchar *subdirname;
1111     GDir *dir = g_dir_open (topdir, 0, NULL);
1112
1113     if (G_UNLIKELY (dir == NULL))
1114       return NULL;
1115
1116     while ((subdirname = g_dir_read_name (dir))) {
1117       gchar *ltmp = g_build_filename (topdir, subdirname, NULL);
1118
1119       if (g_file_test (ltmp, G_FILE_TEST_IS_DIR)) {
1120         res = g_list_concat (res, sub_get_all_targets (ltmp));
1121       }
1122       g_free (ltmp);
1123     }
1124     g_dir_close (dir);
1125   }
1126
1127   return res;
1128 }
1129
1130 static guint
1131 compare_targets (const GstEncodingTarget * ta, const GstEncodingTarget * tb)
1132 {
1133   if (!g_strcmp0 (ta->name, tb->name)
1134       && !g_strcmp0 (ta->category, tb->category))
1135     return -1;
1136
1137   return 0;
1138 }
1139
1140 /**
1141  * gst_encoding_list_all_targets:
1142  * @categoryname: (allow-none): The category, for ex: #GST_ENCODING_CATEGORY_DEVICE.
1143  * Can be %NULL.
1144  *
1145  * List all available #GstEncodingTarget for the specified category, or all categories
1146  * if @categoryname is %NULL.
1147  *
1148  * Returns: (transfer full) (element-type GstEncodingTarget): The list of #GstEncodingTarget
1149  *
1150  * Since: 0.10.32
1151  */
1152 GList *
1153 gst_encoding_list_all_targets (const gchar * categoryname)
1154 {
1155   GList *res;
1156   GList *tmp1, *tmp2;
1157   gchar *topdir;
1158
1159   /* Get user-locals */
1160   topdir = g_build_filename (g_get_home_dir (), ".gstreamer-" GST_MAJORMINOR,
1161       GST_ENCODING_TARGET_DIRECTORY, NULL);
1162   res = get_all_targets (topdir, categoryname);
1163   g_free (topdir);
1164
1165   /* Get system-wide */
1166   topdir = g_build_filename (GST_DATADIR, "gstreamer-" GST_MAJORMINOR,
1167       GST_ENCODING_TARGET_DIRECTORY, NULL);
1168   tmp1 = get_all_targets (topdir, categoryname);
1169   g_free (topdir);
1170
1171   /* Merge system-wide targets */
1172   /* FIXME : We should merge the system-wide profiles into the user-locals
1173    * instead of stopping at identical target names */
1174   for (tmp2 = tmp1; tmp2; tmp2 = tmp2->next) {
1175     GstEncodingTarget *target = (GstEncodingTarget *) tmp2->data;
1176     if (g_list_find_custom (res, target, (GCompareFunc) compare_targets))
1177       gst_encoding_target_unref (target);
1178     else
1179       res = g_list_append (res, target);
1180   }
1181   g_list_free (tmp1);
1182
1183   return res;
1184 }