mkm3u: Determine and write out accurate durations for episodes and chapters.
[epls] / mkm3u
diff --git a/mkm3u b/mkm3u
index 0078f4d..32b9bf2 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
@@ -149,27 +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<si> \d+)
-              (?: \. \ (?P<st> .*) — (?: D \d+ \. \ )? |
-                  D \d+ \. \ |
-                  (?= E \d+ \. \ ) |
-                  \. \ ) |
-            \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+) \ )?
@@ -182,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" % 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))
@@ -208,15 +251,15 @@ class VideoDir (object):
       disc = VideoDisc(path)
       ts = season
       any, bad = False, False
-      epname = m.group("epname")
-      if epname is not None: eplist = [epname]
-      else: eplist = m.group("eplist").split(", ")
+      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: bad = True; continue
-        if not any:
-          #print(";; `%s'" % path, file = SYS.stderr)
-          any = True
+        if mm is None:
+          #print(";;\t`%s'?" % eprange, file = SYS.stderr)
+          bad = True; continue
+        if not any: any = True
         i = filter(mm.group("si"), int)
         if i is not None:
           try: ts = seasons[i]
@@ -228,17 +271,25 @@ class VideoDir (object):
         for k in range(start, end + 1):
           ts.set_episode_disc(k, disc)
           #print(";;\tepisode %d.%d" % (ts.i, k), file = SYS.stderr)
-      if not any: pass #print(";; `%s' ignored" % path, file = SYS.stderr)
-      elif bad: raise ExpectedError("bad ep list in `%s'", fn)
+      if not any:
+        #print(";;\tignored", file = SYS.stderr)
+        pass
+      elif bad:
+        raise ExpectedError("bad ep list in `%s'", fn)
     me.seasons = seasons
 
 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
@@ -272,15 +323,17 @@ 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, startch = None):
+  def __init__(me, season, i, neps, title, src, tno = None,
+               startch = None, endch = None):
     me.season = season
     me.i, me.neps, me.title = i, neps, title
     me.chapters = []
     me.source, me.tno = src, tno
-    me.url = src.url(tno, startch, None)
+    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)
@@ -294,8 +347,8 @@ class BaseSeason (object):
     me.episodes = []
     me.implicitp = implicitp
     me.ep_i, episodes = 1, []
-  def add_episode(me, j, neps, title, src, tno, startch):
-    ep = Episode(me, j, neps, title, src, tno, startch)
+  def add_episode(me, j, neps, title, src, tno, startch, endch):
+    ep = Episode(me, j, neps, title, src, tno, startch, endch)
     me.episodes.append(ep)
     src.nuses += neps; me.ep_i += neps
     return ep
@@ -326,10 +379,10 @@ class MovieSeason (BaseSeason):
     super().__init__(series, *args, **kw)
     me.title = title
     me.i = None
-  def add_episode(me, j, neps, title, src, tno, startch):
+  def add_episode(me, j, neps, title, src, tno, startch, endch):
     if me.title is None and title is None:
       raise ExpectedError("movie or movie season must have a title")
-    return super().add_episode(j, neps, title, src, tno, startch)
+    return super().add_episode(j, neps, title, src, tno, startch, endch)
   def _eplabel(me, i, neps, title):
     if me.title is None:
       label = title
@@ -378,11 +431,11 @@ 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))
 
 MODE_UNSET = 0
 MODE_SINGLE = 1
@@ -532,7 +585,7 @@ class EpisodeListParser (object):
   def _process_episode(me, ww):
 
     opts = ww.nextword(); check(opts is not None, "missing title/options")
-    ti = None; sname = None; neps = 1; epi = None; ch = None
+    ti = None; sname = None; neps = 1; epi = None; loch = hich = None
     for k, v in me._keyvals(opts):
       if k is None:
         if v.isdigit(): ti = int(v)
@@ -541,7 +594,10 @@ class EpisodeListParser (object):
       elif k == "s": sname = v
       elif k == "n": neps = getint(v)
       elif k == "ep": epi = getint(v)
-      elif k == "ch": ch = getint(v)
+      elif k == "ch":
+        try: sep = v.index("-")
+        except ValueError: loch, hich = getint(v), None
+        else: loch, hich = getint(v[:sep]), getint(v[sep + 1:]) + 1
       else: raise ExpectedError("unknown episode option `%s'" % k)
     check(ti is not None, "missing title number")
     series = me._get_series(sname)
@@ -563,7 +619,7 @@ class EpisodeListParser (object):
       try: src = me._isos[series.name]
       except KeyError: src = me._auto_epsrc(series)
 
-    episode = season.add_episode(epi, neps, title, src, ti, ch)
+    episode = season.add_episode(epi, neps, title, src, ti, loch, hich)
     me._pl.add_episode(episode)
     me._cur_episode = episode