Compare commits

..

3 Commits

Author SHA1 Message Date
b5dbccef85 fix(core): no existence validation of ts files 2026-04-27 23:16:23 +01:00
2ef48609d9 fix(state): shallow copy of empty state 2026-04-27 23:13:36 +01:00
d97f15233b fix(core): temp file written to cwd
Now uses temp file module to prevent race conditions.
2026-04-27 23:13:23 +01:00
2 changed files with 52 additions and 49 deletions

View File

@@ -2,6 +2,7 @@
import os import os
import datetime import datetime
import subprocess import subprocess
import tempfile
from rewind.state import load_state, add_marker_to_state, remove_marker_from_state from rewind.state import load_state, add_marker_to_state, remove_marker_from_state
from rewind.config import Config from rewind.config import Config
@@ -96,7 +97,7 @@ get_duration() is used as little as possible since it is slow.
end_timestamp of a file is the start time of the next file. end_timestamp of a file is the start time of the next file.
""" """
def _get_ts_files(start_timestamp: float, end_timestamp: float) -> tuple[list[str], float, float]: def _get_ts_files(start_timestamp: float, end_timestamp: float) -> tuple[list[str], float, float]:
ts_files = load_state()["files"] ts_files = [f for f in load_state()["files"] if os.path.exists(f["path"])]
selected_files = [] selected_files = []
start_offset = 0.0 start_offset = 0.0
end_offset = 0.0 end_offset = 0.0
@@ -120,61 +121,62 @@ def _get_ts_files(start_timestamp: float, end_timestamp: float) -> tuple[list[st
return selected_files, start_offset, end_offset return selected_files, start_offset, end_offset
def _concat_ts_files(file_list: list[str], start_offset: float, end_offset: float, length: float, output_file: str) -> None: def _concat_ts_files(file_list: list[str], start_offset: float, end_offset: float, length: float, output_file: str) -> None:
with open("file_list.txt", "w") as f: tmp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False)
try:
for file_path in file_list: for file_path in file_list:
f.write(f"file '{file_path}'\n") tmp_file.write(f"file '{file_path}'\n")
tmp_file.close()
cmd = ["ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-nostats", "-progress", "pipe:1"] cmd = ["ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-nostats", "-progress", "pipe:1"]
if start_offset > 0: if start_offset > 0:
cmd += ["-ss", str(start_offset)] cmd += ["-ss", str(start_offset)]
if end_offset > 0: if end_offset > 0:
cmd += ["-t", str(length)] cmd += ["-t", str(length)]
cmd += ["-f", "concat", "-safe", "0", "-i", "file_list.txt", "-c", "copy"] cmd += ["-f", "concat", "-safe", "0", "-i", tmp_file.name, "-c", "copy"]
cmd.append(output_file) cmd.append(output_file)
process = subprocess.Popen( process = subprocess.Popen(
cmd, cmd,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, text=True,
bufsize=1, bufsize=1,
) )
init_ms_val = 0 init_ms_val = 0
init_ms_val_set = False init_ms_val_set = False
with tqdm( with tqdm(
total=length, total=length,
unit="s", unit="s",
unit_scale=True, unit_scale=True,
unit_divisor=60, unit_divisor=60,
desc="Processing", desc="Processing",
leave=True, leave=True,
) as pbar: ) as pbar:
for line in process.stdout: for line in process.stdout: # type: ignore[union-attr]
line = line.strip() line = line.strip()
if line.startswith("out_time_ms="):
out_time_ms = int(line.split("=")[1])
if line.startswith("out_time_ms="): if not init_ms_val_set:
out_time_ms = int(line.split("=")[1]) init_ms_val = out_time_ms
init_ms_val_set = True
out_time_ms -= init_ms_val
if not init_ms_val_set: seconds = abs(out_time_ms / 1_000_000)
init_ms_val = out_time_ms pbar.n = min(seconds, length)
init_ms_val_set = True pbar.refresh()
out_time_ms -= init_ms_val
seconds = abs(out_time_ms / 1_000_000) elif line == "progress=end":
pbar.n = min(seconds, length) break
pbar.refresh()
elif line == "progress=end": ret = process.wait()
break if ret != 0:
raise RuntimeError("ffmpeg failed")
ret = process.wait() finally:
os.remove("file_list.txt") os.unlink(tmp_file.name)
if ret != 0:
raise RuntimeError("ffmpeg failed")
def get_duration(file_path: str) -> float: def get_duration(file_path: str) -> float:
result = subprocess.run( result = subprocess.run(
@@ -182,10 +184,11 @@ def get_duration(file_path: str) -> float:
"format=duration", "-of", "format=duration", "-of",
"default=noprint_wrappers=1:nokey=1", file_path], "default=noprint_wrappers=1:nokey=1", file_path],
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT stderr=subprocess.PIPE,
text=True,
) )
if result.returncode != 0: if result.returncode != 0:
raise RuntimeError(f"ffprobe failed for file {file_path}") raise RuntimeError(f"ffprobe failed for file {file_path}")
return float(result.stdout) return float(result.stdout.strip())

View File

@@ -21,7 +21,7 @@ def get_state_file_path() -> Path:
def load_state() -> dict: def load_state() -> dict:
path = get_state_file_path() path = get_state_file_path()
if not path.exists(): if not path.exists():
return EMPTY_STATE.copy() return {"files": [], "markers": []}
with path.open() as f: with path.open() as f:
return json.load(f) return json.load(f)