Git Product home page Git Product logo

python-video-converter's Introduction

Video Converter

Build Status

Video Converter is a Python module for converting video files from one format and codec to another.

It uses the FFmpeg multimedia framework for actual file processing, and adds an easy-to-use API for probing and converting media files on top of it.

Quickstart

from converter import Converter
c = Converter()

info = c.probe('test1.ogg')

conv = c.convert('test1.ogg', '/tmp/output.mkv', {
    'format': 'mkv',
    'audio': {
        'codec': 'mp3',
        'samplerate': 11025,
        'channels': 2
    },
    'video': {
        'codec': 'h264',
        'width': 720,
        'height': 400,
        'fps': 15
    }})

for timecode in conv:
    print "Converting (%f) ...\r" % timecode

Documentation and tests

There's a fair amount of documentation in doc/ directory. To generate it from Sphinx sources, use:

python setup.py doc

and then visit doc/_build/html/index.html.

To run the automated tests:

python setup.py test

The test suite assumes you already have the required ffmpeg and ffprobe tools installed on your system.

Installation and requirements

To install the package:

python setup.py install

Note that this only installs the Python Video Converter library. The ffmpeg and ffprobe tools should be installed on the system separately, with all the codec and format support you require.

If you need to compile and install the tools manually, have a look at the example script test/install-ffmpeg.sh (used for automated test suite). It may or may not be useful for your requirements, so don't just blindly run it - check that it does what you need first.

Authors and Copyright

Copyright © 2011-2013. Python Video Converter contributors. See the AUTHORS.txt File.

Licensing and Patents

Although FFmpeg is licensed under LGPL/GPL, Video Converter only invokes the existing ffmpeg executables on the system (ie. doesn’t link to the ffmpeg libraries), so it doesn’t need to be LGPL/GPL as well.

The same applies to patents. If you’re in a country which recognizes software patents, it’s up to you to ensure you’re complying with the patent laws. Please read the FFMpeg Legal FAQ for more information.

python-video-converter's People

Contributors

cepreu2github avatar kami avatar koles46 avatar legrisdev avatar marvin avatar mutschler avatar omidraha avatar ouhouhsami avatar senko avatar tahajahangir avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-video-converter's Issues

Buffer or FileLike Object to converter

It could be cool to be able to give a Buffer of FileLike Object to probe and convert methods.

For example when you work with a Django FileField, you want to use filesystem abstract layer and just work with File object.

remote probing through html

Hi,

I'm trying to probe video info through a web service, I have a webserver based on Flask + uwsgi where I upload a video and would like to return video info.

I use the simple info = c.probe("path/to/filename") which works perfect on command-line, but when I run it through the html call, I get an error I can't make anything of it:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.5/dist-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "home.py", line 42, in decorated_function
    return f(*args, **kwargs)
  File "home.py", line 93, in uploaded_file
    info = c.probe(os.path.join(os.getcwd(),'uploads',filename))
  File "/usr/local/lib/python3.5/dist-packages/converter/__init__.py", line 224, in probe
    return self.ffmpeg.probe(fname, posters_as_video)
  File "/usr/local/lib/python3.5/dist-packages/converter/ffmpeg.py", line 387, in probe
    '-show_format', '-show_streams', fname])
  File "/usr/local/lib/python3.5/dist-packages/converter/ffmpeg.py", line 354, in _spawn
    close_fds=True)
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1484, in _execute_child
    self.pid = _posixsubprocess.fork_exec(
AttributeError: 'NoneType' object has no attribute 'fork_exec'

I already tried looking in current issues, #5 looked promising but solution applies to conversion, not probing.

I'm stuck. Your help is highly appreciated.

ValueError: could not convert string to float: N/A

I got this error. What am I doing wrong?

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/converter/__init__.py", line 162, in convert info = self.ffmpeg.probe(infile) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/converter/ffmpeg.py", line 367, in probe info.parse_ffprobe(raw) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/converter/ffmpeg.py", line 253, in parse_ffprobe self.format.parse_ffprobe(k, v) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/converter/ffmpeg.py", line 78, in parse_ffprobe self.duration = float(val) ValueError: could not convert string to float: N/A

"quality" option on h264 codec breaks program (error)

Hey,

I am using this code:

from converter import Converter
c = Converter()

conv = c.convert('input.mp4', 'video-transcoded.mkv', {
    'format': 'mkv',
    'audio': {
        'codec': 'ac3',
    },
    'video': {
        'codec': 'h264',
        'width': 1280,
        'height': 720,
        'quality': 25,
        'preset': 'slow'
    }
})

for timecode in conv:
    print "Converting (%f) ...\r" % timecode

And I get this error:

root@nas:/scripts/tools# python encode.test.py 
Traceback (most recent call last):
  File "encode.test.py", line 18, in <module>
    for timecode in conv:
  File "/usr/local/lib/python2.7/dist-packages/converter/__init__.py", line 184, in convert
    timeout=timeout):
  File "/usr/local/lib/python2.7/dist-packages/converter/ffmpeg.py", line 416, in convert
    p = self._spawn(cmds)
  File "/usr/local/lib/python2.7/dist-packages/converter/ffmpeg.py", line 334, in _spawn
    logger.debug('Spawning ffmpeg with command: ' + ' '.join(cmds))
