Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamic FPS selection on DFXPReader #292

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions pycaption/dfxp/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@
}

DFXP_DEFAULT_LANGUAGE_CODE = "en"
DFXP_DEFAULT_FRAMERATE = "30"
DFXP_DEFAULT_FRAMERATEMULTIPLIER = "1000 1000"


class DFXPReader(BaseReader):
Expand All @@ -81,6 +83,7 @@ def __init__(self, *args, **kw):
self.read_invalid_positioning = (
kw.get('read_invalid_positioning', False))
self.nodes = []
self.framerate = self._get_framerate(DFXP_DEFAULT_FRAMERATE, DFXP_DEFAULT_FRAMERATEMULTIPLIER)

def detect(self, content):
if '</tt>' in content.lower():
Expand All @@ -101,6 +104,11 @@ def read(self, content):

default_language = dfxp_document.tt.attrs.get('xml:lang',
DEFAULT_LANGUAGE_CODE)
framerate = dfxp_document.tt.attrs.get('ttp:framerate',
DFXP_DEFAULT_FRAMERATE)
framerate_multiplier = dfxp_document.tt.attrs.get('ttp:frameratemultiplier',
DFXP_DEFAULT_FRAMERATEMULTIPLIER)
self.framerate = self._get_framerate(framerate, framerate_multiplier)

# Each div represents all the captions for a single language.
for div in dfxp_document.find_all('div'):
Expand Down Expand Up @@ -169,6 +177,13 @@ def _find_and_convert_times(self, p_tag):

return start, end

@staticmethod
def _get_framerate(framerate, framerate_multiplier):
numerator, denominator = framerate_multiplier.split()
framerate_multiplier = int(numerator) / int(denominator)
framerate = float(framerate) * framerate_multiplier
return framerate

def _convert_timestamp_to_microseconds(self, stamp):
match = TIME_EXPRESSION_PATTERN.search(stamp)
if not match:
Expand All @@ -180,8 +195,7 @@ def _convert_timestamp_to_microseconds(self, stamp):
else:
return self._convert_time_count_to_microseconds(match)

@staticmethod
def _convert_clock_time_to_microseconds(clock_time_match):
def _convert_clock_time_to_microseconds(self, clock_time_match):
microseconds = int(clock_time_match.group('hours')) * \
MICROSECONDS_PER_UNIT["hours"]
microseconds += int(clock_time_match.group('minutes')) * \
Expand All @@ -192,12 +206,11 @@ def _convert_clock_time_to_microseconds(clock_time_match):
microseconds += int(clock_time_match.group('sub_frames').ljust(
3, '0')) * MICROSECONDS_PER_UNIT["milliseconds"]
elif clock_time_match.group('frames'):
microseconds += int(clock_time_match.group('frames')) / 30 * \
microseconds += int(clock_time_match.group('frames')) / self.framerate * \
MICROSECONDS_PER_UNIT["seconds"]
return int(microseconds)

