2024-01-13 08:50:03 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
from argparse import ArgumentParser
|
2024-01-13 09:35:14 +00:00
|
|
|
from tempfile import TemporaryDirectory, NamedTemporaryFile
|
2024-01-13 08:50:03 +00:00
|
|
|
import logging
|
|
|
|
import cv2
|
|
|
|
import asyncio
|
2024-01-13 09:35:14 +00:00
|
|
|
import ffmpeg
|
2024-01-20 10:34:59 +00:00
|
|
|
from shutil import move
|
2024-01-13 08:50:03 +00:00
|
|
|
from pathlib import Path
|
|
|
|
from wand.image import Image
|
|
|
|
|
|
|
|
log = logging.getLogger('distortioner')
|
|
|
|
|
|
|
|
ap = ArgumentParser(
|
|
|
|
description = 'a script that makes memetic distorted videos'
|
|
|
|
)
|
|
|
|
|
|
|
|
class TicketedDict(dict):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self._ni = 0
|
|
|
|
self._log = logging.getLogger('TicketedDict')
|
|
|
|
self.event = asyncio.Event()
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def has_next(self):
|
|
|
|
self._log.debug("has_next is %s for %i", self._ni in self, self._ni)
|
|
|
|
return self._ni in self
|
|
|
|
|
|
|
|
async def wait(self):
|
|
|
|
self._log.debug("requested wait")
|
|
|
|
while not self.has_next():
|
|
|
|
await self.event.wait()
|
|
|
|
self._log.debug("wait broke")
|
|
|
|
self.event.clear()
|
|
|
|
|
|
|
|
async def pop(self):
|
|
|
|
self._log.debug("requested pop")
|
|
|
|
await self.wait()
|
|
|
|
ret = super().pop(self._ni)
|
|
|
|
self._ni += 1
|
|
|
|
return ret
|
|
|
|
|
|
|
|
def notify(self, *args, **kwargs):
|
|
|
|
self._log.debug("requested notify")
|
|
|
|
return self.event.set(*args, **kwargs)
|
|
|
|
|
|
|
|
ap.add_argument('input')
|
|
|
|
ap.add_argument('output')
|
|
|
|
ap.add_argument(
|
2024-01-20 10:34:59 +00:00
|
|
|
'--distort-scale', '-d',
|
2024-01-13 08:50:03 +00:00
|
|
|
default = 60.0,
|
|
|
|
type = float,
|
2024-01-20 10:34:59 +00:00
|
|
|
help = 'Percentage of image scale.',
|
|
|
|
dest = 'distort_percentage'
|
2024-01-13 08:50:03 +00:00
|
|
|
)
|
|
|
|
ap.add_argument(
|
2024-01-20 10:34:59 +00:00
|
|
|
'--distort-scale-end', '-D',
|
2024-01-13 08:50:03 +00:00
|
|
|
default = None,
|
|
|
|
type = float,
|
2024-01-20 10:34:59 +00:00
|
|
|
help = 'If specified, scaling will gradually change towards specified percentage.',
|
|
|
|
dest = 'distort_percentage_end'
|
2024-01-13 08:50:03 +00:00
|
|
|
)
|
|
|
|
ap.add_argument(
|
|
|
|
'--distort-end','--distort', '-E',
|
|
|
|
default = None,
|
|
|
|
type = float,
|
|
|
|
help = 'If specified, distortion change will happen only up to specific video progress.'
|
|
|
|
)
|
|
|
|
ap.add_argument(
|
|
|
|
'--vibrato-frequency','--vibrato-freq', '-f',
|
2024-01-20 10:34:59 +00:00
|
|
|
default = None,
|
2024-01-13 08:50:03 +00:00
|
|
|
type = float,
|
2024-01-20 10:34:59 +00:00
|
|
|
help = 'Modulation frequency in Hertz. Range is 0.1 - 20000.0. Recommended value is 10.0 Hz.'
|
2024-01-13 08:50:03 +00:00
|
|
|
)
|
|
|
|
ap.add_argument(
|
|
|
|
'--vibrato-modulation-depth','--vibrato-depth', '-m',
|
2024-01-20 10:34:59 +00:00
|
|
|
default = None,
|
2024-01-13 08:50:03 +00:00
|
|
|
type = float,
|
2024-01-20 10:34:59 +00:00
|
|
|
help = 'Depth of modulation as a percentage. Range is 0.0 - 1.0. Recommended value is 1.0.'
|
2024-01-13 08:50:03 +00:00
|
|
|
)
|
|
|
|
ap.add_argument(
|
|
|
|
'--debug',
|
|
|
|
action = 'store_true',
|
|
|
|
default = False,
|
|
|
|
help = 'Print debugging messages.'
|
|
|
|
)
|
|
|
|
def process_image(source, destination, distort):
|
2024-01-20 10:34:59 +00:00
|
|
|
log = logging.getLogger("distortioner.process_image")
|
|
|
|
log.debug("src:'%s', dst:'%s' ", source, destination)
|
2024-01-13 08:50:03 +00:00
|
|
|
with Image(filename=source) as original:
|
|
|
|
dst_width = int(original.width*(distort / 100.))
|
|
|
|
dst_height = int(original.height*(distort / 100.))
|
|
|
|
log.debug("dst:'%s' size:%ix%i", destination, dst_width, dst_height)
|
|
|
|
with original.clone() as distorted, \
|
|
|
|
open(destination, mode='wb') as out:
|
|
|
|
distorted.liquid_rescale(dst_width, dst_height)
|
|
|
|
distorted.resize(original.width, original.height)
|
|
|
|
distorted.save(out)
|
|
|
|
|
|
|
|
async def process_frames(coro, queue_in, out_pile):
|
2024-01-20 10:34:59 +00:00
|
|
|
log = logging.getLogger("distortioner.process_frames")
|
|
|
|
log.debug("started")
|
2024-01-13 08:50:03 +00:00
|
|
|
while True:
|
2024-01-20 10:34:59 +00:00
|
|
|
log.debug("queue_in.get")
|
|
|
|
try:
|
|
|
|
frame_data = await queue_in.get()
|
|
|
|
except asyncio.exceptions.CancelledError:
|
|
|
|
return
|
2024-01-13 08:50:03 +00:00
|
|
|
nr = frame_data.pop('nr')
|
|
|
|
log.debug("processing frame '%s'", frame_data)
|
|
|
|
await asyncio.to_thread(coro, **frame_data)
|
|
|
|
queue_in.task_done()
|
|
|
|
out_pile[nr]=frame_data['destination']
|
|
|
|
log.debug("put item to output pile, notifying")
|
|
|
|
out_pile.notify()
|
|
|
|
log.debug("notified")
|
|
|
|
|
|
|
|
|
|
|
|
async def read_frames(capture, frames_distorted, frames_original, queue, tasks, distort_start, distort_end=None, distort_end_frame=None):
|
2024-01-20 10:34:59 +00:00
|
|
|
log = logging.getLogger("distortioner.read_frames")
|
|
|
|
log.debug("started")
|
2024-01-13 08:50:03 +00:00
|
|
|
frames_read = 0
|
2024-01-20 10:34:59 +00:00
|
|
|
distort = distort_start
|
2024-01-13 08:50:03 +00:00
|
|
|
if distort_end_frame is None:
|
|
|
|
distort_end_frame = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
|
|
|
|
while True:
|
|
|
|
read_ok, frame = capture.read()
|
|
|
|
if not read_ok:
|
|
|
|
break
|
|
|
|
log.debug("reading frame %i", frames_read)
|
|
|
|
if distort_end is not None:
|
|
|
|
distort = distort_start \
|
|
|
|
+ (distort_end - distort_start) \
|
|
|
|
* (min(frames_read, distort_end_frame) / distort_end_frame )
|
|
|
|
frame_filename = f'frame_{str(frames_read).zfill(32)}.png'
|
|
|
|
frame_original = str(Path(frames_original)/frame_filename)
|
|
|
|
frame_distorted = str(Path(frames_distorted)/frame_filename)
|
|
|
|
cv2.imwrite(frame_original, frame)
|
2024-01-20 10:34:59 +00:00
|
|
|
log.debug("requesting frame dump %i: filename: %s", frames_read, frame_filename)
|
2024-01-13 08:50:03 +00:00
|
|
|
await queue.put({
|
|
|
|
'source': frame_original,
|
|
|
|
'destination': frame_distorted,
|
|
|
|
'distort': distort,
|
|
|
|
'nr': frames_read
|
|
|
|
})
|
|
|
|
frames_read += 1
|
|
|
|
log.info("waiting for queue to empty")
|
|
|
|
await queue.join()
|
|
|
|
log.info("quitting")
|
|
|
|
for worker in tasks:
|
|
|
|
worker.cancel()
|
|
|
|
|
|
|
|
async def write_frames(output, pile):
|
2024-01-20 10:34:59 +00:00
|
|
|
log = logging.getLogger("distortioner.write_frames")
|
|
|
|
log.debug("started")
|
2024-01-13 08:50:03 +00:00
|
|
|
while True:
|
2024-01-20 10:34:59 +00:00
|
|
|
log.debug("getting next item to write ...")
|
|
|
|
try:
|
|
|
|
frame_distorted = await pile.pop()
|
|
|
|
except asyncio.exceptions.CancelledError:
|
|
|
|
return
|
|
|
|
log.info("writing frame to video '%s'", frame_distorted)
|
2024-01-13 08:50:03 +00:00
|
|
|
newframe = cv2.imread(frame_distorted)
|
|
|
|
output.write(newframe)
|
|
|
|
log.debug("finished frame '%s'", frame_distorted)
|
|
|
|
|
|
|
|
|
|
|
|
async def distort_video(capture, output, distort_start, distort_end=None, distort_end_frame=None):
|
2024-01-20 10:34:59 +00:00
|
|
|
log = logging.getLogger("distortioner.distort_video")
|
|
|
|
log.debug("started")
|
2024-01-13 08:50:03 +00:00
|
|
|
distort = distort_start
|
|
|
|
video_width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
|
|
|
|
video_height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
|
|
|
output_pile = TicketedDict()
|
|
|
|
with \
|
|
|
|
TemporaryDirectory() as frames_distorted, \
|
|
|
|
TemporaryDirectory() as frames_original:
|
|
|
|
log.debug(frames_distorted)
|
|
|
|
log.debug(frames_original)
|
|
|
|
log.debug("creating queues")
|
|
|
|
capture_queue = asyncio.Queue(20)
|
|
|
|
output_queue = asyncio.PriorityQueue()
|
|
|
|
workers = [ asyncio.create_task(process_frames(process_image, capture_queue, output_pile)) for i in range(10) ]
|
|
|
|
workers += [ asyncio.create_task(write_frames(output, output_pile)) ]
|
|
|
|
generator = asyncio.create_task(read_frames(
|
|
|
|
capture, frames_distorted, frames_original, capture_queue, workers, distort_start, distort_end, distort_end_frame
|
|
|
|
))
|
2024-01-20 10:34:59 +00:00
|
|
|
await asyncio.gather(*workers)
|
2024-01-13 08:50:03 +00:00
|
|
|
|
|
|
|
log.debug('done with distorting video frames')
|
|
|
|
|
2024-01-13 09:35:14 +00:00
|
|
|
def distort_audio(distorted_video, in_audio, audio_freq, audio_mod, out_filename):
|
|
|
|
video = ffmpeg.input(distorted_video).video
|
|
|
|
audio = ffmpeg.input(in_audio).audio.filter(
|
|
|
|
"vibrato",
|
|
|
|
f=audio_freq,
|
|
|
|
d=audio_mod
|
|
|
|
# Documentation : https://ffmpeg.org/ffmpeg-filters.html#vibrato
|
|
|
|
)
|
|
|
|
(
|
|
|
|
ffmpeg
|
|
|
|
.concat(video, audio, v=1, a=1) # v = video stream, a = audio stream
|
|
|
|
.output(out_filename)
|
|
|
|
.run(overwrite_output=True)
|
|
|
|
# Documentation : https://kkroening.github.io/ffmpeg-python/
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-01-13 08:50:03 +00:00
|
|
|
def main():
|
|
|
|
args = ap.parse_args()
|
|
|
|
if args.debug:
|
|
|
|
logging.basicConfig(level=logging.DEBUG)
|
|
|
|
else:
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
log.debug(args)
|
|
|
|
if args.distort_percentage <= 0.0:
|
|
|
|
raise ValueError("--distort_percentage must be positive number")
|
|
|
|
|
|
|
|
capture = cv2.VideoCapture(args.input)
|
|
|
|
fps = capture.get(cv2.CAP_PROP_FPS)
|
|
|
|
video_width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
|
|
|
|
video_height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
2024-01-13 09:35:14 +00:00
|
|
|
frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
|
2024-01-13 08:50:03 +00:00
|
|
|
log.info("video: name:'%s', fps:%i, frames:%i, size:%ix%i", args.input, fps, frames, video_width, video_height)
|
2024-01-13 09:35:14 +00:00
|
|
|
if args.distort_end:
|
|
|
|
frames *= (args.distort_end / 100.)
|
|
|
|
with TemporaryDirectory() as tmpout:
|
|
|
|
tmpout = Path(tmpout) / 'tmp.mp4'
|
|
|
|
output = cv2.VideoWriter(str(tmpout), cv2.VideoWriter_fourcc(*'mp4v'), fps, (video_width, video_height))
|
|
|
|
asyncio.run(distort_video(capture, output, args.distort_percentage, args.distort_percentage_end, frames-1))
|
|
|
|
capture.release()
|
|
|
|
output.release()
|
2024-01-20 10:34:59 +00:00
|
|
|
if args.vibrato_frequency is not None and args.vibrato_modulation_depth is not None:
|
|
|
|
distort_audio(tmpout, args.input, args.vibrato_frequency, args.vibrato_modulation_depth, args.output)
|
|
|
|
else:
|
|
|
|
move(tmpout, args.output)
|
2024-01-13 08:50:03 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|
|
|
|
|