basic.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import wave
  2. def maxwait(songs, context, conf):
  3. wait = int(conf.get("EF_MAXWAIT_SEC", 0))
  4. if wait == 0:
  5. return True
  6. if "time" not in context["status"]:
  7. return True, "no song playing?"
  8. curpos, duration = map(int, context["status"]["time"].split(":"))
  9. remaining = duration - curpos
  10. if remaining > wait:
  11. return False, "remaining %d max allowed %d" % (remaining, wait)
  12. return True
  13. def get_duration(path):
  14. """get track duration in seconds"""
  15. if path.lower().endswith(".wav"):
  16. with wave.open(path, "r") as f:
  17. frames = f.getnframes()
  18. rate = f.getframerate()
  19. duration = frames / rate
  20. return int(duration)
  21. try:
  22. import mutagen
  23. except ModuleNotFoundError:
  24. raise ImportError("mutagen not installed")
  25. audio = mutagen.File(path)
  26. if audio is None:
  27. return None
  28. return int(audio.info.length)
  29. def percentwait(songs, context, conf, getdur=get_duration):
  30. """
  31. Similar to maxwait, but the maximum waiting time is proportional to the
  32. duration of the audio we're going to add.
  33. This filter observe the EF_MAXWAIT_PERC variable.
  34. The variable must be an integer representing the percentual.
  35. If the variable is 0 or unset, the filter will not run.
  36. For example, if the currently playing track still has 1 minute to go and we
  37. are adding a jingle of 40seconds, then if EF_MAXWAIT_PERC==200 the audio
  38. will be added (40s*200% = 1m20s) while if EF_MAXWAIT_PERC==100 it will be
  39. filtered out.
  40. """
  41. percentwait = int(conf.get("EF_MAXWAIT_PERC", 0))
  42. if percentwait == 0:
  43. return True
  44. if "time" not in context["status"]:
  45. return True, "no song playing?"
  46. curpos, duration = map(int, context["status"]["time"].split(":"))
  47. remaining = duration - curpos
  48. eventduration = 0
  49. for uri in songs["uris"]:
  50. if not uri.startswith("file://"):
  51. return True, "%s is not a file" % uri
  52. path = uri[len("file://") :] # strips file://
  53. songduration = getdur(path)
  54. if songduration is None:
  55. continue
  56. eventduration += songduration
  57. wait = eventduration * (percentwait / 100.0)
  58. if remaining > wait:
  59. return False, "remaining %d max allowed %d" % (remaining, wait)
  60. return True