TypeError: sequence item 14: expected string, int found
root@nas:/scripts/tools# 

And without quality option it works..

Please help me.

EDIT:
And I also debugged the _spawn method:
Spawning ffmpeg with command: /usr/bin/ffprobe -show_format -show_streams filename.mp4

How can I get the logger to work?

converter.ffmpeg.FFMpegError: ffmpeg binary not found: ffmpeg

I have seen the source code, and the error occurs at line 318 of the ffmpeg.py file.

I just do not understand what I did wrong. I followed the installation instructions. Does anyone know how to fix this?

Thanks in advance.


I realized that I had to install ffmpeg separately, I did so from ffmpeg.org , but it still wants me to have an ffprobe, which is within the ffmpeg package I think, so I am trying to get it configured right.

Maybe add 1 line to the readme, stating that you need to install ffmpeg separately (helpful for noobs like me)? 👍


Actually I'm getting confused on how to import a folder with C programs into a python file.

Hope someone can show me some example code to get it setup.

Thanks. :)

I get an Exception but the conversion worked.

I get the following error:

<FFMpegConvertError error="[libx264 @ 0x1fcb7c0] kb/s:4683.39", pid=30866, cmd="/usr/bin/ffmpeg -i /opt/test/media/2015/07/19/99756898-1509-48ba-84db-5b70ff2fd8d2 -acodec aac -ac 2 -ar 48000 -strict experimental -vcodec libx264 -r 30 -s 1920x1080 -aspect 1920:1080 -sn -f mp4 -y /opt/test/media/2015/07/19/99756898-1509-48ba-84db-5b70ff2fd8d2.mp4">

Even though the conversion works fine, I don't get any errors when I run it from the command line either.

cannot import name 'Converter' from 'converter'

The full traceback is...

Traceback (most recent call last):
  File "converter.py", line 2, in <module>
    from converter import Converter
  File "/home/souza/Desktop/converter.py", line 2, in <module>
    from converter import Converter
ImportError: cannot import name 'Converter' from 'converter' (/home/souza/Desktop/converter.py)

I installed using pip and the script is exactly the same as the one on README... Someone had an
idea

Windows compatible?

I'm trying to use the module on Windows 7 64bit with python 2.7 and get this error when trying to invoke the convert method of the Converter class -

File "C:\python27\lib\subprocess.py", line 637, in init
raise ValueError("close_fds is not supported on Windows "
ValueError: close_fds is not supported on Windows platforms if you redirect stdi
n/stdout/stderr

Is there a work around for this or is the module simply incompatible with windows?

Quick start example contains SyntaxError

Pasting the quick start example into a python file and running it raises a SyntaxError because the dict isn't properly closed.

$ python convert.py 
  File "convert.py", line 18
    })
     ^
SyntaxError: invalid syntax

Explicit licensing to MIT

While it has always been implicit that python-video-converter is open source and available under a permissive license, it was recently noted that we don’t say it explicitly anywhere, ie. the project doesn’t have an explicit license. As such, it can be argued it’s under all-rights-reserved copyright.

To fix this, I am proposing to (re)license to MIT, a popular open source license. The full text of the license would go into LICENSE.txt file and would read as this:

Copyright (C) 2011.-2017. Python Video Converter contributors

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.

So I’m asking all contributors to the package - are you okay with this change? If so, please indicate in the comments / reactions to this GitHub issue.

Pinging @tahajahangir @mutschler @Kami @omidraha @KoleS46 @ouhouhsami @cepreu2github @legrisdev @marvin

Why no PIP package?

I am new to python and came across this repo while searching for a good ffmpeg wrapper in python.

This one is better than all packages I found on pip. So just wondering why this is not distributed via pip?

Is there any technical reason for this?

Strange Unknown ffmpeg error [fixed]

I'm trying to run the converter using Celery. When executing the command I get this in the logfile:

