Skip to content

Commit

Permalink
[playback] option to select specific audio/subtitle languages added
Browse files Browse the repository at this point in the history
Signed-off-by: Sandmann79 <[email protected]>
  • Loading branch information
Sandmann79 committed Oct 26, 2024
1 parent 8b25b8a commit 1c9606f
Show file tree
Hide file tree
Showing 13 changed files with 169 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -868,3 +868,11 @@ msgstr "Eintrag entfernen"
msgctxt "#30284"
msgid "Clear List"
msgstr "Liste leeren"

msgctxt "#30285"
msgid "Audio Languages"
msgstr "Audiosprachen"

msgctxt "#30286"
msgid "Subtitle Languages"
msgstr "Untertitelsprachen"
Original file line number Diff line number Diff line change
Expand Up @@ -879,3 +879,12 @@ msgstr ""
msgctxt "#30284"
msgid "Clear List"
msgstr ""

msgctxt "#30285"
msgid "Audio Languages"
msgstr ""

msgctxt "#30286"
msgid "Subtitle Languages"
msgstr ""

Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,16 @@ msgctxt "#30284"
msgid "Clear List"
msgstr ""

#, fuzzy
#msgctxt "#30285"
#msgid "Audio Languages"
#msgstr "Idioma"

#, fuzzy
#msgctxt "#30286"
#msgid "Subtitle Languages"
#msgstr "Idiomas disponibles:"

#~ msgctxt "#30006"
#~ msgid "Store Credentials instead of using the Cookie?"
#~ msgstr "¿Almacenar las credenciales en vez de usar la cookie?"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -875,6 +875,16 @@ msgctxt "#30284"
msgid "Clear List"
msgstr ""

#, fuzzy
#msgctxt "#30285"
#msgid "Audio Languages"
#msgstr "Langue"

#, fuzzy
#msgctxt "#30286"
#msgid "Subtitle Languages"
#msgstr "Langues disponibles:"

#~ msgctxt "#30006"
#~ msgid "Store Credentials instead of using the Cookie?"
#~ msgstr "Stocker les informations d'identification au lieu d'utiliser le cookie?"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,16 @@ msgctxt "#30284"
msgid "Clear List"
msgstr ""

#, fuzzy
#msgctxt "#30285"
#msgid "Audio Languages"
#msgstr "שפה"

#, fuzzy
#msgctxt "#30286"
#msgid "Subtitle Languages"
#msgstr "שפות זמינות:"

#~ msgctxt "#30006"
#~ msgid "Store Credentials instead of using the Cookie?"
#~ msgstr "לאחסן אישורים במקום להשתמש בעוגיות?"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,16 @@ msgctxt "#30284"
msgid "Clear List"
msgstr ""

#, fuzzy
#msgctxt "#30285"
#msgid "Audio Languages"
#msgstr "Nyelv"

#, fuzzy
#msgctxt "#30286"
#msgid "Subtitle Languages"
#msgstr "Elérhető nyelvek:"

#~ msgctxt "#30006"
#~ msgid "Store Credentials instead of using the Cookie?"
#~ msgstr "Hitelesítési adatokat tárol a Cookie használata helyett?"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -874,6 +874,16 @@ msgctxt "#30284"
msgid "Clear List"
msgstr ""

#, fuzzy
#msgctxt "#30285"
#msgid "Audio Languages"
#msgstr "Lingua"

#, fuzzy
#msgctxt "#30286"
#msgid "Subtitle Languages"
#msgstr "Lingue disponibili:"

#~ msgctxt "#30006"
#~ msgid "Store Credentials instead of using the Cookie?"
#~ msgstr "Memorizzare le credenziali invece di utilizzare il cookie?"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -885,6 +885,16 @@ msgctxt "#30284"
msgid "Clear List"
msgstr "Wyczyść pliki dziennika"

#, fuzzy
#msgctxt "#30285"
#msgid "Audio Languages"
#msgstr "Język"

#, fuzzy
#msgctxt "#30286"
#msgid "Subtitle Languages"
#msgstr "Dostępne języki:"

#~ msgctxt "#30071"
#~ msgid "Display TV-Show instead of Seasons in Watchlist"
#~ msgstr "Pokazuj serial zamiast sezonów w obserwowanych"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -891,6 +891,16 @@ msgctxt "#30284"
msgid "Clear List"
msgstr ""

