render까지 8초 shortform pipeline 형성
This commit is contained in:
1 parent
05747f6b8f
commit
659fd53b97
30 files changed
+1203
-30
No files matched your search
+51
-1
@@ -1,5 +1,6 @@
|
||||
"""메모리 위에서만 도는 오디오 처리. 파일도 서브프로세스도 없다."""
|
||||
"""파일도 서브프로세스도 없이 메모리에서 처리하는 오디오 유틸."""
|
||||
import io
|
||||
from fractions import Fraction
|
||||
|
||||
import av
|
||||
import numpy as np
|
||||
@@ -40,6 +41,55 @@ def encode_mp3(pcm: np.ndarray, sample_rate: int = SAMPLE_RATE) -> bytes:
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def decode_audio(media: bytes, sample_rate: int = SAMPLE_RATE) -> np.ndarray | None:
|
||||
"""비디오·오디오 컨테이너에서 오디오 트랙을 꺼낸다. 트랙이 없으면 None."""
|
||||
container = av.open(io.BytesIO(media))
|
||||
try:
|
||||
if not container.streams.audio:
|
||||
return None
|
||||
resampler = av.audio.resampler.AudioResampler(
|
||||
format="s16", layout="mono", rate=sample_rate)
|
||||
chunks = []
|
||||
for frame in container.decode(audio=0):
|
||||
for resampled in resampler.resample(frame):
|
||||
chunks.append(resampled.to_ndarray().reshape(-1))
|
||||
for resampled in resampler.resample(None):
|
||||
chunks.append(resampled.to_ndarray().reshape(-1))
|
||||
finally:
|
||||
container.close()
|
||||
return np.concatenate(chunks) if chunks else None
|
||||
|
||||
|
||||
def apply_limiter(pcm: np.ndarray, sample_rate: int = SAMPLE_RATE,
|
||||
limit: float = 0.94, attack: int = 5, release: int = 60) -> np.ndarray:
|
||||
"""ffmpeg alimiter를 그대로 태운다. 리미터가 컴프레서처럼 작동해 목소리가 또렷해진다."""
|
||||
graph = av.filter.Graph()
|
||||
source = graph.add_abuffer(format="s16", layout="mono", sample_rate=sample_rate,
|
||||
time_base=Fraction(1, sample_rate))
|
||||
limiter = graph.add("alimiter", f"limit={limit}:attack={attack}:release={release}")
|
||||
# alimiter는 부동소수로 처리하므로 싱크 앞에서 s16으로 되돌린다
|
||||
to_s16 = graph.add("aformat", "sample_fmts=s16:channel_layouts=mono")
|
||||
sink = graph.add("abuffersink")
|
||||
source.link_to(limiter)
|
||||
limiter.link_to(to_s16)
|
||||
to_s16.link_to(sink)
|
||||
graph.configure()
|
||||
|
||||
frame = av.AudioFrame.from_ndarray(pcm.reshape(1, -1), format="s16", layout="mono")
|
||||
frame.rate = sample_rate
|
||||
frame.time_base = Fraction(1, sample_rate)
|
||||
graph.push(frame)
|
||||
graph.push(None)
|
||||
|
||||
chunks = []
|
||||
while True:
|
||||
try:
|
||||
chunks.append(sink.pull().to_ndarray().reshape(-1))
|
||||
except (av.error.EOFError, av.error.BlockingIOError):
|
||||
break
|
||||
return np.concatenate(chunks).astype(np.int16) if chunks else pcm
|
||||
|
||||
|
||||
def trim_silence(pcm: np.ndarray, threshold_db: float = -45,
|
||||
keep_lead: float = 0.05, keep_trail: float = 0.12,
|
||||
sample_rate: int = SAMPLE_RATE) -> np.ndarray:
|
||||
|
||||
Reference in new issue
Block a user