fix: Windows环境下进度条因stdout阻塞迟迟未能显示
顺便重构一下`hevc_encode`,这样就“轻”多了。
This commit is contained in:
16
.vscode/launch.json
vendored
Normal file
16
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
// Use IntelliSense to learn about possible attributes.
|
||||||
|
// Hover to view descriptions of existing attributes.
|
||||||
|
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Python Debugger: Current File with Arguments",
|
||||||
|
"type": "debugpy",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${file}",
|
||||||
|
"console": "integratedTerminal",
|
||||||
|
"args": "${command:pickArgs}"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -46,70 +46,79 @@ def get_duration(file_path: Path):
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
def read_progress(ostream_line, dur, pbar):
|
def set_progress(line: str, dur, pbar):
|
||||||
if not ostream_line.startswith("out_time_ms="):
|
if not line.startswith("out_time_ms="):
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
us = int(ostream_line.split('=')[1])
|
us = int(line.split('=')[1])
|
||||||
if us < 0:
|
if us < 0:
|
||||||
return
|
return
|
||||||
secs = us / 1_000_000
|
current_sec = us / 1_000_000
|
||||||
if secs > dur * 1.1: # Allow 10% overshoot
|
pbar.n = min(current_sec, dur)
|
||||||
pbar.n = dur
|
|
||||||
else:
|
|
||||||
pbar.n = secs
|
|
||||||
pbar.refresh()
|
pbar.refresh()
|
||||||
except (ValueError, OverflowError):
|
except (ValueError, IndexError, OverflowError):
|
||||||
pass
|
return
|
||||||
|
|
||||||
|
|
||||||
def hevc_encode(infile: Path, outfile: Path, progress: bool = True):
|
def start_ffmpeg(infile: Path, outfile: Path):
|
||||||
# too heavy bro.
|
|
||||||
dur = get_duration(infile)
|
|
||||||
cmd = [
|
cmd = [
|
||||||
"ffmpeg", "-y", "-i", str(infile),
|
"ffmpeg", "-y", "-i", str(infile),
|
||||||
"-progress", "pipe:1", "-nostats",
|
"-progress", "pipe:1", "-nostats", "-loglevel", "error",
|
||||||
*COMPRESS_OPTIONS, str(outfile)
|
*COMPRESS_OPTIONS, str(outfile)
|
||||||
]
|
]
|
||||||
logger.debug(f"Duration: {dur:.2f} seconds")
|
return subprocess.Popen(
|
||||||
logger.debug(f"Command: {' '.join(cmd)}")
|
cmd,
|
||||||
proc = subprocess.Popen(
|
stdout=subprocess.PIPE,
|
||||||
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
stderr=subprocess.STDOUT,
|
||||||
text=True, encoding='utf-8', bufsize=1)
|
bufsize=1,
|
||||||
progress = progress and is_tty()
|
text=True,
|
||||||
pbar = None if not progress else get_progress_bar(
|
encoding='utf-8')
|
||||||
total=dur, unit='s',
|
|
||||||
bar_format='{l_bar}{bar}| {n:.2f}/{total:.2f}({unit})')
|
|
||||||
try:
|
def clean_on_failure(proc: subprocess.Popen, outfile: Path):
|
||||||
while True:
|
|
||||||
line = proc.stdout.readline()
|
|
||||||
if not line and proc.poll() is not None:
|
|
||||||
break
|
|
||||||
if not pbar:
|
|
||||||
continue
|
|
||||||
read_progress(line.strip(), dur, pbar)
|
|
||||||
proc.wait()
|
|
||||||
if proc.returncode != 0:
|
|
||||||
raise subprocess.CalledProcessError(proc.returncode, cmd)
|
|
||||||
except (
|
|
||||||
KeyboardInterrupt,
|
|
||||||
subprocess.CalledProcessError
|
|
||||||
) as e:
|
|
||||||
if proc.poll() is None:
|
if proc.poll() is None:
|
||||||
proc.kill()
|
proc.kill()
|
||||||
proc.wait()
|
proc.wait()
|
||||||
logger.error(
|
|
||||||
f"Encoding failed with code {proc.returncode}:"
|
|
||||||
f" {e.__class__.__name__}")
|
|
||||||
if outfile.exists():
|
if outfile.exists():
|
||||||
try:
|
try:
|
||||||
outfile.unlink()
|
outfile.unlink()
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def hevc_encode(infile: Path, outfile: Path, progress: bool = True):
|
||||||
|
dur = get_duration(infile)
|
||||||
|
logger.debug(f"Duration: {dur:.2f} seconds")
|
||||||
|
proc = start_ffmpeg(infile, outfile)
|
||||||
|
logger.debug(f"Command: {proc.args}")
|
||||||
|
|
||||||
|
pbar = get_progress_bar(
|
||||||
|
total=dur, unit='s',
|
||||||
|
bar_format='{l_bar}{bar}| {n:.2f}/{total:.2f}({unit})'
|
||||||
|
) if progress and is_tty() else None
|
||||||
|
|
||||||
|
try:
|
||||||
|
for line in iter(proc.stdout.readline, ''):
|
||||||
|
set_progress(line.strip(), dur, pbar)
|
||||||
|
if proc.poll() is not None:
|
||||||
|
break
|
||||||
|
|
||||||
|
proc.wait()
|
||||||
|
if proc.returncode != 0:
|
||||||
|
raise subprocess.CalledProcessError(proc.returncode, "ffmpeg")
|
||||||
|
except (
|
||||||
|
KeyboardInterrupt,
|
||||||
|
subprocess.CalledProcessError
|
||||||
|
) as e:
|
||||||
|
logger.error(
|
||||||
|
f"Encoding failed with code {proc.returncode}:"
|
||||||
|
f" {e.__class__.__name__}")
|
||||||
|
clean_on_failure(proc, outfile)
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
if pbar:
|
if pbar:
|
||||||
pbar.close()
|
pbar.close()
|
||||||
|
proc.stdout.close()
|
||||||
|
|
||||||
|
|
||||||
def build_file_list(srcdir, extensions):
|
def build_file_list(srcdir, extensions):
|
||||||
|
|||||||
Reference in New Issue
Block a user