#, fuzzy
#msgctxt "#30285"
#msgid "Audio Languages"
#msgstr "Idioma"

#, fuzzy
#msgctxt "#30286"
#msgid "Subtitle Languages"
#msgstr "Idiomas Disponíveis:"

#~ msgctxt "#30006"
#~ msgid "Store Credentials instead of using the Cookie?"
#~ msgstr "Armazenar credenciais em vez de usar Cookie?"
Expand Down
19 changes: 18 additions & 1 deletion plugin.video.amazon-test/resources/lib/configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ def getConfig(cfile, defvalue=''):

return value if value else defvalue


def writeConfig(cfile, value):
cfgfile = OSPJoin(writeConfig.configPath, cfile)
cfglockfile = OSPJoin(writeConfig.configPath, cfile + '.lock')
Expand All @@ -45,3 +44,21 @@ def writeConfig(cfile, value):
l.close()
if time.time() - modified > 0.1:
xbmcvfs.delete(cfglockfile)

def langSettings(config_id):
from .common import Globals
_g = Globals()
supported_langs = ['all', 'ar', 'bg', 'ca', 'cmn', 'cs', 'da', 'de', 'en', 'es', 'et', 'fi', 'fr', 'he', 'hi', 'hr', 'hu', 'is', 'it', 'ja',
'ko', 'lt', 'lv', 'nb', 'nl', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sr', 'sv', 'ta', 'te', 'th', 'tr', 'uk', 'vi', 'yue']
langs = getConfig(config_id, supported_langs[0])
presel = [supported_langs.index(x) for x in langs.split(',') if x in supported_langs]
sel = _g.dialog.multiselect('Languages', supported_langs, preselect=presel)

if not sel is None:
if len(sel) == 0:
sel = supported_langs[0]
elif 0 in sel and len(sel) > 1:
sel.remove(0)
langs = ','.join([supported_langs[x] for x in sel])
writeConfig(config_id, langs)
_g.addon.setSetting(config_id, langs)
101 changes: 58 additions & 43 deletions plugin.video.amazon-test/resources/lib/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from contextlib import contextmanager
from kodi_six.utils import py2_decode
from resources.lib.logging import Log
from .configs import getConfig

try:
from BaseHTTPServer import BaseHTTPRequestHandler # Python2 HTTP Server
Expand Down Expand Up @@ -249,9 +250,11 @@ def _AlterGPR(self, endpoint, headers, data):

# Grab the subtitle urls, merge them in a single list, append the locale codes to let Kodi figure
# out which URL has which language, then sort them neatly in a human digestible order.
chosen_langs = getConfig('sub_langs', 'all').split(',')
content = json.loads(content)
content['subtitles'] = []
newsubs = []
chosen_found = 0

# Count the number of duplicates with the same ISO 639-1 codes
langCount = {'forcedNarratives': {}, 'subtitleUrls': {}}
Expand All @@ -260,8 +263,12 @@ def _AlterGPR(self, endpoint, headers, data):
for i in range(0, len(content[sub_type])):
lang = self.split_lang(content[sub_type][i]['languageCode'])
if lang not in langCount[sub_type]:
if lang in chosen_langs:
chosen_found += 1
langCount[sub_type][lang] = 0
langCount[sub_type][lang] += 1
if chosen_found == 0:
chosen_langs = 'all'

# Merge the different subtitles lists in a single one, and append a spurious name file
# to let Kodi figure out the locale, while at the same time enabling subtitles to be
Expand All @@ -270,20 +277,22 @@ def _AlterGPR(self, endpoint, headers, data):
if sub_type in content:
for i in range(0, len(content[sub_type])):
fn = self._AdjustLocale(content[sub_type][i]['languageCode'], langCount[sub_type][self.split_lang(content[sub_type][i]['languageCode'])])
variants = '{}{}'.format(
'-[CC]' if 'sdh' == content[sub_type][i]['type'] else '',
'.Forced' if 'forcedNarratives' == sub_type else ''
)
# Proxify the URLs, with a make believe Kodi-friendly file name
escapedurl = quote_plus(content[sub_type][i]['url'])
content[sub_type][i]['url'] = 'http://127.0.0.1:{}/subtitles/{}/{}{}.srt'.format(
self.server.port,
escapedurl,
fn,
variants
)
cl = py2_decode(convertLanguage(self.split_lang(fn), ENGLISH_NAME))
newsubs.append((content[sub_type][i], cl, fn, variants, escapedurl))
ic = self.split_lang(fn)
if ic in chosen_langs or chosen_langs == 'all':
variants = '{}{}'.format(
'-[CC]' if 'sdh' == content[sub_type][i]['type'] else '',
'.Forced' if 'forcedNarratives' == sub_type else ''
)
# Proxify the URLs, with a make believe Kodi-friendly file name
escapedurl = quote_plus(content[sub_type][i]['url'])
content[sub_type][i]['url'] = 'http://127.0.0.1:{}/subtitles/{}/{}{}.srt'.format(
self.server.port,
escapedurl,
fn,
variants
)
cl = py2_decode(convertLanguage(ic, ENGLISH_NAME))
newsubs.append((content[sub_type][i], cl, fn, variants, escapedurl))
del content[sub_type] # Reduce the data transfer by removing the lists we merged

# Create the new merged subtitles list, and append time stretched variants.
Expand All @@ -294,7 +303,6 @@ def _AlterGPR(self, endpoint, headers, data):

def _AlterMPD(self, endpoint, headers, data):
""" MPD alteration for better language parsing """

try:
from urllib.parse import urlparse
except ImportError:
Expand Down Expand Up @@ -338,6 +346,8 @@ def _rebase(data):

# Count the number of duplicates with the same ISO 639-1 codes
Log('[PS] Parsing languages', Log.DEBUG)
chosen_langs = getConfig('audio_langs', 'all').split(',')
chosen_found = 0
languages = []
langCount = {}
for lang in re.findall(r'<AdaptationSet[^>]*audioTrackId="([^"]+)"[^>]*>', buffer):
Expand All @@ -346,8 +356,12 @@ def _rebase(data):
for lang in languages:
lang = self.split_lang(lang)
if lang not in langCount:
if lang in chosen_langs:
chosen_found += 1
langCount[lang] = 0
langCount[lang] += 1
if chosen_found == 0:
chosen_langs = 'all'

# Send corrected AdaptationSets, one at a time through chunked transfer
Log('[PS] Altering <AdaptationSet>s', Log.DEBUG)
Expand All @@ -362,34 +376,35 @@ def _rebase(data):
if trackId is not None:
trackId = trackId.groups()
lang = re.search(r'\s+lang="([^"]+)"', setTag).group(1)
imp = ' impaired="true"' if 'descriptive' == trackId[1] else ''
newLocale = self._AdjustLocale(trackId[0], langCount[self.split_lang(trackId[0])])
setTag = setTag.replace('lang="{}"'.format(lang), 'lang="{}"{}'.format(newLocale, imp))
repres = re.findall(r'<Representation[^>]*>.*?</Representation>', setData, flags=re.DOTALL)
if len(repres):
best_found = [0, '', False]
found_atmos = False
while 0 < len(repres):
track = repres.pop(0)
atmos = re.search(r'<SupplementalProperty[^>]*value="JOC"[^>]*>', track) is not None
bitrate = int(re.search(r'\s+bandwidth="([^"]+)"', track).group(1))
if atmos and not found_atmos:
found_atmos = True
best_found[0] = 0
if bitrate > best_found[0]:
if atmos or (not atmos and not found_atmos) or self.server._s.enable_atmos is False:
best_found = [bitrate, track, atmos]
setData = setData.replace(track, '' if 0 < len(repres) else best_found[1])
setTag = re.sub(r' (min|max)Bandwidth="[^"]+"', '', setTag)
atmos_apx = ' (Atmos)' if best_found[2] and self.server._s._g.KodiVersion < 21 else ''
if self.server._s._g.KodiVersion > 18:
setTag = '{} name="{} kbps{}">'.format(setTag[:-1], int(best_found[0] / 1000), atmos_apx)
else:
setTag = re.sub(r'( lang="[^"]+)"', r'\1 {} [{} kbps]{}"'.format('' if '-' in newLocale else '-', int(best_found[0] / 1000), atmos_apx), setTag)

Log('[PS] ' + setTag, Log.DEBUG)
self._SendChunk(gzstream, setTag)
self._SendChunk(gzstream, _rebase(setData))
if lang in chosen_langs or chosen_langs == 'all':
imp = ' impaired="true"' if 'descriptive' == trackId[1] else ''
newLocale = self._AdjustLocale(trackId[0], langCount[self.split_lang(trackId[0])])
setTag = setTag.replace('lang="{}"'.format(lang), 'lang="{}"{}'.format(newLocale, imp))
repres = re.findall(r'<Representation[^>]*>.*?</Representation>', setData, flags=re.DOTALL)
if len(repres):
best_found = [0, '', False]
found_atmos = False
while 0 < len(repres):
track = repres.pop(0)
atmos = re.search(r'<SupplementalProperty[^>]*value="JOC"[^>]*>', track) is not None
bitrate = int(re.search(r'\s+bandwidth="([^"]+)"', track).group(1))
if atmos and not found_atmos:
found_atmos = True
best_found[0] = 0
if bitrate > best_found[0]:
if atmos or (not atmos and not found_atmos) or self.server._s.enable_atmos is False:
best_found = [bitrate, track, atmos]
setData = setData.replace(track, '' if 0 < len(repres) else best_found[1])
setTag = re.sub(r' (min|max)Bandwidth="[^"]+"', '', setTag)
atmos_apx = ' (Atmos)' if best_found[2] and self.server._s._g.KodiVersion < 21 else ''
if self.server._s._g.KodiVersion > 18:
setTag = '{} name="{} kbps{}">'.format(setTag[:-1], int(best_found[0] / 1000), atmos_apx)
else:
setTag = re.sub(r'( lang="[^"]+)"', r'\1 {} [{} kbps]{}"'.format('' if '-' in newLocale else '-', int(best_found[0] / 1000), atmos_apx), setTag)

Log('[PS] ' + setTag, Log.DEBUG)
self._SendChunk(gzstream, setTag)
self._SendChunk(gzstream, _rebase(setData))
buffer = buffer[pos.end(2):]

# Send the rest and signal EOT
Expand Down
3 changes: 3 additions & 0 deletions plugin.video.amazon-test/resources/lib/startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ def EntryPoint(argv):
_g.pv.Browse('root/Watchlist/watchlist', export=5)
elif hasattr(_g.pv, 'getPage'):
_g.pv.getPage(_g.watchlist, export=2)
elif mode == 'langSettings':
from .configs import langSettings
langSettings(args.get('url'))
elif mode == 'Search':
Search(args.get('searchstring'))
elif mode in ['LogIn', 'remLoginData', 'removeUser', 'renameUser', 'switchUser', 'createZIP', 'removeLogs']:
Expand Down
3 changes: 3 additions & 0 deletions plugin.video.amazon-test/resources/settings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,14 @@
</category>
<!-- Language -->
<category label="30021">
<setting id="proxy_mpdalter" type="bool" label="30248" default="true" visible="false"/>
<!-- Audio -->
<setting label="30033" type="lsep"/>
<setting id="audio_langs" type="action" label="30285" action="RunPlugin(plugin://plugin.video.amazon-test/?mode=langSettings&url=audio_langs)" enable="eq(-2,true)" />
<setting id="audio_description" type="bool" label="30005" default="false"/>
<!-- Subtitles -->
<setting label="30034" type="lsep"/>
<setting id="sub_langs" type="action" label="30286" action="RunPlugin(plugin://plugin.video.amazon-test/?mode=langSettings&url=sub_langs)" enable="eq(-5,true)" />
<setting id="sub_stretch" type="bool" label="30028" default="false"/>
<setting id="sub_stretch_factor" type="enum" values="FILM/NTSC (24/23.976)|NTSC/FILM (23.976/24)|PAL/NTSC (25/23.976)|NTSC/PAL (23.976/25)|PAL/FILM (25/24)|FILM/PAL (24/25)" label="30027" default="0" enable="eq(-1,true)" subsetting="true"/>
<!-- Menu -->
Expand Down

0 comments on commit 1c9606f

Please sign in to comment.