X-Git-Url: https://git.distorted.org.uk/~mdw/epls/blobdiff_plain/0411af2c915f74bbd1c1f9f2373d0fd3d8e9080c..6202a568ca15cfe6e1144420d24cc9ec4e8eea34:/mkm3u diff --git a/mkm3u b/mkm3u index 9b308aa..5867236 100755 --- a/mkm3u +++ b/mkm3u @@ -5,6 +5,7 @@ from contextlib import contextmanager import optparse as OP import os as OS import re as RX +import subprocess as SP import sys as SYS class ExpectedError (Exception): pass @@ -59,6 +60,12 @@ class Words (object): if begin < 0: return None else: return s[begin:].rstrip() +def program_output(*args, **kw): + try: return SP.check_output(*args, **kw) + except SP.CalledProcessError as e: + raise ExpectedError("program `%s' failed with code %d" % + (e.cmd, e.returncode)) + URL_SAFE_P = 256*[False] for ch in \ b"ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ @@ -94,7 +101,10 @@ class Source (object): me.used_titles = dict() me.used_chapters = set() me.nuses = 0 - def url(me, title = None, start_chapter = None, end_chapter = None): + def _duration(me, title, start_chapter, end_chapter): + return -1 + def url_and_duration(me, title = None, + start_chapter = None, end_chapter = None): if title == "-": if me.TITLEP: raise ExpectedError("missing title number") if start_chapter is not None or end_chapter is not None: @@ -112,6 +122,9 @@ class Source (object): suffix = "#%d:%d" % (title, start_chapter) else: suffix = "#%d:%d-%d:%d" % (title, start_chapter, title, end_chapter - 1) + + duration = me._duration(title, start_chapter, end_chapter) + if end_chapter is not None: keys = [(title, ch) for ch in range(start_chapter, end_chapter)] set = me.used_chapters @@ -129,7 +142,7 @@ class Source (object): if end_chapter is not None: for ch in range(start_chapter, end_chapter): me.used_chapters.add((title, ch)) - return me.PREFIX + ROOT + urlencode(me.fn) + suffix + return me.PREFIX + ROOT + urlencode(me.fn) + suffix, duration class VideoDisc (Source): PREFIX = "dvd://" @@ -139,6 +152,26 @@ class VideoDisc (Source): super().__init__(fn, *args, **kw) me.neps = 0 + def _duration(me, title, start_chapter, end_chapter): + path = OS.path.join(ROOT, me.fn) + ntitle = int(program_output(["dvd-info", path, "titles"])) + if not 1 <= title <= ntitle: + raise ExpectedError("bad title %d for `%s': must be in 1 .. %d" % + (title, me.fn, ntitle)) + if start_chapter is None: + durq = "duration:%d" % title + else: + nch = int(program_output(["dvd-info", path, "chapters:%d" % title])) + if end_chapter is None: end_chapter = nch + else: end_chapter -= 1 + if not 1 <= start_chapter <= end_chapter <= nch: + raise ExpectedError("bad chapter range %d .. %d for `%s' title %d: " + "must be in 1 .. %d" % + (start_chapter, end_chapter, me.fn, title, nch)) + durq = "duration:%d.%d-%d" % (title, start_chapter, end_chapter) + duration = int(program_output(["dvd-info", path, durq])) + return duration + class VideoSeason (object): def __init__(me, i, title): me.i = i @@ -149,28 +182,28 @@ class VideoSeason (object): raise ExpectedError("season %d episode %d already taken" % (me.i, i)) me.episodes[i] = disc; disc.neps += 1 -def some_group(m, *gg): - for g in gg: - s = m.group(g) +def match_group(m, *groups, dflt = None, mustp = False): + for g in groups: + try: s = m.group(g) + except IndexError: continue if s is not None: return s - return None + if mustp: raise ValueError("no match found") + else: return dflt class VideoDir (object): - _R_ISO_PRE = RX.compile(r""" ^ - (?: S (?P \d+) - (?: \. \ (?P .*) — (?: D \d+ \. \ )? | - D \d+ \. \ | - (?= E \d+ \. \ ) | - \. \ ) | - (?P \d+) \. \ ) - (?: (?P - (?: S \d+ \ )? E \d+ (?: – \d+)? - (?: , \ (?: S \d+ \ )? E \d+ (?: – \d+)?)*) | - (?P E \d+) \. \ .* | - .*) - \. iso $ - """, RX.X) + _R_ISO_PRE = list(map(lambda pats: + list(map(lambda pat: + RX.compile("^" + pat + r"\.iso$", RX.X), + pats)), + [[r""" S (?P \d+) \. \ (?P .*) — (?: D \d+ \. \ )? + (?P .*) """, + r""" S (?P \d+) (?: D \d+)? \. \ (?P .*) """, + r""" S (?P \d+) \. \ (?P E \d+ .*) """, + r""" S (?P \d+) (?P E \d+) \. \ .* """], + [r""" (?P \d+) [A-Z]? \. \ (?P .*) — (?P .*) """], + [r""" \d+ \. \ (?P [ES] \d+ .*) """], + [r""" (?P \d+ ) \. \ .* """]])) _R_ISO_EP = RX.compile(r""" ^ (?: S (?P \d+) \ )? @@ -183,25 +216,34 @@ class VideoDir (object): fns.sort() season = None seasons = {} + styles = me._R_ISO_PRE for fn in fns: path = OS.path.join(dir, fn) if not fn.endswith(".iso"): continue - m = me._R_ISO_PRE.match(fn) - if not m: - #print(";; `%s' ignored (regex mismatch)" % path, file = SYS.stderr) + #print(";; `%s'" % path, file = SYS.stderr) + for sty in styles: + for r in sty: + m = r.match(fn) + if m: styles = [sty]; break + else: + continue + break + else: + #print(";;\tignored (regex mismatch)", file = SYS.stderr) continue - i = filter(m.group("si"), int) - stitle = m.group("st") - check(i is not None or stitle is None, + si = filter(match_group(m, "si"), int) + stitle = match_group(m, "stitle") + + check(si is not None or stitle is None, "explicit season title without number in `%s'" % fn) - if i is not None: - if season is None or i != season.i: - check(season is None or i == season.i + 1, + if si is not None: + if season is None or si != season.i: + check(season is None or si == season.i + 1, "season %d /= %d" % - (i, season is None and -1 or season.i + 1)) - check(i not in seasons, "season %d already seen" % i) - seasons[i] = season = VideoSeason(i, stitle) + (si, season is None and -1 or season.i + 1)) + check(si not in seasons, "season %d already seen" % si) + seasons[si] = season = VideoSeason(si, stitle) else: check(stitle == season.title, "season title `%s' /= `%s'" % (stitle, season.title)) @@ -209,14 +251,9 @@ class VideoDir (object): disc = VideoDisc(path) ts = season any, bad = False, False - epname = m.group("epname") - epexpr = m.group("eplist") - epnum = m.group("epnum") - if epname is not None: eplist = [epname] - elif epexpr is not None: eplist = epexpr.split(", ") - elif epnum is not None: eplist = ["E" + epnum] - else: continue - #print(";; `%s'" % path, file = SYS.stderr) + epnum = match_group(m, "epnum") + if epnum is not None: eplist = ["E" + epnum] + else: eplist = match_group(m, "epex", mustp = True).split(", ") for eprange in eplist: mm = me._R_ISO_EP.match(eprange) if mm is None: @@ -235,7 +272,7 @@ class VideoDir (object): ts.set_episode_disc(k, disc) #print(";;\tepisode %d.%d" % (ts.i, k), file = SYS.stderr) if not any: - #print(";;\tignored" % path, file = SYS.stderr) + #print(";;\tignored", file = SYS.stderr) pass elif bad: raise ExpectedError("bad ep list in `%s'", fn) @@ -245,9 +282,14 @@ class AudioDisc (Source): PREFIX = "file://" TITLEP = CHAPTERP = False -class AudioEpisode (Source): - PREFIX = "file://" - TITLEP = CHAPTERP = False + def _duration(me, title, start_chapter, end_chaptwr): + out = program_output(["metaflac", + "--show-total-samples", "--show-sample-rate", + OS.path.join(ROOT, me.fn)]) + nsamples, hz = map(float, out.split()) + return int(nsamples/hz) + +class AudioEpisode (AudioDisc): def __init__(me, fn, i, *args, **kw): super().__init__(fn, *args, **kw) me.i = i @@ -281,7 +323,8 @@ class AudioDir (object): class Chapter (object): def __init__(me, episode, title, i): me.title, me.i = title, i - me.url = episode.source.url(episode.tno, i, i + 1) + me.url, me.duration = \ + episode.source.url_and_duration(episode.tno, i, i + 1) class Episode (object): def __init__(me, season, i, neps, title, src, tno = None, @@ -290,7 +333,7 @@ class Episode (object): me.i, me.neps, me.title = i, neps, title me.chapters = [] me.source, me.tno = src, tno - me.url = src.url(tno, startch, endch) + me.url, me.duration = src.url_and_duration(tno, startch, endch) def add_chapter(me, title, j): ch = Chapter(me, title, j) me.chapters.append(ch) @@ -311,9 +354,9 @@ class BaseSeason (object): return ep def _epnames(me, i, neps): playlist = me.series.playlist - if neps == 1: return playlist.epname, "%d" % i - elif neps == 2: return playlist.epnames, "%d, %d" % (i, i + 1) - else: return playlist.epnames, "%d–%d" % (i, i + neps - 1) + if neps == 1: return playlist.epname, ["%d" % i] + elif neps == 2: return playlist.epnames, ["%d" % i, "%d" % (i + 1)] + else: return playlist.epnames, ["%d–%d" % (i, i + neps - 1)] class Season (BaseSeason): def __init__(me, series, title, i, *args, **kw): @@ -322,13 +365,21 @@ class Season (BaseSeason): def _eplabel(me, i, neps, title): epname, epn = me._epnames(i, neps) if title is None: - if me.implicitp: label = "%s %s" % (epname, epn) - elif me.title is None: label = "%s %d.%s" % (epname, me.i, epn) - else: label = "%s—%s %s" % (me.title, epname, epn) + if me.implicitp: + label = "%s %s" % (epname, ", ".join(epn)) + elif me.title is None: + label = "%s %s" % \ + (epname, ", ".join("%d.%s" % (me.i, e) for e in epn)) + else: + label = "%s—%s %s" % (me.title, epname, ", ".join(epn)) else: - if me.implicitp: label = "%s. %s" % (epn, title) - elif me.title is None: label = "%d.%s. %s" % (me.i, epn, title) - else: label = "%s—%s. %s" % (me.title, epn, title) + if me.implicitp: + label = "%s. %s" % (", ".join(epn), title) + elif me.title is None: + label = "%s. %s" % \ + (", ".join("%d.%s" % (me.i, e) for e in epn), title) + else: + label = "%s—%s. %s" % (me.title, ", ".join(epn), title) return label class MovieSeason (BaseSeason): @@ -345,7 +396,7 @@ class MovieSeason (BaseSeason): label = title elif title is None: epname, epn = me._epnames(i, neps) - label = "%s—%s %s" % (me.title, epname, epn) + label = "%s—%s %s" % (me.title, epname, ", ".join(epn)) else: label = "%s—%s" % (me.title, title) return label @@ -386,13 +437,39 @@ class Playlist (object): f.write("\n") for ep in season: label = ep.label() - if me.nseries > 1: label = ep.season.series.title + " " + label + if me.nseries > 1 and ep.season.series.title is not None: + if ep.season.i is None: sep = "—" + else: sep = " " + label = ep.season.series.title + sep + label if not ep.chapters: - f.write("#EXTINF:0,,%s\n%s\n" % (label, ep.url)) + f.write("#EXTINF:%d,,%s\n%s\n" % (ep.duration, label, ep.url)) else: for ch in ep.chapters: - f.write("#EXTINF:0,,%s: %s\n%s\n" % - (label, ch.title, ch.url)) + f.write("#EXTINF:%d,,%s: %s\n%s\n" % + (ch.duration, label, ch.title, ch.url)) + +DEFAULT_EXPVAR = 0.05 +R_DURMULT = RX.compile(r""" ^ + (\d+ (?: \. \d+)?) x +$ """, RX.X) +R_DUR = RX.compile(r""" ^ + (?: (?: (\d+) :)? (\d+) :)? (\d+) + (?: / (\d+ (?: \. \d+)?) \%)? +$ """, RX.X) +def parse_duration(s, base = None, basevar = DEFAULT_EXPVAR): + if base is not None: + m = R_DURMULT.match(s) + if m is not None: return base*float(m.group(1)), basevar + m = R_DUR.match(s) + if not m: raise ExpectedError("invalid duration spec `%s'" % s) + hr, min, sec = map(lambda g: filter(m.group(g), int, 0), [1, 2, 3]) + var = filter(m.group(4), lambda x: float(x)/100.0) + if var is None: var = DEFAULT_EXPVAR + return 3600*hr + 60*min + sec, var +def format_duration(d): + if d >= 3600: return "%d:%02d:%02d" % (d//3600, (d//60)%60, d%60) + elif d >= 60: return "%d:%02d" % (d//60, d%60) + else: return "%d s" % d MODE_UNSET = 0 MODE_SINGLE = 1 @@ -406,6 +483,7 @@ class EpisodeListParser (object): me._series = {}; me._vdirs = {}; me._audirs = {}; me._isos = {} me._series_wanted = series_wanted me._chaptersp = chapters_wanted_p + me._explen, me._expvar = None, DEFAULT_EXPVAR if series_wanted is None: me._mode = MODE_UNSET else: me._mode = MODE_MULTI @@ -492,6 +570,12 @@ class EpisodeListParser (object): me._cur_episode = me._cur_chapter = None me._pl.done_season() + elif cmd == "explen": + w = ww.rest(); check(w is not None, "missing duration spec") + d, v = parse_duration(w) + me._explen = d + if v is not None: me._expvar = v + elif cmd == "epname": for k, v in me._keyvals(opts): me._bad_keyval("epname", k, v) name = ww.rest(); check(name is not None, "missing episode name") @@ -536,6 +620,7 @@ class EpisodeListParser (object): w = ww.rest(); check(w is not None, "missing count"); n = getint(w) src = me._auto_epsrc(series) src.nuses += n + else: raise ExpectedError("unknown command `%s'" % cmd) @@ -543,6 +628,7 @@ class EpisodeListParser (object): opts = ww.nextword(); check(opts is not None, "missing title/options") ti = None; sname = None; neps = 1; epi = None; loch = hich = None + explen, expvar, explicitlen = me._explen, me._expvar, False for k, v in me._keyvals(opts): if k is None: if v.isdigit(): ti = int(v) @@ -551,6 +637,11 @@ class EpisodeListParser (object): elif k == "s": sname = v elif k == "n": neps = getint(v) elif k == "ep": epi = getint(v) + elif k == "l": + if v == "-": me._explen, me._expvar = None, DEFAULT_EXPVAR + else: + explen, expvar = parse_duration(v, explen, expvar) + explicitlen = True elif k == "ch": try: sep = v.index("-") except ValueError: loch, hich = getint(v), None @@ -577,6 +668,17 @@ class EpisodeListParser (object): except KeyError: src = me._auto_epsrc(series) episode = season.add_episode(epi, neps, title, src, ti, loch, hich) + + if episode.duration != -1 and explen is not None: + if not explicitlen: explen *= neps + if not explen*(1 - expvar) <= episode.duration <= explen*(1 + expvar): + if season.i is None: epid = "episode %d" % epi + else: epid = "episode %d.%d" % (season.i, epi) + raise ExpectedError \ + ("%s duration %s %g%% > %g%% from expected %s" % + (epid, format_duration(episode.duration), + abs(100*(episode.duration - explen)/explen), 100*expvar, + format_duration(explen))) me._pl.add_episode(episode) me._cur_episode = episode