rtsp: Port to GIO
[platform/upstream/gstreamer.git] / gst-libs / gst / tag / lang.c
1 /* GStreamer language codes and names utility functions
2  * Copyright (C) 2009 Tim-Philipp Müller <tim centricular net>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:gsttaglanguagecodes
22  * @short_description: mappings for ISO-639 language codes and names
23  * @see_also: #GstTagList
24  *
25  * <refsect2>
26  * <para>
27  * Provides helper functions to convert between the various ISO-639 language
28  * codes, and to map language codes to language names.
29  * </para>
30  * </refsect2>
31  */
32
33 #ifdef HAVE_CONFIG_H
34 #include "config.h"
35 #endif
36
37 #undef GETTEXT_PACKAGE
38 #define GETTEXT_PACKAGE "iso_639"
39
40 #define ISO_639_XML_PATH ISO_CODES_PREFIX "/share/xml/iso-codes/iso_639.xml"
41 #define ISO_CODES_LOCALEDIR ISO_CODES_PREFIX "/share/locale"
42
43 #include <gst/gst-i18n-plugin.h>
44 #include <gst/gst.h>
45
46 #include <string.h>
47 #include <stdlib.h>
48
49 #include "tag.h"
50 #include "lang-tables.dat"
51
52 #ifndef GST_DISABLE_GST_DEBUG
53
54 #define GST_CAT_DEFAULT ensure_debug_category()
55
56 static GstDebugCategory *
57 ensure_debug_category (void)
58 {
59   static gsize cat_gonce = 0;
60
61   if (g_once_init_enter (&cat_gonce)) {
62     gsize cat_done;
63
64     cat_done = (gsize) _gst_debug_category_new ("tag-langcodes", 0,
65         "GstTag language codes and names");
66
67     g_once_init_leave (&cat_gonce, cat_done);
68   }
69
70   return (GstDebugCategory *) cat_gonce;
71 }
72
73 #else
74
75 #define ensure_debug_category() /* NOOP */
76
77 #endif /* GST_DISABLE_GST_DEBUG */
78
79 /* ------------------------------------------------------------------------- */
80
81 /* Loading and initing */
82
83 #if defined(HAVE_ISO_CODES)
84 static const gchar *
85 get_val (const gchar ** names, const gchar ** vals, const gchar * name)
86 {
87   while (names != NULL && *names != NULL) {
88     if (strcmp (*names, name) == 0)
89       return *vals;
90     ++names;
91     ++vals;
92   }
93   return NULL;
94 }
95
96 static void
97 parse_start_element (GMarkupParseContext * ctx, const gchar * element_name,
98     const gchar ** attr_names, const gchar ** attr_vals,
99     gpointer user_data, GError ** error)
100 {
101   GHashTable *ht = (GHashTable *) user_data;
102   const gchar *c1, *c2t, *c2b, *name, *tname;
103
104   if (strcmp (element_name, "iso_639_entry") != 0)
105     return;
106
107   c1 = get_val (attr_names, attr_vals, "iso_639_1_code");
108
109   /* only interested in languages with an ISO 639-1 code for now */
110   if (c1 == NULL)
111     return;
112
113   c2t = get_val (attr_names, attr_vals, "iso_639_2T_code");
114   c2b = get_val (attr_names, attr_vals, "iso_639_2B_code");
115   name = get_val (attr_names, attr_vals, "name");
116
117   if (c2t == NULL || c2b == NULL || name == NULL) {
118     GST_WARNING ("broken iso_639.xml entry: c2t=%p, c2b=%p, name=%p", c2t,
119         c2b, name);
120     return;
121   }
122
123   /* translate language name */
124   tname = _(name);
125
126   /* if no translation was found, it will return the input string, which we
127    * we don't want to put into the hash table because it will be freed again */
128   if (G_UNLIKELY (tname == name))
129     tname = g_intern_string (name);
130
131   /* now overwrite default/fallback mappings with names in locale language */
132   g_hash_table_replace (ht, (gpointer) g_intern_string (c1), (gpointer) tname);
133   g_hash_table_replace (ht, (gpointer) g_intern_string (c2b), (gpointer) tname);
134   if (strcmp (c2t, c2b) != 0) {
135     g_hash_table_replace (ht, (gpointer) g_intern_string (c2t),
136         (gpointer) tname);
137   }
138
139   GST_LOG ("%s %s %s : %s - %s", c1, c2t, c2b, name, tname);
140 }
141
142 static void
143 gst_tag_load_iso_639_xml (GHashTable * ht)
144 {
145   GMappedFile *f;
146   GError *err = NULL;
147   gchar *xml_data;
148   gsize xml_len;
149
150 #ifdef ENABLE_NLS
151   GST_DEBUG ("binding text domain %s to locale dir %s", GETTEXT_PACKAGE,
152       ISO_CODES_LOCALEDIR);
153   bindtextdomain (GETTEXT_PACKAGE, ISO_CODES_LOCALEDIR);
154   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
155 #endif
156
157   f = g_mapped_file_new (ISO_639_XML_PATH, FALSE, NULL);
158   if (f != NULL) {
159     xml_data = (gchar *) g_mapped_file_get_contents (f);
160     xml_len = g_mapped_file_get_length (f);
161   } else {
162     if (!g_file_get_contents (ISO_639_XML_PATH, &xml_data, &xml_len, &err)) {
163       GST_WARNING ("Could not read %s: %s", ISO_639_XML_PATH, err->message);
164       g_error_free (err);
165       return;
166     }
167   }
168
169   if (g_utf8_validate (xml_data, xml_len, NULL)) {
170     GMarkupParser xml_parser = { parse_start_element, NULL, NULL, NULL, NULL };
171     GMarkupParseContext *ctx;
172
173     ctx = g_markup_parse_context_new (&xml_parser, 0, ht, NULL);
174     if (!g_markup_parse_context_parse (ctx, xml_data, xml_len, &err)) {
175       GST_WARNING ("Parsing iso_639.xml failed: %s", err->message);
176       g_error_free (err);
177     }
178     g_markup_parse_context_free (ctx);
179   } else {
180     GST_WARNING ("iso_639.xml file is not valid UTF-8");
181     GST_MEMDUMP ("iso_639.xml file", (guint8 *) xml_data, xml_len);
182   }
183
184   /* ... and clean up */
185   if (f != NULL)
186     g_mapped_file_unref (f);
187   else
188     g_free (xml_data);
189 }
190 #endif /* HAVE_ISO_CODES */
191
192 static GHashTable *
193 gst_tag_get_iso_639_ht (void)
194 {
195   static gsize once_val = 0;
196   int i;
197
198   if (g_once_init_enter (&once_val)) {
199     GHashTable *ht;
200     gsize done_val;
201
202     GST_MEMDUMP ("iso 639 language names (internal default/fallback)",
203         (guint8 *) iso_639_names, sizeof (iso_639_names));
204
205     /* maps code -> language name; all strings are either interned strings
206      * or const static strings from lang-table.c */
207     ht = g_hash_table_new (g_str_hash, g_str_equal);
208
209     /* set up default/fallback mappings */
210     for (i = 0; i < G_N_ELEMENTS (iso_639_codes); ++i) {
211       GST_LOG ("%3d %s %s %c%c 0x%04x  %s", i, iso_639_codes[i].iso_639_1,
212           iso_639_codes[i].iso_639_2,
213           ((iso_639_codes[i].flags & ISO_639_FLAG_2B)) ? 'B' : '.',
214           ((iso_639_codes[i].flags & ISO_639_FLAG_2T)) ? 'T' : '.',
215           iso_639_codes[i].name_offset,
216           iso_639_names + iso_639_codes[i].name_offset);
217
218 #ifdef HAVE_ISO_CODES
219       /* intern these in order to minimise allocations when interning strings
220        * read from the xml file later */
221       g_intern_static_string (iso_639_codes[i].iso_639_1);
222       g_intern_static_string (iso_639_codes[i].iso_639_2);
223       g_intern_static_string (iso_639_names + iso_639_codes[i].name_offset);
224 #endif
225
226       /* and add default mapping (these strings are always valid) */
227       g_hash_table_insert (ht, (gpointer) iso_639_codes[i].iso_639_1,
228           (gpointer) (iso_639_names + iso_639_codes[i].name_offset));
229       g_hash_table_insert (ht, (gpointer) iso_639_codes[i].iso_639_2,
230           (gpointer) (iso_639_names + iso_639_codes[i].name_offset));
231     }
232
233 #ifdef HAVE_ISO_CODES
234     {
235       GstClockTime ts = gst_util_get_timestamp ();
236
237       gst_tag_load_iso_639_xml (ht);
238
239       ts = gst_util_get_timestamp () - ts;
240       GST_INFO ("iso_639.xml loading took %.2gms", (double) ts / GST_MSECOND);
241     }
242 #else
243     GST_INFO ("iso-codes disabled or not available");
244 #endif
245
246     done_val = (gsize) ht;
247     g_once_init_leave (&once_val, done_val);
248   }
249
250   return (GHashTable *) once_val;
251 }
252
253 /* ------------------------------------------------------------------------- */
254
255 static int
256 qsort_strcmp_func (const void *p1, const void *p2)
257 {
258   return strcmp (*(char *const *) p1, *(char *const *) p2);
259 }
260
261 /**
262  * gst_tag_get_language_codes:
263  *
264  * Returns a list of known language codes (in form of two-letter ISO-639-1
265  * codes). This is useful for UIs to build a list of available languages for
266  * tagging purposes (e.g. to tag an audio track appropriately in a video or
267  * audio editor).
268  *
269  * Returns: NULL-terminated string array with two-letter language codes. Free
270  *     with g_strfreev() when no longer needed.
271  *
272  * Since: 0.10.26
273  */
274 gchar **
275 gst_tag_get_language_codes (void)
276 {
277   GHashTableIter iter;
278   GHashTable *ht;
279   gpointer key;
280   gchar **codes;
281   int i;
282
283   ensure_debug_category ();
284
285   ht = gst_tag_get_iso_639_ht ();
286
287   /* we have at least two keys for each language (-1 code and -2 code) */
288   codes = g_new (gchar *, (g_hash_table_size (ht) / 2) + 1);
289
290   i = 0;
291   g_hash_table_iter_init (&iter, ht);
292   while (g_hash_table_iter_next (&iter, &key, NULL)) {
293     const gchar *lang_code = key;
294
295     if (strlen (lang_code) == 2) {
296       codes[i] = g_strdup (lang_code);
297       ++i;
298     }
299   }
300   codes[i] = NULL;
301
302   /* be nice and sort the list */
303   qsort (&codes[0], i, sizeof (gchar *), qsort_strcmp_func);
304
305   return codes;
306 }
307
308 /**
309  * gst_tag_get_language_name:
310  * @language_code: two or three-letter ISO-639 language code
311  *
312  * Returns the name of the language given an ISO-639 language code as
313  * found in a GST_TAG_LANGUAGE_CODE tag. The name will be translated
314  * according to the current locale (if the library was built against the
315  * iso-codes package, otherwise the English name will be returned).
316  *
317  * Language codes are case-sensitive and expected to be lower case.
318  *
319  * Returns: language name in UTF-8 format, or NULL if @language_code could
320  *     not be mapped to a language name. The returned string must not be
321  *     modified and does not need to freed; it will stay valid until the
322  *     application is terminated.
323  *
324  * Since: 0.10.26
325  */
326 const gchar *
327 gst_tag_get_language_name (const gchar * language_code)
328 {
329   const gchar *lang_name;
330   GHashTable *ht;
331
332   g_return_val_if_fail (language_code != NULL, NULL);
333
334   ensure_debug_category ();
335
336   ht = gst_tag_get_iso_639_ht ();
337
338   lang_name = g_hash_table_lookup (ht, (gpointer) language_code);
339   GST_LOG ("%s -> %s", language_code, GST_STR_NULL (lang_name));
340
341   return lang_name;
342 }
343
344 /**
345  * gst_tag_get_language_code_iso_639_1:
346  * @lang_code: ISO-639 language code (e.g. "deu" or "ger" or "de")
347  *
348  * Returns two-letter ISO-639-1 language code given a three-letter ISO-639-2
349  * language code or two-letter ISO-639-1 language code (both are accepted for
350  * convenience).
351  *
352  * Language codes are case-sensitive and expected to be lower case.
353  *
354  * Returns: two-letter ISO-639-1 language code string that maps to @lang_code,
355  *     or NULL if no mapping is known. The returned string must not be
356  *     modified or freed.
357  *
358  * Since: 0.10.26
359  */
360 const gchar *
361 gst_tag_get_language_code_iso_639_1 (const gchar * lang_code)
362 {
363   const gchar *c = NULL;
364   int i;
365
366   g_return_val_if_fail (lang_code != NULL, NULL);
367
368   ensure_debug_category ();
369
370   /* FIXME: we are being a bit inconsistent here in the sense that will only
371    * map the language codes from our static table. Theoretically the iso-codes
372    * XML file might have had additional codes that are now in the hash table.
373    * We keep it simple for now and don't waste memory on additional tables. */
374   for (i = 0; i < G_N_ELEMENTS (iso_639_codes); ++i) {
375     /* we check both codes here, so function can be used in a more versatile
376      * way, to convert a language tag to a two-letter language code and/or
377      * verify an existing code */
378     if (strcmp (lang_code, iso_639_codes[i].iso_639_1) == 0 ||
379         strcmp (lang_code, iso_639_codes[i].iso_639_2) == 0) {
380       c = iso_639_codes[i].iso_639_1;
381       break;
382     }
383   }
384
385   GST_LOG ("%s -> %s", lang_code, GST_STR_NULL (c));
386
387   return c;
388 }
389
390 static const gchar *
391 gst_tag_get_language_code_iso_639_2X (const gchar * lang_code, guint8 flags)
392 {
393   int i;
394
395   /* FIXME: we are being a bit inconsistent here in the sense that we will only
396    * map the language codes from our static table. Theoretically the iso-codes
397    * XML file might have had additional codes that are now in the hash table.
398    * We keep it simple for now and don't waste memory on additional tables.
399    * Also, we currently only parse the iso_639.xml file if language names or
400    * a list of all codes is requested, and it'd be nice to keep it like that. */
401   for (i = 0; i < G_N_ELEMENTS (iso_639_codes); ++i) {
402     /* we check both codes here, so function can be used in a more versatile
403      * way, to convert a language tag to a three-letter language code and/or
404      * verify an existing code */
405     if (strcmp (lang_code, iso_639_codes[i].iso_639_1) == 0 ||
406         strcmp (lang_code, iso_639_codes[i].iso_639_2) == 0) {
407       if ((iso_639_codes[i].flags & flags) == flags) {
408         return iso_639_codes[i].iso_639_2;
409       } else if (i > 0 && (iso_639_codes[i - 1].flags & flags) == flags &&
410           iso_639_codes[i].name_offset == iso_639_codes[i - 1].name_offset) {
411         return iso_639_codes[i - 1].iso_639_2;
412       } else if ((i + 1) < G_N_ELEMENTS (iso_639_codes) &&
413           (iso_639_codes[i + 1].flags & flags) == flags &&
414           iso_639_codes[i].name_offset == iso_639_codes[i + 1].name_offset) {
415         return iso_639_codes[i + 1].iso_639_2;
416       }
417     }
418   }
419   return NULL;
420 }
421
422 /**
423  * gst_tag_get_language_code_iso_639_2T:
424  * @lang_code: ISO-639 language code (e.g. "deu" or "ger" or "de")
425  *
426  * Returns three-letter ISO-639-2 "terminological" language code given a
427  * two-letter ISO-639-1 language code or a three-letter ISO-639-2 language
428  * code (both are accepted for convenience).
429  *
430  * The "terminological" code is derived from the local name of the language
431  * (e.g. "deu" for German instead of "ger"). In most scenarios, the
432  * "terminological" codes are prefered over the "bibliographic" ones.
433  *
434  * Language codes are case-sensitive and expected to be lower case.
435  *
436  * Returns: three-letter ISO-639-2 language code string that maps to @lang_code,
437  *     or NULL if no mapping is known. The returned string must not be
438  *     modified or freed.
439  *
440  * Since: 0.10.26
441  */
442 const gchar *
443 gst_tag_get_language_code_iso_639_2T (const gchar * lang_code)
444 {
445   const gchar *c;
446
447   g_return_val_if_fail (lang_code != NULL, NULL);
448
449   ensure_debug_category ();
450
451   c = gst_tag_get_language_code_iso_639_2X (lang_code, ISO_639_FLAG_2T);
452
453   GST_LOG ("%s -> %s", lang_code, GST_STR_NULL (c));
454
455   return c;
456 }
457
458 /**
459  * gst_tag_get_language_code_iso_639_2B:
460  * @lang_code: ISO-639 language code (e.g. "deu" or "ger" or "de")
461  *
462  * Returns three-letter ISO-639-2 "bibliographic" language code given a
463  * two-letter ISO-639-1 language code or a three-letter ISO-639-2 language
464  * code (both are accepted for convenience).
465  *
466  * The "bibliographic" code is derived from the English name of the language
467  * (e.g. "ger" for German instead of "de" or "deu"). In most scenarios, the
468  * "terminological" codes are prefered.
469  *
470  * Language codes are case-sensitive and expected to be lower case.
471  *
472  * Returns: three-letter ISO-639-2 language code string that maps to @lang_code,
473  *     or NULL if no mapping is known. The returned string must not be
474  *     modified or freed.
475  *
476  * Since: 0.10.26
477  */
478 const gchar *
479 gst_tag_get_language_code_iso_639_2B (const gchar * lang_code)
480 {
481   const gchar *c;
482
483   g_return_val_if_fail (lang_code != NULL, NULL);
484
485   ensure_debug_category ();
486
487   c = gst_tag_get_language_code_iso_639_2X (lang_code, ISO_639_FLAG_2B);
488
489   GST_LOG ("%s -> %s", lang_code, GST_STR_NULL (c));
490
491   return c;
492 }
493
494 /**
495  * gst_tag_check_language_code:
496  * @lang_code: ISO-639 language code (e.g. "deu" or "ger" or "de")
497  *
498  * Check if a given string contains a known ISO 639 language code.
499  *
500  * This is useful in situations where it's not clear whether a given
501  * string is a language code (which should be put into a #GST_TAG_LANGUAGE_CODE
502  * tag) or a free-form language name descriptor (which should be put into a
503  * #GST_TAG_LANGUAGE_NAME tag instead).
504  *
505  * Returns: TRUE if the two- or three-letter language code in @lang_code
506  *     is a valid ISO-639 language code.
507  *
508  * Since: 0.10.37
509  */
510 gboolean
511 gst_tag_check_language_code (const gchar * lang_code)
512 {
513   return (gst_tag_get_language_code_iso_639_1 (lang_code) != NULL);
514 }