| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2018-2026 Mike Fährmann |
| 4 |
# |
| 5 |
# This program is free software; you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License version 2 as |
| 7 |
# published by the Free Software Foundation. |
| 8 |
|
| 9 |
"""Convert Pixiv Ugoira to WebM""" |
| 10 |
|
| 11 |
from .common import PostProcessor |
| 12 |
from .. import util, output |
| 13 |
import subprocess |
| 14 |
import tempfile |
| 15 |
import zipfile |
| 16 |
import shutil |
| 17 |
import os |
| 18 |
|
| 19 |
try: |
| 20 |
from math import gcd |
| 21 |
except ImportError: |
| 22 |
def gcd(a, b): |
| 23 |
while b: |
| 24 |
a, b = b, a % b |
| 25 |
return a |
| 26 |
|
| 27 |
|
| 28 |
class UgoiraPP(PostProcessor): |
| 29 |
|
| 30 |
def __init__(self, job, options): |
| 31 |
PostProcessor.__init__(self, job) |
| 32 |
self.args = options.get("ffmpeg-args") or () |
| 33 |
self.twopass = options.get("ffmpeg-twopass", False) |
| 34 |
self.output = options.get("ffmpeg-output", "error") |
| 35 |
self.delete = not options.get("keep-files", False) |
| 36 |
self.repeat = options.get("repeat-last-frame", True) |
| 37 |
self.metadata = options.get("metadata", True) |
| 38 |
self.mtime = options.get("mtime", True) |
| 39 |
self.mkvm_args = options.get("mkvmerge-args") or () |
| 40 |
self.mkvm_mtime = options.get("mkvmerge-mtime", False) |
| 41 |
self.mkvm_output = options.get("mkvmerge-output", False) |
| 42 |
self.mkvm_metadata = options.get("mkvmerge-metadata", True) |
| 43 |
self.skip = options.get("skip", True) |
| 44 |
self.uniform = self._convert_zip = self._convert_files = False |
| 45 |
|
| 46 |
ffmpeg = options.get("ffmpeg-location") |
| 47 |
self.ffmpeg = util.expand_path(ffmpeg) if ffmpeg else "ffmpeg" |
| 48 |
|
| 49 |
mkvmerge = options.get("mkvmerge-location") |
| 50 |
self.mkvmerge = util.expand_path(mkvmerge) if mkvmerge else "mkvmerge" |
| 51 |
|
| 52 |
ext = options.get("extension") |
| 53 |
mode = options.get("mode") or options.get("ffmpeg-demuxer") |
| 54 |
if mode is None or mode == "auto": |
| 55 |
if ext in (None, "webm", "mkv") and ( |
| 56 |
mkvmerge or shutil.which("mkvmerge")): |
| 57 |
mode = "mkvmerge" |
| 58 |
else: |
| 59 |
mode = "concat" |
| 60 |
|
| 61 |
if mode == "mkvmerge": |
| 62 |
self._process = self._process_mkvmerge |
| 63 |
self._finalize = self._finalize_mkvmerge |
| 64 |
elif mode == "image2": |
| 65 |
self._process = self._process_image2 |
| 66 |
self._finalize = None |
| 67 |
elif mode == "archive": |
| 68 |
if ext is None: |
| 69 |
ext = "zip" |
| 70 |
self._convert_impl = self.convert_to_archive |
| 71 |
self._tempdir = util.NullContext |
| 72 |
else: |
| 73 |
self._process = self._process_concat |
| 74 |
self._finalize = None |
| 75 |
self.extension = "webm" if ext is None else ext |
| 76 |
self.log.debug("using %s demuxer", mode) |
| 77 |
|
| 78 |
rate = options.get("framerate", "auto") |
| 79 |
if rate == "uniform": |
| 80 |
self.uniform = True |
| 81 |
elif rate != "auto": |
| 82 |
self.calculate_framerate = lambda _: (None, rate) |
| 83 |
|
| 84 |
if options.get("libx264-prevent-odd", True): |
| 85 |
# get last video-codec argument |
| 86 |
vcodec = None |
| 87 |
for index, arg in enumerate(self.args): |
| 88 |
arg, _, stream = arg.partition(":") |
| 89 |
if arg == "-vcodec" or arg in ("-c", "-codec") and ( |
| 90 |
not stream or stream.partition(":")[0] in ("v", "V")): |
| 91 |
vcodec = self.args[index + 1] |
| 92 |
# use filter when using libx264/5 |
| 93 |
self.prevent_odd = ( |
| 94 |
vcodec in ("libx264", "libx265") or |
| 95 |
not vcodec and self.extension.lower() in ("mp4", "mkv")) |
| 96 |
else: |
| 97 |
self.prevent_odd = False |
| 98 |
|
| 99 |
self.args_pp = args = [] |
| 100 |
if isinstance(self.output, str): |
| 101 |
args += ("-hide_banner", "-loglevel", self.output) |
| 102 |
if self.prevent_odd: |
| 103 |
args += ("-vf", "crop=iw-mod(iw\\,2):ih-mod(ih\\,2)") |
| 104 |
|
| 105 |
job.register_hooks({ |
| 106 |
"prepare": self.prepare, |
| 107 |
"file" : self.convert_from_zip, |
| 108 |
"after" : self.convert_from_files, |
| 109 |
}, options) |
| 110 |
|
| 111 |
def prepare(self, pathfmt): |
| 112 |
self._convert_zip = self._convert_files = False |
| 113 |
if "_ugoira_frame_data" not in pathfmt.kwdict: |
| 114 |
self._frames = None |
| 115 |
return |
| 116 |
|
| 117 |
self._frames = pathfmt.kwdict["_ugoira_frame_data"] |
| 118 |
index = pathfmt.kwdict.get("_ugoira_frame_index") |
| 119 |
if index is None: |
| 120 |
self._convert_zip = True |
| 121 |
if self.delete: |
| 122 |
pathfmt.set_extension(self.extension) |
| 123 |
pathfmt.build_path() |
| 124 |
else: |
| 125 |
pathfmt.build_path() |
| 126 |
frame = self._frames[index].copy() |
| 127 |
frame["index"] = index |
| 128 |
frame["path"] = pathfmt.realpath |
| 129 |
frame["ext"] = pathfmt.extension |
| 130 |
|
| 131 |
if not index: |
| 132 |
self._files = [frame] |
| 133 |
else: |
| 134 |
self._files.append(frame) |
| 135 |
if len(self._files) >= len(self._frames): |
| 136 |
self._convert_files = True |
| 137 |
|
| 138 |
def convert_from_zip(self, pathfmt): |
| 139 |
if not self._convert_zip: |
| 140 |
return |
| 141 |
self._zip_source = True |
| 142 |
self._zip_ext = ext = pathfmt.extension |
| 143 |
|
| 144 |
with self._tempdir() as tempdir: |
| 145 |
if tempdir: |
| 146 |
try: |
| 147 |
with zipfile.ZipFile(pathfmt.temppath) as zfile: |
| 148 |
zfile.extractall(tempdir) |
| 149 |
except FileNotFoundError: |
| 150 |
pathfmt.realpath = pathfmt.temppath |
| 151 |
return |
| 152 |
except Exception as exc: |
| 153 |
pathfmt.realpath = pathfmt.temppath |
| 154 |
self.log.error( |
| 155 |
"%s: Unable to extract frames from %s (%s: %s)", |
| 156 |
pathfmt.kwdict.get("id"), pathfmt.filename, |
| 157 |
exc.__class__.__name__, exc) |
| 158 |
return self.log.traceback(exc) |
| 159 |
|
| 160 |
if self.convert(pathfmt, tempdir): |
| 161 |
if self.delete: |
| 162 |
pathfmt.delete = True |
| 163 |
elif pathfmt.extension != ext: |
| 164 |
self.log.info(pathfmt.filename) |
| 165 |
pathfmt.set_extension(ext) |
| 166 |
pathfmt.build_path() |
| 167 |
|
| 168 |
def convert_from_files(self, pathfmt): |
| 169 |
if not self._convert_files: |
| 170 |
return |
| 171 |
self._zip_source = False |
| 172 |
|
| 173 |
with tempfile.TemporaryDirectory() as tempdir: |
| 174 |
for frame in self._files: |
| 175 |
|
| 176 |
# update frame filename extension |
| 177 |
frame["file"] = name = \ |
| 178 |
f"{frame['file'].partition('.')[0]}.{frame['ext']}" |
| 179 |
|
| 180 |
if tempdir: |
| 181 |
# move frame into tempdir |
| 182 |
try: |
| 183 |
self._copy_file(frame["path"], tempdir + "/" + name) |
| 184 |
except OSError as exc: |
| 185 |
self.log.debug("Unable to copy frame %s (%s: %s)", |
| 186 |
name, exc.__class__.__name__, exc) |
| 187 |
return |
| 188 |
|
| 189 |
pathfmt.kwdict["num"] = 0 |
| 190 |
self._frames = self._files |
| 191 |
if self.convert(pathfmt, tempdir): |
| 192 |
self.log.info(pathfmt.filename) |
| 193 |
if self.delete: |
| 194 |
self.log.debug("Deleting frames") |
| 195 |
for frame in self._files: |
| 196 |
util.remove_file(frame["path"]) |
| 197 |
|
| 198 |
def convert(self, pathfmt, tempdir): |
| 199 |
pathfmt.set_extension(self.extension) |
| 200 |
pathfmt.build_path() |
| 201 |
if self.skip and pathfmt.exists(): |
| 202 |
return True |
| 203 |
|
| 204 |
return self._convert_impl(pathfmt, tempdir) |
| 205 |
|
| 206 |
def convert_to_animation(self, pathfmt, tempdir): |
| 207 |
# process frames and collect command-line arguments |
| 208 |
args = self._process(pathfmt, tempdir) |
| 209 |
if self.args_pp: |
| 210 |
args += self.args_pp |
| 211 |
if self.args: |
| 212 |
args += self.args |
| 213 |
|
| 214 |
# ensure target directory exists |
| 215 |
os.makedirs(pathfmt.realdirectory, exist_ok=True) |
| 216 |
|
| 217 |
# invoke ffmpeg |
| 218 |
try: |
| 219 |
if self.twopass: |
| 220 |
if "-f" not in self.args: |
| 221 |
args += ("-f", self.extension) |
| 222 |
args += ("-passlogfile", tempdir + "/ffmpeg2pass", "-pass") |
| 223 |
self._exec(args + ["1", "-y", os.devnull]) |
| 224 |
self._exec(args + ["2", pathfmt.realpath]) |
| 225 |
else: |
| 226 |
args.append(pathfmt.realpath) |
| 227 |
self._exec(args) |
| 228 |
if self._finalize: |
| 229 |
self._finalize(pathfmt, tempdir) |
| 230 |
except OSError as exc: |
| 231 |
output.stderr_write("\n") |
| 232 |
self.log.error("Unable to invoke FFmpeg (%s: %s)", |
| 233 |
exc.__class__.__name__, exc) |
| 234 |
self.log.traceback(exc) |
| 235 |
pathfmt.realpath = pathfmt.temppath |
| 236 |
except Exception as exc: |
| 237 |
output.stderr_write("\n") |
| 238 |
self.log.error("%s: %s", exc.__class__.__name__, exc) |
| 239 |
self.log.traceback(exc) |
| 240 |
pathfmt.realpath = pathfmt.temppath |
| 241 |
else: |
| 242 |
if self.mtime: |
| 243 |
pathfmt.set_mtime() |
| 244 |
return True |
| 245 |
|
| 246 |
def convert_to_archive(self, pathfmt, tempdir): |
| 247 |
frames = self._frames |
| 248 |
|
| 249 |
if self.metadata: |
| 250 |
if isinstance(self.metadata, str): |
| 251 |
metaname = self.metadata |
| 252 |
else: |
| 253 |
metaname = "animation.json" |
| 254 |
framedata = util.json_dumps([ |
| 255 |
{"file": frame["file"], "delay": frame["delay"]} |
| 256 |
for frame in frames |
| 257 |
]).encode() |
| 258 |
|
| 259 |
if self._zip_source: |
| 260 |
zpath = pathfmt.temppath |
| 261 |
if self.delete: |
| 262 |
self.delete = False |
| 263 |
elif self._zip_ext != self.extension: |
| 264 |
self._copy_file(zpath, pathfmt.realpath) |
| 265 |
zpath = pathfmt.realpath |
| 266 |
|
| 267 |
if self.metadata: |
| 268 |
with zipfile.ZipFile(zpath, "a") as zfile: |
| 269 |
zinfo = zipfile.ZipInfo(metaname) |
| 270 |
if self.mtime: |
| 271 |
zinfo.date_time = zfile.infolist()[0].date_time |
| 272 |
with zfile.open(zinfo, "w") as fp: |
| 273 |
fp.write(framedata) |
| 274 |
else: |
| 275 |
if self.mtime: |
| 276 |
dt = pathfmt.kwdict["date_url"] or pathfmt.kwdict["date"] |
| 277 |
mtime = (dt.year, dt.month, dt.day, |
| 278 |
dt.hour, dt.minute, dt.second) |
| 279 |
with zipfile.ZipFile(pathfmt.realpath, "w") as zfile: |
| 280 |
for frame in frames: |
| 281 |
zinfo = zipfile.ZipInfo.from_file( |
| 282 |
frame["path"], frame["file"]) |
| 283 |
if self.mtime: |
| 284 |
zinfo.date_time = mtime |
| 285 |
with open(frame["path"], "rb") as src, \ |
| 286 |
zfile.open(zinfo, "w") as dst: |
| 287 |
shutil.copyfileobj(src, dst, 1024*8) |
| 288 |
if self.metadata: |
| 289 |
zinfo = zipfile.ZipInfo(metaname) |
| 290 |
if self.mtime: |
| 291 |
zinfo.date_time = mtime |
| 292 |
with zfile.open(zinfo, "w") as fp: |
| 293 |
fp.write(framedata) |
| 294 |
|
| 295 |
return True |
| 296 |
|
| 297 |
_convert_impl = convert_to_animation |
| 298 |
_tempdir = tempfile.TemporaryDirectory |
| 299 |
|
| 300 |
def _exec(self, args): |
| 301 |
self.log.debug(args) |
| 302 |
out = None if self.output else subprocess.DEVNULL |
| 303 |
if retcode := util.Popen(args, stdout=out, stderr=out).wait(): |
| 304 |
output.stderr_write("\n") |
| 305 |
self.log.error("Non-zero exit status when running %s (%s)", |
| 306 |
args, retcode) |
| 307 |
raise ValueError() |
| 308 |
return retcode |
| 309 |
|
| 310 |
def _copy_file(self, src, dst): |
| 311 |
shutil.copyfile(src, dst) |
| 312 |
|
| 313 |
def _process_concat(self, pathfmt, tempdir): |
| 314 |
rate_in, rate_out = self.calculate_framerate(self._frames) |
| 315 |
args = [self.ffmpeg, "-f", "concat"] |
| 316 |
if rate_in: |
| 317 |
args += ("-r", str(rate_in)) |
| 318 |
args += ("-i", self._write_ffmpeg_concat(tempdir)) |
| 319 |
if rate_out: |
| 320 |
args += ("-r", str(rate_out)) |
| 321 |
return args |
| 322 |
|
| 323 |
def _process_image2(self, pathfmt, tempdir): |
| 324 |
tempdir += "/" |
| 325 |
frames = self._frames |
| 326 |
|
| 327 |
# add extra frame if necessary |
| 328 |
if self.repeat and not self._delay_is_uniform(frames): |
| 329 |
last = frames[-1] |
| 330 |
delay_gcd = self._delay_gcd(frames) |
| 331 |
if last["delay"] - delay_gcd > 0: |
| 332 |
last["delay"] -= delay_gcd |
| 333 |
|
| 334 |
self.log.debug("non-uniform delays; inserting extra frame") |
| 335 |
last_copy = last.copy() |
| 336 |
frames.append(last_copy) |
| 337 |
name, _, ext = last_copy["file"].rpartition(".") |
| 338 |
last_copy["file"] = f"{int(name) + 1:>06}.{ext}" |
| 339 |
shutil.copyfile(tempdir + last["file"], |
| 340 |
tempdir + last_copy["file"]) |
| 341 |
|
| 342 |
# adjust frame mtime values |
| 343 |
ts = 0 |
| 344 |
for frame in frames: |
| 345 |
os.utime(tempdir + frame["file"], ns=(ts, ts)) |
| 346 |
ts += frame["delay"] * 1000000 |
| 347 |
|
| 348 |
return [ |
| 349 |
self.ffmpeg, |
| 350 |
"-f", "image2", |
| 351 |
"-ts_from_file", "2", |
| 352 |
"-pattern_type", "sequence", |
| 353 |
"-i", (f"{tempdir.replace('%', '%%')}%06d." |
| 354 |
f"{frame['file'].rpartition('.')[2]}"), |
| 355 |
] |
| 356 |
|
| 357 |
def _process_mkvmerge(self, pathfmt, tempdir): |
| 358 |
self._realpath = pathfmt.realpath |
| 359 |
pathfmt.realpath = f"{tempdir}/temp.{self.extension}" |
| 360 |
|
| 361 |
return [ |
| 362 |
self.ffmpeg, |
| 363 |
"-r", "25", |
| 364 |
"-f", "concat", |
| 365 |
"-i", self._write_ffmpeg_concat(tempdir, False), |
| 366 |
] |
| 367 |
|
| 368 |
def _finalize_mkvmerge(self, pathfmt, tempdir): |
| 369 |
args = [ |
| 370 |
self.mkvmerge, |
| 371 |
"-o", pathfmt.path, # mkvmerge does not support "raw" paths |
| 372 |
"--timecodes", "0:" + self._write_mkvmerge_timecodes(tempdir), |
| 373 |
] |
| 374 |
if self.mkvm_mtime and (dt := pathfmt.kwdict.get("date_url") or |
| 375 |
pathfmt.kwdict.get("date")): |
| 376 |
args += ("--date", str(dt)) |
| 377 |
if not self.mkvm_metadata: |
| 378 |
args.append("--disable-track-statistics-tags") |
| 379 |
if not self.mkvm_output: |
| 380 |
args.append("--quiet") |
| 381 |
if self.extension == "webm": |
| 382 |
args.append("--webm") |
| 383 |
if self.mkvm_args: |
| 384 |
args += self.mkvm_args |
| 385 |
args += ("=", pathfmt.realpath) |
| 386 |
|
| 387 |
pathfmt.realpath = self._realpath |
| 388 |
self._exec(args) |
| 389 |
|
| 390 |
def _write_ffmpeg_concat(self, tempdir, duration=True): |
| 391 |
content = ["ffconcat version 1.0"] |
| 392 |
|
| 393 |
if duration: |
| 394 |
for frame in self._frames: |
| 395 |
content.append(f"file '{frame['file']}'\n" |
| 396 |
f"duration {frame['delay'] / 1000}") |
| 397 |
else: |
| 398 |
for frame in self._frames: |
| 399 |
content.append(f"file '{frame['file']}'") |
| 400 |
if self.repeat: |
| 401 |
content.append(f"file '{frame['file']}'") |
| 402 |
content.append("") |
| 403 |
|
| 404 |
ffconcat = tempdir + "/ffconcat.txt" |
| 405 |
with open(ffconcat, "w", encoding="utf-8") as fp: |
| 406 |
fp.write("\n".join(content)) |
| 407 |
return ffconcat |
| 408 |
|
| 409 |
def _write_mkvmerge_timecodes(self, tempdir): |
| 410 |
content = ["# timecode format v2"] |
| 411 |
|
| 412 |
delay_sum = 0 |
| 413 |
for frame in self._frames: |
| 414 |
content.append(str(delay_sum)) |
| 415 |
delay_sum += frame["delay"] |
| 416 |
content.append(str(delay_sum)) |
| 417 |
content.append("") |
| 418 |
|
| 419 |
timecodes = tempdir + "/timecodes.tc" |
| 420 |
with open(timecodes, "w", encoding="utf-8") as fp: |
| 421 |
fp.write("\n".join(content)) |
| 422 |
return timecodes |
| 423 |
|
| 424 |
def calculate_framerate(self, frames): |
| 425 |
if self._delay_is_uniform(frames): |
| 426 |
return (f"1000/{frames[0]['delay']}", None) |
| 427 |
|
| 428 |
if not self.uniform: |
| 429 |
gcd = self._delay_gcd(frames) |
| 430 |
if gcd >= 10: |
| 431 |
return (None, f"1000/{gcd}") |
| 432 |
|
| 433 |
return (None, None) |
| 434 |
|
| 435 |
def _delay_gcd(self, frames): |
| 436 |
result = frames[0]["delay"] |
| 437 |
for f in frames: |
| 438 |
result = gcd(result, f["delay"]) |
| 439 |
return result |
| 440 |
|
| 441 |
def _delay_is_uniform(self, frames): |
| 442 |
delay = frames[0]["delay"] |
| 443 |
for f in frames: |
| 444 |
if f["delay"] != delay: |
| 445 |
return False |
| 446 |
return True |
| 447 |
|
| 448 |
|
| 449 |
__postprocessor__ = UgoiraPP |