import optparse as OP
import os as OS
import re as RX
+import subprocess as SP
import sys as SYS
class ExpectedError (Exception): pass
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" \
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:
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
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://"
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
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<si> \d+)
- (?: \. \ (?P<st> .*) — (?: D \d+ \. \ )? |
- D \d+ \. \ |
- (?= E \d+ \. \ ) |
- \. \ ) |
- (?P<epnum> \d+) \. \ )
- (?: (?P<eplist>
- (?: S \d+ \ )? E \d+ (?: – \d+)?
- (?: , \ (?: S \d+ \ )? E \d+ (?: – \d+)?)*) |
- (?P<epname> 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<si> \d+) \. \ (?P<stitle> .*) — (?: D \d+ \. \ )?
+ (?P<epex> .*) """,
+ r""" S (?P<si> \d+) (?: D \d+)? \. \ (?P<epex> .*) """,
+ r""" S (?P<si> \d+) \. \ (?P<epex> E \d+ .*) """,
+ r""" S (?P<si> \d+) (?P<epex> E \d+) \. \ .* """],
+ [r""" (?P<si> \d+) [A-Z]? \. \ (?P<stitle> .*) — (?P<epex> .*) """],
+ [r""" \d+ \. \ (?P<epex> [ES] \d+ .*) """],
+ [r""" (?P<epnum> \d+ ) \. \ .* """]]))
_R_ISO_EP = RX.compile(r""" ^
(?: S (?P<si> \d+) \ )?
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))
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:
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)
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
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,
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)
label = ep.label()
if me.nseries > 1: label = ep.season.series.title + " " + 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
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
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")
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)
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)
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
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