yta-video-opengl 0.0.21__py3-none-any.whl → 0.0.23__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,253 +0,0 @@
1
- """
2
- The pyav container stores the information based
3
- on the packets timestamps (called 'pts'). Some
4
- of the packets are considered key_frames because
5
- they include those key frames.
6
-
7
- Also, this library uses those key frames to start
8
- decodifying from there to the next one, obtaining
9
- all the frames in between able to be read and
10
- modified.
11
-
12
- This cache system will look for the range of
13
- frames that belong to the key frame related to the
14
- frame we are requesting in the moment, keeping in
15
- memory all those frames to be handled fast. It
16
- will remove the old frames if needed to use only
17
- the 'size' we set when creating it.
18
-
19
- A stream can have 'fps = 60' but use another
20
- different time base that make the pts values go 0,
21
- 256, 512... for example. The 'time_base' is the
22
- only accurate way to obtain the pts.
23
-
24
- Feel free to move this explanation to other
25
- place, its about the duration.
26
-
27
- The stream 'duration' parameter is measured
28
- on ticks, the amount of ticks that the
29
- stream lasts. Here below is an example:
30
-
31
- - Duration raw: 529200
32
- - Time base: 1/44100
33
- - Duration (seconds): 12.0
34
- """
35
- from av.container import InputContainer
36
- from av.video.stream import VideoStream
37
- from av.audio.stream import AudioStream
38
- from av.video.frame import VideoFrame
39
- from av.audio.frame import AudioFrame
40
- from av.packet import Packet
41
- from yta_validation.parameter import ParameterValidator
42
- from quicktions import Fraction
43
- from collections import OrderedDict
44
- from typing import Union
45
- from abc import abstractmethod, ABC
46
-
47
- import numpy as np
48
- import math
49
-
50
-
51
- class FrameCache(ABC):
52
- """
53
- Class to manage the frames cache of a video
54
- or audio.
55
- """
56
-
57
- @property
58
- @abstractmethod
59
- def fps(
60
- self
61
- ) -> Union[int, Fraction, None]:
62
- """
63
- The frames per second.
64
- """
65
- pass
66
-
67
- @property
68
- def time_base(
69
- self
70
- ) -> Union[Fraction, None]:
71
- """
72
- The time base of the stream.
73
- """
74
- return self.stream.time_base
75
-
76
- def __init__(
77
- self,
78
- container: InputContainer,
79
- stream: Union[VideoStream, AudioStream],
80
- size: Union[int, None] = None
81
- ):
82
- ParameterValidator.validate_mandatory_instance_of('container', container, InputContainer)
83
- ParameterValidator.validate_mandatory_instance_of('stream', stream, [VideoStream, AudioStream])
84
- ParameterValidator.validate_number_between('size', size, 1, 120)
85
-
86
- self.container: InputContainer = container
87
- """
88
- The pyav container.
89
- """
90
- self.stream: Union[VideoStream, AudioStream] = stream
91
- """
92
- The pyav stream.
93
- """
94
- self.cache: OrderedDict = OrderedDict()
95
- """
96
- The cache ordered dictionary.
97
- """
98
- self.key_frames_pts: list[int] = []
99
- """
100
- The list that contains the timestamps of the
101
- key frame packets, ordered from begining to
102
- end.
103
- """
104
- self.size: int = size
105
- """
106
- The size of the cache.
107
- """
108
-
109
- self._last_packet_accessed: Union[Packet, None] = None
110
- """
111
- The last packet that has been accessed
112
- """
113
-
114
- self._prepare()
115
-
116
- def _prepare(
117
- self
118
- ):
119
- # Index key frames
120
- for packet in self.container.demux(self.stream):
121
- if packet.is_keyframe:
122
- self.key_frames_pts.append(packet.pts)
123
-
124
- # The cache size will be auto-calculated to
125
- # use the amount of frames of the biggest
126
- # interval of frames that belongs to a key
127
- # frame, or a value by default
128
- # TODO: Careful if this is too big
129
- # Intervals, but in number of frames
130
- intervals = np.diff(
131
- # Intervals of time between keyframes
132
- np.array(self.key_frames_pts) * self.time_base
133
- ) * self.fps
134
-
135
- self.size = (
136
- math.ceil(np.max(intervals))
137
- if intervals.size > 0 else
138
- (
139
- self.size
140
- if self.size is not None else
141
- # TODO: Make this a setting (?)
142
- 60
143
- )
144
- )
145
-
146
- self.container.seek(0)
147
-
148
- def _get_nearest_keyframe_pts(
149
- self,
150
- pts: int
151
- ):
152
- """
153
- Get the fps of the keyframe that is the
154
- nearest to the provided 'pts'. Useful to
155
- seek and start decoding frames from that
156
- keyframe.
157
- """
158
- return max(
159
- (
160
- key_frame_pts
161
- for key_frame_pts in self.key_frames_pts
162
- if key_frame_pts <= pts
163
- ),
164
- # If no key frames, just 0
165
- default = 0
166
- )
167
-
168
- def _store_frame_in_cache(
169
- self,
170
- frame: Union[VideoFrame, AudioFrame]
171
- ) -> Union[VideoFrame, AudioFrame]:
172
- """
173
- Store the provided 'frame' in cache if it
174
- is not on it, removing the first item of
175
- the cache if full.
176
- """
177
- if frame.pts not in self.cache:
178
- self.cache[frame.pts] = frame
179
-
180
- # Clean cache if full
181
- if len(self.cache) > self.size:
182
- self.cache.popitem(last = False)
183
-
184
- return frame
185
-
186
- def _seek(
187
- self,
188
- pts: int
189
- ):
190
- """
191
- Seek to the given 'pts' This is useful
192
- when working with 'container.demux' and
193
- iterating over packets, not when using
194
- 'stream.decode' and getting frames
195
- directly.
196
- """
197
- self.container.seek(
198
- offset = pts,
199
- stream = self.stream
200
- )
201
-
202
- def clear(
203
- self
204
- ) -> 'VideoFrameCache':
205
- """
206
- Clear the cache by removing all the items.
207
- """
208
- self.cache.clear()
209
-
210
- return self
211
-
212
- def get_frame(
213
- self,
214
- t: Union[int, float, Fraction]
215
- ) -> Union[VideoFrame, AudioFrame]:
216
- """
217
- Get the single frame that is in the 't'
218
- time moment provided.
219
- """
220
- for frame in self.get_frames(t):
221
- return frame
222
-
223
- @abstractmethod
224
- def get_frames(
225
- self,
226
- start: Union[int, float, Fraction],
227
- end: Union[int, float, Fraction]
228
- ):
229
- pass
230
-
231
-
232
- """
233
- There is a way of editing videos being
234
- able to arbitrary access to frames, that
235
- is transforming the source videos to
236
- intra-frame videos. This is a ffmpeg
237
- command that can do it:
238
-
239
- - `ffmpeg -i input.mp4 -c:v libx264 -x264opts keyint=1 -preset fast -crf 18 -c:a copy output_intra.mp4`
240
-
241
- Once you have the 'output_intra.mp4',
242
- each packet can decodify its frame
243
- depending not on the previous one, being
244
- able to seek and jump easy.
245
-
246
- There are 3 type of video codifications,
247
- the I-frame (intra-coded), in which any
248
- frame can be decoded by itself, P-frame
249
- (predicted), that need one or more
250
- previous frames to be decoded, and
251
- B-frame (bidirectional predicted), that
252
- needs previous and future frames.
253
- """
@@ -1,195 +0,0 @@
1
-
2
- from yta_video_opengl.reader.cache import FrameCache
3
- from yta_video_opengl.reader.cache.utils import trim_audio_frame
4
- from yta_video_opengl.t import T
5
- from yta_validation.parameter import ParameterValidator
6
- from av.container import InputContainer
7
- from av.audio.stream import AudioStream
8
- from av.audio.frame import AudioFrame
9
- from quicktions import Fraction
10
- from typing import Union
11
-
12
-
13
- class AudioFrameCache(FrameCache):
14
- """
15
- Cache for the audio frames.
16
- """
17
-
18
- @property
19
- def fps(
20
- self
21
- ) -> Union[Fraction, int]:
22
- """
23
- The frames per second.
24
- """
25
- return self.stream.rate
26
-
27
- @property
28
- def frame_duration(
29
- self
30
- ) -> int:
31
- """
32
- The frame duration in ticks, which is the
33
- minimum amount of time, 1 / time_base.
34
- """
35
- return self.stream.frames
36
-
37
- def __init__(
38
- self,
39
- container: InputContainer,
40
- stream: AudioStream,
41
- size: Union[int, None] = None
42
- ):
43
- ParameterValidator.validate_mandatory_instance_of('stream', stream, AudioStream)
44
-
45
- super().__init__(container, stream, size)
46
-
47
- def _seek(
48
- self,
49
- pts: int
50
- ):
51
- """
52
- Seek to the given 'pts' only if it is not
53
- the next 'pts' to the last read, and it
54
- will also apply a pad to avoid problems
55
- when reading audio frames.
56
- """
57
- # I found that it is recommended to
58
- # read ~100ms before the pts we want to
59
- # actually read so we obtain the frames
60
- # clean (this is important in audio).
61
- # This solves a problem I had related
62
- # to some artifacts on the audio when
63
- # trimming exactly without this pad.
64
- pts_pad = int(0.1 / self.time_base)
65
- self.container.seek(
66
- offset = max(0, pts - pts_pad),
67
- stream = self.stream
68
- )
69
-
70
- def get_frame(
71
- self,
72
- t: Union[int, float, Fraction]
73
- ) -> AudioFrame:
74
- """
75
- Get the video frame that is in the 't'
76
- time moment provided.
77
- """
78
- t: T = T.from_fps(t, self.fps)
79
- for frame in self.get_frames(t.truncated, t.next(1).truncated):
80
- return frame
81
-
82
- def get_frames(
83
- self,
84
- start: Union[int, float, Fraction],
85
- end: Union[int, float, Fraction]
86
- ):
87
- """
88
- Get all the audio frames in the range
89
- between the provided 'start' and 'end'
90
- time (in seconds).
91
-
92
- This method is an iterator that yields
93
- the frame, its t and its index.
94
- """
95
- # TODO: Validate 'start' and 'end' are mandatory
96
- # positive numbers
97
- # Make sure the 'start' and 'end' time moments
98
- # provided are truncated values based on the
99
- # stream time base
100
- start = T(start, self.time_base).truncated
101
- end = T(end, self.time_base).truncated
102
-
103
- if end <= start:
104
- raise Exception(f'The time range start:{str(float(start))} - end:{str(float(end))}) is not valid.')
105
-
106
- key_frame_pts = self._get_nearest_keyframe_pts(start / self.time_base)
107
-
108
- if (
109
- self._last_packet_accessed is None or
110
- self._last_packet_accessed.pts != key_frame_pts
111
- ):
112
- self._seek(key_frame_pts)
113
-
114
- for packet in self.container.demux(self.stream):
115
- if packet.pts is None:
116
- continue
117
-
118
- self._last_packet_accessed = packet
119
-
120
- for frame in packet.decode():
121
- if frame.pts is None:
122
- continue
123
-
124
- # We store all the frames in cache
125
- self._store_frame_in_cache(frame)
126
-
127
- current_frame_time = frame.pts * self.time_base
128
- # End is not included, its the start of the
129
- # next frame actually
130
- frame_end = current_frame_time + (frame.samples / self.stream.sample_rate)
131
-
132
- # For the next comments imagine we are looking
133
- # for the [1.0, 2.0) audio time range
134
- # Previous frame and nothing is inside
135
- if frame_end <= start:
136
- # From 0.25 to 1.0
137
- continue
138
-
139
- # We finished, nothing is inside and its after
140
- if current_frame_time >= end:
141
- # From 2.0 to 2.75
142
- return
143
-
144
- """
145
- If we need audio from 1 to 2, audio is:
146
- - from 0 to 0.75 (Not included, omit)
147
- - from 0.5 to 1.5 (Included, take 1.0 to 1.5)
148
- - from 0.5 to 2.5 (Included, take 1.0 to 2.0)
149
- - from 1.25 to 1.5 (Included, take 1.25 to 1.5)
150
- - from 1.25 to 2.5 (Included, take 1.25 to 2.0)
151
- - from 2.5 to 3.5 (Not included, omit)
152
- """
153
-
154
- # Here below, at least a part is inside
155
- if (
156
- current_frame_time < start and
157
- frame_end > start
158
- ):
159
- # A part at the end is included
160
- end_time = (
161
- # From 0.5 to 1.5 0> take 1.0 to 1.5
162
- frame_end
163
- if frame_end <= end else
164
- # From 0.5 to 2.5 => take 1.0 to 2.0
165
- end
166
- )
167
- #print('A part at the end is included.')
168
- frame = trim_audio_frame(
169
- frame = frame,
170
- start = start,
171
- end = end_time,
172
- time_base = self.time_base
173
- )
174
- elif (
175
- current_frame_time >= start and
176
- current_frame_time < end
177
- ):
178
- end_time = (
179
- # From 1.25 to 1.5 => take 1.25 to 1.5
180
- frame_end
181
- if frame_end <= end else
182
- # From 1.25 to 2.5 => take 1.25 to 2.0
183
- end
184
- )
185
- # A part at the begining is included
186
- #print('A part at the begining is included.')
187
- frame = trim_audio_frame(
188
- frame = frame,
189
- start = current_frame_time,
190
- end = end_time,
191
- time_base = self.time_base
192
- )
193
-
194
- # If the whole frame is in, past as it is
195
- yield frame
@@ -1,48 +0,0 @@
1
- from av.audio.frame import AudioFrame
2
- from quicktions import Fraction
3
- from typing import Union
4
-
5
-
6
- def trim_audio_frame(
7
- frame: AudioFrame,
8
- start: Union[int, float, Fraction],
9
- end: Union[int, float, Fraction],
10
- time_base: Fraction
11
- ) -> AudioFrame:
12
- """
13
- Trim an audio frame to obtain the part between
14
- [start, end), that is provided in seconds.
15
- """
16
- # (channels, n_samples)
17
- samples = frame.to_ndarray()
18
- n_samples = samples.shape[1]
19
-
20
- # In seconds
21
- frame_start = frame.pts * float(time_base)
22
- frame_end = frame_start + (n_samples / frame.sample_rate)
23
-
24
- # Overlapping
25
- cut_start = max(frame_start, float(start))
26
- cut_end = min(frame_end, float(end))
27
-
28
- if cut_start >= cut_end:
29
- # No overlapping
30
- return None
31
-
32
- # To sample indexes
33
- start_index = int(round((cut_start - frame_start) * frame.sample_rate))
34
- end_index = int(round((cut_end - frame_start) * frame.sample_rate))
35
-
36
- new_frame = AudioFrame.from_ndarray(
37
- # end_index is not included: so [start, end)
38
- array = samples[:, start_index:end_index],
39
- format = frame.format,
40
- layout = frame.layout
41
- )
42
-
43
- # Set needed attributes
44
- new_frame.sample_rate = frame.sample_rate
45
- new_frame.time_base = time_base
46
- new_frame.pts = int(round(cut_start / float(time_base)))
47
-
48
- return new_frame
@@ -1,113 +0,0 @@
1
-
2
- from yta_video_opengl.reader.cache import FrameCache
3
- from yta_video_opengl.t import T
4
- from yta_validation.parameter import ParameterValidator
5
- from av.container import InputContainer
6
- from av.video.stream import VideoStream
7
- from av.video.frame import VideoFrame
8
- from quicktions import Fraction
9
- from typing import Union
10
-
11
-
12
- class VideoFrameCache(FrameCache):
13
- """
14
- Cache for the video frames.
15
- """
16
-
17
- @property
18
- def fps(
19
- self
20
- ) -> Union[Fraction, None]:
21
- """
22
- The frames per second.
23
- """
24
- return self.stream.average_rate
25
-
26
- @property
27
- def frame_duration(
28
- self
29
- ) -> int:
30
- """
31
- The frame duration in ticks, which is the
32
- minimum amount of time, 1 / time_base.
33
- """
34
- return self.stream.duration / self.stream.frames
35
-
36
- def __init__(
37
- self,
38
- container: InputContainer,
39
- stream: VideoStream,
40
- size: Union[int, None] = None
41
- ):
42
- ParameterValidator.validate_mandatory_instance_of('stream', stream, VideoStream)
43
-
44
- super().__init__(container, stream, size)
45
-
46
- def get_frame(
47
- self,
48
- t: Union[int, float, Fraction]
49
- ) -> VideoFrame:
50
- """
51
- Get the video frame that is in the 't'
52
- time moment provided.
53
- """
54
- print(f'Getting frame from {str(float(t))}')
55
- print(f'FPS: {str(self.fps)}')
56
- t: T = T.from_fps(t, self.fps)
57
- print(f'So the actual frame is from {str(float(t.truncated))} to {str(float(t.next(1).truncated))}')
58
- for frame in self.get_frames(t.truncated, t.next(1).truncated):
59
- return frame
60
-
61
- def get_frames(
62
- self,
63
- start: Union[int, float, Fraction],
64
- end: Union[int, float, Fraction]
65
- ):
66
- """
67
- Get all the frames in the range between
68
- the provided 'start' and 'end' time in
69
- seconds.
70
-
71
- This method is an iterator that yields
72
- the frame, its t and its index.
73
- """
74
- # TODO: Validate 'start' and 'end' are mandatory
75
- # positive numbers
76
- # Make sure the 'start' and 'end' time moments
77
- # provided are truncated values based on the
78
- # stream time base
79
- start = T(start, self.time_base).truncated
80
- end = T(end, self.time_base).truncated
81
-
82
- if end <= start:
83
- raise Exception(f'The time range start:{str(float(start))} - end:{str(float(end))}) is not valid.')
84
-
85
- key_frame_pts = self._get_nearest_keyframe_pts(start / self.time_base)
86
-
87
- if (
88
- self._last_packet_accessed is None or
89
- self._last_packet_accessed.pts != key_frame_pts
90
- ):
91
- self._seek(key_frame_pts)
92
-
93
- for packet in self.container.demux(self.stream):
94
- if packet.pts is None:
95
- continue
96
-
97
- self._last_packet_accessed = packet
98
-
99
- for frame in packet.decode():
100
- if frame.pts is None:
101
- continue
102
-
103
- # We store all the frames in cache
104
- self._store_frame_in_cache(frame)
105
-
106
- current_frame_time = frame.pts * self.time_base
107
-
108
- # We want the range [start, end)
109
- if start <= current_frame_time < end:
110
- yield frame
111
-
112
- if current_frame_time >= end:
113
- break