@staticmethod
def _convert_time_count_to_microseconds(time_count_match):
def _convert_time_count_to_microseconds(self, time_count_match):
value = float(time_count_match.group('time_count'))
metric = time_count_match.group("metric")
if metric == "h":
Expand All @@ -209,7 +222,7 @@ def _convert_time_count_to_microseconds(time_count_match):
elif metric == "ms":
microseconds = value * MICROSECONDS_PER_UNIT["milliseconds"]
elif metric == "f":
microseconds = value / 30 * MICROSECONDS_PER_UNIT["seconds"]
microseconds = value / self.framerate * MICROSECONDS_PER_UNIT["seconds"]
elif metric == "t":
raise NotImplementedError("The tick metric for time count is "
"not currently implemented.")
Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
sample_dfxp_invalid_positioning_value_template,
sample_dfxp_multiple_captions_with_the_same_timing,
sample_dfxp_with_ampersand_character, sample_dfxp_with_nested_spans,
dfxp_style_region_align_conflict, dfxp_with_concurrent_captions,
dfxp_style_region_align_conflict, dfxp_with_concurrent_captions, sample_dfxp_framerate
)
from tests.fixtures.microdvd import ( # noqa: F401
sample_microdvd, sample_microdvd_2,
Expand Down
47 changes: 46 additions & 1 deletion tests/fixtures/dfxp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1508,4 +1508,49 @@ def sample_dfxp_default_styling_p_tags():
</p>
</div>
</body>
</tt>"""
</tt>"""


@pytest.fixture(scope="session")
def sample_dfxp_framerate():
return """\
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<tt xml:lang="en" xmlns="http://www.w3.org/ns/ttml"
xmlns:tts="http://www.w3.org/ns/ttml#styling"
xmlns:ttm="http://www.w3.org/ns/ttml#metadata"
xmlns:ttp="http://www.w3.org/ns/ttml#parameter"
xmlns:smpte="http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt"
xmlns:m608="http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt#cea608"
ttp:timeBase="media" ttp:frameRate="24" ttp:frameRateMultiplier="1000 1001">
<head>
<metadata>
<ttm:desc>SMPTE 2052 Timed Text Captions document created by MacCaption™ version 7.0.12</ttm:desc>
<smpte:information xmlns:m608="http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt#cea608"
origin="http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt#cea608"
mode="Preserved" m608:channel="CC1" m608:programName="Demo" m608:captionService="F1C1CC"/>
</metadata>
<styling>
<style xml:id="basic" tts:color="white" tts:backgroundColor="black" tts:showBackground="whenActive"
tts:fontFamily="monospace" tts:fontSize="80%" tts:fontWeight="normal" tts:fontStyle="normal"/>
</styling>
<layout>
<region xml:id="pop1" tts:backgroundColor="transparent" tts:showBackground="whenActive"/>
<region xml:id="pop2" tts:backgroundColor="transparent" tts:showBackground="whenActive"/>
<region xml:id="pop3" tts:backgroundColor="transparent" tts:showBackground="whenActive"/>
<region xml:id="pop4" tts:backgroundColor="transparent" tts:showBackground="whenActive"/>
</layout>
</head>
<body>
<div>
<p begin="00:00:00:15" end="00:00:08:05" region="bottom" style="default">
MAN 2:<br/>
E equals m c-squared is<br/>
not about an old Einstein.
</p>
<p begin="00:00:08:05" end="00:00:09:16" region="bottom" style="default">
MAN 2:<br/>
It's all about an eternal Einstein.
</p>
</div>
</body>
</tt>"""
14 changes: 14 additions & 0 deletions tests/test_dfxp.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ def test_proper_timestamps(self, sample_dfxp):
assert 17000000 == paragraph.start
assert 18752000 == paragraph.end

def test_proper_timestamps_framerate(self, sample_dfxp_framerate):
captions = DFXPReader().read(sample_dfxp_framerate)
paragraph = captions.get_captions("en")[1]

assert 8208541 == paragraph.start
assert 9667333 == paragraph.end

def test_incorrect_time_format(self, sample_dfxp_incorrect_time_format):
with pytest.raises(CaptionReadTimingError) as exc_info:
DFXPReader().read(sample_dfxp_incorrect_time_format)
Expand Down Expand Up @@ -71,6 +78,13 @@ def test_convert_timestamp_to_microseconds(self):
with pytest.raises(NotImplementedError):
reader._convert_timestamp_to_microseconds("2.3t")

def test_convert_timestamp_to_microseconds_framerate(self):
reader = DFXPReader()
reader.framerate = 24

assert 66666 == reader._convert_timestamp_to_microseconds("1.6f")
assert 625000 == reader._convert_timestamp_to_microseconds("00:00:00:15")

@pytest.mark.parametrize('timestamp, microseconds', [
('12:23:34', 44614000000), ('23:34:45:56', 84886866666),
('34:45:56.7', 125156700000), ('13:24:35.67', 48275670000),
Expand Down