Source: lib/util/language_utils.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.LanguageUtils');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.util.ManifestParserUtils');
  9. /**
  10. * @summary A set of language utility functions.
  11. * @final
  12. * @export
  13. */
  14. shaka.util.LanguageUtils = class {
  15. /**
  16. * Check if |locale1| and |locale2| are locale-compatible.
  17. *
  18. * Locale-compatible is defined as all components in each locale match. Since
  19. * we only respect the language and region components, we only check that
  20. * the language and region components match.
  21. *
  22. * Examples:
  23. * Locale A | Locale B | Locale Compatible
  24. * ---------------------------------------
  25. * en-US | en-US | true
  26. * en | en-US | false
  27. * en-US | en-CA | false
  28. *
  29. * @param {string} locale1
  30. * @param {string} locale2
  31. * @return {boolean}
  32. * @export
  33. */
  34. static areLocaleCompatible(locale1, locale2) {
  35. const LanguageUtils = shaka.util.LanguageUtils;
  36. // Even through they SHOULD already be normalized, let's just be safe and
  37. // do it again.
  38. locale1 = LanguageUtils.normalize(locale1);
  39. locale2 = LanguageUtils.normalize(locale2);
  40. return locale1 == locale2;
  41. }
  42. /**
  43. * Check if |locale1| and |locale2| are language-compatible.
  44. *
  45. * Language compatible is when the language component of each locale matches.
  46. * This means that no matter what region they have (or don't have) as long as
  47. * the language components match, they are language-compatible.
  48. *
  49. * Examples:
  50. * Locale A | Locale B | Language-Compatible
  51. * -----------------------------------------
  52. * en-US | en-US | true
  53. * en-US | en | true
  54. * en-US | en-CA | true
  55. * en-CA | fr-CA | false
  56. *
  57. * @param {string} locale1
  58. * @param {string} locale2
  59. * @return {boolean}
  60. * @export
  61. */
  62. static areLanguageCompatible(locale1, locale2) {
  63. const LanguageUtils = shaka.util.LanguageUtils;
  64. // Even through they SHOULD already be normalized, let's just be safe and
  65. // do it again.
  66. locale1 = LanguageUtils.normalize(locale1);
  67. locale2 = LanguageUtils.normalize(locale2);
  68. // Get all components. This should only be language and region
  69. // since we do not support dialect.
  70. /** @type {!Array.<string>} */
  71. const locale1Components = LanguageUtils.disassembleLocale_(locale1);
  72. /** @type {!Array.<string>} */
  73. const locale2Components = LanguageUtils.disassembleLocale_(locale2);
  74. // We are language compatible if we have the same language.
  75. return locale1Components[0] == locale2Components[0];
  76. }
  77. /**
  78. * Check if |possibleParent| is the parent locale of |possibleChild|. Because
  79. * we do not support dialects, the parent-child relationship is a lot simpler.
  80. * In a parent child relationship:
  81. * - The parent and child have the same language-component
  82. * - The parent has no region-component
  83. * - The child has a region-component
  84. *
  85. * Example:
  86. * Locale A | Locale B | Is A The parent of B?
  87. * --------------------------------------------
  88. * en-US | en-US | no
  89. * en-US | en | no
  90. * en | en-US | yes
  91. * en | en | no
  92. * en | fr | no
  93. *
  94. * @param {string} possibleParent
  95. * @param {string} possibleChild
  96. * @return {boolean}
  97. * @export
  98. */
  99. static isParentOf(possibleParent, possibleChild) {
  100. const LanguageUtils = shaka.util.LanguageUtils;
  101. // Even through they SHOULD already be normalized, let's just be safe and
  102. // do it again.
  103. possibleParent = LanguageUtils.normalize(possibleParent);
  104. possibleChild = LanguageUtils.normalize(possibleChild);
  105. // Get all components. This should only be language and region
  106. // since we do not support dialect.
  107. /** @type {!Array.<string>} */
  108. const possibleParentComponents =
  109. LanguageUtils.disassembleLocale_(possibleParent);
  110. /** @type {!Array.<string>} */
  111. const possibleChildComponents =
  112. LanguageUtils.disassembleLocale_(possibleChild);
  113. return possibleParentComponents[0] == possibleChildComponents[0] &&
  114. possibleParentComponents.length == 1 &&
  115. possibleChildComponents.length == 2;
  116. }
  117. /**
  118. * Check if |localeA| shares the same parent with |localeB|. Since we don't
  119. * support dialect, we will only look at language and region. For two locales
  120. * to be siblings:
  121. * - Both must have language-components
  122. * - Both must have region-components
  123. * - Both must have the same language-component
  124. *
  125. * Example:
  126. * Locale A | Locale B | Siblings?
  127. * --------------------------------------------
  128. * en-US | en-US | yes
  129. * en-US | en-CA | yes
  130. * en-US | en | no
  131. * en | en-US | no
  132. * en | en | no
  133. * en | fr | no
  134. *
  135. * @param {string} localeA
  136. * @param {string} localeB
  137. * @return {boolean}
  138. * @export
  139. */
  140. static isSiblingOf(localeA, localeB) {
  141. const LanguageUtils = shaka.util.LanguageUtils;
  142. // Even through they SHOULD already be normalized, let's just be safe and
  143. // do it again.
  144. localeA = LanguageUtils.normalize(localeA);
  145. localeB = LanguageUtils.normalize(localeB);
  146. // Get all components. This should only be language and region
  147. // since we do not support dialect.
  148. /** @type {!Array.<string>} */
  149. const localeAComponents = LanguageUtils.disassembleLocale_(localeA);
  150. /** @type {!Array.<string>} */
  151. const localeBComponents = LanguageUtils.disassembleLocale_(localeB);
  152. return localeAComponents.length == 2 &&
  153. localeBComponents.length == 2 &&
  154. localeAComponents[0] == localeBComponents[0];
  155. }
  156. /**
  157. * Normalize a locale. This will take a locale and canonicalize it to a state
  158. * that we are prepared to work with.
  159. *
  160. * We only support with:
  161. * - language
  162. * - language-REGION
  163. *
  164. * If given a dialect, we will discard it. We will convert any 3-character
  165. * codes to 2-character codes. We will force language codes to lowercase and
  166. * region codes to uppercase.
  167. *
  168. * @param {string} locale
  169. * @return {string}
  170. * @export
  171. */
  172. static normalize(locale) {
  173. const LanguageUtils = shaka.util.LanguageUtils;
  174. const components = locale.split('-');
  175. // We are only going to use the language and the region. If there was
  176. // a dialect or anything else, we are throwing it a way.
  177. let language = components[0] || '';
  178. let region = components[1] || '';
  179. // Convert the language to lower case. It is standard for the language code
  180. // to be in lower case, but it will also make the map look-up easier.
  181. language = language.toLowerCase();
  182. language = LanguageUtils.isoMap_.get(language) || language;
  183. // Convert the region to upper case. It is standard for the region to be in
  184. // upper case. If there is no upper code, then it will be an empty string
  185. // and this will be a no-op.
  186. region = region.toUpperCase();
  187. return region ?
  188. language + '-' + region :
  189. language;
  190. }
  191. /**
  192. * Check if two language codes are siblings. Language codes are siblings if
  193. * they share the same base language while neither one is the base language.
  194. *
  195. * For example, "en-US" and "en-CA" are siblings but "en-US" and "en" are not
  196. * siblings.
  197. *
  198. * @param {string} a
  199. * @param {string} b
  200. * @return {boolean}
  201. * @export
  202. */
  203. static areSiblings(a, b) {
  204. const LanguageUtils = shaka.util.LanguageUtils;
  205. const baseA = LanguageUtils.getBase(a);
  206. const baseB = LanguageUtils.getBase(b);
  207. return a != baseA && b != baseB && baseA == baseB;
  208. }
  209. /**
  210. * Compute a numerical relatedness for language codes. Language codes with a
  211. * higher relatedness are a better match. Unrelated language codes have a
  212. * relatedness score of 0.
  213. *
  214. * @param {string} target
  215. * @param {string} candidate
  216. * @return {number}
  217. * @export
  218. */
  219. static relatedness(target, candidate) {
  220. const LanguageUtils = shaka.util.LanguageUtils;
  221. target = LanguageUtils.normalize(target);
  222. candidate = LanguageUtils.normalize(candidate);
  223. // An exact match is the top score.
  224. if (candidate == target) {
  225. return 4;
  226. }
  227. // Next is a parent of the target language.
  228. if (LanguageUtils.isParentOf(candidate, target)) {
  229. return 3;
  230. }
  231. // Next is a sibling of the target language.
  232. if (LanguageUtils.isSiblingOf(candidate, target)) {
  233. return 2;
  234. }
  235. // Next is a child of the target language.
  236. if (LanguageUtils.isParentOf(target, candidate)) {
  237. return 1;
  238. }
  239. // Otherwise, they are unrelated.
  240. return 0;
  241. }
  242. /**
  243. * Get the normalized base language for a language code.
  244. *
  245. * @param {string} lang
  246. * @return {string}
  247. * @export
  248. */
  249. static getBase(lang) {
  250. const LanguageUtils = shaka.util.LanguageUtils;
  251. const splitAt = lang.indexOf('-');
  252. let major;
  253. if (splitAt >= 0) {
  254. major = lang.substring(0, splitAt);
  255. } else {
  256. major = lang;
  257. }
  258. // Convert the major code to lower case. It is standard for the major code
  259. // to be in lower case, but it will also make the map look-up easier.
  260. major = major.toLowerCase();
  261. major = LanguageUtils.isoMap_.get(major) || major;
  262. return major;
  263. }
  264. /**
  265. * Get the normalized language of the given text stream. Will return 'und' if
  266. * a language is not found on the text stream.
  267. *
  268. * This should always be used to get the language from a text stream.
  269. *
  270. * @param {shaka.extern.Stream} stream
  271. * @return {string}
  272. * @export
  273. */
  274. static getLocaleForText(stream) {
  275. const LanguageUtils = shaka.util.LanguageUtils;
  276. const ContentType = shaka.util.ManifestParserUtils.ContentType;
  277. goog.asserts.assert(
  278. stream.type == ContentType.TEXT,
  279. 'Can only get language from text streams');
  280. const language = stream.language || 'und';
  281. return LanguageUtils.normalize(language);
  282. }
  283. /**
  284. * Get the normalized locale for the given variant. This will look through
  285. * the variant to find the locale that represents the content in the variant.
  286. * This will return 'und' if no language can be found.
  287. *
  288. * This should always be used to get the locale from a variant.
  289. *
  290. * @param {shaka.extern.Variant} variant
  291. * @return {string}
  292. * @export
  293. */
  294. static getLocaleForVariant(variant) {
  295. const LanguageUtils = shaka.util.LanguageUtils;
  296. // Our preference order is:
  297. // 1. Variant
  298. // 2. Audio Stream
  299. // 3. Video Stream
  300. //
  301. // We are going to consider all falsy strings to be invalid locales, this
  302. // will include empty strings.
  303. if (variant.language) {
  304. return LanguageUtils.normalize(variant.language);
  305. }
  306. if (variant.audio && variant.audio.language) {
  307. return LanguageUtils.normalize(variant.audio.language);
  308. }
  309. if (variant.video && variant.video.language) {
  310. return LanguageUtils.normalize(variant.video.language);
  311. }
  312. // No language was found, but we still want to return a valid string.
  313. return 'und';
  314. }
  315. /**
  316. * Find the locale in |searchSpace| that comes closest to |target|. If no
  317. * locale is found to be close to |target|, then |null| will be returned.
  318. *
  319. * @param {string} target
  320. * @param {!Iterable.<string>} searchSpace
  321. * @return {?string}
  322. * @export
  323. */
  324. static findClosestLocale(target, searchSpace) {
  325. const LanguageUtils = shaka.util.LanguageUtils;
  326. /** @type {string} */
  327. const safeTarget = LanguageUtils.normalize(target);
  328. /** @type {!Set.<string>} */
  329. const safeSearchSpace = new Set();
  330. for (const option of searchSpace) {
  331. safeSearchSpace.add(LanguageUtils.normalize(option));
  332. }
  333. // Preference 1 - The option is an exact match. For example, "en-US" is an
  334. // exact match of "en-US". So if there is an option that is an exact
  335. // match, it would be the best match possible.
  336. for (const option of safeSearchSpace) {
  337. if (option == safeTarget) {
  338. return option;
  339. }
  340. }
  341. // Preference 2 - The option is the parent of the target. For example,
  342. // "en" is the parent of "en-US". So if there is an option with
  343. // "en", it should be good enough when our preference is "en-US".
  344. for (const option of safeSearchSpace) {
  345. if (LanguageUtils.isParentOf(option, safeTarget)) {
  346. return option;
  347. }
  348. }
  349. // Preference 3 - The option is a sibling of the target. For example,
  350. // "en-US" is a sibling of "en-CA". So if there is an option with
  351. // "en_CA", it should be good enough when our preference is "en-US".
  352. for (const option of safeSearchSpace) {
  353. if (LanguageUtils.isSiblingOf(option, safeTarget)) {
  354. return option;
  355. }
  356. }
  357. // Preference 4 - The option is a child of the target. For example,
  358. // "en-US" is the child of "en". SO it there is an option with
  359. // "en-US", it should be good enough when our preference is "en".
  360. for (const option of safeSearchSpace) {
  361. if (LanguageUtils.isParentOf(safeTarget, option)) {
  362. return option;
  363. }
  364. }
  365. // Failed to find anything.
  366. return null;
  367. }
  368. /**
  369. * Take a locale string and break it into its component. Check that each
  370. * component matches what we would expect internally for locales. This
  371. * should ONLY be used to verify locales that have been normalized.
  372. *
  373. * @param {string} locale
  374. * @return {!Array.<string>}
  375. * @private
  376. */
  377. static disassembleLocale_(locale) {
  378. const components = locale.split('-');
  379. goog.asserts.assert(
  380. components.length <= 2,
  381. [
  382. 'Locales should not have more than 2 components. ',
  383. locale,
  384. ' has too many components.',
  385. ].join());
  386. return components;
  387. }
  388. };
  389. /**
  390. * A map from 3-letter language codes (ISO 639-2) to 2-letter language codes
  391. * (ISO 639-1) for all languages which have both in the registry.
  392. *
  393. * @const {!Map.<string, string>}
  394. * @private
  395. */
  396. shaka.util.LanguageUtils.isoMap_ = new Map([
  397. ['aar', 'aa'], ['abk', 'ab'], ['afr', 'af'], ['aka', 'ak'], ['alb', 'sq'],
  398. ['amh', 'am'], ['ara', 'ar'], ['arg', 'an'], ['arm', 'hy'], ['asm', 'as'],
  399. ['ava', 'av'], ['ave', 'ae'], ['aym', 'ay'], ['aze', 'az'], ['bak', 'ba'],
  400. ['bam', 'bm'], ['baq', 'eu'], ['bel', 'be'], ['ben', 'bn'], ['bih', 'bh'],
  401. ['bis', 'bi'], ['bod', 'bo'], ['bos', 'bs'], ['bre', 'br'], ['bul', 'bg'],
  402. ['bur', 'my'], ['cat', 'ca'], ['ces', 'cs'], ['cha', 'ch'], ['che', 'ce'],
  403. ['chi', 'zh'], ['chu', 'cu'], ['chv', 'cv'], ['cor', 'kw'], ['cos', 'co'],
  404. ['cre', 'cr'], ['cym', 'cy'], ['cze', 'cs'], ['dan', 'da'], ['deu', 'de'],
  405. ['div', 'dv'], ['dut', 'nl'], ['dzo', 'dz'], ['ell', 'el'], ['eng', 'en'],
  406. ['epo', 'eo'], ['est', 'et'], ['eus', 'eu'], ['ewe', 'ee'], ['fao', 'fo'],
  407. ['fas', 'fa'], ['fij', 'fj'], ['fin', 'fi'], ['fra', 'fr'], ['fre', 'fr'],
  408. ['fry', 'fy'], ['ful', 'ff'], ['geo', 'ka'], ['ger', 'de'], ['gla', 'gd'],
  409. ['gle', 'ga'], ['glg', 'gl'], ['glv', 'gv'], ['gre', 'el'], ['grn', 'gn'],
  410. ['guj', 'gu'], ['hat', 'ht'], ['hau', 'ha'], ['heb', 'he'], ['her', 'hz'],
  411. ['hin', 'hi'], ['hmo', 'ho'], ['hrv', 'hr'], ['hun', 'hu'], ['hye', 'hy'],
  412. ['ibo', 'ig'], ['ice', 'is'], ['ido', 'io'], ['iii', 'ii'], ['iku', 'iu'],
  413. ['ile', 'ie'], ['ina', 'ia'], ['ind', 'id'], ['ipk', 'ik'], ['isl', 'is'],
  414. ['ita', 'it'], ['jav', 'jv'], ['jpn', 'ja'], ['kal', 'kl'], ['kan', 'kn'],
  415. ['kas', 'ks'], ['kat', 'ka'], ['kau', 'kr'], ['kaz', 'kk'], ['khm', 'km'],
  416. ['kik', 'ki'], ['kin', 'rw'], ['kir', 'ky'], ['kom', 'kv'], ['kon', 'kg'],
  417. ['kor', 'ko'], ['kua', 'kj'], ['kur', 'ku'], ['lao', 'lo'], ['lat', 'la'],
  418. ['lav', 'lv'], ['lim', 'li'], ['lin', 'ln'], ['lit', 'lt'], ['ltz', 'lb'],
  419. ['lub', 'lu'], ['lug', 'lg'], ['mac', 'mk'], ['mah', 'mh'], ['mal', 'ml'],
  420. ['mao', 'mi'], ['mar', 'mr'], ['may', 'ms'], ['mkd', 'mk'], ['mlg', 'mg'],
  421. ['mlt', 'mt'], ['mon', 'mn'], ['mri', 'mi'], ['msa', 'ms'], ['mya', 'my'],
  422. ['nau', 'na'], ['nav', 'nv'], ['nbl', 'nr'], ['nde', 'nd'], ['ndo', 'ng'],
  423. ['nep', 'ne'], ['nld', 'nl'], ['nno', 'nn'], ['nob', 'nb'], ['nor', 'no'],
  424. ['nya', 'ny'], ['oci', 'oc'], ['oji', 'oj'], ['ori', 'or'], ['orm', 'om'],
  425. ['oss', 'os'], ['pan', 'pa'], ['per', 'fa'], ['pli', 'pi'], ['pol', 'pl'],
  426. ['por', 'pt'], ['pus', 'ps'], ['que', 'qu'], ['roh', 'rm'], ['ron', 'ro'],
  427. ['rum', 'ro'], ['run', 'rn'], ['rus', 'ru'], ['sag', 'sg'], ['san', 'sa'],
  428. ['sin', 'si'], ['slk', 'sk'], ['slo', 'sk'], ['slv', 'sl'], ['sme', 'se'],
  429. ['smo', 'sm'], ['sna', 'sn'], ['snd', 'sd'], ['som', 'so'], ['sot', 'st'],
  430. ['spa', 'es'], ['sqi', 'sq'], ['srd', 'sc'], ['srp', 'sr'], ['ssw', 'ss'],
  431. ['sun', 'su'], ['swa', 'sw'], ['swe', 'sv'], ['tah', 'ty'], ['tam', 'ta'],
  432. ['tat', 'tt'], ['tel', 'te'], ['tgk', 'tg'], ['tgl', 'tl'], ['tha', 'th'],
  433. ['tib', 'bo'], ['tir', 'ti'], ['ton', 'to'], ['tsn', 'tn'], ['tso', 'ts'],
  434. ['tuk', 'tk'], ['tur', 'tr'], ['twi', 'tw'], ['uig', 'ug'], ['ukr', 'uk'],
  435. ['urd', 'ur'], ['uzb', 'uz'], ['ven', 've'], ['vie', 'vi'], ['vol', 'vo'],
  436. ['wel', 'cy'], ['wln', 'wa'], ['wol', 'wo'], ['xho', 'xh'], ['yid', 'yi'],
  437. ['yor', 'yo'], ['zha', 'za'], ['zho', 'zh'], ['zul', 'zu'],
  438. ]);