music-kraken-core/music_kraken/audio/codec.py

58 lines
1.7 KiB
Python
Raw Normal View History

2024-01-15 10:40:48 +00:00
from pathlib import Path
2023-06-14 10:38:36 +00:00
from typing import List, Tuple
2023-06-15 07:58:48 +00:00
from tqdm import tqdm
from ffmpeg_progress_yield import FfmpegProgress
2023-04-05 14:11:30 +00:00
2023-09-10 14:27:09 +00:00
from ..utils.config import main_settings, logging_settings
2023-04-05 14:11:30 +00:00
from ..objects import Target
2023-09-10 14:27:09 +00:00
LOGGER = logging_settings["codex_logger"]
2024-05-15 10:30:54 +00:00
def correct_codec(target: Target, bitrate_kb: int = main_settings["bitrate"], audio_format: str = main_settings["audio_format"], skip_intervals: List[Tuple[float, float]] = None):
2023-06-14 10:38:36 +00:00
if not target.exists:
LOGGER.warning(f"Target doesn't exist: {target.file_path}")
return
2023-06-15 07:58:48 +00:00
2024-05-15 10:30:54 +00:00
skip_intervals = skip_intervals or []
2023-06-15 07:58:48 +00:00
bitrate_b = int(bitrate_kb / 1024)
2023-06-14 15:43:20 +00:00
output_target = Target(
2024-01-15 10:40:48 +00:00
file_path=Path(str(target.file_path) + "." + audio_format)
)
2023-06-15 07:58:48 +00:00
# get the select thingie
2023-06-14 10:38:36 +00:00
# https://stackoverflow.com/questions/50594412/cut-multiple-parts-of-a-video-with-ffmpeg
aselect_list: List[str] = []
start = 0
2023-06-14 15:43:20 +00:00
next_start = 0
2024-05-15 10:30:54 +00:00
for end, next_start in skip_intervals:
2023-06-14 10:38:36 +00:00
aselect_list.append(f"between(t,{start},{end})")
start = next_start
aselect_list.append(f"gte(t,{next_start})")
select = f"aselect='{'+'.join(aselect_list)}',asetpts=N/SR/TB"
2023-06-15 07:58:48 +00:00
# build the ffmpeg command
ffmpeg_command = [
2023-09-10 14:27:09 +00:00
str(main_settings["ffmpeg_binary"]),
2023-06-15 07:58:48 +00:00
"-i", str(target.file_path),
"-af", select,
"-b", str(bitrate_b),
str(output_target.file_path)
]
# run the ffmpeg command with a progressbar
ff = FfmpegProgress(ffmpeg_command)
2024-05-10 15:33:07 +00:00
with tqdm(total=100, desc=f"processing") as pbar:
2023-06-15 07:58:48 +00:00
for progress in ff.run_command_with_progress():
2023-06-16 21:27:08 +00:00
pbar.update(progress-pbar.n)
2023-06-15 07:58:48 +00:00
LOGGER.debug(ff.stderr)
output_target.copy_content(target)
output_target.delete()