[2014-05-15 13:01:50,184: INFO/Worker-1] [TRANSCODE] Retrieved transcoding task for file testvideo in 2014/05
[2014-05-15 13:01:50,184: INFO/Worker-1] [DO_TRANSCODE] Converting testvideo to flv 640x480
[2014-05-15 13:01:50,192: INFO/Worker-1] Spawning ffmpeg with command: /usr/local/bin/ffprobe -show_format -show_streams /home/storage/advideo/source/2014/05/testvideo
[2014-05-15 13:01:50,268: INFO/Worker-1] Spawning ffmpeg with command: /usr/local/bin/ffmpeg -probesize 2147483647 -analyzeduration 2147483647 -i /home/storage/advideo/source/2014/05/testvideo -acodec libmp3lame -ac 2 -ab 128k -ar 44100 -vcodec flv -r 18 -vb 1536k -s 640x360 -aspect 640:480 -vf pad=640:480:0:60 -sn -f flv -y /tmp/transcoding/91daeef2b6c245bcb3f23772d040552d.flv
[2014-05-15 13:01:50,301: ERROR/MainProcess] Task tasks.advideo[1cf57028-81f6-4776-bc5f-c02354c096a4] raised unexpected: FFMpegConvertError('Unknown ffmpeg error',)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(_args, *_kwargs)
File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 437, in protected_call
return self.run(_args, *_kwargs)
File "/data/tasks/tasks.py", line 81, in advideo
{ 'codec': 'flv', 'width': 640, 'height': 480, 'fps': 18, 'bitrate': 1536, 'mode': 'pad'}
File "/data/tasks/tasks.py", line 62, in dotranscode
for timecode in conv:
File "/usr/local/lib/python2.7/dist-packages/converter/init.py", line 213, in convert
timeout=timeout):
File "/usr/local/lib/python2.7/dist-packages/converter/ffmpeg.py", line 490, in convert
total_output, line, pid=p.pid)
FFMpegConvertError: Unknown ffmpeg error

If I do the ffmpeg command on the command line, there is no problem at al. I allready set the timeout to None

PS. I'm running Debian Wheezy. I've tried the same setup on my laptop with Linux Mint 16 without any problems. Could be a debian related problem with the process communication?

Please help.... ;-)

Custom options

Is there any way of specifying custom options? Could not find something looking at the source.
I need to add -movflags +faststart

Thumbnail rotation issue

When video is recorded from iPhone, it has some metadata information of orientation. While creating the thumbnail from ffmpeg it doesn't take that into the consideration and creates thumbnail of different orientation.

It would be great if you read that orientation in thumbnail() and pass the rotating argument to ffmpeg accordingly

May be this snippet should work under thumbnails()

        probe = self.probe(fname)
        rotation = 0
        for stream in probe.streams:
            if stream.type == 'video' and stream.metadata.get('rotate'):
                rotation = int(stream.metadata.get('rotate'))
                break
        if rotation == 180:
            cmds.extend(["-vf", "vflip,hflip"])
        elif rotation == 90:
            cmds.extend(["-vf", "transpose=1"])
        elif rotation == 270 or rotation == -90:
            cmds.extend(["-vf", "transpose=2"])

Exception when converting small videos even if the conversion worked

Hi,

When converting very small videos (for instance 2-3 seconds), the exception "Unknown ffmpeg error" is raised, because the yielded variable did not have the time to be set to True (I think). But the video has correctly been converted!

Line 493 of ffmpeg.py:

if not yielded:
    raise FFMpegConvertError('Unknown ffmpeg error', cmd,
         total_output, line, pid=p.pid)

FFMpegConvertError when running setup.py test

Running on freebsd. Compiled ffmpeg from source.

root@cringe:/usr/local/share/python-video-converter # python setup.py test
running test
.E........
======================================================================
ERROR: test_converter (__main__.TestFFMpeg)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/share/python-video-converter/test/test.py", line 297, in test_converter
    self.assertTrue(verify_progress(conv))
  File "/usr/local/share/python-video-converter/test/test.py", line 22, in verify_progress
    li = list(p)
  File "../converter/__init__.py", line 213, in convert
    timeout=timeout):
  File "../converter/ffmpeg.py", line 495, in convert
    total_output, line, pid=p.pid)
FFMpegConvertError: <FFMpegConvertError error="video:0kB audio:10kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 2.264493%", pid=60621, cmd="/usr/local/bin/ffmpeg -i test.aac -acodec libmp3lame -ac 1 -ab 32k -vn -sn -f mp3 -y /usr/local/share/python-video-converter/test/H6CUK34E50P1LGDCIV13/output.mp3">

----------------------------------------------------------------------
Ran 10 tests in 21.516s

FAILED (errors=1)
Traceback (most recent call last):
  File "setup.py", line 51, in <module>
    packages=['converter'],
  File "/usr/local/lib/python2.7/distutils/core.py", line 151, in setup
    dist.run_commands()
  File "/usr/local/lib/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "/usr/local/lib/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "setup.py", line 20, in run
    raise Exception('tests failed')
Exception: tests failed

Multiple audio streams?

