probe.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import subprocess, logging
  2. class Probe:
  3. encoding = 'utf-8'
  4. ffprobe_exec = 'ffprobe'
  5. def __init__(self, ffprobe_exec='ffprobe', logLevel=logging.WARN):
  6. self.logger = logging.getLogger(__name__)
  7. self.logger.setLevel(logLevel)
  8. if ffprobe_exec:
  9. self.ffprobe_exec = ffprobe_exec
  10. def probe(self, path):
  11. self.logger.debug(f"Probing: {path}")
  12. streams = []
  13. # Sanity
  14. if not path.exists():
  15. self.logger.warn(f"No such file: {path}")
  16. return streams
  17. # ffprobe
  18. args = [ self.ffprobe_exec, '-hide_banner', '-show_streams', path ]
  19. self.logger.debug(f"ffprobe command: {args}")
  20. probe = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  21. self.logger.debug(f"ffprobe result: {probe}")
  22. data = probe.stdout.decode(self.encoding)
  23. if probe.returncode != 0:
  24. self.logger.error(f"ffprobe error ({probe.returncode}): {probe.stderr.decode(self.encoding)}")
  25. self.logger.debug(f"ffprobe stdout: {data}")
  26. return steams
  27. # Parse streams
  28. prefix = None
  29. stream = None
  30. for line in data.splitlines():
  31. if line == "[STREAM]":
  32. stream = {}
  33. elif line == "[/STREAM]":
  34. streams.append(stream)
  35. steam = None
  36. elif line == "[SIDE_DATA]":
  37. prefix = 'SIDE_DATA'
  38. elif line == "[/SIDE_DATA]":
  39. prefix = None
  40. elif stream is not None:
  41. try:
  42. (key, val) = line.split('=', 1)
  43. if prefix is not None:
  44. key = f"{prefix}:{key}"
  45. except ValueError:
  46. self.logger.error(f"Skipping unexpected stream data ({path}): {line}")
  47. continue
  48. stream[key] = val
  49. # Return
  50. return streams