forked from bantonj/PyTimeCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpytimecode.py
More file actions
422 lines (351 loc) · 14.4 KB
/
pytimecode.py
File metadata and controls
422 lines (351 loc) · 14.4 KB
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#!-*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2014 Joshua Banton and PyTimeCode developers
#
# 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.
import re
__version__ = '0.3.1'
format_re = re.compile(r'%(?P<pad>\d+)?(?P<var>\w+)')
global_fmt = '%02H:%02M:%02S:%02f'
ffmpeg_fmt = '%02H:%02M:%02S.%05m'
class Timecode(object):
def __init__(self, framerate, start_timecode=None, start_seconds=None,
frames=None):
"""The main timecode class.
Does all the calculation over frames, so the main data it holds is
frames, then when required it converts the frames to a timecode by
using the frame rate setting.
:param str framerate: The frame rate of the Timecode instance. It
should be one of ['23.98', '24', '25', '29.97', '30', '50', '59.94',
'60', 'ms'] where "ms" equals to 1000 fps. Can not be skipped.
Setting the framerate will automatically set the :attr:`.drop_frame`
attribute to correct value.
:param start_timecode: The start timecode. Use this to be able to
set the timecode of this Timecode instance. It can be skipped and
then the frames attribute will define the timecode, and if it is also
skipped then the start_second attribute will define the start
timecode, and if start_seconds is also skipped then the default value
of '00:00:00:00' will be used.
:type start_timecode: str or None
:param start_seconds: A float or integer value showing the seconds.
:param int frames: Timecode objects can be initialized with an
integer number showing the total frames.
"""
self.drop_frame = False
self.int_framerate = -1
self.framerate = self._validate_framerate(framerate)
self.frames = None
# attribute override order
# start_timecode > frames > start_seconds
if start_timecode:
self.frames = self.tc_to_frames(start_timecode)
else:
if frames is not None: # because 0==False, and frames can be 0
self.frames = frames
elif start_seconds is not None:
self.frames = self.float_to_tc(start_seconds)
else:
# use default value of 00:00:00:00
self.frames = self.tc_to_frames('00:00:00:00')
def _validate_framerate(self, framerate):
"""validates the given framerate value
"""
# set the int_frame_rate
if framerate == '29.97':
self.int_framerate = 30
self.drop_frame = True
elif framerate == '59.94':
self.int_framerate = 60
self.drop_frame = True
elif framerate == '23.98':
self.int_framerate = 24
elif framerate == 'ms':
self.int_framerate = 1000
framerate = 1000
elif framerate == 'frames':
self.int_framerate = 1
else:
self.int_framerate = int(framerate)
return framerate
def set_timecode(self, timecode):
"""Sets the frames by using the given timecode
"""
self.frames = self.tc_to_frames(timecode)
def float_to_tc(self, seconds):
"""set the frames by using the given seconds
"""
return int(seconds * self.int_framerate)
def tc_to_frames(self, timecode):
"""Converts the given timecode to frames
"""
hours, minutes, seconds, frames = map(int, timecode.split(':'))
ffps = float(self.framerate)
if self.drop_frame:
# Number of drop frames is 6% of framerate rounded to nearest
# integer
drop_frames = int(round(ffps * .066666))
else:
drop_frames = 0
# We don't need the exact framerate anymore, we just need it rounded to
# nearest integer
ifps = self.int_framerate
# Number of frames per hour (non-drop)
hour_frames = ifps * 60 * 60
# Number of frames per minute (non-drop)
minute_frames = ifps * 60
# Total number of minutes
total_minutes = (60 * hours) + minutes
frame_number = \
((hour_frames * hours) + (minute_frames * minutes) +
(ifps * seconds) + frames) - \
(drop_frames * (total_minutes - (total_minutes // 10)))
frames = frame_number + 1
return frames
def frames_to_tc(self, frames):
"""Converts frames back to timecode
:returns str: the string representation of the current time code
"""
ffps = float(self.framerate)
if self.drop_frame:
# Number of frames to drop on the minute marks is the nearest
# integer to 6% of the framerate
drop_frames = int(round(ffps * .066666))
else:
drop_frames = 0
# Number of frames in an hour
frames_per_hour = int(round(ffps * 60 * 60))
# Number of frames in a day - timecode rolls over after 24 hours
frames_per_24_hours = frames_per_hour * 24
# Number of frames per ten minutes
frames_per_10_minutes = int(round(ffps * 60 * 10))
# Number of frames per minute is the round of the framerate * 60 minus
# the number of dropped frames
frames_per_minute = int(round(ffps)*60) - drop_frames
frame_number = frames - 1
if frame_number < 0:
# Negative time. Add 24 hours.
frame_number += frames_per_24_hours
# If frame_number is greater than 24 hrs, next operation will rollover
# clock
frame_number %= frames_per_24_hours
if self.drop_frame:
d = frame_number // frames_per_10_minutes
m = frame_number % frames_per_10_minutes
if m > drop_frames:
frame_number += (drop_frames * 9 * d) + \
drop_frames * ((m - drop_frames) // frames_per_minute)
else:
frame_number += drop_frames * 9 * d
ifps = self.int_framerate
frs = frame_number % ifps
secs = (frame_number // ifps) % 60
mins = ((frame_number // ifps) // 60) % 60
hrs = (((frame_number // ifps) // 60) // 60)
return hrs, mins, secs, frs
@classmethod
def parse_timecode(cls, timecode):
"""parses timecode string frames '00:00:00:00' or '00:00:00;00' or
milliseconds '00:00:00:000'
"""
bfr = timecode.replace(';', ':').replace('.', ':').split(':')
hrs = int(bfr[0])
mins = int(bfr[1])
secs = int(bfr[2])
frs = int(bfr[3])
return hrs, mins, secs, frs
def __iter__(self):
return self
def next(self):
self.add_frames(1)
return self
def back(self):
self.sub_frames(1)
return self
def add_frames(self, frames):
"""adds or subtracts frames number of frames
"""
self.frames += frames
def sub_frames(self, frames):
"""adds or subtracts frames number of frames
"""
self.add_frames(-frames)
def mult_frames(self, frames):
"""multiply frames
"""
self.frames *= frames
def div_frames(self, frames):
"""adds or subtracts frames number of frames"""
self.frames = self.frames / frames
def __eq__(self, other):
"""the overridden equality operator
"""
if isinstance(other, Timecode):
return self.framerate == other.framerate and \
self.frames == other.frames
elif isinstance(other, str):
new_tc = Timecode(self.framerate, other)
return self.__eq__(new_tc)
elif isinstance(other, int):
return self.frames == other
def __add__(self, other):
"""returns new Timecode instance with the given timecode or frames
added to this one
"""
# duplicate current one
tc = Timecode(self.framerate, frames=self.frames)
if isinstance(other, Timecode):
tc.add_frames(other.frame_number)
elif isinstance(other, int):
tc.add_frames(other)
else:
raise TimecodeError(
'Type %s not supported for arithmetic.' %
other.__class__.__name__
)
return tc
def __sub__(self, other):
"""returns new Timecode object with added timecodes"""
tc = Timecode(self.framerate, frames=self.frames)
if isinstance(other, Timecode):
tc.sub_frames(other.frame_number)
elif isinstance(other, int):
tc.sub_frames(other)
else:
raise TimecodeError(
'Type %s not supported for arithmetic.' %
other.__class__.__name__
)
return tc
def __mul__(self, other):
"""returns new Timecode object with added timecodes"""
if isinstance(other, Timecode):
multiplied_frames = self.frames * other.frames
elif isinstance(other, int):
multiplied_frames = self.frames * other
else:
raise TimecodeError(
'Type %s not supported for arithmetic.' %
other.__class__.__name__
)
return Timecode(self.framerate, frames=multiplied_frames)
def __div__(self, other):
"""returns new Timecode object with added timecodes"""
if isinstance(other, Timecode):
div_frames = self.frames / other.frames
elif isinstance(other, int):
div_frames = self.frames / other
else:
raise TimecodeError(
'Type %s not supported for arithmetic.' %
other.__class__.__name__
)
return Timecode(self.framerate, frames=div_frames)
def __iadd__(self, other):
return self.__add__(other)
def __isub__(self, other):
return self.__sub__(other)
def __imul__(self, other):
return self.__mul__(other)
def __idiv__(self, other):
return self.__div__(other)
def __repr__(self):
return self.format()
def __attrs__(self):
"""Replaces format directives with values."""
return {
'H': self.hrs,
'M': self.mins,
'S': self.secs,
'f': self.frs,
'm': self.ms,
}
def format(self, fmt=global_fmt):
"""Format the stdout string.
The following directives can be embedded in the format string.
Format directives support padding, for example: "%04l".
+-----------+-------------------------------------+
| Directive | Meaning |
+===========+=====================================+
| ``%h`` | hours |
+-----------+-------------------------------------+
| ``%m`` | minutes |
+-----------+-------------------------------------+
| ``%s`` | seconds |
+-----------+-------------------------------------+
| ``%f`` | frames |
+-----------+-------------------------------------+
| ``%m`` | miliseconds |
+-----------+-------------------------------------+
:param fmt: Format string. Default is '%4l %h%p%t %R'.
:return: Formatted string.
"""
format_char_types = {
'H': 'i',
'M': 'i',
'S': 'i',
'f': 'i',
'm': 'i'
}
for m in format_re.finditer(fmt):
var = m.group('var')
pad = m.group('pad')
try:
fmt_char = format_char_types[var]
except KeyError as err:
raise FormatError("Bad directive: %%%s" % var)
_old = '%s%s' % (pad or '', var)
_new = '(%s)%s%s' % (var, pad or '', fmt_char)
fmt = fmt.replace(_old, _new)
return fmt % self.__attrs__()
@property
def hrs(self):
hrs, mins, secs, frs = self.frames_to_tc(self.frames)
return hrs
@property
def mins(self):
hrs, mins, secs, frs = self.frames_to_tc(self.frames)
return mins
@property
def secs(self):
hrs, mins, secs, frs = self.frames_to_tc(self.frames)
return secs
@property
def frs(self):
hrs, mins, secs, frs = self.frames_to_tc(self.frames)
return frs
@property
def frame_number(self):
"""returns the 0 based frame number of the current timecode instance
"""
return self.frames - 1
@property
def ms(self):
"""returns the 0 based frame number of the current timecode instance
"""
hrs, mins, secs, frs = self.frames_to_tc(self.frames)
return int(frs / float(self.framerate) * 100000)
class TimecodeError(Exception):
"""Raised when an error occurred in timecode calculation
"""
pass
if __name__ == '__main__':
a = Timecode('29.97', '00:00:01:20')
b = Timecode('29.97', '00:00:00:15')
print a.format(ffmpeg_fmt)