set_cd_marker.py 9.4 KB

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