set_cd_marker.py 9.4 KB

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