Skip to content

Commit

Permalink
FFmpegProcessor.crop() returns asset with correct dimensions.
Browse files Browse the repository at this point in the history
  • Loading branch information
eseifert committed Aug 6, 2018
1 parent a3c4cbd commit addaf8c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
19 changes: 18 additions & 1 deletion madam/ffmpeg.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,24 @@ def crop(self, asset, x, y, width, height):
if min_x == asset.width or min_y == asset.height or max_x <= min_x or max_y <= min_y:
raise OperatorError('Invalid cropping area: <x=%r, y=%r, width=%r, height=%r>' % (x, y, width, height))

return None
width = max_x - min_x
height = max_y - min_y

result = io.BytesIO()
with _FFmpegContext(asset.essence, result) as ctx:
command = ['ffmpeg', '-v', 'error',
'-i', ctx.input_path, '-codec', 'copy',
'-f:v', 'crop=w=%d:h=%d:x=%d:y=%d' % (width, height, x, y),
'-f', encoder_name, '-y', ctx.output_path]

try:
subprocess_run(command, stderr=subprocess.PIPE, check=True)
except CalledProcessError as ffmpeg_error:
error_message = ffmpeg_error.stderr.decode('utf-8')
raise OperatorError('Could not convert video asset: %s' % error_message)

return Asset(essence=result, mime_type=mime_type,
width=width, height=height)


class FFmpegMetadataProcessor(MetadataProcessor):
Expand Down
12 changes: 12 additions & 0 deletions tests/test_video.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,18 @@ def test_crop_with_original_dimensions_returns_identical_asset(self, processor,

assert cropped_asset is video_asset

def test_crop_returns_asset_with_correct_dimensions(self, processor, video_asset):
crop_width = video_asset.width // 2
crop_height = video_asset.height // 2
crop_x = (video_asset.width - crop_width) // 2
crop_y = (video_asset.height - crop_height) // 2
crop_operator = processor.crop(x=crop_x, y=crop_y, width=crop_width, height=crop_height)

cropped_asset = crop_operator(video_asset)

assert cropped_asset.width == crop_width
assert cropped_asset.height == crop_height

@pytest.mark.parametrize('x, y, width, height', [
(-DEFAULT_WIDTH, -DEFAULT_HEIGHT, DEFAULT_WIDTH, DEFAULT_HEIGHT),
(DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_WIDTH, DEFAULT_HEIGHT),
Expand Down

0 comments on commit addaf8c

Please sign in to comment.