-
Notifications
You must be signed in to change notification settings - Fork 4
/
pygamevideo.py
281 lines (208 loc) · 7.54 KB
/
pygamevideo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
from typing import Union
import time
import os
import atexit
import pygame
import numpy
import cv2
from ffpyplayer.player import MediaPlayer
__version__ = "2.0.0"
class Video:
"""
Pygame video player.
"""
def __init__(self, filepath: Union[str, os.PathLike]) -> None:
"""
Parameters
----------
@param filepath File path to the video to load.
"""
self.is_ready = False
self.load(filepath)
# Release before exiting interpreter to prevent segfault
atexit.register(self.release)
def __repr__(self) -> str:
return f"<{__name__}.{self.__class__.__name__}(frame#{self.current_frame})>"
def __del__(self) -> None:
self.release()
def load(self, filepath: Union[str, os.PathLike]) -> None:
"""
Load a video from file path.
This method is also called implicitly when instantiated.
Parameters
----------
@param filepath File path to the video to load.
"""
filepath = str(filepath)
if not os.path.exists(filepath):
raise FileNotFoundError(f"No such file or directory: '{filepath}'")
self.filepath = filepath
self.is_playing = False
self.is_paused = False
self.is_looped = False
self.draw_frame = 0
self.start_time = 0
self.__start_time = 0
self.__volume = 1.0
self.is_muted = False
self.__volume_before_mute = 1.0
self.__vidcap = cv2.VideoCapture(self.filepath)
ff_opts = {"fast": True, "framedrop": True, "paused": True}
self.__ff = MediaPlayer(self.filepath, ff_opts=ff_opts)
self.fps = self.__vidcap.get(cv2.CAP_PROP_FPS)
self.total_frames = int(self.__vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
self.frame_width = int(self.__vidcap.get(cv2.CAP_PROP_FRAME_WIDTH))
self.frame_height = int(self.__vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.frame_surf = pygame.Surface((self.frame_width, self.frame_height)).convert()
self.is_ready = True
def reload(self) -> None:
""" Reload the video from the same filepath. """
self.release()
self.load(self.filepath)
def release(self) -> None:
""" Release the resources used by the video player. """
if self.is_ready:
self.__vidcap.release()
self.__ff.close_player()
self.is_ready = False
# Control methods
def play(self, loop: bool = False) -> None:
"""
Start playing the video.
Parameters
----------
@param loop Whether to loop or not when the video playback ends.
"""
if self.is_ready and not self.is_playing:
self.is_playing = True
self.is_looped = loop
self.seek_frame(0)
self.draw_frame = 0
self.start_time = time.time()
self.__start_time = time.time()
self.__ff.set_pause(False)
def stop(self) -> None:
"""
Stop playing the video.
"""
self.is_playing = False
self.is_paused = False
self.__ff.set_pause(True)
def pause(self) -> None:
""" Pause the video. """
if self.is_playing:
self.is_paused = True
self.__ff.set_pause(True)
def resume(self) -> None:
""" Resume the video. """
if self.is_playing:
self.is_paused = False
self.__ff.set_pause(False)
def toggle_pause(self) -> None:
""" Switch between paused states. """
if self.is_playing:
if self.is_paused: self.resume()
else: self.pause()
# Audio methods
def mute(self) -> None:
""" Mute audio playback. """
# MediaPlayer.set_mute doesn't work!
self.is_muted = True
self.__volume_before_mute = self.volume
self.__ff.set_volume(0.0)
def unmute(self) -> None:
""" Unmute audio playback. """
self.is_muted = False
self.__ff.set_volume(self.__volume_before_mute)
@property
def volume(self) -> float:
""" Volume of the audio playback. """
return self.__volume
@volume.setter
def volume(self, value: float) -> None:
self.__volume = value
if not self.is_muted:
self.__ff.set_volume(value)
# Duration methods & properties
@property
def duration(self) -> float:
""" Total duration of the video in milliseconds. """
return (self.total_frames / self.fps) * 1000
@property
def current_time(self) -> float:
""" Current time into the video in milliseconds. """
if not self.is_ready or not self.is_playing: return 0
return self.__vidcap.get(cv2.CAP_PROP_POS_MSEC)
@property
def remaining_time(self) -> float:
""" Remaining time left in the video in milliseconds. """
return self.duration - self.current_time
@property
def current_frame(self) -> int:
""" Current frame into the video. """
return self.__vidcap.get(cv2.CAP_PROP_POS_FRAMES)
@property
def remaining_frames(self) -> int:
""" Remaining frames left in the video. """
return self.frame_count - self.current_frame
def seek_time(self, timepoint: float) -> None:
"""
Seek into desired timepoint.
Parameters
----------
@param time Time in milliseconds to seek to.
"""
self.start_time = self.__start_time + timepoint / 1000
self.draw_frame = int((time.time() - self.start_time) * self.fps)
self.__vidcap.set(cv2.CAP_PROP_POS_MSEC, timepoint)
self.__ff.seek(timepoint / 1000, relative=False)
def seek_frame(self, frame: int) -> None:
"""
Seek into desired frame.
Parameters
----------
@param frame Frame number to seek to.
"""
self.seek_time((frame / self.fps) * 1000)
# Process & draw video
def get_frame(self) -> pygame.Surface:
"""
Advance the video and return the current frame.
Must be called once per frame.
"""
if not self.is_playing or not self.is_ready:
return self.frame_surf
elapsed_frames = int((time.time() - self.start_time) * self.fps)
if self.draw_frame >= elapsed_frames:
return self.frame_surf
else:
target_frames = elapsed_frames - self.draw_frame
self.draw_frame += target_frames
if not self.is_paused:
for _ in range(target_frames):
success, frame = self.__vidcap.read()
if not success:
if self.is_looped:
self.seek_frame(0)
return self.frame_surf
else:
self.stop()
return self.frame_surf
pygame.pixelcopy.array_to_surface(
self.frame_surf,
numpy.flip(numpy.rot90(frame[::-1]))
)
return self.frame_surf
def draw_to(self,
dest_surface: pygame.Surface,
position: Union[tuple[float, float], pygame.Vector2, pygame.Rect]
) -> None:
"""
Blit the current video frame to the surface.
Parameters
----------
@param dest_surface Destination surface to draw the video on.
@param position Position to draw the video frame at.
"""
frame = self.get_frame()
dest_surface.blit(frame, position)