mkm3u, *.epls: Check that episode lengths are within expected bounds.
[epls] / mkm3u
diff --git a/mkm3u b/mkm3u
index 21c9a4b..982475c 100755 (executable)
--- 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
@@ -249,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
@@ -285,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,
@@ -294,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)
@@ -392,11 +431,34 @@ class Playlist (object):
         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
@@ -410,6 +472,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
 
@@ -496,6 +559,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")
@@ -540,6 +609,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)
 
@@ -547,6 +617,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)
@@ -555,6 +626,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
@@ -581,6 +657,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