Initial commit
This commit is contained in:
10
pyvidplayer2/.gitignore
vendored
Normal file
10
pyvidplayer2/.gitignore
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
__pycache__/
|
||||
build/
|
||||
dist/
|
||||
*.egg-info/
|
||||
build.txt
|
||||
test.py
|
||||
test.mp4
|
||||
resources/
|
||||
.VSCodeCounter/
|
||||
video/
|
||||
21
pyvidplayer2/LICENSE
Normal file
21
pyvidplayer2/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 ree1261
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
85
pyvidplayer2/README.md
Normal file
85
pyvidplayer2/README.md
Normal file
@@ -0,0 +1,85 @@
|
||||
# pyvidplayer2 (please report all bugs!)
|
||||
|
||||
Introducing pyvidplayer2, the successor to pyvidplayer. It's better in
|
||||
pretty much every way, and finally allows an easy and reliable way to play videos in Python.
|
||||
|
||||
All the features from the original library have been ported over, with the exception of ```alt_resize()```. Since pyvidplayer2 has a completely revamped foundation, the unreliability of ```set_size()``` has been quashed, and a fallback function is now redundant.
|
||||
|
||||
# Features (tested on Windows)
|
||||
- Easy to implement (4 lines of code)
|
||||
- Fast and reliable
|
||||
- Adjust playback speed
|
||||
- No audio/video sync issues
|
||||
- Subtitle support (.srt, .ass, etc)
|
||||
- Play multiple videos in parallel
|
||||
- Built in GUI
|
||||
- Support for Pygame, Pyglet, Tkinter, and PyQT6
|
||||
- Can play all ffmpeg supported video formats
|
||||
- Post process effects
|
||||
- Webcam feed
|
||||
|
||||
# Installation
|
||||
```
|
||||
pip install pyvidplayer2
|
||||
```
|
||||
Note: FFMPEG (just the essentials is fine) must be installed and accessible via the system PATH. Here's an online article on how to do this (windows):
|
||||
https://phoenixnap.com/kb/ffmpeg-windows.
|
||||
|
||||
# Quickstart
|
||||
|
||||
Refer to the examples folder for more basic guides, and documentation.md contains more detailed information.
|
||||
|
||||
```
|
||||
import pygame
|
||||
from pyvidplayer2 import Video
|
||||
|
||||
|
||||
# create video object
|
||||
|
||||
vid = Video("video.mp4")
|
||||
|
||||
win = pygame.display.set_mode(vid.current_size)
|
||||
pygame.display.set_caption(vid.name)
|
||||
|
||||
|
||||
while vid.active:
|
||||
key = None
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
vid.stop()
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
key = pygame.key.name(event.key)
|
||||
|
||||
if key == "r":
|
||||
vid.restart() #rewind video to beginning
|
||||
elif key == "p":
|
||||
vid.toggle_pause() #pause/plays video
|
||||
elif key == "m":
|
||||
vid.toggle_mute() #mutes/unmutes video
|
||||
elif key == "right":
|
||||
vid.seek(15) #skip 15 seconds in video
|
||||
elif key == "left":
|
||||
vid.seek(-15) #rewind 15 seconds in video
|
||||
elif key == "up":
|
||||
vid.set_volume(1.0) #max volume
|
||||
elif key == "down":
|
||||
vid.set_volume(0.0) #min volume
|
||||
elif key == "1":
|
||||
vid.set_speed(1.0) #regular playback speed
|
||||
elif key == "2":
|
||||
vid.set_speed(2.0) #doubles video speed
|
||||
|
||||
# only draw new frames, and only update the screen if something is drawn
|
||||
|
||||
if vid.draw(win, (0, 0), force_draw=False):
|
||||
pygame.display.update()
|
||||
|
||||
pygame.time.wait(16) # around 60 fps
|
||||
|
||||
|
||||
# close video when done
|
||||
|
||||
vid.close()
|
||||
pygame.quit()
|
||||
|
||||
```
|
||||
180
pyvidplayer2/documentation.md
Normal file
180
pyvidplayer2/documentation.md
Normal file
@@ -0,0 +1,180 @@
|
||||
# Video(path, chunk_size=300, max_threads=1, max_chunks=1, subs=None, post_process=PostProcessing.none, interp=cv2.INTER_LINEAR, use_pygame_audio=False)
|
||||
|
||||
Main object used to play videos. It uses FFMPEG to extract chunks of audio from videos and then feeds it into a Pyaudio stream. Finally, it uses OpenCV to display the appropriate video frames. Videos can only be played simultaneously if they're using Pyaudio (see use_pygame_audio below). This object uses Pygame for graphics. See bottom for other supported libraries.
|
||||
|
||||
## Arguments
|
||||
- ```path``` - Path to video file. I tested a few popular video types, such as mkv, mp4, mov, avi, and 3gp, but theoretically anything FFMPEG can extract data from should work.
|
||||
- ```chunk_size``` - How much audio is extracted at a time, in seconds. Increasing this value can mean less total extracts, but slower extracts.
|
||||
- ```max_threads``` - Maximum number of chunks that can be extracted at any given time. Increasing this value can speed up extract at the expense of cpu usage.
|
||||
- ```max_chunks``` - Maximum number of chunks allowed to be extracted and reserved. Increasing this value can help with buffering, but will use more memory.
|
||||
- ```subs``` - Pass a Subtitle class here for the video to display subtitles.
|
||||
- ```post_process``` - Post processing function that is applied whenever a frame is rendered. This is PostProcessing.none by default, which means no alterations are taking place.
|
||||
- ```interp``` - Interpolation technique used when resizing frames. In general, the three main ones are cv2.INTER_LINEAR, which is balanced, cv2.INTER_CUBIC, which is slower but produces better results, and cv2.INTER_AREA, which is better for downscaling.
|
||||
- ```use_pygame_audio``` - Specifies whether to use Pyaudio or Pygame to play audio.
|
||||
|
||||
## Attributes
|
||||
- ```path``` - Same as given argument.
|
||||
- ```name``` - Name of file without the directory and extension.
|
||||
- ```ext``` - Type of video (mp4, mkv, mov, etc).
|
||||
- ```frame``` - Current frame index. Starts from 0.
|
||||
- ```frame_rate``` - How many frames are in one second.
|
||||
- ```frame_count``` - How many total frames there are.
|
||||
- ```frame_delay``` - Time between frames in order to maintain frame rate (in fractions of a second).
|
||||
- ```duration``` - Length of video in seconds.
|
||||
- ```original_size```
|
||||
- ```current_size```
|
||||
- ```aspect_ratio``` - Width divided by height.
|
||||
- ```chunk_size``` - Same as given argument.
|
||||
- ```max_chunks``` - Same as given argument.
|
||||
- ```max_threads``` - Same as given argument.
|
||||
- ```frame_data``` - Current video frame as a NumPy ndarray.
|
||||
- ```frame_surf``` - Current video frame as a Pygame Surface.
|
||||
- ```active``` - Whether the video is currently playing. This is unaffected by pausing and resuming.
|
||||
- ```buffering``` - Whether the video is waiting for audio to extract.
|
||||
- ```paused```
|
||||
- ```muted```
|
||||
- ```speed``` - Float from 0.5 to 10.0 that multiplies the playback speed.
|
||||
- ```subs``` - Same as given argument.
|
||||
- ```post_func``` - Same as given argument.
|
||||
- ```interp``` - Same as given argument.
|
||||
- ```use_pygame_audio``` - Same as given argument.
|
||||
|
||||
## Methods
|
||||
- ```play()```
|
||||
- ```stop()```
|
||||
- ```resize(size)```
|
||||
- ```change_resolution(height)``` - Given a height, the video will scale its width while maintaining aspect ratio.
|
||||
- ```close()``` - Releases resources. Always recommended to call when done.
|
||||
- ```restart() ```
|
||||
- ```set_speed(speed)``` - Accepts a float from 0.5 (half speed) to 10.0 (ten times speed)
|
||||
- ```get_speed()```
|
||||
- ```set_volume(volume)``` - Adjusts the volume of the video, from 0.0 (min) to 1.0 (max).
|
||||
- ```get_volume()```
|
||||
- ```get_paused()```
|
||||
- ```toggle_pause()``` - Pauses if the video is playing, and resumes if the video is paused.
|
||||
- ```pause()```
|
||||
- ```resume()```
|
||||
- ```toggle_mute()```
|
||||
- ```mute()```
|
||||
- ```unmute()```
|
||||
- ```get_pos()``` - Returns the current position in seconds.
|
||||
- ```seek(time, relative=True)``` - Changes the current position in the video. If relative is true, the given time will be added or subtracted to the current time. Otherwise, the current position will be set to the given time exactly. Time must be given in seconds, and seeking will be accurate to one tenth of a second.
|
||||
- ```draw(surf, pos, force_draw=True)``` - Draws the current video frame onto the given surface, at the given position. If force_draw is true, a surface will be drawn every time this is called. Otherwise, only new frames will be drawn. This reduces cpu usage, but will cause flickering if anything is drawn under or above the video. This method also returns whether a frame was drawn.
|
||||
- ```preview()``` - Opens a window and plays the video. This method will hang until the video closes. Videos are played at 60 fps with force_draw disabled.
|
||||
|
||||
# VideoPlayer(video, rect, interactable=True, loop=False, preview_thumbnails=0)
|
||||
|
||||
VideoPlayers are GUI containers for videos. This seeks to mimic standard video players, so clicking it will play/pause playback, and the GUI will only show when the mouse is hovering over it. Only supported for Pygame.
|
||||
|
||||
## Arguments
|
||||
- ```video``` - Video object to play.
|
||||
- ```rect``` - An x, y, width, and height of the VideoPlayer. The topleft corner will be the x, y coordinate.
|
||||
- ```interactable``` - Enables the GUI.
|
||||
- ```loop``` - Whether the contained video will restart after it finishes. If the queue is not empty, the entire queue will loop, not just the current video.
|
||||
- ```preview_thumbnails``` - Number of preview thumbnails loaded and saved in memory. When seeking, a preview window will show the closest loaded frame. The higher this number is, the more frames are loaded, increasing the preview accuracy, but also increasing initial load time and memory usage. Because of this, this value is defaulted to 0, which turns seek previewing off.
|
||||
|
||||
## Attributes
|
||||
- ```video``` - Same as given argument.
|
||||
- ```frame_rect``` - Same as given argument.
|
||||
- ```vid_rect``` - This is the video fitted into the frame_rect while maintaining aspect ratio. Black bars will appear in any unused space.
|
||||
- ```interactable``` - Same as given argument.
|
||||
- ```loop``` - Same as given argument.
|
||||
- ```queue_``` - Videos to play after the current one finishes.
|
||||
- ```preview_thumbnails``` - Same as given argument.
|
||||
|
||||
## Methods
|
||||
- ```zoom_to_fill()``` - Zooms in the video so that the entire frame_rect is filled in, while maintaining aspect ratio.
|
||||
- ```zoom_out()``` - Reverts zoom_to_fill()
|
||||
- ```queue(input)``` - Accepts a path to a video or a Video object and adds it to the queue. Passing a path will not load the video until it becomes the active video. Passing a Video object will cause it to silently load its first audio chunk, so changing videos will be as seamless as possible.
|
||||
- ```get_queue()```
|
||||
- ```resize(size)```
|
||||
- ```move(pos, relative)``` - Moves the VideoPlayer. If relative is true, the given coordinates will be added onto the current coordinates. Otherwise, the current coordinates will be set to the given coordinates.
|
||||
- ```update(events, show_ui=None)``` - Allows the VideoPlayer to make calculations. It must be given the returns of pygame.event.get(). The GUI automatically shows up when your mouse hovers over the video player, so show_ui can be used to override that. This method also returns show_ui.
|
||||
- ```draw(surface)``` - Draws the VideoPlayer onto the given Surface.
|
||||
- ```close()``` - Releases resources. Always recommended to call when done.
|
||||
- ```skip()``` - Moves onto the next video in the queue.
|
||||
- ```get_video()``` - Returns currently playing video.
|
||||
|
||||
# Subtitles(path, colour="white", highlight=(0, 0, 0, 128), font=pygame.font.SysFont("arial", 30), encoding="utf-8-sig")
|
||||
|
||||
Object used for handling subtitles. Only supported for Pygame.
|
||||
|
||||
## Arguments
|
||||
- ```path``` - Path to subtitle file. This can be any file pysubs2 can read, including .srt, .ass, .vtt, and others.
|
||||
- ```colour``` - Colour of text.
|
||||
- ```highlight``` - Background colour of text. Accepts RGBA, so it can be made completely transparent.
|
||||
- ```font``` - Pygame Font or SysFont object used to render Surfaces. This includes the size of the text.
|
||||
- ```encoding``` - Encoding used to open the srt file.
|
||||
- ```offset``` - The higher this number is, the close the subtitle is to the top of the screen.
|
||||
|
||||
## Attributes
|
||||
- ```path``` - Same as given argument.
|
||||
- ```encoding``` - Same as given argument.
|
||||
- ```start``` - Starting timestamp of current subtitle.
|
||||
- ```end``` - Ending timestamp of current subtitle.
|
||||
- ```text``` - Current subtitle text.
|
||||
- ```surf``` - Current text in a Pygame Surface.
|
||||
- ```colour``` - Same as given argument.
|
||||
- ```highlight``` - Same as given argument.
|
||||
- ```font``` - Same as given argument.
|
||||
- ```offset``` - Same as given argument.
|
||||
|
||||
## Methods
|
||||
- ```set_font(font)```
|
||||
- ```get_font()```
|
||||
|
||||
# Webcam(post_process=PostProcessing.none, interp=cv2.INTER_LINEAR, fps=30)
|
||||
|
||||
Object used for displaying a webcam feed. Only supported for Pygame.
|
||||
|
||||
## Arguments
|
||||
- ```post_process``` - Post processing function that is applied whenever a frame is rendered. This is PostProcessing.none by default, which means no alterations are taking place.
|
||||
- ```interp``` - Interpolation technique used when resizing frames. In general, the three main ones are cv2.INTER_LINEAR, which is balanced, cv2.INTER_CUBIC, which is slower but produces better results, and cv2.INTER_AREA, which is better for downscaling.
|
||||
- ```fps``` - Maximum number of frames captured from the webcam per second.
|
||||
|
||||
## Attributes
|
||||
- ```post_process``` - Same as given argument.
|
||||
- ```interp``` - Same as given argument.
|
||||
- ```fps``` - Same as given argument.
|
||||
- ```original_size```
|
||||
- ```current_size```
|
||||
- ```aspect_ratio``` - Width divided by height.
|
||||
- ```active``` - Whether the webcam is currently playing.
|
||||
- ```frame_data``` - Current video frame as a NumPy ndarray.
|
||||
- ```frame_surf``` - Current video frame as a Pygame Surface.
|
||||
|
||||
## Methods
|
||||
- ```play()```
|
||||
- ```stop()```
|
||||
- ```resize(size)```
|
||||
- ```change_resolution(height)``` - Given a height, the video will scale its width while maintaining aspect ratio.
|
||||
- ```close()``` - Releases resources. Always recommended to call when done.
|
||||
- ```get_pos()``` - Returns how long the webcam has been active. Is not reset if webcam is stopped.
|
||||
- ```draw(surf, pos, force_draw=True)``` - Draws the current video frame onto the given surface, at the given position. If force_draw is true, a surface will be drawn every time this is called. Otherwise, only new frames will be drawn. This reduces cpu usage, but will cause flickering if anything is drawn under or above the video. This method also returns whether a frame was drawn.
|
||||
- ```preview()``` - Opens a window and plays the webcam. This method will hang until the window is closed. Videos are played at whatever fps the webcam object is set to.
|
||||
|
||||
# PostProcessing
|
||||
Used to apply various filters to video playback. Mostly for fun. Works across all graphics libraries.
|
||||
- ```none``` - Default. Nothing happens.
|
||||
- ```blur``` - Slightly blurs frames.
|
||||
- ```sharpen``` - An okay-looking sharpen. Looks pretty bad for small resolutions.
|
||||
- ```greyscale``` - Removes colour from frame.
|
||||
- ```noise``` - Adds a static-like filter. Very intensive.
|
||||
- ```letterbox``` - Adds black bars above and below the frame to look more cinematic.
|
||||
- ```cel_shading``` - Thickens borders for a comic book style filter.
|
||||
|
||||
# Supported Graphics Libraries
|
||||
- Pygame (```Video```) <- default and best supported
|
||||
- Tkinter (```VideoTkinter```)
|
||||
- Pyglet (```VideoPyglet```)
|
||||
- PyQT6 (```VideoPyQT```)
|
||||
|
||||
To use other libraries instead of Pygame, use their respective video object. Each preview method will use their respective graphics API to create a window and draw frames. See the examples folder for details. Note that Subtitles, Webcam, and VideoPlayer only work with Pygame installed.
|
||||
|
||||
# Get Version
|
||||
|
||||
```
|
||||
print(pyvidplayer2.get_version_info())
|
||||
```
|
||||
|
||||
Returns a dictionary with the version of pyvidplayer2, FFMPEG, and Pygame.
|
||||
13
pyvidplayer2/examples/all_previews_demo.py
Normal file
13
pyvidplayer2/examples/all_previews_demo.py
Normal file
@@ -0,0 +1,13 @@
|
||||
'''
|
||||
This shows off each graphics api and their respective preview methods
|
||||
'''
|
||||
|
||||
|
||||
from pyvidplayer2 import Video, VideoTkinter, VideoPyglet, VideoPyQT
|
||||
|
||||
PATH = r"resources\trailer1.mp4"
|
||||
|
||||
Video(PATH).preview()
|
||||
VideoTkinter(PATH).preview()
|
||||
VideoPyglet(PATH).preview()
|
||||
VideoPyQT(PATH).preview()
|
||||
7
pyvidplayer2/examples/cel_shading_demo.py
Normal file
7
pyvidplayer2/examples/cel_shading_demo.py
Normal file
@@ -0,0 +1,7 @@
|
||||
'''
|
||||
This is an example of the cel shading post process you can apply to your videos
|
||||
'''
|
||||
|
||||
from pyvidplayer2 import Video, PostProcessing
|
||||
|
||||
Video(r"resources\medic.mov", post_process=PostProcessing.cel_shading).preview()
|
||||
13
pyvidplayer2/examples/custom_post_processing_demo.py
Normal file
13
pyvidplayer2/examples/custom_post_processing_demo.py
Normal file
@@ -0,0 +1,13 @@
|
||||
'''
|
||||
This example shows how you can merge and create new post processing functions
|
||||
'''
|
||||
|
||||
|
||||
from pyvidplayer2 import Video, PostProcessing
|
||||
|
||||
# applies a letterbox, cel shading, and greyscale to video
|
||||
|
||||
def custom_process(data):
|
||||
return PostProcessing.letterbox(PostProcessing.cel_shading(PostProcessing.greyscale(data)))
|
||||
|
||||
Video(r"resources\birds.avi", post_process=custom_process).preview()
|
||||
11
pyvidplayer2/examples/custom_subtitles_demo.py
Normal file
11
pyvidplayer2/examples/custom_subtitles_demo.py
Normal file
@@ -0,0 +1,11 @@
|
||||
'''
|
||||
This is an example of custom subtitle fonts
|
||||
'''
|
||||
|
||||
|
||||
from pyvidplayer2 import Subtitles, Video
|
||||
from pygame.font import Font
|
||||
|
||||
subtitles = Subtitles(r"resources\subs2.srt", font=Font(r"resources\font.ttf", 60), highlight=(255, 0, 0, 128), offset=500)
|
||||
|
||||
Video(r"resources\trailer2.mp4", subs=subtitles).preview()
|
||||
39
pyvidplayer2/examples/many_videos_demo.py
Normal file
39
pyvidplayer2/examples/many_videos_demo.py
Normal file
@@ -0,0 +1,39 @@
|
||||
'''
|
||||
This is an example of a VideoCollection, which allows you to treat a large
|
||||
amount of ParallelVideos as one
|
||||
'''
|
||||
|
||||
|
||||
import pygame
|
||||
from pyvidplayer2 import Video, VideoPlayer
|
||||
|
||||
win = pygame.display.set_mode((1066, 744))
|
||||
pygame.display.set_caption("video collection demo")
|
||||
|
||||
|
||||
videos = [VideoPlayer(Video(r"resources\billiejean.mp4"), (0, 0, 426, 240), interactable=False),
|
||||
VideoPlayer(Video(r"resources\trailer1.mp4"), (426, 0, 256, 144), interactable=False),
|
||||
VideoPlayer(Video(r"resources\medic.mov"), (682, 0, 256, 144), interactable=False),
|
||||
VideoPlayer(Video(r"resources\trailer2.mp4"), (426, 144, 640, 360), interactable=False),
|
||||
VideoPlayer(Video(r"resources\clip.mp4"), (0, 240, 256, 144), interactable=False),
|
||||
VideoPlayer(Video(r"resources\birds.avi"), (0, 384, 426, 240), interactable=False),
|
||||
VideoPlayer(Video(r"resources\ocean.mkv"), (426, 504, 426, 240), interactable=False)]
|
||||
|
||||
while True:
|
||||
key = None
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
[video.close() for video in videos]
|
||||
pygame.quit()
|
||||
exit()
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
key = pygame.key.name(event.key)
|
||||
|
||||
pygame.time.wait(16)
|
||||
|
||||
win.fill("white")
|
||||
|
||||
[video.update() for video in videos]
|
||||
[video.draw(win) for video in videos]
|
||||
|
||||
pygame.display.update()
|
||||
32
pyvidplayer2/examples/parallel_playing_demo.py
Normal file
32
pyvidplayer2/examples/parallel_playing_demo.py
Normal file
@@ -0,0 +1,32 @@
|
||||
'''
|
||||
This is an example of two videos playing simultaneously
|
||||
'''
|
||||
|
||||
import pygame
|
||||
from pyvidplayer2 import Video
|
||||
|
||||
|
||||
win = pygame.display.set_mode((960, 360))
|
||||
pygame.display.set_caption("parallel playing demo")
|
||||
|
||||
vid1 = Video(r"resources\trailer1.mp4")
|
||||
vid1.resize((480, 360))
|
||||
|
||||
vid2 = Video(r"resources\trailer2.mp4")
|
||||
vid2.resize((480, 360))
|
||||
|
||||
|
||||
while True:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
vid1.close()
|
||||
vid2.close()
|
||||
pygame.quit()
|
||||
exit()
|
||||
|
||||
pygame.time.wait(16)
|
||||
|
||||
vid1.draw(win, (0, 0))
|
||||
vid2.draw(win, (480, 0))
|
||||
|
||||
pygame.display.update()
|
||||
32
pyvidplayer2/examples/parallel_subtitles_demo.py
Normal file
32
pyvidplayer2/examples/parallel_subtitles_demo.py
Normal file
@@ -0,0 +1,32 @@
|
||||
'''
|
||||
This example shows how every video can play subtitles
|
||||
'''
|
||||
|
||||
import pygame
|
||||
from pyvidplayer2 import Video, Subtitles
|
||||
|
||||
|
||||
win = pygame.display.set_mode((960, 360))
|
||||
pygame.display.set_caption("parallel subtitles demo")
|
||||
|
||||
vid1 = Video(r"resources\trailer1.mp4", subs=Subtitles(r"resources\subs1.srt"))
|
||||
vid1.resize((480, 360))
|
||||
|
||||
vid2 = Video(r"resources\trailer2.mp4", subs=Subtitles(r"resources\subs2.srt"))
|
||||
vid2.resize((480, 360))
|
||||
|
||||
|
||||
while True:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
vid1.close()
|
||||
vid2.close()
|
||||
pygame.quit()
|
||||
exit()
|
||||
|
||||
pygame.time.wait(16)
|
||||
|
||||
vid1.draw(win, (0, 0))
|
||||
vid2.draw(win, (480, 0))
|
||||
|
||||
pygame.display.update()
|
||||
59
pyvidplayer2/examples/pip_demo.py
Normal file
59
pyvidplayer2/examples/pip_demo.py
Normal file
@@ -0,0 +1,59 @@
|
||||
'''
|
||||
A quick example showing how pyvidplayer2 can be used in more complicated applications
|
||||
This is a Picture-in-Picture app
|
||||
'''
|
||||
|
||||
|
||||
import pygame
|
||||
from win32gui import SetWindowPos, GetCursorPos, GetWindowRect, GetForegroundWindow, SetForegroundWindow
|
||||
from win32api import GetSystemMetrics
|
||||
from win32con import SWP_NOSIZE, HWND_TOPMOST
|
||||
from win32com.client import Dispatch
|
||||
from pyvidplayer2 import VideoPlayer, Video
|
||||
from cv2 import INTER_AREA
|
||||
|
||||
|
||||
SIZE = (426, 240)
|
||||
FILE = r"resources\billiejean.mp4"
|
||||
|
||||
win = pygame.display.set_mode(SIZE, pygame.NOFRAME)
|
||||
|
||||
# creates the video player
|
||||
|
||||
vid = VideoPlayer(Video(FILE, interp=INTER_AREA), (0, 0, *SIZE))
|
||||
|
||||
# moves the window to the bottom right corner and pins it above other windows
|
||||
|
||||
hwnd = pygame.display.get_wm_info()["window"]
|
||||
SetWindowPos(hwnd, HWND_TOPMOST, GetSystemMetrics(0) - SIZE[0], GetSystemMetrics(1) - SIZE[1] - 48, 0, 0, SWP_NOSIZE)
|
||||
|
||||
clock = pygame.time.Clock()
|
||||
|
||||
shell = Dispatch("WScript.Shell")
|
||||
|
||||
while True:
|
||||
events = pygame.event.get()
|
||||
for event in events:
|
||||
if event.type == pygame.QUIT:
|
||||
vid.close()
|
||||
pygame.quit()
|
||||
quit()
|
||||
|
||||
clock.tick(60)
|
||||
|
||||
# allows the ui to be seamlessly interacted with
|
||||
|
||||
touching = pygame.Rect(GetWindowRect(hwnd)).collidepoint(GetCursorPos())
|
||||
if touching and GetForegroundWindow() != hwnd:
|
||||
|
||||
# weird behaviour with SetForegroundWindow that requires the alt key to be pressed before it's called
|
||||
|
||||
shell.SendKeys("%")
|
||||
SetForegroundWindow(hwnd)
|
||||
|
||||
# handles video playback
|
||||
|
||||
vid.update(events, show_ui=touching)
|
||||
vid.draw(win)
|
||||
|
||||
pygame.display.update()
|
||||
10
pyvidplayer2/examples/playback_speed_demo.py
Normal file
10
pyvidplayer2/examples/playback_speed_demo.py
Normal file
@@ -0,0 +1,10 @@
|
||||
'''
|
||||
This example shows how you can control the playback speed of videos
|
||||
'''
|
||||
|
||||
|
||||
from pyvidplayer2 import Video
|
||||
|
||||
v = Video(r"resources\trailer1.mp4")
|
||||
v.set_speed(2) # twice as fast
|
||||
v.preview()
|
||||
42
pyvidplayer2/examples/post_processing_demo.py
Normal file
42
pyvidplayer2/examples/post_processing_demo.py
Normal file
@@ -0,0 +1,42 @@
|
||||
'''
|
||||
This example gives a side by side comparison between a few available post process effects
|
||||
'''
|
||||
|
||||
|
||||
import pygame
|
||||
from pyvidplayer2 import Video, PostProcessing
|
||||
|
||||
PATH = r"resources\ocean.mkv"
|
||||
|
||||
win = pygame.display.set_mode((960, 240))
|
||||
pygame.display.set_caption("post processing demo")
|
||||
|
||||
# using a video collection to play videos in parallel for a side to side comparison
|
||||
|
||||
videos = [Video(PATH, post_process=PostProcessing.sharpen),
|
||||
Video(PATH),
|
||||
Video(PATH, post_process=PostProcessing.blur)]
|
||||
|
||||
font = pygame.font.SysFont("arial", 30)
|
||||
surfs = [font.render("Sharpen", True, "white"), font.render("Normal", True, "white"), font.render("Blur", True, "white")]
|
||||
|
||||
|
||||
while True:
|
||||
key = None
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
[video.close() for video in videos]
|
||||
pygame.quit()
|
||||
exit()
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
key = pygame.key.name(event.key)
|
||||
|
||||
pygame.time.wait(16)
|
||||
|
||||
for i, surf in enumerate(surfs):
|
||||
x = 320 * i
|
||||
videos[i].draw(win, (x, 0))
|
||||
pygame.draw.rect(win, "black", (x, 0, *surf.get_size()))
|
||||
win.blit(surf, (x, 0))
|
||||
|
||||
pygame.display.update()
|
||||
8
pyvidplayer2/examples/preview_demo.py
Normal file
8
pyvidplayer2/examples/preview_demo.py
Normal file
@@ -0,0 +1,8 @@
|
||||
'''
|
||||
This is the quickest and simplest way to play videos
|
||||
'''
|
||||
|
||||
|
||||
from pyvidplayer2 import Video
|
||||
|
||||
Video(r"resources\trailer1.mp4").preview()
|
||||
22
pyvidplayer2/examples/pyglet_demo.py
Normal file
22
pyvidplayer2/examples/pyglet_demo.py
Normal file
@@ -0,0 +1,22 @@
|
||||
'''
|
||||
This is a quick example of integrating a video into a pyglet project
|
||||
Double buffering is turned off to benefit from turning off force draw on the video
|
||||
'''
|
||||
|
||||
|
||||
import pyglet
|
||||
from pyvidplayer2 import VideoPyglet
|
||||
|
||||
video = VideoPyglet(r"resources\trailer1.mp4")
|
||||
|
||||
def update(dt):
|
||||
video.draw((0, 0), force_draw=False)
|
||||
if not video.active:
|
||||
win.close()
|
||||
|
||||
win = pyglet.window.Window(width=video.current_size[0], height=video.current_size[1], config=pyglet.gl.Config(double_buffer=False), caption=f"pyglet support demo")
|
||||
|
||||
pyglet.clock.schedule_interval(update, 1/60.0)
|
||||
|
||||
pyglet.app.run()
|
||||
video.close()
|
||||
33
pyvidplayer2/examples/pyqt6_demo.py
Normal file
33
pyvidplayer2/examples/pyqt6_demo.py
Normal file
@@ -0,0 +1,33 @@
|
||||
'''
|
||||
This is a quick example of integrating a video into a pyqt6 project
|
||||
'''
|
||||
|
||||
|
||||
from PyQt6.QtWidgets import QApplication, QMainWindow, QWidget
|
||||
from PyQt6.QtCore import QTimer
|
||||
from pyvidplayer2 import VideoPyQT
|
||||
|
||||
|
||||
class Window(QMainWindow):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.canvas = QWidget(self)
|
||||
self.setCentralWidget(self.canvas)
|
||||
|
||||
self.timer = QTimer(self)
|
||||
self.timer.timeout.connect(self.update)
|
||||
self.timer.start(16)
|
||||
|
||||
def paintEvent(self, _):
|
||||
video.draw(self, (0, 0))
|
||||
|
||||
|
||||
video = VideoPyQT(r"resources\trailer1.mp4")
|
||||
|
||||
app = QApplication([])
|
||||
win = Window()
|
||||
win.setWindowTitle(f"pyqt6 support demo")
|
||||
win.setFixedSize(*video.current_size)
|
||||
win.show()
|
||||
app.exec()
|
||||
video.close()
|
||||
32
pyvidplayer2/examples/queue_demo.py
Normal file
32
pyvidplayer2/examples/queue_demo.py
Normal file
@@ -0,0 +1,32 @@
|
||||
'''
|
||||
This example shows how videos can be queued and skipped through with the VideoPlayer object
|
||||
'''
|
||||
|
||||
import pygame
|
||||
from pyvidplayer2 import VideoPlayer, Video
|
||||
|
||||
win = pygame.display.set_mode((1280, 720))
|
||||
|
||||
|
||||
vid = VideoPlayer(Video(r"resources\clip.mp4"), (0, 0, 1280, 720), loop=True)
|
||||
|
||||
vid.queue(Video(r"resources\ocean.mkv"))
|
||||
vid.queue(Video(r"resources\birds.avi"))
|
||||
|
||||
|
||||
while True:
|
||||
events = pygame.event.get()
|
||||
for event in events:
|
||||
if event.type == pygame.QUIT:
|
||||
vid.close()
|
||||
pygame.quit()
|
||||
exit()
|
||||
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
|
||||
vid.skip()
|
||||
|
||||
pygame.time.wait(16)
|
||||
|
||||
vid.update(events)
|
||||
vid.draw(win)
|
||||
|
||||
pygame.display.update()
|
||||
8
pyvidplayer2/examples/subtitles_demo.py
Normal file
8
pyvidplayer2/examples/subtitles_demo.py
Normal file
@@ -0,0 +1,8 @@
|
||||
'''
|
||||
This is an example showing how to add subtitles to a video
|
||||
'''
|
||||
|
||||
|
||||
from pyvidplayer2 import Subtitles, Video
|
||||
|
||||
Video(r"resources\trailer2.mp4", subs=Subtitles(r"resources\subs2.srt")).preview()
|
||||
27
pyvidplayer2/examples/tkinter_demo.py
Normal file
27
pyvidplayer2/examples/tkinter_demo.py
Normal file
@@ -0,0 +1,27 @@
|
||||
'''
|
||||
This is a quick example of integrating a video into a tkinter project
|
||||
'''
|
||||
|
||||
|
||||
import tkinter
|
||||
from pyvidplayer2 import VideoTkinter
|
||||
|
||||
video = VideoTkinter(r"resources\trailer1.mp4")
|
||||
|
||||
def update():
|
||||
video.draw(canvas, (video.current_size[0] / 2, video.current_size[1] / 2), force_draw=False)
|
||||
if video.active:
|
||||
root.after(16, update) # for around 60 fps
|
||||
else:
|
||||
root.destroy()
|
||||
|
||||
root = tkinter.Tk()
|
||||
root.title(f"tkinter support demo")
|
||||
|
||||
canvas = tkinter.Canvas(root, width=video.current_size[0], height=video.current_size[1], highlightthickness=0)
|
||||
canvas.pack()
|
||||
|
||||
update()
|
||||
root.mainloop()
|
||||
|
||||
video.close()
|
||||
46
pyvidplayer2/examples/video_demo.py
Normal file
46
pyvidplayer2/examples/video_demo.py
Normal file
@@ -0,0 +1,46 @@
|
||||
'''
|
||||
This is the same example from the original pyvidplayer
|
||||
The video class still does everything it did, but with many more features
|
||||
'''
|
||||
|
||||
|
||||
import pygame
|
||||
from pyvidplayer2 import Video
|
||||
|
||||
pygame.init()
|
||||
win = pygame.display.set_mode((1280, 720))
|
||||
clock = pygame.time.Clock()
|
||||
|
||||
#provide video class with the path to your video
|
||||
vid = Video(r"resources\medic.mov")
|
||||
|
||||
while True:
|
||||
key = None
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
vid.close()
|
||||
pygame.quit()
|
||||
exit()
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
key = pygame.key.name(event.key)
|
||||
|
||||
#your program frame rate does not affect video playback
|
||||
clock.tick(60)
|
||||
|
||||
if key == "r":
|
||||
vid.restart() #rewind video to beginning
|
||||
elif key == "p":
|
||||
vid.toggle_pause() #pause/plays video
|
||||
elif key == "right":
|
||||
vid.seek(15) #skip 15 seconds in video
|
||||
elif key == "left":
|
||||
vid.seek(-15) #rewind 15 seconds in video
|
||||
elif key == "up":
|
||||
vid.set_volume(1.0) #max volume
|
||||
elif key == "down":
|
||||
vid.set_volume(0.0) #min volume
|
||||
|
||||
#draws the video to the given surface, at the given position
|
||||
vid.draw(win, (0, 0), force_draw=False)
|
||||
|
||||
pygame.display.update()
|
||||
30
pyvidplayer2/examples/videoplayer_demo.py
Normal file
30
pyvidplayer2/examples/videoplayer_demo.py
Normal file
@@ -0,0 +1,30 @@
|
||||
'''
|
||||
This is an example of the built in GUI for videos
|
||||
'''
|
||||
|
||||
|
||||
import pygame
|
||||
from pyvidplayer2 import VideoPlayer, Video
|
||||
|
||||
win = pygame.display.set_mode((1124, 868))
|
||||
pygame.display.set_caption("video player demo")
|
||||
|
||||
vid = VideoPlayer(Video(r"resources\ocean.mkv"), (50, 50, 1024, 768), preview_thumbnails=11)
|
||||
|
||||
|
||||
while True:
|
||||
events = pygame.event.get()
|
||||
for event in events:
|
||||
if event.type == pygame.QUIT:
|
||||
vid.close()
|
||||
pygame.quit()
|
||||
exit()
|
||||
|
||||
pygame.time.wait(16)
|
||||
|
||||
win.fill("white")
|
||||
|
||||
vid.update(events)
|
||||
vid.draw(win)
|
||||
|
||||
pygame.display.update()
|
||||
24
pyvidplayer2/examples/webcam_demo.py
Normal file
24
pyvidplayer2/examples/webcam_demo.py
Normal file
@@ -0,0 +1,24 @@
|
||||
'''
|
||||
Webcam example
|
||||
'''
|
||||
|
||||
import pygame
|
||||
from pyvidplayer2 import Webcam
|
||||
|
||||
webcam = Webcam()
|
||||
|
||||
win = pygame.display.set_mode(webcam.current_size)
|
||||
clock = pygame.time.Clock()
|
||||
|
||||
while True:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
webcam.close()
|
||||
pygame.quit()
|
||||
exit()
|
||||
|
||||
clock.tick(60)
|
||||
|
||||
webcam.draw(win, (0, 0), force_draw=False)
|
||||
|
||||
pygame.display.update()
|
||||
49
pyvidplayer2/pyvidplayer2/__init__.py
Normal file
49
pyvidplayer2/pyvidplayer2/__init__.py
Normal file
@@ -0,0 +1,49 @@
|
||||
import subprocess
|
||||
|
||||
from .post_processing import PostProcessing
|
||||
from .video_tkinter import VideoTkinter
|
||||
|
||||
try:
|
||||
import PyQt6
|
||||
except ImportError:
|
||||
pass
|
||||
else:
|
||||
from .video_pyqt import VideoPyQT
|
||||
|
||||
try:
|
||||
import pygame
|
||||
except ImportError:
|
||||
pass
|
||||
else:
|
||||
pygame.init()
|
||||
|
||||
from .video_pygame import VideoPygame as Video
|
||||
from .subtitles import Subtitles
|
||||
from .video_player import VideoPlayer
|
||||
from .webcam import Webcam
|
||||
|
||||
try:
|
||||
import pyglet
|
||||
except ImportError:
|
||||
pass
|
||||
else:
|
||||
from .video_pyglet import VideoPyglet
|
||||
|
||||
|
||||
_VERSION = "0.9.11"
|
||||
|
||||
|
||||
def get_version_info() -> dict:
|
||||
try:
|
||||
pygame_ver = pygame.version.ver
|
||||
except NameError:
|
||||
pygame_ver = "not installed"
|
||||
|
||||
try:
|
||||
ffmpeg_ver = subprocess.run(["ffmpeg", "-version"], capture_output=True, universal_newlines=True).stdout.split(" ")[2]
|
||||
except FileNotFoundError:
|
||||
ffmpeg_ver = "not installed"
|
||||
|
||||
return {"pyvidplayer2": _VERSION,
|
||||
"ffmpeg": ffmpeg_ver,
|
||||
"pygame": pygame_ver}
|
||||
2
pyvidplayer2/pyvidplayer2/error.py
Normal file
2
pyvidplayer2/pyvidplayer2/error.py
Normal file
@@ -0,0 +1,2 @@
|
||||
class Pyvidplayer2Error(Exception):
|
||||
pass
|
||||
50
pyvidplayer2/pyvidplayer2/mixer_handler.py
Normal file
50
pyvidplayer2/pyvidplayer2/mixer_handler.py
Normal file
@@ -0,0 +1,50 @@
|
||||
import pygame
|
||||
from io import BytesIO
|
||||
|
||||
|
||||
class MixerHandler:
|
||||
def __init__(self) -> None:
|
||||
self.muted = False
|
||||
self.volume = 1
|
||||
|
||||
def get_busy(self):
|
||||
return pygame.mixer.music.get_busy()
|
||||
|
||||
def load(self, bytes):
|
||||
pygame.mixer.music.load(BytesIO(bytes))
|
||||
|
||||
def unload(self):
|
||||
self.stop()
|
||||
pygame.mixer.music.unload()
|
||||
|
||||
def play(self):
|
||||
pygame.mixer.music.play()
|
||||
|
||||
def set_volume(self, vol):
|
||||
self.volume = vol
|
||||
pygame.mixer.music.set_volume(min(1.0, max(0.0, vol)))
|
||||
|
||||
def get_volume(self):
|
||||
return self.volume
|
||||
|
||||
def get_pos(self):
|
||||
return max(0, pygame.mixer.music.get_pos()) / 1000
|
||||
|
||||
def stop(self):
|
||||
pygame.mixer.music.stop()
|
||||
|
||||
def pause(self):
|
||||
pygame.mixer.music.pause()
|
||||
|
||||
def unpause(self):
|
||||
# unpausing the mixer when nothing has been loaded causes weird behaviour
|
||||
if pygame.mixer.music.get_pos() != -1:
|
||||
pygame.mixer.music.unpause()
|
||||
|
||||
def mute(self):
|
||||
self.muted = True
|
||||
pygame.mixer.music.set_volume(0)
|
||||
|
||||
def unmute(self):
|
||||
self.muted = False
|
||||
self.set_volume(self.volume)
|
||||
33
pyvidplayer2/pyvidplayer2/post_processing.py
Normal file
33
pyvidplayer2/pyvidplayer2/post_processing.py
Normal file
@@ -0,0 +1,33 @@
|
||||
import cv2
|
||||
import numpy
|
||||
|
||||
|
||||
class PostProcessing:
|
||||
def none(data: numpy.ndarray) -> numpy.ndarray:
|
||||
return data
|
||||
|
||||
def blur(data: numpy.ndarray) -> numpy.ndarray:
|
||||
return cv2.blur(data, (5, 5))
|
||||
|
||||
def sharpen(data: numpy.ndarray) -> numpy.ndarray:
|
||||
return cv2.filter2D(data, -1, numpy.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]]))
|
||||
|
||||
def greyscale(data: numpy.ndarray) -> numpy.ndarray:
|
||||
return numpy.stack((cv2.cvtColor(data, cv2.COLOR_BGR2GRAY),) * 3, axis=-1)
|
||||
|
||||
def noise(data: numpy.ndarray) -> numpy.ndarray:
|
||||
noise = numpy.zeros(data.shape, dtype=numpy.uint8)
|
||||
cv2.randn(noise, (0,) * 3, (20,) * 3)
|
||||
return data + noise
|
||||
|
||||
def letterbox(data: numpy.ndarray) -> numpy.ndarray:
|
||||
background = numpy.zeros((*data.shape[:2], 3), dtype=numpy.uint8)
|
||||
|
||||
x1, y1 = 0, int(data.shape[0] * 0.1) #topleft crop
|
||||
x2, y2 = data.shape[1], int(data.shape[0] * 0.9) #bottomright crop
|
||||
data = data[y1:y2, x1:x2] # crops image
|
||||
background[y1:y1 + data.shape[0], x1:x1 + data.shape[1]] = data # draws image onto background
|
||||
return background
|
||||
|
||||
def cel_shading(data: numpy.ndarray) -> numpy.ndarray:
|
||||
return cv2.subtract(data, cv2.blur(cv2.merge((cv2.Canny(data, 150, 200),) * 3), (2, 2)))
|
||||
125
pyvidplayer2/pyvidplayer2/pyaudio_handler.py
Normal file
125
pyvidplayer2/pyvidplayer2/pyaudio_handler.py
Normal file
@@ -0,0 +1,125 @@
|
||||
import pyaudio
|
||||
import wave
|
||||
import math
|
||||
import time
|
||||
import numpy
|
||||
from threading import Thread
|
||||
from io import BytesIO
|
||||
|
||||
|
||||
class PyaudioHandler:
|
||||
def __init__(self) -> None:
|
||||
self.stream = None
|
||||
self.wave = None
|
||||
|
||||
self.thread = None
|
||||
self.stop_thread = False
|
||||
|
||||
self.position = 0
|
||||
|
||||
self.loaded = False
|
||||
self.paused = False
|
||||
self.active = False
|
||||
|
||||
self.volume = 1.0
|
||||
self.muted = False
|
||||
|
||||
self.p = pyaudio.PyAudio()
|
||||
self.stream = None
|
||||
|
||||
def get_busy(self):
|
||||
return self.active
|
||||
|
||||
def load(self, bytes):
|
||||
self.unload()
|
||||
|
||||
try:
|
||||
self.wave = wave.open(BytesIO(bytes), "rb")
|
||||
except EOFError:
|
||||
raise EOFError("Audio is empty. This may mean the file is corrupted.")
|
||||
|
||||
if self.stream is None:
|
||||
self.stream = self.p.open(
|
||||
format=self.p.get_format_from_width(self.wave.getsampwidth()),
|
||||
channels=self.wave.getnchannels(),
|
||||
rate=self.wave.getframerate(),
|
||||
output=True)
|
||||
|
||||
self.loaded = True
|
||||
|
||||
def close(self):
|
||||
self.stream.stop_stream()
|
||||
self.stream.close()
|
||||
self.p.terminate()
|
||||
|
||||
def unload(self):
|
||||
if self.loaded:
|
||||
self.stop()
|
||||
|
||||
self.wave.close()
|
||||
|
||||
self.wave = None
|
||||
self.thread = None
|
||||
|
||||
self.loaded = False
|
||||
|
||||
def play(self):
|
||||
self.stop_thread = False
|
||||
self.position = 0
|
||||
self.active = True
|
||||
|
||||
self.wave.rewind()
|
||||
self.thread = Thread(target=self._threaded_play)
|
||||
|
||||
self.thread.start()
|
||||
|
||||
def _threaded_play(self):
|
||||
chunk = 2048
|
||||
data = self.wave.readframes(chunk)
|
||||
|
||||
while data != b'' and not self.stop_thread:
|
||||
|
||||
if self.paused:
|
||||
time.sleep(0.01)
|
||||
else:
|
||||
audio = numpy.frombuffer(data, dtype=numpy.int16)
|
||||
|
||||
if self.volume == 0.0 or self.muted:
|
||||
audio = numpy.zeros_like(audio)
|
||||
else:
|
||||
db = 20 * math.log10(self.volume)
|
||||
audio = (audio * 10**(db/20)).astype(numpy.int16)
|
||||
|
||||
self.stream.write(audio.tobytes())
|
||||
data = self.wave.readframes(chunk)
|
||||
|
||||
self.position += chunk / self.wave.getframerate()
|
||||
|
||||
self.active = False
|
||||
|
||||
def set_volume(self, vol):
|
||||
self.volume = min(1.0, max(0.0, vol))
|
||||
|
||||
def get_volume(self):
|
||||
return self.volume
|
||||
|
||||
def get_pos(self):
|
||||
return self.position
|
||||
|
||||
def stop(self):
|
||||
if self.loaded:
|
||||
self.stop_thread = True
|
||||
self.thread.join()
|
||||
self.position = 0
|
||||
|
||||
def pause(self):
|
||||
self.paused = True
|
||||
|
||||
def unpause(self):
|
||||
self.paused = False
|
||||
|
||||
def mute(self):
|
||||
self.muted = True
|
||||
|
||||
def unmute(self):
|
||||
self.muted = False
|
||||
68
pyvidplayer2/pyvidplayer2/subtitles.py
Normal file
68
pyvidplayer2/pyvidplayer2/subtitles.py
Normal file
@@ -0,0 +1,68 @@
|
||||
import pygame
|
||||
import pysubs2
|
||||
|
||||
|
||||
class Subtitles:
|
||||
def __init__(self, path: str, colour="white", highlight=(0, 0, 0, 128), font=pygame.font.SysFont("arial", 30), encoding="utf-8", offset=50) -> None:
|
||||
self.path = path
|
||||
self.encoding = encoding
|
||||
|
||||
self._subs = iter(pysubs2.load(path, encoding=encoding))
|
||||
|
||||
self.start = 0
|
||||
self.end = 0
|
||||
self.text = ""
|
||||
self.surf = pygame.Surface((0, 0))
|
||||
self.offset = offset
|
||||
|
||||
self.colour = colour
|
||||
self.highlight = highlight
|
||||
self.font = font
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"<Subtitles(path={self.path})>"
|
||||
|
||||
def _to_surf(self, text: str) -> pygame.Surface:
|
||||
h = self.font.render(" ", True, "black").get_height()
|
||||
|
||||
lines = text.strip().split("\n")
|
||||
surfs = [self.font.render(line, True, self.colour) for line in lines]
|
||||
|
||||
surface = pygame.Surface((max([s.get_width() for s in surfs]), len(surfs) * h), pygame.SRCALPHA)
|
||||
surface.fill(self.highlight)
|
||||
for i, surf in enumerate(surfs):
|
||||
surface.blit(surf, (surface.get_width() / 2 - surf.get_width() / 2, i * h))
|
||||
|
||||
return surface
|
||||
|
||||
def _get_next(self) -> bool:
|
||||
try:
|
||||
s = next(self._subs)
|
||||
except StopIteration:
|
||||
self.start = 0
|
||||
self.end = 0
|
||||
self.text = ""
|
||||
self.surf = pygame.Surface((0, 0))
|
||||
return False
|
||||
else:
|
||||
self.start = s.start / 1000
|
||||
self.end = s.end / 1000
|
||||
self.text = s.plaintext
|
||||
self.surf = self._to_surf(self.text)
|
||||
return True
|
||||
|
||||
def _seek(self, time: float) -> None:
|
||||
self._subs = iter(pysubs2.load(self.path, encoding=self.encoding))
|
||||
|
||||
while not (self.start <= time <= self.end):
|
||||
if not self._get_next():
|
||||
break
|
||||
|
||||
def _write_subs(self, surf: pygame.Surface) -> None:
|
||||
surf.blit(self.surf, (surf.get_width() / 2 - self.surf.get_width() / 2, surf.get_height() - self.surf.get_height() - self.offset))
|
||||
|
||||
def set_font(self, font: pygame.font.SysFont) -> None:
|
||||
self.font = font
|
||||
|
||||
def get_font(self) -> pygame.font.SysFont:
|
||||
return self.font
|
||||
299
pyvidplayer2/pyvidplayer2/video.py
Normal file
299
pyvidplayer2/pyvidplayer2/video.py
Normal file
@@ -0,0 +1,299 @@
|
||||
import cv2
|
||||
import subprocess
|
||||
import os
|
||||
from typing import Tuple
|
||||
from threading import Thread
|
||||
from .pyaudio_handler import PyaudioHandler
|
||||
|
||||
try:
|
||||
import pygame
|
||||
except ImportError:
|
||||
pass
|
||||
else:
|
||||
from .mixer_handler import MixerHandler
|
||||
|
||||
|
||||
class Video:
|
||||
def __init__(self, path: str, chunk_size, max_threads, max_chunks, subs, post_process, interp, use_pygame_audio) -> None:
|
||||
|
||||
self.path = path
|
||||
self.name, self.ext = os.path.splitext(os.path.basename(self.path))
|
||||
|
||||
self._vid = cv2.VideoCapture(self.path)
|
||||
|
||||
if not self._vid.isOpened():
|
||||
raise FileNotFoundError(f'Could not find "{self.path}"')
|
||||
|
||||
# file information
|
||||
|
||||
self.frame_count = int(self._vid.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
self.frame_rate = self._vid.get(cv2.CAP_PROP_FPS)
|
||||
self.frame_delay = 1 / self.frame_rate
|
||||
self.duration = self.frame_count / self.frame_rate
|
||||
self.original_size = (int(self._vid.get(cv2.CAP_PROP_FRAME_WIDTH)), int(self._vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))
|
||||
self.current_size = self.original_size
|
||||
self.aspect_ratio = self.original_size[0] / self.original_size[1]
|
||||
|
||||
self.chunk_size = chunk_size
|
||||
self.max_chunks = max_chunks
|
||||
self.max_threads = max_threads
|
||||
|
||||
self._chunks = []
|
||||
self._threads = []
|
||||
self._starting_time = 0
|
||||
self._chunks_claimed = 0
|
||||
self._chunks_played = 0
|
||||
self._stop_loading = False
|
||||
self.frame = 0
|
||||
|
||||
self.frame_data = None
|
||||
self.frame_surf = None
|
||||
|
||||
self.active = False
|
||||
self.buffering = False
|
||||
self.paused = False
|
||||
self.muted = False
|
||||
|
||||
self.subs = subs
|
||||
self.post_func = post_process
|
||||
self.interp = interp
|
||||
self.use_pygame_audio = use_pygame_audio
|
||||
|
||||
if use_pygame_audio:
|
||||
try:
|
||||
self._audio = MixerHandler()
|
||||
except NameError:
|
||||
raise ModuleNotFoundError("Unable to use Pygame audio because Pygame is not installed.")
|
||||
else:
|
||||
self._audio = PyaudioHandler()
|
||||
|
||||
self.speed = 1
|
||||
|
||||
self._missing_ffmpeg = False # for throwing errors
|
||||
|
||||
self.play()
|
||||
|
||||
def _chunks_len(self) -> int:
|
||||
i = 0
|
||||
for c in self._chunks:
|
||||
if c is not None:
|
||||
i += 1
|
||||
return i
|
||||
|
||||
def _convert_seconds(self, seconds: float) -> str:
|
||||
h = int(seconds // 3600)
|
||||
seconds = seconds % 3600
|
||||
m = int(seconds // 60)
|
||||
s = int(seconds % 60)
|
||||
d = round(seconds % 1, 1)
|
||||
return f"{h}:{m}:{s}.{int(d * 10)}"
|
||||
|
||||
def _threaded_load(self, index) -> None:
|
||||
i = index # assigned to variable so another thread does not change it
|
||||
|
||||
self._chunks.append(None)
|
||||
|
||||
s = self._convert_seconds((self._starting_time + (self._chunks_claimed - 1) * self.chunk_size) * (1 / self.speed))
|
||||
|
||||
command = [
|
||||
"ffmpeg",
|
||||
"-i",
|
||||
self.path,
|
||||
"-ss",
|
||||
str(s),
|
||||
"-t",
|
||||
str(self._convert_seconds(self.chunk_size)),
|
||||
"-vn",
|
||||
"-f",
|
||||
"wav",
|
||||
"-loglevel",
|
||||
"quiet",
|
||||
"-"
|
||||
]
|
||||
|
||||
filters = []
|
||||
if self.speed != 1:
|
||||
filters += ["-filter:a", f"atempo={self.speed}"]
|
||||
|
||||
command = command[:7] + filters + command[7:]
|
||||
|
||||
try:
|
||||
p = subprocess.run(command, capture_output=True)
|
||||
except FileNotFoundError:
|
||||
self._missing_ffmpeg = True
|
||||
|
||||
self._chunks[i - self._chunks_played - 1] = p.stdout
|
||||
|
||||
def _update_threads(self) -> None:
|
||||
for t in self._threads:
|
||||
if not t.is_alive():
|
||||
self._threads.remove(t)
|
||||
|
||||
self._stop_loading = self._starting_time + self._chunks_claimed * self.chunk_size >= self.duration
|
||||
if not self._stop_loading and len(self._threads) < self.max_threads and self._chunks_len() + len(self._threads) < self.max_chunks:
|
||||
self._chunks_claimed += 1
|
||||
self._threads.append(Thread(target=self._threaded_load, args=(self._chunks_claimed,)))
|
||||
self._threads[-1].start()
|
||||
|
||||
def _write_subs(self) -> None:
|
||||
p = self.get_pos()
|
||||
|
||||
if p >= self.subs.start:
|
||||
if p > self.subs.end:
|
||||
if self.subs._get_next():
|
||||
self._write_subs()
|
||||
else:
|
||||
self.subs._write_subs(self.frame_surf)
|
||||
|
||||
def _update(self) -> bool:
|
||||
if self._missing_ffmpeg:
|
||||
raise FileNotFoundError("Could not find FFMPEG. Make sure it's downloaded and accessible via $PATH.")
|
||||
|
||||
self._update_threads()
|
||||
|
||||
n = False
|
||||
self.buffering = False
|
||||
|
||||
if self._audio.get_busy() or self.paused:
|
||||
|
||||
while self.get_pos() > self.frame * self.frame_delay:
|
||||
|
||||
has_frame, data = self._vid.read()
|
||||
self.frame += 1
|
||||
|
||||
if has_frame:
|
||||
if self.original_size != self.current_size:
|
||||
data = cv2.resize(data, dsize=self.current_size, interpolation=self.interp)
|
||||
data = self.post_func(data)
|
||||
|
||||
self.frame_data = data
|
||||
self.frame_surf = self._create_frame(data)
|
||||
|
||||
if self.subs is not None:
|
||||
self._write_subs()
|
||||
|
||||
n = True
|
||||
else:
|
||||
break
|
||||
|
||||
elif self.active:
|
||||
if self._chunks and self._chunks[0] is not None:
|
||||
self._chunks_played += 1
|
||||
self._audio.load(self._chunks.pop(0))
|
||||
self._audio.play()
|
||||
elif self._stop_loading and self._chunks_played == self._chunks_claimed:
|
||||
self.stop()
|
||||
else:
|
||||
self.buffering = True
|
||||
|
||||
return n
|
||||
|
||||
def mute(self) -> None:
|
||||
self.muted = True
|
||||
self._audio.mute()
|
||||
|
||||
def unmute(self) -> None:
|
||||
self.muted = False
|
||||
self._audio.unmute()
|
||||
|
||||
def set_speed(self, speed: float) -> None:
|
||||
speed = max(0.5, min(10, speed))
|
||||
if speed != self.speed:
|
||||
self.speed = speed
|
||||
self.seek(0) # must reload audio chunks
|
||||
|
||||
def get_speed(self) -> float:
|
||||
return self.speed
|
||||
|
||||
def play(self) -> None:
|
||||
self.active = True
|
||||
|
||||
def stop(self) -> None:
|
||||
self.restart()
|
||||
self.active = False
|
||||
self.frame_data = None
|
||||
self.frame_surf = None
|
||||
self.paused = False
|
||||
|
||||
def resize(self, size: Tuple[int, int]) -> None:
|
||||
self.current_size = size
|
||||
|
||||
def change_resolution(self, height: int) -> None:
|
||||
self.current_size = (int(height * self.aspect_ratio), height)
|
||||
|
||||
def close(self) -> None:
|
||||
self.stop()
|
||||
self._vid.release()
|
||||
self._audio.unload()
|
||||
for t in self._threads:
|
||||
t.join()
|
||||
if not self.use_pygame_audio:
|
||||
self._audio.close()
|
||||
|
||||
def restart(self) -> None:
|
||||
self.seek(0, relative=False)
|
||||
self.play()
|
||||
|
||||
def set_volume(self, vol: float) -> None:
|
||||
self._audio.set_volume(vol)
|
||||
|
||||
def get_volume(self) -> float:
|
||||
return self._audio.get_volume()
|
||||
|
||||
def get_paused(self) -> bool:
|
||||
# here because the original pyvidplayer had get_paused
|
||||
return self.paused
|
||||
|
||||
def toggle_pause(self) -> None:
|
||||
self.resume() if self.paused else self.pause()
|
||||
|
||||
def toggle_mute(self) -> None:
|
||||
self.unmute() if self.muted else self.mute()
|
||||
|
||||
def pause(self) -> None:
|
||||
if self.active:
|
||||
self.paused = True
|
||||
self._audio.pause()
|
||||
|
||||
def resume(self) -> None:
|
||||
if self.active:
|
||||
self.paused = False
|
||||
self._audio.unpause()
|
||||
|
||||
def get_pos(self) -> float:
|
||||
return self._starting_time + max(0, self._chunks_played - 1) * self.chunk_size + self._audio.get_pos() * self.speed
|
||||
|
||||
def seek(self, time: float, relative=True) -> None:
|
||||
# seeking accurate to 1 tenth of a second
|
||||
|
||||
self._starting_time = (self.get_pos() + time) if relative else time
|
||||
self._starting_time = round(min(max(0, self._starting_time), self.duration), 1)
|
||||
|
||||
for t in self._threads:
|
||||
t.join()
|
||||
self._chunks = []
|
||||
self._threads = []
|
||||
self._chunks_claimed = 0
|
||||
self._chunks_played = 0
|
||||
|
||||
self._audio.unload()
|
||||
|
||||
self._vid.set(cv2.CAP_PROP_POS_FRAMES, self._starting_time * self.frame_rate)
|
||||
self.frame = int(self._vid.get(cv2.CAP_PROP_POS_FRAMES))
|
||||
if self.subs is not None:
|
||||
self.subs._seek(self._starting_time)
|
||||
|
||||
def draw(self, surf, pos: Tuple[int, int], force_draw=True) -> bool:
|
||||
if (self._update() or force_draw) and self.frame_surf is not None:
|
||||
self._render_frame(surf, pos)
|
||||
return True
|
||||
return False
|
||||
|
||||
def _create_frame(self):
|
||||
pass
|
||||
|
||||
def _render_frame(self):
|
||||
pass
|
||||
|
||||
def preview(self):
|
||||
pass
|
||||
259
pyvidplayer2/pyvidplayer2/video_player.py
Normal file
259
pyvidplayer2/pyvidplayer2/video_player.py
Normal file
@@ -0,0 +1,259 @@
|
||||
import pygame
|
||||
import cv2
|
||||
import math
|
||||
from typing import Tuple, List
|
||||
from . import Video
|
||||
|
||||
|
||||
class VideoPlayer:
|
||||
def __init__(self, video: Video, rect: Tuple[int, int, int, int], interactable=True, loop=False, preview_thumbnails=0) -> None:
|
||||
|
||||
self.video = video
|
||||
self.frame_rect = pygame.Rect(rect)
|
||||
self.interactable = interactable
|
||||
self.loop = loop
|
||||
self.preview_thumbnails = min(max(preview_thumbnails, 0), self.video.frame_count)
|
||||
self._show_intervals = self.preview_thumbnails != 0
|
||||
|
||||
self.vid_rect = pygame.Rect(0, 0, 0, 0)
|
||||
self._progress_back = pygame.Rect(0, 0, 0, 0)
|
||||
self._progress_bar = pygame.Rect(0, 0, 0, 0)
|
||||
self._smooth_bar = 0 # used for making the progress bar look smooth when seeking
|
||||
self._font = pygame.font.SysFont("arial", 0)
|
||||
|
||||
self._buffer_rect = pygame.Rect(0, 0, 0, 0)
|
||||
self._buffer_angle = 0
|
||||
|
||||
self._transform(self.frame_rect)
|
||||
|
||||
self._show_ui = False
|
||||
self.queue_ = []
|
||||
|
||||
self._clock = pygame.time.Clock()
|
||||
|
||||
self._seek_pos = 0
|
||||
self._seek_time = 0
|
||||
self._show_seek = False
|
||||
|
||||
self._fade_timer = 0
|
||||
|
||||
if self._show_intervals:
|
||||
self._interval = self.video.duration / self.preview_thumbnails
|
||||
self._interval_frames = []
|
||||
self._get_interval_frames()
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"<VideoPlayer(path={self.path})>"
|
||||
|
||||
def _close_queue(self):
|
||||
for video in self.queue_:
|
||||
try:
|
||||
video.close()
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
def _get_interval_frames(self):
|
||||
size = (int(70 * self.video.aspect_ratio), 70)
|
||||
for i in range(self.preview_thumbnails):
|
||||
self.video._vid.set(cv2.CAP_PROP_POS_FRAMES, int(i * self.video.frame_rate * self._interval))
|
||||
|
||||
self._interval_frames.append(pygame.image.frombuffer(cv2.resize(self.video._vid.read()[1], dsize=size, interpolation=cv2.INTER_AREA).tobytes(), size, "BGR"))
|
||||
|
||||
# add last readable frame
|
||||
|
||||
i = 1
|
||||
while True:
|
||||
self.video._vid.set(cv2.CAP_PROP_POS_FRAMES, self.video.frame_count - i)
|
||||
try:
|
||||
self._interval_frames.append(pygame.image.frombuffer(cv2.resize(self.video._vid.read()[1], dsize=size, interpolation=cv2.INTER_AREA).tobytes(), size, "BGR"))
|
||||
except:
|
||||
i += 1
|
||||
else:
|
||||
break
|
||||
|
||||
self.video._vid.set(cv2.CAP_PROP_POS_FRAMES, 0)
|
||||
|
||||
def _get_closest_frame(self, time):
|
||||
i = math.floor(time // self._interval)
|
||||
if (i + 1) * self._interval - time >= self._interval // 2:
|
||||
return self._interval_frames[i]
|
||||
else:
|
||||
return self._interval_frames[i + 1]
|
||||
|
||||
def _best_fit(self, rect: pygame.Rect, r: float) -> pygame.Rect:
|
||||
s = rect.size
|
||||
r = self.video.aspect_ratio
|
||||
|
||||
w = s[0]
|
||||
h = int(w / r)
|
||||
y = int(s[1] /2 - h / 2)
|
||||
x = 0
|
||||
if h > s[1]:
|
||||
h = s[1]
|
||||
w = int(h * r)
|
||||
x = int(s[0] / 2 - w / 2)
|
||||
y = 0
|
||||
|
||||
return pygame.Rect(rect.x + x, rect.y + y, w, h)
|
||||
|
||||
def _transform(self, rect: pygame.Rect) -> None:
|
||||
self.frame_rect = rect
|
||||
self.vid_rect = self._best_fit(self.frame_rect, self.video.aspect_ratio)
|
||||
self.video.resize(self.vid_rect.size)
|
||||
|
||||
self._progress_back = pygame.Rect(self.frame_rect.x + 10, self.frame_rect.bottom - 25, self.frame_rect.w - 20, 15)
|
||||
self._progress_bar = self._progress_back.copy()
|
||||
|
||||
self._font = pygame.font.SysFont("arial", 10)
|
||||
|
||||
if self.video.frame_data is not None:
|
||||
self.video.frame_surf = pygame.transform.smoothscale(self.video.frame_surf, self.vid_rect.size)
|
||||
|
||||
self._buffer_rect = pygame.Rect(0, 0, 200, 200)
|
||||
self._buffer_rect.center = self.frame_rect.center
|
||||
|
||||
def _move_angle(self, pos: Tuple[int, int], angle: float, distance: int) -> Tuple[float, float]:
|
||||
return pos[0] + math.cos(angle) * distance, pos[1] + math.sin(angle) * distance
|
||||
|
||||
def _convert_seconds(self, time: float) -> str:
|
||||
return self.video._convert_seconds(time).split(".")[0]
|
||||
|
||||
def zoom_to_fill(self):
|
||||
s = max(abs(self.frame_rect.w - self.vid_rect.w), abs(self.frame_rect.h - self.vid_rect.h))
|
||||
self.vid_rect.inflate_ip(s, s)
|
||||
self.video.resize(self.vid_rect.size)
|
||||
self.vid_rect.center = self.frame_rect.center
|
||||
|
||||
def zoom_out(self):
|
||||
self.vid_rect = self._best_fit(self.frame_rect, self.video.aspect_ratio)
|
||||
self.video.resize(self.vid_rect.size)
|
||||
|
||||
def queue(self, input_: str | Video) -> None:
|
||||
self.queue_.append(input_)
|
||||
|
||||
# update once to trigger audio loading
|
||||
try:
|
||||
input_.stop()
|
||||
input_._update()
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
def resize(self, size: Tuple[int, int]) -> None:
|
||||
self.frame_rect.size = size
|
||||
self._transform(self.frame_rect)
|
||||
|
||||
def move(self, pos: Tuple[int, int], relative=False) -> None:
|
||||
if relative:
|
||||
self.frame_rect.move_ip(*pos)
|
||||
else:
|
||||
self.frame_rect.topleft = pos
|
||||
self._transform(self.frame_rect)
|
||||
|
||||
def update(self, events: List[pygame.event.Event] = None, show_ui=None) -> bool:
|
||||
dt = self._clock.tick()
|
||||
|
||||
if not self.video.active:
|
||||
if self.queue_:
|
||||
if self.loop:
|
||||
self.queue(self.video)
|
||||
input_ = self.queue_.pop(0)
|
||||
try:
|
||||
self.video = Video(input_)
|
||||
except TypeError:
|
||||
self.video = input_
|
||||
self.video.play()
|
||||
self._transform(self.frame_rect)
|
||||
elif self.loop:
|
||||
self.video.restart()
|
||||
|
||||
if self.video._update() and self.video.current_size > self.frame_rect.size:
|
||||
self.video.frame_surf = self.video.frame_surf.subsurface(self.frame_rect.x - self.vid_rect.x, self.frame_rect.y - self.vid_rect.y, *self.frame_rect.size)
|
||||
|
||||
if self.interactable:
|
||||
|
||||
mouse = pygame.mouse.get_pos()
|
||||
click = False
|
||||
for event in events:
|
||||
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
|
||||
click = True
|
||||
|
||||
self._show_ui = self.frame_rect.collidepoint(mouse) if show_ui is None else show_ui
|
||||
|
||||
if self._show_ui:
|
||||
self._progress_bar.w = self._progress_back.w * (self.video.get_pos() / self.video.duration)
|
||||
self._smooth_bar += (self._progress_bar.w - self._smooth_bar) / (dt * 0.25)
|
||||
self._show_seek = self._progress_back.collidepoint(mouse)
|
||||
|
||||
if self._show_seek:
|
||||
t = (self._progress_back.w - (self._progress_back.right - mouse[0])) * (self.video.duration / self._progress_back.w)
|
||||
|
||||
self._seek_pos = self._progress_back.w * (round(t, 1) / self.video.duration) + self._progress_back.x
|
||||
self._seek_time = t
|
||||
|
||||
if click:
|
||||
self.video.seek(t, relative=False)
|
||||
self.video.play()
|
||||
|
||||
elif click:
|
||||
self.video.toggle_pause()
|
||||
|
||||
self._buffer_angle += dt / 10
|
||||
|
||||
return self._show_ui
|
||||
|
||||
def draw(self, win: pygame.Surface) -> None:
|
||||
pygame.draw.rect(win, "black", self.frame_rect)
|
||||
if self.video.frame_surf is not None:
|
||||
win.blit(self.video.frame_surf, self.frame_rect.topleft if self.video.current_size > self.frame_rect.size else self.vid_rect.topleft)
|
||||
|
||||
if self._show_ui:
|
||||
pygame.draw.line(win, (50, 50, 50), (self._progress_back.x, self._progress_back.centery), (self._progress_back.right, self._progress_back.centery), 5)
|
||||
if self._smooth_bar > 1:
|
||||
pygame.draw.line(win, "white", (self._progress_bar.x, self._progress_bar.centery), (self._progress_bar.x + self._smooth_bar, self._progress_bar.centery), 5)
|
||||
|
||||
f = self._font.render(self.video.name, True, "white")
|
||||
win.blit(f, (self.frame_rect.x + 10, self.frame_rect.y + 10))
|
||||
|
||||
f = self._font.render(self._convert_seconds(self.video.get_pos()), True, "white")
|
||||
win.blit(f, (self.frame_rect.x + 10, self._progress_bar.top - f.get_height() - 10))
|
||||
|
||||
if self._show_seek:
|
||||
pygame.draw.line(win, "white", (self._seek_pos, self._progress_back.top), (self._seek_pos, self._progress_back.bottom), 2)
|
||||
|
||||
f = self._font.render(self._convert_seconds(self._seek_time), True, "white")
|
||||
win.blit(f, (self._seek_pos - f.get_width() // 2, self._progress_back.y - 10 - f.get_height()))
|
||||
|
||||
if self._show_intervals:
|
||||
surf = self._get_closest_frame(self._seek_time)
|
||||
x = self._seek_pos - surf.get_width() // 2
|
||||
x = min(max(x, self.frame_rect.x), self.frame_rect.right - surf.get_width())
|
||||
win.blit(surf, (x, self._progress_back.y - 80 - f.get_height()))
|
||||
|
||||
if self.interactable:
|
||||
if self.video.buffering:
|
||||
for i in range(6):
|
||||
a = math.radians(self._buffer_angle + i * 60)
|
||||
pygame.draw.line(win, "white", self._move_angle(self.frame_rect.center, a, 10), self._move_angle(self.frame_rect.center, a, 30))
|
||||
elif self.video.paused:
|
||||
pygame.draw.rect(win, "white", (self.frame_rect.centerx - 15, self.frame_rect.centery - 20, 10, 40))
|
||||
pygame.draw.rect(win, "white", (self.frame_rect.centerx + 5, self.frame_rect.centery - 20, 10, 40))
|
||||
|
||||
def close(self) -> None:
|
||||
self.video.close()
|
||||
self._close_queue()
|
||||
|
||||
def skip(self) -> None:
|
||||
self.video.stop() if self.loop else self.video.close()
|
||||
|
||||
def get_next(self) -> None | Video | str:
|
||||
return self.queue_[0] if self.queue_ else None
|
||||
|
||||
def clear_queue(self) -> None:
|
||||
self._close_queue()
|
||||
self.queue_ = []
|
||||
|
||||
def get_video(self) -> Video:
|
||||
return self.video
|
||||
|
||||
def get_queue(self) -> List:
|
||||
return self.queue_
|
||||
34
pyvidplayer2/pyvidplayer2/video_pygame.py
Normal file
34
pyvidplayer2/pyvidplayer2/video_pygame.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import cv2
|
||||
import pygame
|
||||
import numpy
|
||||
from .video import Video
|
||||
from typing import Tuple
|
||||
from .post_processing import PostProcessing
|
||||
|
||||
|
||||
class VideoPygame(Video):
|
||||
def __init__(self, path: str, chunk_size=300, max_threads=1, max_chunks=1, subs=None, post_process=PostProcessing.none, interp=cv2.INTER_LINEAR, use_pygame_audio=False) -> None:
|
||||
Video.__init__(self, path, chunk_size, max_threads, max_chunks, subs, post_process, interp, use_pygame_audio)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"<VideoPygame(path={self.path})>"
|
||||
|
||||
def _create_frame(self, data: numpy.ndarray) -> pygame.Surface:
|
||||
return pygame.image.frombuffer(data.tobytes(), self.current_size, "BGR")
|
||||
|
||||
def _render_frame(self, surf: pygame.Surface, pos: Tuple[int, int]) -> None:
|
||||
surf.blit(self.frame_surf, pos)
|
||||
|
||||
def preview(self) -> None:
|
||||
win = pygame.display.set_mode(self.current_size)
|
||||
pygame.display.set_caption(f"pygame - {self.name}")
|
||||
self.play()
|
||||
while self.active:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
self.stop()
|
||||
pygame.time.wait(16)
|
||||
self.draw(win, (0, 0), force_draw=False)
|
||||
pygame.display.update()
|
||||
pygame.display.quit()
|
||||
self.close()
|
||||
36
pyvidplayer2/pyvidplayer2/video_pyglet.py
Normal file
36
pyvidplayer2/pyvidplayer2/video_pyglet.py
Normal file
@@ -0,0 +1,36 @@
|
||||
import cv2
|
||||
import pyglet
|
||||
import numpy
|
||||
from .video import Video
|
||||
from typing import Tuple
|
||||
from .post_processing import PostProcessing
|
||||
|
||||
|
||||
class VideoPyglet(Video):
|
||||
def __init__(self, path: str, chunk_size=300, max_threads=1, max_chunks=1, post_process=PostProcessing.none, interp=cv2.INTER_LINEAR, use_pygame_audio=False) -> None:
|
||||
Video.__init__(self, path, chunk_size, max_threads, max_chunks, None, post_process, interp, use_pygame_audio)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"<VideoPyglet(path={self.path})>"
|
||||
|
||||
def _create_frame(self, data: numpy.ndarray) -> pyglet.image.ImageData:
|
||||
return pyglet.image.ImageData(*self.current_size, "BGR", cv2.flip(data, 0).tobytes())
|
||||
|
||||
def _render_frame(self, pos: Tuple[int, int]) -> None:
|
||||
self.frame_surf.blit(*pos)
|
||||
|
||||
def draw(self, pos: Tuple[int, int], force_draw=True) -> bool:
|
||||
if (self._update() or force_draw) and self.frame_surf is not None:
|
||||
self._render_frame(pos) # (0, 0) pos draws the video bottomleft
|
||||
return True
|
||||
return False
|
||||
|
||||
def preview(self) -> None:
|
||||
def update(dt):
|
||||
self.draw((0, 0), force_draw=False)
|
||||
if not self.active:
|
||||
win.close()
|
||||
win = pyglet.window.Window(width=self.current_size[0], height=self.current_size[1], config=pyglet.gl.Config(double_buffer=False), caption=f"pyglet - {self.name}")
|
||||
pyglet.clock.schedule_interval(update, 1/60.0)
|
||||
pyglet.app.run()
|
||||
self.close()
|
||||
41
pyvidplayer2/pyvidplayer2/video_pyqt.py
Normal file
41
pyvidplayer2/pyvidplayer2/video_pyqt.py
Normal file
@@ -0,0 +1,41 @@
|
||||
import cv2
|
||||
import numpy
|
||||
from .video import Video
|
||||
from typing import Tuple
|
||||
from PyQt6.QtGui import QImage, QPixmap, QPainter
|
||||
from PyQt6.QtWidgets import QApplication, QMainWindow, QWidget
|
||||
from PyQt6.QtCore import QTimer
|
||||
from .post_processing import PostProcessing
|
||||
|
||||
|
||||
class VideoPyQT(Video):
|
||||
def __init__(self, path: str, chunk_size=300, max_threads=1, max_chunks=1, post_process=PostProcessing.none, interp=cv2.INTER_LINEAR, use_pygame_audio=False) -> None:
|
||||
Video.__init__(self, path, chunk_size, max_threads, max_chunks, None, post_process, interp, use_pygame_audio)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"<VideoPyQT(path={self.path})>"
|
||||
|
||||
def _create_frame(self, data: numpy.ndarray) -> QImage:
|
||||
return QImage(data, data.shape[1], data.shape[0], data.strides[0], QImage.Format.Format_BGR888)
|
||||
|
||||
def _render_frame(self, win: QMainWindow, pos: Tuple[int, int]) -> None: #must be called in paintEvent
|
||||
QPainter(win).drawPixmap(*pos, QPixmap.fromImage(self.frame_surf))
|
||||
|
||||
def preview(self) -> None:
|
||||
class Window(QMainWindow):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.canvas = QWidget(self)
|
||||
self.setCentralWidget(self.canvas)
|
||||
self.timer = QTimer(self)
|
||||
self.timer.timeout.connect(self.update)
|
||||
self.timer.start(16)
|
||||
def paintEvent(self_, _):
|
||||
self.draw(self_, (0, 0))
|
||||
app = QApplication([])
|
||||
win = Window()
|
||||
win.setWindowTitle(f"pyqt6 - {self.name}")
|
||||
win.setFixedSize(*self.current_size)
|
||||
win.show()
|
||||
app.exec()
|
||||
self.close()
|
||||
36
pyvidplayer2/pyvidplayer2/video_tkinter.py
Normal file
36
pyvidplayer2/pyvidplayer2/video_tkinter.py
Normal file
@@ -0,0 +1,36 @@
|
||||
import cv2
|
||||
import numpy
|
||||
import tkinter
|
||||
from .video import Video
|
||||
from typing import Tuple
|
||||
from .post_processing import PostProcessing
|
||||
|
||||
|
||||
class VideoTkinter(Video):
|
||||
def __init__(self, path: str, chunk_size=300, max_threads=1, max_chunks=1, post_process=PostProcessing.none, interp=cv2.INTER_LINEAR, use_pygame_audio=False) -> None:
|
||||
Video.__init__(self, path, chunk_size, max_threads, max_chunks, None, post_process, interp, use_pygame_audio)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"<VideoTkinter(path={self.path})>"
|
||||
|
||||
def _create_frame(self, data: numpy.ndarray) -> tkinter.PhotoImage:
|
||||
h, w = data.shape[:2]
|
||||
return tkinter.PhotoImage(width=w, height=h, data=f"P6 {w} {h} 255 ".encode() + cv2.cvtColor(data, cv2.COLOR_BGR2RGB).tobytes(), format='PPM')
|
||||
|
||||
def _render_frame(self, canvas: tkinter.Canvas, pos: Tuple[int, int]) -> None:
|
||||
canvas.create_image(*pos, image=self.frame_surf)
|
||||
|
||||
def preview(self) -> None:
|
||||
def update():
|
||||
self.draw(canvas, (self.current_size[0] / 2, self.current_size[1] / 2), force_draw=False)
|
||||
if self.active:
|
||||
root.after(16, update) # for around 60 fps
|
||||
else:
|
||||
root.destroy()
|
||||
root = tkinter.Tk()
|
||||
root.title(f"tkinter - {self.name}")
|
||||
canvas = tkinter.Canvas(root, width=self.current_size[0], height=self.current_size[1], highlightthickness=0)
|
||||
canvas.pack()
|
||||
update()
|
||||
root.mainloop()
|
||||
self.close()
|
||||
107
pyvidplayer2/pyvidplayer2/webcam.py
Normal file
107
pyvidplayer2/pyvidplayer2/webcam.py
Normal file
@@ -0,0 +1,107 @@
|
||||
import cv2
|
||||
import pygame
|
||||
import time
|
||||
import numpy
|
||||
from .post_processing import PostProcessing
|
||||
from .error import Pyvidplayer2Error
|
||||
from typing import Tuple
|
||||
|
||||
|
||||
class Webcam:
|
||||
def __init__(self, post_process=PostProcessing.none, interp=cv2.INTER_LINEAR, fps=30) -> None:
|
||||
self._vid = cv2.VideoCapture(0)
|
||||
|
||||
if not self._vid.isOpened():
|
||||
raise Pyvidplayer2Error("Failed to find webcam.")
|
||||
|
||||
self.original_size = (int(self._vid.get(cv2.CAP_PROP_FRAME_WIDTH)), int(self._vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))
|
||||
self.current_size = self.original_size
|
||||
self.aspect_ratio = self.original_size[0] / self.original_size[1]
|
||||
|
||||
self.frame_data = None
|
||||
self.frame_surf = None
|
||||
|
||||
self.active = False
|
||||
|
||||
self.post_func = post_process
|
||||
self.interp = interp
|
||||
self.fps = fps
|
||||
|
||||
self._frame_delay = 1 / self.fps
|
||||
self._frames = 0
|
||||
self._last_tick = 0
|
||||
|
||||
self.play()
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"<Webcam(fps={self.fps})>"
|
||||
|
||||
def _update(self) -> bool:
|
||||
if self.active:
|
||||
|
||||
if time.time() - self._last_tick > self._frame_delay:
|
||||
|
||||
has_frame, data = self._vid.read()
|
||||
|
||||
if has_frame:
|
||||
if self.original_size != self.current_size:
|
||||
data = cv2.resize(data, dsize=self.current_size, interpolation=self.interp)
|
||||
data = self.post_func(data)
|
||||
|
||||
self.frame_data = data
|
||||
self.frame_surf = self._create_frame(data)
|
||||
|
||||
self._frames += 1
|
||||
self._last_tick = time.time()
|
||||
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def play(self) -> None:
|
||||
self.active = True
|
||||
|
||||
def stop(self) -> None:
|
||||
self.active = False
|
||||
self.frame_data = None
|
||||
self.frame_surf = None
|
||||
|
||||
def resize(self, size: Tuple[int, int]) -> None:
|
||||
self.current_size = size
|
||||
|
||||
def change_resolution(self, height: int) -> None:
|
||||
self.current_size = (int(height * self.aspect_ratio), height)
|
||||
|
||||
def close(self) -> None:
|
||||
self.stop()
|
||||
self._vid.release()
|
||||
|
||||
def get_pos(self) -> float:
|
||||
return self._frames / self.fps
|
||||
|
||||
def draw(self, surf, pos: Tuple[int, int], force_draw=True) -> bool:
|
||||
if (self._update() or force_draw) and self.frame_surf is not None:
|
||||
self._render_frame(surf, pos)
|
||||
return True
|
||||
return False
|
||||
|
||||
def _create_frame(self, data: numpy.ndarray) -> pygame.Surface:
|
||||
return pygame.image.frombuffer(data.tobytes(), self.current_size, "BGR")
|
||||
|
||||
def _render_frame(self, surf: pygame.Surface, pos: Tuple[int, int]):
|
||||
surf.blit(self.frame_surf, pos)
|
||||
|
||||
def preview(self) -> None:
|
||||
win = pygame.display.set_mode(self.current_size)
|
||||
pygame.display.set_caption(f"webcam")
|
||||
self.play()
|
||||
while self.active:
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
self.stop()
|
||||
pygame.time.wait(int(self._frame_delay * 1000))
|
||||
self.draw(win, (0, 0), force_draw=False)
|
||||
pygame.display.update()
|
||||
pygame.display.quit()
|
||||
self.close()
|
||||
|
||||
5
pyvidplayer2/requirements.txt
Normal file
5
pyvidplayer2/requirements.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
numpy<1.25,>=1.21
|
||||
opencv_python
|
||||
pygame
|
||||
pysubs2
|
||||
PyAudio
|
||||
27
pyvidplayer2/setup.py
Normal file
27
pyvidplayer2/setup.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from setuptools import setup
|
||||
from pyvidplayer2 import _VERSION
|
||||
|
||||
|
||||
with open("README.md", 'r') as f:
|
||||
long_desc = f.read()
|
||||
|
||||
|
||||
setup(
|
||||
name="pyvidplayer2",
|
||||
version=_VERSION,
|
||||
description="Video playback in Python",
|
||||
long_description=long_desc,
|
||||
long_description_content_type = "text/markdown",
|
||||
author="Anray Liu",
|
||||
author_email="anrayliu@gmail.com",
|
||||
license="MIT",
|
||||
packages=["pyvidplayer2"],
|
||||
install_requires=["numpy<1.25,>=1.21",
|
||||
"opencv_python",
|
||||
"pygame",
|
||||
"pysubs2",
|
||||
"PyAudio"],
|
||||
url="https://github.com/ree1261/pyvidplayer2",
|
||||
platforms=["windows"],
|
||||
keywords=["pygame", "video", "playback"],
|
||||
)
|
||||
Reference in New Issue
Block a user