forge.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. from datetime import datetime, timedelta
  2. from time import sleep
  3. import os
  4. from subprocess import Popen
  5. import logging
  6. from config_manager import get_config
  7. def get_timefile_exact(time):
  8. '''
  9. time is of type `datetime`; it is not "rounded" to match the real file;
  10. that work is done in get_timefile(time)
  11. '''
  12. return os.path.join(
  13. get_config()['AUDIO_INPUT'],
  14. time.strftime(get_config()['AUDIO_INPUT_FORMAT'])
  15. )
  16. def round_timefile(exact):
  17. '''
  18. This will round the datetime, so to match the file organization structure
  19. '''
  20. return datetime(exact.year, exact.month, exact.day, exact.hour)
  21. def get_timefile(exact):
  22. return get_timefile_exact(round_timefile(exact))
  23. def get_files_and_intervals(start, end, rounder=round_timefile):
  24. '''
  25. both arguments are datetime objects
  26. returns an iterator whose elements are (filename, start_cut, end_cut)
  27. Cuts are expressed in seconds
  28. '''
  29. if end <= start:
  30. raise ValueError("end < start!")
  31. while start <= end:
  32. begin = rounder(start)
  33. start_cut = (start - begin).total_seconds()
  34. if end < begin + timedelta(seconds=3599):
  35. end_cut = (begin + timedelta(seconds=3599) - end).total_seconds()
  36. else:
  37. end_cut = 0
  38. yield (begin, start_cut, end_cut)
  39. start = begin + timedelta(hours=1)
  40. def mp3_join(named_intervals, target):
  41. '''
  42. Note that these are NOT the intervals returned by get_files_and_intervals,
  43. as they do not supply a filename, but only a datetime.
  44. What we want in input is basically the same thing, but with get_timefile()
  45. applied on the first element
  46. This function make the (quite usual) assumption that the only start_cut (if
  47. any) is at the first file, and the last one is at the last file
  48. '''
  49. ffmpeg = get_config()['FFMPEG_PATH']
  50. startskip = None
  51. endskip = None
  52. files = []
  53. for (filename, start_cut, end_cut) in named_intervals:
  54. # this happens only one time, and only at the first iteration
  55. if start_cut:
  56. assert startskip is None
  57. startskip = start_cut
  58. # this happens only one time, and only at the first iteration
  59. if end_cut:
  60. assert endskip is None
  61. endskip = end_cut
  62. assert '|' not in filename
  63. files.append(filename)
  64. cmdline = [ffmpeg, '-i', 'concat:%s' % '|'.join(files), '-acodec',
  65. 'copy']
  66. if startskip is not None:
  67. cmdline += ['-ss', str(startskip)]
  68. else:
  69. startskip = 0
  70. if endskip is not None:
  71. cmdline += ['-t', str(len(files)*3600 - (startskip + endskip))]
  72. cmdline += [target]
  73. return cmdline
  74. def create_mp3(start, end, outfile, options={}, **kwargs):
  75. intervals = [(get_timefile(begin), start_cut, end_cut)
  76. for begin, start_cut, end_cut
  77. in get_files_and_intervals(start, end)]
  78. if os.path.exists(outfile):
  79. raise OSError("file '%s' already exists" % outfile)
  80. for path, _s, _e in intervals:
  81. if not os.path.exists(path):
  82. raise OSError("file '%s' does not exist; recording system broken?"
  83. % path)
  84. p = Popen(mp3_join(intervals, outfile) + get_config()['FFMPEG_OPTIONS'])
  85. if get_config()['FORGE_TIMEOUT'] == 0:
  86. p.wait()
  87. else:
  88. start = datetime.now()
  89. while (datetime.now() - start).total_seconds() \
  90. < get_config()['FORGE_TIMEOUT']:
  91. p.poll()
  92. if p.returncode is None:
  93. sleep(1)
  94. else:
  95. break
  96. if p.returncode is None:
  97. os.kill(p.pid, 15)
  98. try:
  99. os.remove(outfile)
  100. except:
  101. pass
  102. raise Exception('timeout') # TODO: make a specific TimeoutError
  103. if p.returncode != 0:
  104. raise OSError("return code was %d" % p.returncode)
  105. return True
  106. def main_cmd(options):
  107. log = logging.getLogger('forge_main')
  108. outfile = os.path.abspath(os.path.join(options.cwd, options.outfile))
  109. log.debug('will forge an mp3 into %s' % (outfile))
  110. create_mp3(options.starttime, options.endtime, outfile)