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

55 lines
1.7 KiB
Python
Raw Normal View History

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
from ..utils.shared import BITRATE, AUDIO_FORMAT, CODEX_LOGGER as LOGGER, FFMPEG_BINARY
2023-04-05 14:11:30 +00:00
from ..objects import Target
2023-06-15 07:58:48 +00:00
def correct_codec(target: Target, bitrate_kb: int = BITRATE, audio_format: str = AUDIO_FORMAT, interval_list: 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
interval_list = interval_list or []
bitrate_b = int(bitrate_kb / 1024)
2023-06-14 15:43:20 +00:00
output_target = Target(
path=target._path,
2023-06-15 07:58:48 +00:00
file=str(target._file) + "." + 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
2023-06-14 10:38:36 +00:00
for end, next_start in interval_list:
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 = [
str(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)
2023-06-16 21:27:08 +00:00
with tqdm(total=100, desc=f"removing {len(interval_list)} segments") 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()