set_cd_marker.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. #!/usr/bin/env python3
  2. # Copyright © 2024 Noah Vogt <noah@noahvogt.com>
  3. # This program is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, either version 3 of the License, or
  6. # (at your option) any later version.
  7. # This program is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU General Public License for more details.
  11. # You should have received a copy of the GNU General Public License
  12. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. from os import path, mkdir, listdir
  14. from shlex import split
  15. from subprocess import Popen
  16. from re import match
  17. from utils import (
  18. get_yyyy_mm_dd_date,
  19. make_sure_file_exists,
  20. is_valid_cd_record_checkfile,
  21. get_unix_milis,
  22. log,
  23. warn,
  24. error_msg,
  25. expand_dir,
  26. mark_end_of_recording,
  27. )
  28. from input import get_cachefile_content, validate_cd_record_config
  29. import config as const
  30. def get_reset_marker(yyyy_mm_dd: str) -> int:
  31. max_reset = 0
  32. for file in listdir(path.join(const.CD_RECORD_OUTPUT_BASEDIR, yyyy_mm_dd)):
  33. print(file)
  34. if (
  35. match(r"[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]+\.wav$", file)
  36. and len(file) == 22
  37. ):
  38. print(f"file {file} reached")
  39. max_reset = max(int(file[11:18]), max_reset)
  40. print(max_reset)
  41. return max_reset + 1
  42. def start_cd_recording() -> None:
  43. cachefile_content = get_cachefile_content(const.CD_RECORD_CACHEFILE)
  44. yyyy_mm_dd = get_yyyy_mm_dd_date()
  45. cd_num = get_reset_marker(yyyy_mm_dd)
  46. ensure_output_dir_exists(yyyy_mm_dd)
  47. while cachefile_content[1].strip() != "9001":
  48. filename = path.join(
  49. const.CD_RECORD_OUTPUT_BASEDIR,
  50. yyyy_mm_dd,
  51. f"{yyyy_mm_dd}-{cd_num:0{const.CD_RECORD_FILENAME_ZFILL}}.wav",
  52. )
  53. unix_milis = get_unix_milis()
  54. log(f"starting cd #{cd_num} recording...")
  55. cmd = "ffmpeg -y {} -ar 44100 -t {} {}".format(
  56. const.CD_RECORD_FFMPEG_INPUT_ARGS,
  57. const.CD_RECORD_MAX_SECONDS,
  58. filename,
  59. )
  60. process = Popen(split(cmd))
  61. cachefile = expand_dir(const.CD_RECORD_CACHEFILE)
  62. log("updating active ffmpeg pid")
  63. try:
  64. with open(
  65. cachefile, mode="w+", encoding="utf-8-sig"
  66. ) as file_writer:
  67. file_writer.write(cachefile_content[0].strip() + "\n")
  68. # reset marker to 1
  69. file_writer.write("1\n")
  70. file_writer.write(f"{process.pid}\n")
  71. file_writer.write(f"{unix_milis}\n")
  72. file_writer.write(f"{unix_milis}\n")
  73. file_writer.write(f"{cd_num}\n")
  74. except (FileNotFoundError, PermissionError, IOError) as error:
  75. error_msg(
  76. "Failed to write to cachefile '{}'. Reason: {}".format(
  77. cachefile, error
  78. )
  79. )
  80. fresh_cachefile_content = get_cachefile_content(
  81. const.CD_RECORD_CACHEFILE
  82. )
  83. update_cue_sheet(
  84. fresh_cachefile_content, yyyy_mm_dd, unix_milis, initial_run=True
  85. )
  86. _ = process.communicate()[0] # wait for subprocess to end
  87. cachefile_content = get_cachefile_content(const.CD_RECORD_CACHEFILE)
  88. cd_num += 1
  89. if process.returncode not in [255, 0]:
  90. mark_end_of_recording(cachefile_content)
  91. error_msg(f"ffmpeg terminated with exit code {process.returncode}")
  92. def ensure_output_dir_exists(date):
  93. cue_sheet_dir = path.join(expand_dir(const.CD_RECORD_OUTPUT_BASEDIR), date)
  94. try:
  95. if not path.exists(cue_sheet_dir):
  96. mkdir(cue_sheet_dir)
  97. except (FileNotFoundError, PermissionError, IOError) as error:
  98. error_msg(
  99. "Failed to create to cue sheet directory '{}'. Reason: {}".format(
  100. cue_sheet_dir, error
  101. )
  102. )
  103. def create_cachefile_for_marker(
  104. cachefile_content: list,
  105. yyyy_mm_dd: str,
  106. unix_milis: int,
  107. initial_run=False,
  108. ) -> None:
  109. cachefile = expand_dir(const.CD_RECORD_CACHEFILE)
  110. if initial_run:
  111. marker = 1
  112. else:
  113. marker = int(cachefile_content[1]) + 1
  114. if marker > 99:
  115. return
  116. if (
  117. not (initial_run)
  118. and unix_milis - int(cachefile_content[4])
  119. < const.CD_RECORD_MIN_TRACK_MILIS
  120. ):
  121. return
  122. log("writing cd marker {} to cachefile...".format(marker))
  123. try:
  124. with open(cachefile, mode="w+", encoding="utf-8-sig") as file_writer:
  125. file_writer.write(f"{yyyy_mm_dd}\n")
  126. file_writer.write(f"{marker}\n")
  127. if initial_run:
  128. file_writer.write("000\n") # fake pid, gets overriden later
  129. file_writer.write(f"{unix_milis}\n")
  130. else:
  131. file_writer.write(f"{cachefile_content[2].strip()}\n")
  132. file_writer.write(f"{cachefile_content[3].strip()}\n")
  133. file_writer.write(f"{unix_milis}\n")
  134. if initial_run:
  135. file_writer.write("1\n")
  136. else:
  137. file_writer.write(f"{cachefile_content[5].strip()}\n")
  138. except (FileNotFoundError, PermissionError, IOError) as error:
  139. error_msg(
  140. "Failed to write to cachefile '{}'. Reason: {}".format(
  141. cachefile, error
  142. )
  143. )
  144. def update_cue_sheet(
  145. cachefile_content: list, yyyy_mm_dd: str, unix_milis: int, initial_run=False
  146. ) -> None:
  147. cue_sheet_dir = path.join(
  148. expand_dir(const.CD_RECORD_OUTPUT_BASEDIR), yyyy_mm_dd
  149. )
  150. # use current cachefile data for here cd_num only
  151. fresh_cachefile_content = get_cachefile_content(const.CD_RECORD_CACHEFILE)
  152. cd_num = (
  153. fresh_cachefile_content[5].strip().zfill(const.CD_RECORD_FILENAME_ZFILL)
  154. )
  155. cue_sheet_path = path.join(cue_sheet_dir, f"sheet-{cd_num}.cue")
  156. wave_path = path.join(cue_sheet_dir, f"{yyyy_mm_dd}-{cd_num}.wav")
  157. if initial_run:
  158. log("updating cue sheet...")
  159. try:
  160. if not path.exists(cue_sheet_dir):
  161. mkdir(cue_sheet_dir)
  162. with open(
  163. cue_sheet_path, mode="w+", encoding="utf-8-sig"
  164. ) as file_writer:
  165. file_writer.write(f'FILE "{wave_path}" WAVE\n')
  166. file_writer.write(" TRACK 01 AUDIO\n")
  167. file_writer.write(" INDEX 01 00:00:00\n")
  168. except (FileNotFoundError, PermissionError, IOError) as error:
  169. error_msg(
  170. "Failed to write to cue sheet file '{}'. Reason: {}".format(
  171. cue_sheet_path, error
  172. )
  173. )
  174. else:
  175. marker = int(cachefile_content[1]) + 1
  176. if marker > 99:
  177. warn("An Audio CD can only hold up to 99 tracks.")
  178. return
  179. start_milis = int(cachefile_content[3])
  180. last_track_milis = int(cachefile_content[4])
  181. diff_to_max_milis = const.CD_RECORD_MAX_SECONDS * 1000 - (
  182. unix_milis - start_milis
  183. )
  184. if (
  185. not initial_run
  186. and diff_to_max_milis < const.CD_RECORD_MIN_TRACK_MILIS
  187. ):
  188. warn(
  189. "Tried to set CD Marker too close to maximum time, "
  190. + "moving backwards in time..."
  191. )
  192. unix_milis = (
  193. unix_milis - const.CD_RECORD_MIN_TRACK_MILIS + diff_to_max_milis
  194. )
  195. if unix_milis - last_track_milis < const.CD_RECORD_MIN_TRACK_MILIS:
  196. warn(
  197. f"Minimum track length of {const.CD_RECORD_MIN_TRACK_MILIS}"
  198. + "ms not satisfied, skipping..."
  199. )
  200. return
  201. milis_diff = unix_milis - start_milis
  202. mins = milis_diff // 60000
  203. milis_diff -= 60000 * mins
  204. secs = int(milis_diff / 1000)
  205. milis_diff -= 1000 * secs
  206. frames = int(75 / 1000 * milis_diff)
  207. log("updating cue sheet...")
  208. try:
  209. with open(
  210. cue_sheet_path, mode="a", encoding="utf-8-sig"
  211. ) as file_writer:
  212. file_writer.write(" TRACK {:02d} AUDIO\n".format(marker))
  213. file_writer.write(
  214. " INDEX 01 {:02d}:{:02d}:{:02d}\n".format(
  215. mins, secs, frames
  216. )
  217. )
  218. except (FileNotFoundError, PermissionError, IOError) as error:
  219. error_msg(
  220. "Failed to write to cue sheet file '{}'. Reason: {}".format(
  221. cue_sheet_path, error
  222. )
  223. )
  224. def set_cd_marker() -> None:
  225. cachefile_content = get_cachefile_content(const.CD_RECORD_CACHEFILE)
  226. yyyy_mm_dd = get_yyyy_mm_dd_date()
  227. unix_milis = get_unix_milis()
  228. cachefile_and_time_data = (cachefile_content, yyyy_mm_dd, unix_milis)
  229. if is_valid_cd_record_checkfile(*cachefile_and_time_data[:-1]):
  230. create_cachefile_for_marker(*cachefile_and_time_data)
  231. update_cue_sheet(*cachefile_and_time_data)
  232. else:
  233. create_cachefile_for_marker(*cachefile_and_time_data, initial_run=True)
  234. update_cue_sheet(*cachefile_and_time_data, initial_run=True)
  235. start_cd_recording()
  236. def main() -> None:
  237. validate_cd_record_config()
  238. make_sure_file_exists(const.CD_RECORD_CACHEFILE)
  239. set_cd_marker()
  240. if __name__ == "__main__":
  241. main()