Lucas Tonon
Lucas Tonon

Reputation: 35

How do I get duration of an In Memory Video in Python / Django?

So I was successfully using the following code to get the duration of a saved video in Django.

def get_video_length(file_path):
command = [
    'ffprobe',
    '-v',
    'error',
    '-show_entries',
    'format=duration',
    '-of',
    'default=noprint_wrappers=1:nokey=1',
    file_path
  ]

try:
    output = check_output( command, stderr=STDOUT ).decode()
except CalledProcessError as e:
    output = e.output.decode()

return output

But now I need to get the duration of an uploaded file before saving it. I have a serializer with a FileField and on validate method I should check the video duration. For instance:

class VideoSerializer(serializers.Serializer):
video = serializers.FileField(required=True, validators=[validate_media_extension, validate_video_duration])

Then on validate_video_duration I needed to call some method like get_video_length, but I need an alternative to get the duration from the video in memory. The object that I have is an instance of InMemoryUploadedFile (https://docs.djangoproject.com/en/2.2/_modules/django/core/files/uploadedfile/)

Upvotes: 1

Views: 843

Answers (1)

Daniel Hepper
Daniel Hepper

Reputation: 29967

You should be able to pass the file as stdin.

def get_video_length(inmemory_file):

    command = [
        'ffprobe',
        '-v',
        'error',
        '-show_entries',
        'format=duration',
        '-of',
        'default=noprint_wrappers=1:nokey=1',
        '-'
      ]

    try:
        output = check_output(
            command,
            stdin=inmemory_file.open(),
            stderr=STDOUT
        ).decode()
    except CalledProcessError as e:
        output = e.output.decode()

    return output

That being said, I'd expect video files to be too large to be handled in-memory.

Upvotes: 1

Related Questions