Debian Codegraph @

av/subtitles/subtitle.py

raw
1 import cython
2 from cython.cimports.cpython import PyBuffer_FillInfo, PyBytes_FromString
3 from cython.cimports.libc.string import memcpy
4
5
6 @cython.final
7 @cython.cclass
8 class SubtitleProxy:
9 def __dealloc__(self):
10 lib.avsubtitle_free(cython.address(self.struct))
11
12
13 _cinit_bypass_sentinel = cython.declare(object, object())
14
15
16 @cython.final
17 @cython.cclass
18 class SubtitleSet:
19 """
20 A :class:`SubtitleSet` can contain many :class:`Subtitle` objects.
21
22 Wraps :ffmpeg:`AVSubtitle`.
23 """
24
25 def __cinit__(self, proxy_or_sentinel=None):
26 if proxy_or_sentinel is _cinit_bypass_sentinel:
27 # Creating empty SubtitleSet for encoding
28 self.proxy = SubtitleProxy()
29 self.rects = ()
30 elif isinstance(proxy_or_sentinel, SubtitleProxy):
31 # Creating from decoded subtitle
32 self.proxy = proxy_or_sentinel
33 self.rects = tuple(
34 build_subtitle(self, i) for i in range(self.proxy.struct.num_rects)
35 )
36 else:
37 raise TypeError(
38 "SubtitleSet requires a SubtitleProxy or use SubtitleSet.create()"
39 )
40
41 @staticmethod
42 def create(
43 text: bytes,
44 start: int,
45 end: int,
46 pts: int = 0,
47 subtitle_format: int = 1,
48 ) -> SubtitleSet:
49 """
50 Create a SubtitleSet for encoding.
51
52 :param text: The subtitle text in ASS dialogue format
53 (e.g. ``b"0,0,Default,,0,0,0,,Hello World"``)
54 :param start: Start display time as offset from pts (typically 0)
55 :param end: End display time as offset from pts (i.e., duration)
56 :param pts: Presentation timestamp in stream time_base units
57 :param subtitle_format: Subtitle format (default 1 for text)
58 :return: A SubtitleSet ready for encoding
59
60 .. note::
61 All timing values should be in stream time_base units.
62 For MKV (time_base=1/1000), units are milliseconds.
63 For MP4 (time_base=1/1000000), units are microseconds.
64 """
65 subset: SubtitleSet = SubtitleSet(_cinit_bypass_sentinel)
66
67 subset.proxy.struct.format = subtitle_format
68 subset.proxy.struct.start_display_time = start
69 subset.proxy.struct.end_display_time = end
70 subset.proxy.struct.pts = pts
71
72 subset.proxy.struct.num_rects = 1
73 subset.proxy.struct.rects = cython.cast(
74 cython.pointer[cython.pointer[lib.AVSubtitleRect]],
75 lib.av_mallocz(cython.sizeof(cython.pointer[lib.AVSubtitleRect])),
76 )
77 if subset.proxy.struct.rects == cython.NULL:
78 raise MemoryError("Failed to allocate subtitle rects array")
79
80 rect: cython.pointer[lib.AVSubtitleRect] = cython.cast(
81 cython.pointer[lib.AVSubtitleRect],
82 lib.av_mallocz(cython.sizeof(lib.AVSubtitleRect)),
83 )
84 if rect == cython.NULL:
85 lib.av_free(subset.proxy.struct.rects)
86 subset.proxy.struct.rects = cython.NULL
87 raise MemoryError("Failed to allocate subtitle rect")
88
89 subset.proxy.struct.rects[0] = rect
90
91 rect.x = 0
92 rect.y = 0
93 rect.w = 0
94 rect.h = 0
95 rect.nb_colors = 0
96 rect.type = lib.SUBTITLE_ASS
97 rect.text = cython.NULL
98 rect.flags = 0
99
100 text_len: cython.Py_ssize_t = len(text)
101 rect.ass = cython.cast(cython.p_char, lib.av_malloc(text_len + 1))
102 if rect.ass == cython.NULL:
103 raise MemoryError("Failed to allocate subtitle text")
104 memcpy(rect.ass, cython.cast(cython.p_char, text), text_len)
105 rect.ass[text_len] = 0
106
107 subset.rects = (AssSubtitle(subset, 0),)
108
109 return subset
110
111 def __repr__(self):
112 return (
113 f"<{self.__class__.__module__}.{self.__class__.__name__} at 0x{id(self):x}>"
114 )
115
116 @property
117 def format(self):
118 return self.proxy.struct.format
119
120 @format.setter
121 def format(self, value: int):
122 self.proxy.struct.format = value
123
124 @property
125 def start_display_time(self):
126 return self.proxy.struct.start_display_time
127
128 @start_display_time.setter
129 def start_display_time(self, value: int):
130 self.proxy.struct.start_display_time = value
131
132 @property
133 def end_display_time(self):
134 return self.proxy.struct.end_display_time
135
136 @end_display_time.setter
137 def end_display_time(self, value: int):
138 self.proxy.struct.end_display_time = value
139
140 @property
141 def pts(self):
142 """Same as packet pts, in av.time_base."""
143 return self.proxy.struct.pts
144
145 @pts.setter
146 def pts(self, value: int):
147 self.proxy.struct.pts = value
148
149 def __len__(self):
150 return len(self.rects)
151
152 def __iter__(self):
153 return iter(self.rects)
154
155 def __getitem__(self, i):
156 return self.rects[i]
157
158
159 @cython.cfunc
160 def build_subtitle(subtitle: SubtitleSet, index: cython.int) -> Subtitle:
161 """Build an av.Stream for an existing AVStream.
162
163 The AVStream MUST be fully constructed and ready for use before this is called.
164 """
165 if index < 0 or cython.cast(cython.uint, index) >= subtitle.proxy.struct.num_rects:
166 raise ValueError("subtitle rect index out of range")
167
168 ptr: cython.pointer[lib.AVSubtitleRect] = subtitle.proxy.struct.rects[index]
169
170 if ptr.type == lib.SUBTITLE_BITMAP:
171 return BitmapSubtitle(subtitle, index)
172 if ptr.type == lib.SUBTITLE_ASS or ptr.type == lib.SUBTITLE_TEXT:
173 return AssSubtitle(subtitle, index)
174
175 raise ValueError("unknown subtitle type %r" % ptr.type)
176
177
178 @cython.cclass
179 class Subtitle:
180 """
181 An abstract base class for each concrete type of subtitle.
182 Wraps :ffmpeg:`AVSubtitleRect`
183 """
184
185 def __cinit__(self, subtitle: SubtitleSet, index: cython.int):
186 if (
187 index < 0
188 or cython.cast(cython.uint, index) >= subtitle.proxy.struct.num_rects
189 ):
190 raise ValueError("subtitle rect index out of range")
191 self.proxy = subtitle.proxy
192 self.ptr = self.proxy.struct.rects[index]
193
194 if self.ptr.type == lib.SUBTITLE_NONE:
195 self.type = b"none"
196 elif self.ptr.type == lib.SUBTITLE_BITMAP:
197 self.type = b"bitmap"
198 elif self.ptr.type == lib.SUBTITLE_TEXT:
199 self.type = b"text"
200 elif self.ptr.type == lib.SUBTITLE_ASS:
201 self.type = b"ass"
202 else:
203 raise ValueError(f"unknown subtitle type {self.ptr.type!r}")
204
205 def __repr__(self):
206 return f"<av.{self.__class__.__name__} at 0x{id(self):x}>"
207
208
209 @cython.final
210 @cython.cclass
211 class BitmapSubtitle(Subtitle):
212 def __cinit__(self, subtitle: SubtitleSet, index: cython.int):
213 self.planes = tuple(
214 BitmapSubtitlePlane(self, i) for i in range(4) if self.ptr.linesize[i]
215 )
216
217 def __repr__(self):
218 return (
219 f"<{self.__class__.__module__}.{self.__class__.__name__} "
220 f"{self.width}x{self.height} at {self.x},{self.y}; at 0x{id(self):x}>"
221 )
222
223 @property
224 def x(self):
225 return self.ptr.x
226
227 @property
228 def y(self):
229 return self.ptr.y
230
231 @property
232 def width(self):
233 return self.ptr.w
234
235 @property
236 def height(self):
237 return self.ptr.h
238
239 @property
240 def nb_colors(self):
241 return self.ptr.nb_colors
242
243 def __len__(self):
244 return len(self.planes)
245
246 def __iter__(self):
247 return iter(self.planes)
248
249 def __getitem__(self, i):
250 return self.planes[i]
251
252
253 @cython.final
254 @cython.cclass
255 class BitmapSubtitlePlane:
256 def __cinit__(self, subtitle: BitmapSubtitle, index: cython.int):
257 if index >= 4:
258 raise ValueError("BitmapSubtitles have only 4 planes")
259 if not subtitle.ptr.linesize[index]:
260 raise ValueError("plane does not exist")
261
262 self.subtitle = subtitle
263 self.index = index
264 self.buffer_size = subtitle.ptr.w * subtitle.ptr.h
265 self._buffer = cython.cast(cython.p_void, subtitle.ptr.data[index])
266
267 # New-style buffer support.
268 def __getbuffer__(self, view: cython.pointer[Py_buffer], flags: cython.int):
269 PyBuffer_FillInfo(view, self, self._buffer, self.buffer_size, 0, flags)
270
271
272 @cython.final
273 @cython.cclass
274 class AssSubtitle(Subtitle):
275 """
276 Represents an ASS/Text subtitle format, as opposed to a bitmap Subtitle format.
277 """
278
279 def __repr__(self):
280 return f"<av.AssSubtitle {self.dialogue!r} at 0x{id(self):x}>"
281
282 @property
283 def ass(self):
284 """
285 Returns the subtitle in the ASS/SSA format. Used by the vast majority of subtitle formats.
286 """
287 if self.ptr.ass is not cython.NULL:
288 return PyBytes_FromString(self.ptr.ass)
289 return b""
290
291 @property
292 def dialogue(self):
293 """
294 Extract the dialogue from the ass format. Strip comments.
295 """
296 comma_count: cython.short = 0
297 i: cython.Py_ssize_t = 0
298 state: cython.bint = False
299 ass_text: bytes = self.ass
300 char, next_char = cython.declare(cython.uchar)
301 result: bytearray = bytearray()
302 text_len: cython.Py_ssize_t = len(ass_text)
303
304 while comma_count < 8 and i < text_len:
305 if ass_text[i] == b","[0]:
306 comma_count += 1
307 i += 1
308
309 while i < text_len:
310 char = ass_text[i]
311 next_char = 0 if i + 1 >= text_len else ass_text[i + 1]
312
313 if char == b"\\"[0] and next_char == b"N"[0]:
314 result.append(b"\n"[0])
315 i += 2
316 continue
317
318 if not state:
319 if char == b"{"[0] and next_char != b"\\"[0]:
320 state = True
321 else:
322 result.append(char)
323 elif char == b"}"[0]:
324 state = False
325 i += 1
326
327 return bytes(result)
328
329 @property
330 def text(self):
331 """
332 Rarely used attribute. You're probably looking for dialogue.
333 """
334 if self.ptr.text is not cython.NULL:
335 return PyBytes_FromString(self.ptr.text)
336 return b""