Hi,

are there any plans to support multiple audio streams? that would be awesome.
I have many files with 2 or more audio streams, and curretly im only able to convert one of them (automatic selected?)

converter.ffmpeg.FFMpegError: ffmpeg binary not found: ffmpeg

This is the following stack trace when I run the script:

Traceback (most recent call last):
  File "convo.py", line 2, in <module>
    c = Converter()
  File "C:\Users\Yash\AppData\Local\Programs\Python\Python38\lib\site-packages\converter\__init__.py", line 26, in __init__
    self.ffmpeg = FFMpeg(ffmpeg_path=ffmpeg_path,
  File "C:\Users\Yash\AppData\Local\Programs\Python\Python38\lib\site-packages\converter\ffmpeg.py", line 345, in __init__
    raise FFMpegError("ffmpeg binary not found: " + self.ffmpeg_path)
converter.ffmpeg.FFMpegError: ffmpeg binary not found: ffmpeg

c.thumbnail not working with latest ffmpeg build

c.thumbnail not working with latest ffmpeg build, and also raises errors when running the tests.

Changing the following in ffmpeg.py on line 415 seems to fix the issue:

  • currently: 'sameq'
  • changed to: '-q:v','0'

If you could please review, that would be appreciated.

Thanks

Add support for subtitles

It would be good if this script would allow converting subtitles also. Example ffmpeg usage:

C:\ffmpeg.exe -i "D:\input.mkv" -vcodec copy -acodec copy -scodec mov_text -map 0 D:\output.mp4

MP4 output requires the mov_text codec, but other containers could use copy instead.

The option -map 0 also copies ALL streams instead of just the first of each. Perhaps you want to expand upon that as well as per http://ffmpeg.org/ffmpeg.html#Subtitle-options_003a so users can copy all subtitle streams.

Fast Seeking

To enable fast seeking we need to specify option -ss before input parameter -i. However in python-video-converter by default will use slow seeking because option -ss placed after input -i, see:

cmds = [self.ffmpeg_path, '-i', infile]

Here is my (dirty) implementation to enable fast seeking, rizkyabdilah@a17054c

Please review and consider implement fast seeking, thanks.

probe incorrectly report video stream for mp3 files with poster image

Here is a STREAM section of poster image for a mp3 file, reporter by ffprobe:

[STREAM]
index=1
codec_name=mjpeg
codec_long_name=MJPEG (Motion JPEG)
profile=unknown
codec_type=video
codec_time_base=1/90000
codec_tag_string=[0][0][0][0]
codec_tag=0x0000
width=0
height=0
has_b_frames=0
sample_aspect_ratio=0:1
display_aspect_ratio=0:0
pix_fmt=unknown
level=-99
timecode=N/A
id=N/A
r_frame_rate=90000/1
avg_frame_rate=0/0
time_base=1/90000
start_pts=N/A
start_time=N/A
duration_ts=26818560
duration=297.984000
bit_rate=N/A
nb_frames=N/A
nb_read_frames=N/A
nb_read_packets=N/A
DISPOSITION:default=0
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=1
TAG:title=
TAG:comment=Cover (front)
[/STREAM]

add pypi license classifier

setup.py doesn't contain a pypi license classifier and there's also no license file in the root of the tree, so I'm wondering what license the project is actually using.

Unicode Error while calling convert function

When i was trying to covert a WMV file it shows this error

Traceback (most recent call last):
File "/virtualenvs/celery/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(_args, *_kwargs)
File "/virtualenvs/celery/local/lib/python2.7/site-packages/celery/app/trace.py", line 437, in protected_call
return self.run(_args, *_kwargs)
File "/virtualenvs/celery/inviterjobs/workers/finalvideo/tasks.py", line 38, in finalvideo
for timecode in converter_convert:
File "/virtualenvs/celery/local/lib/python2.7/site-packages/converter/ffmpeg.py", line 453, in convert
ret = ret.decode(console_encoding)
File "/virtualenvs/celery/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc2 in position 9: unexpected end of data

Incompatible with Threads

This module, as excellent as it is, does not seem to allow you to convert videos if the conversation is kicked off in a child thread.

Having done some digging, it seems to be down to the use of Pythons signals library, whose docs state: "only the main thread can set a new signal handler".

It would be nice if the module supported threads, so that multiple videos could be converted simultaneously.

Timeout Error

I found out the timeout in ffmpeg.convert have no meaning, because the function signal.alarm is in the While True loop.

Issue with multihreading with PythonVideoConverter in Django

Hi,
I am running the python video converter library without multi threading inside Django. It's working fine. but while Enabling the multi threading It's giving error.

ValueError: signal only works in main thread

OS- ubuntu18.04
Python version - 3.6

Thanks for your Time

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.