This repository has been archived on 2020-08-22. You can view files and clone it, but cannot push or open issues or pull requests.
pyaudviz/src/components/video.py

276 lines
9.4 KiB
Python
Raw Normal View History

from PIL import Image, ImageDraw
from PyQt5 import uic, QtGui, QtCore, QtWidgets
2017-06-06 11:14:39 -04:00
import os
import subprocess
import threading
from queue import PriorityQueue
from . import __base__
class Video:
'''Video Component Frame-Fetcher'''
2017-06-06 20:50:53 -04:00
def __init__(self, **kwargs):
mandatoryArgs = [
2017-06-15 15:09:45 -04:00
'ffmpeg', # path to ffmpeg, usually core.FFMPEG_BIN
'videoPath',
'width',
'height',
2017-06-15 15:09:45 -04:00
'scale', # percentage scale
'frameRate', # frames per second
'chunkSize', # number of bytes in one frame
2017-06-15 15:09:45 -04:00
'parent', # mainwindow object
'component', # component object
]
2017-06-06 20:50:53 -04:00
for arg in mandatoryArgs:
try:
exec('self.%s = kwargs[arg]' % arg)
except KeyError:
raise __base__.BadComponentInit(arg, self.__doc__)
2017-06-06 11:14:39 -04:00
self.frameNo = -1
self.currentFrame = 'None'
2017-06-06 20:50:53 -04:00
if 'loopVideo' in kwargs and kwargs['loopVideo']:
self.loopValue = '-1'
else:
self.loopValue = '0'
self.command = [
2017-06-06 20:50:53 -04:00
self.ffmpeg,
'-thread_queue_size', '512',
2017-06-06 20:50:53 -04:00
'-r', str(self.frameRate),
'-stream_loop', self.loopValue,
2017-06-06 20:50:53 -04:00
'-i', self.videoPath,
'-f', 'image2pipe',
'-pix_fmt', 'rgba',
2017-06-23 23:00:24 -04:00
'-filter:v', 'scale=%s:%s' % scale(
self.scale, self.width, self.height, str),
'-vcodec', 'rawvideo', '-',
]
2017-06-06 11:14:39 -04:00
self.frameBuffer = PriorityQueue()
2017-06-06 20:50:53 -04:00
self.frameBuffer.maxsize = self.frameRate
self.finishedFrames = {}
2017-06-06 11:14:39 -04:00
self.thread = threading.Thread(
target=self.fillBuffer,
name=self.__doc__
)
self.thread.daemon = True
self.thread.start()
2017-06-06 11:14:39 -04:00
def frame(self, num):
while True:
if num in self.finishedFrames:
image = self.finishedFrames.pop(num)
2017-06-15 15:09:45 -04:00
return finalizeFrame(
self.component, image, self.width, self.height)
i, image = self.frameBuffer.get()
self.finishedFrames[i] = image
self.frameBuffer.task_done()
2017-06-06 11:14:39 -04:00
def fillBuffer(self):
2017-06-06 20:50:53 -04:00
pipe = subprocess.Popen(
2017-06-06 11:14:39 -04:00
self.command, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, bufsize=10**8
)
while True:
if self.parent.canceled:
break
self.frameNo += 1
# If we run out of frames, use the last good frame and loop.
if len(self.currentFrame) == 0:
self.frameBuffer.put((self.frameNo-1, self.lastFrame))
continue
2017-06-06 20:50:53 -04:00
self.currentFrame = pipe.stdout.read(self.chunkSize)
if len(self.currentFrame) != 0:
self.frameBuffer.put((self.frameNo, self.currentFrame))
self.lastFrame = self.currentFrame
2017-06-06 11:14:39 -04:00
class Component(__base__.Component):
'''Video'''
modified = QtCore.pyqtSignal(int, dict)
def widget(self, parent):
self.parent = parent
2017-06-03 22:58:40 -04:00
self.settings = parent.settings
2017-06-06 11:14:39 -04:00
page = uic.loadUi(os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'video.ui'
))
2017-06-03 22:58:40 -04:00
self.videoPath = ''
self.x = 0
self.y = 0
self.loopVideo = False
2017-06-06 11:14:39 -04:00
2017-06-03 22:58:40 -04:00
page.lineEdit_video.textChanged.connect(self.update)
page.pushButton_video.clicked.connect(self.pickVideo)
page.checkBox_loop.stateChanged.connect(self.update)
2017-06-15 15:09:45 -04:00
page.checkBox_distort.stateChanged.connect(self.update)
page.spinBox_scale.valueChanged.connect(self.update)
page.spinBox_x.valueChanged.connect(self.update)
page.spinBox_y.valueChanged.connect(self.update)
2017-06-06 11:14:39 -04:00
self.page = page
return page
def update(self):
2017-06-03 22:58:40 -04:00
self.videoPath = self.page.lineEdit_video.text()
self.loopVideo = self.page.checkBox_loop.isChecked()
2017-06-15 15:09:45 -04:00
self.distort = self.page.checkBox_distort.isChecked()
self.scale = self.page.spinBox_scale.value()
self.xPosition = self.page.spinBox_x.value()
self.yPosition = self.page.spinBox_y.value()
self.parent.drawPreview()
super().update()
2017-06-06 11:14:39 -04:00
def previewRender(self, previewWorker):
self.videoFormats = previewWorker.core.videoFormats
width = int(previewWorker.core.settings.value('outputWidth'))
height = int(previewWorker.core.settings.value('outputHeight'))
2017-06-15 15:09:45 -04:00
self.updateChunksize(width, height)
2017-06-06 08:55:22 -04:00
frame = self.getPreviewFrame(width, height)
if not frame:
return self.blankFrame(width, height)
2017-06-06 08:55:22 -04:00
else:
return frame
2017-06-06 11:14:39 -04:00
def preFrameRender(self, **kwargs):
super().preFrameRender(**kwargs)
width = int(self.worker.core.settings.value('outputWidth'))
height = int(self.worker.core.settings.value('outputHeight'))
self.blankFrame_ = self.blankFrame(width, height)
2017-06-15 15:09:45 -04:00
self.updateChunksize(width, height)
2017-06-06 11:14:39 -04:00
self.video = Video(
2017-06-06 20:50:53 -04:00
ffmpeg=self.parent.core.FFMPEG_BIN, videoPath=self.videoPath,
width=width, height=height, chunkSize=self.chunkSize,
frameRate=int(self.settings.value("outputFrameRate")),
2017-06-15 15:09:45 -04:00
parent=self.parent, loopVideo=self.loopVideo,
component=self, scale=self.scale
) if os.path.exists(self.videoPath) else None
2017-06-06 11:14:39 -04:00
def frameRender(self, moduleNo, arrayNo, frameNo):
if self.video:
return self.video.frame(frameNo)
else:
return self.blankFrame_
def loadPreset(self, pr, presetName=None):
super().loadPreset(pr, presetName)
2017-06-03 22:58:40 -04:00
self.page.lineEdit_video.setText(pr['video'])
self.page.checkBox_loop.setChecked(pr['loop'])
2017-06-15 15:09:45 -04:00
self.page.checkBox_distort.setChecked(pr['distort'])
self.page.spinBox_scale.setValue(pr['scale'])
self.page.spinBox_x.setValue(pr['x'])
self.page.spinBox_y.setValue(pr['y'])
2017-06-06 11:14:39 -04:00
def savePreset(self):
2017-06-03 22:58:40 -04:00
return {
'preset': self.currentPreset,
2017-06-06 11:14:39 -04:00
'video': self.videoPath,
'loop': self.loopVideo,
2017-06-15 15:09:45 -04:00
'distort': self.distort,
'scale': self.scale,
'x': self.xPosition,
'y': self.yPosition,
2017-06-03 22:58:40 -04:00
}
2017-06-06 11:14:39 -04:00
2017-06-03 22:58:40 -04:00
def pickVideo(self):
imgDir = self.settings.value("backgroundDir", os.path.expanduser("~"))
2017-06-23 23:00:24 -04:00
filename, _ = QtWidgets.QFileDialog.getOpenFileName(
2017-06-06 11:14:39 -04:00
self.page, "Choose Video",
imgDir, "Video Files (%s)" % " ".join(self.videoFormats)
2017-06-06 11:14:39 -04:00
)
if filename:
2017-06-03 22:58:40 -04:00
self.settings.setValue("backgroundDir", os.path.dirname(filename))
self.page.lineEdit_video.setText(filename)
self.update()
2017-06-06 11:14:39 -04:00
def getPreviewFrame(self, width, height):
2017-06-06 08:55:22 -04:00
if not self.videoPath or not os.path.exists(self.videoPath):
return
2017-06-15 15:09:45 -04:00
command = [
self.parent.core.FFMPEG_BIN,
'-thread_queue_size', '512',
'-i', self.videoPath,
'-f', 'image2pipe',
'-pix_fmt', 'rgba',
2017-06-23 23:00:24 -04:00
'-filter:v', 'scale=%s:%s' % scale(
self.scale, width, height, str),
'-vcodec', 'rawvideo', '-',
'-ss', '90',
'-vframes', '1',
]
2017-06-06 11:14:39 -04:00
pipe = subprocess.Popen(
command, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, bufsize=10**8
)
byteFrame = pipe.stdout.read(self.chunkSize)
2017-06-15 15:09:45 -04:00
frame = finalizeFrame(self, byteFrame, width, height)
pipe.stdout.close()
pipe.kill()
2017-06-15 15:09:45 -04:00
return frame
def updateChunksize(self, width, height):
if self.scale != 100 and not self.distort:
width, height = scale(self.scale, width, height, int)
self.chunkSize = 4*width*height
def command(self, arg):
if not arg.startswith('preset=') and '=' in arg:
key, arg = arg.split('=', 1)
if key == 'path' and os.path.exists(arg):
if os.path.splitext(arg)[1] in self.core.videoFormats:
self.page.lineEdit_video.setText(arg)
self.page.spinBox_scale.setValue(100)
self.page.checkBox_loop.setChecked(True)
return
else:
print("Not a supported video format")
quit(1)
super().command(arg)
def commandHelp(self):
print('Load a video:\n path=/filepath/to/video.mp4')
2017-06-23 23:00:24 -04:00
2017-06-15 15:09:45 -04:00
def scale(scale, width, height, returntype=None):
width = (float(width) / 100.0) * float(scale)
height = (float(height) / 100.0) * float(scale)
if returntype == str:
return (str(int(width)), str(int(height)))
elif returntype == int:
return (int(width), int(height))
else:
return (width, height)
2017-06-23 23:00:24 -04:00
2017-06-15 15:09:45 -04:00
def finalizeFrame(self, imageData, width, height):
if self.distort:
try:
image = Image.frombytes(
'RGBA',
(width, height),
imageData)
except ValueError:
print('#### ignored invalid data caused by distortion ####')
image = self.blankFrame(width, height)
2017-06-15 15:09:45 -04:00
else:
image = Image.frombytes(
'RGBA',
scale(self.scale, width, height, int),
imageData)
if self.scale != 100 \
2017-06-23 23:00:24 -04:00
or self.xPosition != 0 or self.yPosition != 0:
frame = self.blankFrame(width, height)
2017-06-15 15:09:45 -04:00
frame.paste(image, box=(self.xPosition, self.yPosition))
else:
frame = image
return frame