Skip to content

Video editing with Python

First 'real' commit of MoviePy. I'm so excited ! Let's hope it's not too buggy.

Zulko55c2602c3308
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..61a16668
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,40 @@
+*.py[cod]
+
+# C extensions
+*.so
+
+# Packages
+*.egg
+*.egg-info
+dist
+build
+eggs
+parts
+bin
+var
+sdist
+develop-eggs
+.installed.cfg
+lib
+lib64
+__pycache__
+
+# Installer logs
+pip-log.txt
+
+# Unit test / coverage reports
+.coverage
+.tox
+nosetests.xml
+
+# Translations
+*.mo
+
+# Mr Developer
+.mr.developer.cfg
+.project
+.pydevproject
+
+# Temp files
+
+*~
diff --git a/CHANGES.txt b/CHANGES.txt
new file mode 100644
index 00000000..d5aa3c02
--- /dev/null
+++ b/CHANGES.txt
@@ -0,0 +1 @@
+v0.1.0, 08/2013 -- Initial release.
diff --git a/LICENCE.txt b/LICENCE.txt
new file mode 100644
index 00000000..9b50051b
--- /dev/null
+++ b/LICENCE.txt
@@ -0,0 +1,25 @@
+The MIT License (MIT)
+[OSI Approved License]
+
+The MIT License (MIT)
+
+Copyright (c) 2013 Zulko
+
+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.
+
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 00000000..2985d188
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,2 @@
+include *.txt
+recursive-include docs *.txt
diff --git a/README.md b/README.md
index e69de29b..89acc195 100644
--- a/README.md
+++ b/README.md
@@ -0,0 +1,63 @@
+MoviePy
+========
+
+MoviePy is Python module for script-based movie editing, which enables
+basic operations (cuts, concatenations, title insertions) to be done
+in a few lines. It can also be used for advanced compositing.
+
+See the full documentation online at `http://zulko.github.io/moviepy/`_
+
+
+A typical MoviePy script looks like that:
+
+ from moviepy import *
+
+ # Load myHolidays.mp4 and select the subclip 00:00:50 - 00:00:60
+ clip = MovieClip("myHolidays.mp4").subclip(50,60)
+
+ # Generate a text clip (many options available ! )
+ txt_clip = TextClip("My Holidays 2013",fontsize=70,color='white')
+ txt_clip = txt_clip.set_pos(('center','center')).set_duration(10)
+
+ # Overlay the text clip above the first clip
+ video = CompositeVideoClip(clip.size, [clip, txt_clip])
+
+ # write the result to a file in any format
+ video.write("myHolidays_edited.avi",fps=25, codec='DIVX')
+
+
+
+Download And Installation
+--------------------------
+
+You can `download MoviePy`_ on Github. Just unzip everything in one folder, open a terminal and type ::
+
+ sudo python setup.py install
+
+MoviePy is a very small program but it relies on many existing Python libraries that you will need to install first:
+
+- `OpenCV 2.4.6`_ or more recent, to read and write movie files.
+- PyGame_ for video and sound previews
+- `Scipy and Numpy`_, for image and sound manipulation
+- `Scikit Image`_ for advanced image manipulation
+- The Decorator_ module for better code readability
+
+And it needs some external software:
+
+- ffmpeg_, for writing movies and many other useful operations.
+- imageMagick_ for text generation, GIF support, and much more in the future.
+
+All these are normally easy to install (on linux, they will certainly be in your repos).
+
+
+.. _`download MoviePy`: https://github.com/Zulko/moviepy
+.. _`OpenCV 2.4.6`: http://sourceforge.net/projects/opencvlibrary/files/
+.. _Pygame: http://www.pygame.org/download.shtml
+.. _`Scipy and Numpy`: http://www.scipy.org/install.html
+.. _`Scikit Image`: http://scikit-image.org/download.html
+.. _Decorator: https://pypi.python.org/pypi/decorator
+
+
+.. _ffmpeg: http://www.ffmpeg.org/download.html
+.. _imageMagick: http://www.imagemagick.org/script/index.php
+
diff --git a/a__init__.py b/a__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/docs/Makefile b/docs/Makefile
new file mode 100644
index 00000000..a1f83541
--- /dev/null
+++ b/docs/Makefile
@@ -0,0 +1,180 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS = -E
+SPHINXBUILD = sphinx-build
+PAPER =
+BUILDDIR = ../../docs
+PDFBUILDDIR = /tmp
+PDF = ../manual.pdf
+
+# User-friendly check for sphinx-build
+ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
+$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
+endif
+
+# Internal variables.
+PAPEROPT_a4 = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+# the i18n builder cannot share the environment and doctrees with the others
+I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+
+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
+
+help:
+ @echo "Please use \`make <target>' where <target> is one of"
+ @echo " html to make standalone HTML files"
+ @echo " dirhtml to make HTML files named index.html in directories"
+ @echo " singlehtml to make a single large HTML file"
+ @echo " pickle to make pickle files"
+ @echo " json to make JSON files"
+ @echo " htmlhelp to make HTML files and a HTML help project"
+ @echo " qthelp to make HTML files and a qthelp project"
+ @echo " devhelp to make HTML files and a Devhelp project"
+ @echo " epub to make an epub"
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+ @echo " latexpdf to make LaTeX files and run them through pdflatex"
+ @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
+ @echo " text to make text files"
+ @echo " man to make manual pages"
+ @echo " texinfo to make Texinfo files"
+ @echo " info to make Texinfo files and run them through makeinfo"
+ @echo " gettext to make PO message catalogs"
+ @echo " changes to make an overview of all changed/added/deprecated items"
+ @echo " xml to make Docutils-native XML files"
+ @echo " pseudoxml to make pseudoxml-XML files for display purposes"
+ @echo " linkcheck to check all external links for integrity"
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
+
+clean:
+ rm -rf $(BUILDDIR)/*
+
+html:
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+dirhtml:
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+singlehtml:
+ $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
+ @echo
+ @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
+
+pickle:
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+ @echo
+ @echo "Build finished; now you can process the pickle files."
+
+json:
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
+ @echo
+ @echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+ @echo
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
+ ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+qthelp:
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+ @echo
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/MoviePy.qhcp"
+ @echo "To view the help file:"
+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/MoviePy.qhc"
+
+devhelp:
+ $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
+ @echo
+ @echo "Build finished."
+ @echo "To view the help file:"
+ @echo "# mkdir -p $$HOME/.local/share/devhelp/MoviePy"
+ @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/MoviePy"
+ @echo "# devhelp"
+
+epub:
+ $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
+ @echo
+ @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
+
+latex:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo
+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+ @echo "Run \`make' in that directory to run these through (pdf)latex" \
+ "(use \`make latexpdf' here to do that automatically)."
+
+latexpdf:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(PDFBUILDDIR)/latex
+ @echo "Running LaTeX files through pdflatex..."
+ $(MAKE) -C $(PDFBUILDDIR)/latex all-pdf
+ cp $(PDFBUILDDIR)/latex/*.pdf $(PDF)
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+latexpdfja:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo "Running LaTeX files through platex and dvipdfmx..."
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+text:
+ $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
+ @echo
+ @echo "Build finished. The text files are in $(BUILDDIR)/text."
+
+man:
+ $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
+ @echo
+ @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
+
+texinfo:
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+ @echo
+ @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
+ @echo "Run \`make' in that directory to run these through makeinfo" \
+ "(use \`make info' here to do that automatically)."
+
+info:
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+ @echo "Running Texinfo files through makeinfo..."
+ make -C $(BUILDDIR)/texinfo info
+ @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
+
+gettext:
+ $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
+ @echo
+ @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
+
+changes:
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+ @echo
+ @echo "The overview file is in $(BUILDDIR)/changes."
+
+linkcheck:
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+ @echo
+ @echo "Link check complete; look for any errors in the above output " \
+ "or in $(BUILDDIR)/linkcheck/output.txt."
+
+doctest:
+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+ @echo "Testing of doctests in the sources finished, look at the " \
+ "results in $(BUILDDIR)/doctest/output.txt."
+
+xml:
+ $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
+ @echo
+ @echo "Build finished. The XML files are in $(BUILDDIR)/xml."
+
+pseudoxml:
+ $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
+ @echo
+ @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
diff --git a/docs/_static/logo.png b/docs/_static/logo.png
new file mode 100644
index 00000000..29d9b34c
Binary files /dev/null and b/docs/_static/logo.png differ
diff --git a/docs/_static/moviepy.css b/docs/_static/moviepy.css
new file mode 100644
index 00000000..e63a929b
--- /dev/null
+++ b/docs/_static/moviepy.css
@@ -0,0 +1,18 @@
+@import url(flasky.css)
+
+.indexwrapper .sphinxsidebar { visibility: hidden; }
+
+.indexwrapper div.body #wand.section h1 {
+ background-image: url(wand.png);
+ background-size: 75px 75px;
+ background-repeat: no-repeat;
+ padding-left: 75px;
+ padding-top: 10px;
+ height: 75px;
+}
+
+.logo img.logo { width: 120px; height: 120px; padding-right: 30px; }
+
+div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body h6
+ { font-family: 'Times New Roman', 'Garamond', 'Georgia', serif; }
+
diff --git a/docs/_themes/.gitignore b/docs/_themes/.gitignore
new file mode 100644
index 00000000..66b6e4c2
--- /dev/null
+++ b/docs/_themes/.gitignore
@@ -0,0 +1,3 @@
+*.pyc
+*.pyo
+.DS_Store
diff --git a/docs/_themes/LICENSE b/docs/_themes/LICENSE
new file mode 100644
index 00000000..8daab7ee
--- /dev/null
+++ b/docs/_themes/LICENSE
@@ -0,0 +1,37 @@
+Copyright (c) 2010 by Armin Ronacher.
+
+Some rights reserved.
+
+Redistribution and use in source and binary forms of the theme, with or
+without modification, are permitted provided that the following conditions
+are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+* The names of the contributors may not be used to endorse or
+ promote products derived from this software without specific
+ prior written permission.
+
+We kindly ask you to only use these themes in an unmodified manner just
+for Flask and Flask-related products, not for unrelated projects. If you
+like the visual style and want to use it for your own projects, please
+consider making some larger changes to the themes (such as changing
+font faces, sizes, colors or margins).
+
+THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
diff --git a/docs/_themes/README b/docs/_themes/README
new file mode 100644
index 00000000..b3292bdf
--- /dev/null
+++ b/docs/_themes/README
@@ -0,0 +1,31 @@
+Flask Sphinx Styles
+===================
+
+This repository contains sphinx styles for Flask and Flask related
+projects. To use this style in your Sphinx documentation, follow
+this guide:
+
+1. put this folder as _themes into your docs folder. Alternatively
+ you can also use git submodules to check out the contents there.
+2. add this to your conf.py:
+
+ sys.path.append(os.path.abspath('_themes'))
+ html_theme_path = ['_themes']
+ html_theme = 'flask'
+
+The following themes exist:
+
+- 'flask' - the standard flask documentation theme for large
+ projects
+- 'flask_small' - small one-page theme. Intended to be used by
+ very small addon libraries for flask.
+
+The following options exist for the flask_small theme:
+
+ [options]
+ index_logo = '' filename of a picture in _static
+ to be used as replacement for the
+ h1 in the index.rst file.
+ index_logo_height = 120px height of the index logo
+ github_fork = '' repository name on github for the
+ "fork me" badge
diff --git a/docs/_themes/flask/layout.html b/docs/_themes/flask/layout.html
new file mode 100644
index 00000000..5caa4e29
--- /dev/null
+++ b/docs/_themes/flask/layout.html
@@ -0,0 +1,25 @@
+{%- extends "basic/layout.html" %}
+{%- block extrahead %}
+ {{ super() }}
+ {% if theme_touch_icon %}
+ <link rel="apple-touch-icon" href="{{ pathto('_static/' ~ theme_touch_icon, 1) }}" />
+ {% endif %}
+ <link media="only screen and (max-device-width: 480px)" href="{{
+ pathto('_static/small_flask.css', 1) }}" type= "text/css" rel="stylesheet" />
+{% endblock %}
+{%- block relbar2 %}{% endblock %}
+{% block header %}
+ {{ super() }}
+ {% if pagename == 'index' %}
+ <div class=indexwrapper>
+ {% endif %}
+{% endblock %}
+{%- block footer %}
+ <div class="footer">
+ &copy; Copyright {{ copyright }}.
+ Created using <a href="http://sphinx.pocoo.org/">Sphinx</a>.
+ </div>
+ {% if pagename == 'index' %}
+ </div>
+ {% endif %}
+{%- endblock %}
diff --git a/docs/_themes/flask/relations.html b/docs/_themes/flask/relations.html
new file mode 100644
index 00000000..3bbcde85
--- /dev/null
+++ b/docs/_themes/flask/relations.html
@@ -0,0 +1,19 @@
+<h3>Related Topics</h3>
+<ul>
+ <li><a href="{{ pathto(master_doc) }}">Documentation overview</a><ul>
+ {%- for parent in parents %}
+ <li><a href="{{ parent.link|e }}">{{ parent.title }}</a><ul>
+ {%- endfor %}
+ {%- if prev %}
+ <li>Previous: <a href="{{ prev.link|e }}" title="{{ _('previous chapter')
+ }}">{{ prev.title }}</a></li>
+ {%- endif %}
+ {%- if next %}
+ <li>Next: <a href="{{ next.link|e }}" title="{{ _('next chapter')
+ }}">{{ next.title }}</a></li>
+ {%- endif %}
+ {%- for parent in parents %}
+ </ul></li>
+ {%- endfor %}
+ </ul></li>
+</ul>
diff --git a/docs/_themes/flask/static/flasky.css_t b/docs/_themes/flask/static/flasky.css_t
new file mode 100644
index 00000000..b5ca39bc
--- /dev/null
+++ b/docs/_themes/flask/static/flasky.css_t
@@ -0,0 +1,395 @@
+/*
+ * flasky.css_t
+ * ~~~~~~~~~~~~
+ *
+ * :copyright: Copyright 2010 by Armin Ronacher.
+ * :license: Flask Design License, see LICENSE for details.
+ */
+
+{% set page_width = '940px' %}
+{% set sidebar_width = '220px' %}
+
+@import url("basic.css");
+
+/* -- page layout ----------------------------------------------------------- */
+
+body {
+ font-family: 'Georgia', serif;
+ font-size: 17px;
+ background-color: white;
+ color: #000;
+ margin: 0;
+ padding: 0;
+}
+
+div.document {
+ width: {{ page_width }};
+ margin: 30px auto 0 auto;
+}
+
+div.documentwrapper {
+ float: left;
+ width: 100%;
+}
+
+div.bodywrapper {
+ margin: 0 0 0 {{ sidebar_width }};
+}
+
+div.sphinxsidebar {
+ width: {{ sidebar_width }};
+}
+
+hr {
+ border: 1px solid #B1B4B6;
+}
+
+div.body {
+ background-color: #ffffff;
+ color: #3E4349;
+ padding: 0 30px 0 30px;
+}
+
+img.floatingflask {
+ padding: 0 0 10px 10px;
+ float: right;
+}
+
+div.footer {
+ width: {{ page_width }};
+ margin: 20px auto 30px auto;
+ font-size: 14px;
+ color: #888;
+ text-align: right;
+}
+
+div.footer a {
+ color: #888;
+}
+
+div.related {
+ display: none;
+}
+
+div.sphinxsidebar a {
+ color: #444;
+ text-decoration: none;
+ border-bottom: 1px dotted #999;
+}
+
+div.sphinxsidebar a:hover {
+ border-bottom: 1px solid #999;
+}
+
+div.sphinxsidebar {
+ font-size: 14px;
+ line-height: 1.5;
+}
+
+div.sphinxsidebarwrapper {
+ padding: 18px 10px;
+}
+
+div.sphinxsidebarwrapper p.logo {
+ padding: 0 0 20px 0;
+ margin: 0;
+ text-align: center;
+}
+
+div.sphinxsidebar h3,
+div.sphinxsidebar h4 {
+ font-family: 'Garamond', 'Georgia', serif;
+ color: #444;
+ font-size: 24px;
+ font-weight: normal;
+ margin: 0 0 5px 0;
+ padding: 0;
+}
+
+div.sphinxsidebar h4 {
+ font-size: 20px;
+}
+
+div.sphinxsidebar h3 a {
+ color: #444;
+}
+
+div.sphinxsidebar p.logo a,
+div.sphinxsidebar h3 a,
+div.sphinxsidebar p.logo a:hover,
+div.sphinxsidebar h3 a:hover {
+ border: none;
+}
+
+div.sphinxsidebar p {
+ color: #555;
+ margin: 10px 0;
+}
+
+div.sphinxsidebar ul {
+ margin: 10px 0;
+ padding: 0;
+ color: #000;
+}
+
+div.sphinxsidebar input {
+ border: 1px solid #ccc;
+ font-family: 'Georgia', serif;
+ font-size: 1em;
+}
+
+/* -- body styles ----------------------------------------------------------- */
+
+a {
+ color: #004B6B;
+ text-decoration: underline;
+}
+
+a:hover {
+ color: #6D4100;
+ text-decoration: underline;
+}
+
+div.body h1,
+div.body h2,
+div.body h3,
+div.body h4,
+div.body h5,
+div.body h6 {
+ font-family: 'Garamond', 'Georgia', serif;
+ font-weight: normal;
+ margin: 30px 0px 10px 0px;
+ padding: 0;
+}
+
+{% if theme_index_logo %}
+div.indexwrapper h1 {
+ text-indent: -999999px;
+ background: url({{ theme_index_logo }}) no-repeat center center;
+ height: {{ theme_index_logo_height }};
+}
+{% endif %}
+
+div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }
+div.body h2 { font-size: 180%; }
+div.body h3 { font-size: 150%; }
+div.body h4 { font-size: 130%; }
+div.body h5 { font-size: 100%; }
+div.body h6 { font-size: 100%; }
+
+a.headerlink {
+ color: #ddd;
+ padding: 0 4px;
+ text-decoration: none;
+}
+
+a.headerlink:hover {
+ color: #444;
+ background: #eaeaea;
+}
+
+div.body p, div.body dd, div.body li {
+ line-height: 1.4em;
+}
+
+div.admonition {
+ background: #fafafa;
+ margin: 20px -30px;
+ padding: 10px 30px;
+ border-top: 1px solid #ccc;
+ border-bottom: 1px solid #ccc;
+}
+
+div.admonition tt.xref, div.admonition a tt {
+ border-bottom: 1px solid #fafafa;
+}
+
+dd div.admonition {
+ margin-left: -60px;
+ padding-left: 60px;
+}
+
+div.admonition p.admonition-title {
+ font-family: 'Garamond', 'Georgia', serif;
+ font-weight: normal;
+ font-size: 24px;
+ margin: 0 0 10px 0;
+ padding: 0;
+ line-height: 1;
+}
+
+div.admonition p.last {
+ margin-bottom: 0;
+}
+
+div.highlight {
+ background-color: white;
+}
+
+dt:target, .highlight {
+ background: #FAF3E8;
+}
+
+div.note {
+ background-color: #eee;
+ border: 1px solid #ccc;
+}
+
+div.seealso {
+ background-color: #ffc;
+ border: 1px solid #ff6;
+}
+
+div.topic {
+ background-color: #eee;
+}
+
+p.admonition-title {
+ display: inline;
+}
+
+p.admonition-title:after {
+ content: ":";
+}
+
+pre, tt {
+ font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;
+ font-size: 0.9em;
+}
+
+img.screenshot {
+}
+
+tt.descname, tt.descclassname {
+ font-size: 0.95em;
+}
+
+tt.descname {
+ padding-right: 0.08em;
+}
+
+img.screenshot {
+ -moz-box-shadow: 2px 2px 4px #eee;
+ -webkit-box-shadow: 2px 2px 4px #eee;
+ box-shadow: 2px 2px 4px #eee;
+}
+
+table.docutils {
+ border: 1px solid #888;
+ -moz-box-shadow: 2px 2px 4px #eee;
+ -webkit-box-shadow: 2px 2px 4px #eee;
+ box-shadow: 2px 2px 4px #eee;
+}
+
+table.docutils td, table.docutils th {
+ border: 1px solid #888;
+ padding: 0.25em 0.7em;
+}
+
+table.field-list, table.footnote {
+ border: none;
+ -moz-box-shadow: none;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+}
+
+table.footnote {
+ margin: 15px 0;
+ width: 100%;
+ border: 1px solid #eee;
+ background: #fdfdfd;
+ font-size: 0.9em;
+}
+
+table.footnote + table.footnote {
+ margin-top: -15px;
+ border-top: none;
+}
+
+table.field-list th {
+ padding: 0 0.8em 0 0;
+}
+
+table.field-list td {
+ padding: 0;
+}
+
+table.footnote td.label {
+ width: 0px;
+ padding: 0.3em 0 0.3em 0.5em;
+}
+
+table.footnote td {
+ padding: 0.3em 0.5em;
+}
+
+dl {
+ margin: 0;
+ padding: 0;
+}
+
+dl dd {
+ margin-left: 30px;
+}
+
+blockquote {
+ margin: 0 0 0 30px;
+ padding: 0;
+}
+
+ul, ol {
+ margin: 10px 0 10px 30px;
+ padding: 0;
+}
+
+pre {
+ background: #eee;
+ padding: 7px 30px;
+ margin: 15px -30px;
+ line-height: 1.3em;
+}
+
+dl pre, blockquote pre, li pre {
+ margin-left: -60px;
+ padding-left: 60px;
+}
+
+dl dl pre {
+ margin-left: -90px;
+ padding-left: 90px;
+}
+
+tt {
+ background-color: #ecf0f3;
+ color: #222;
+ /* padding: 1px 2px; */
+}
+
+tt.xref, a tt {
+ background-color: #FBFBFB;
+ border-bottom: 1px solid white;
+}
+
+a.reference {
+ text-decoration: none;
+ border-bottom: 1px dotted #004B6B;
+}
+
+a.reference:hover {
+ border-bottom: 1px solid #6D4100;
+}
+
+a.footnote-reference {
+ text-decoration: none;
+ font-size: 0.7em;
+ vertical-align: top;
+ border-bottom: 1px dotted #004B6B;
+}
+
+a.footnote-reference:hover {
+ border-bottom: 1px solid #6D4100;
+}
+
+a:hover tt {
+ background: #EEE;
+}
diff --git a/docs/_themes/flask/static/small_flask.css b/docs/_themes/flask/static/small_flask.css
new file mode 100644
index 00000000..1c6df309
--- /dev/null
+++ b/docs/_themes/flask/static/small_flask.css
@@ -0,0 +1,70 @@
+/*
+ * small_flask.css_t
+ * ~~~~~~~~~~~~~~~~~
+ *
+ * :copyright: Copyright 2010 by Armin Ronacher.
+ * :license: Flask Design License, see LICENSE for details.
+ */
+
+body {
+ margin: 0;
+ padding: 20px 30px;
+}
+
+div.documentwrapper {
+ float: none;
+ background: white;
+}
+
+div.sphinxsidebar {
+ display: block;
+ float: none;
+ width: 102.5%;
+ margin: 50px -30px -20px -30px;
+ padding: 10px 20px;
+ background: #333;
+ color: white;
+}
+
+div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p,
+div.sphinxsidebar h3 a {
+ color: white;
+}
+
+div.sphinxsidebar a {
+ color: #aaa;
+}
+
+div.sphinxsidebar p.logo {
+ display: none;
+}
+
+div.document {
+ width: 100%;
+ margin: 0;
+}
+
+div.related {
+ display: block;
+ margin: 0;
+ padding: 10px 0 20px 0;
+}
+
+div.related ul,
+div.related ul li {
+ margin: 0;
+ padding: 0;
+}
+
+div.footer {
+ display: none;
+}
+
+div.bodywrapper {
+ margin: 0;
+}
+
+div.body {
+ min-height: 0;
+ padding: 0;
+}
diff --git a/docs/_themes/flask/theme.conf b/docs/_themes/flask/theme.conf
new file mode 100644
index 00000000..26b77e51
--- /dev/null
+++ b/docs/_themes/flask/theme.conf
@@ -0,0 +1,9 @@
+[theme]
+inherit = basic
+stylesheet = flasky.css
+pygments_style = flask_theme_support.FlaskyStyle
+
+[options]
+index_logo = 'logo.png'
+index_logo_height = 120px
+github_fork = 'http://github.com/zulko/moviepy'
diff --git a/docs/_themes/flask_small/layout.html b/docs/_themes/flask_small/layout.html
new file mode 100644
index 00000000..aa1716aa
--- /dev/null
+++ b/docs/_themes/flask_small/layout.html
@@ -0,0 +1,22 @@
+{% extends "basic/layout.html" %}
+{% block header %}
+ {{ super() }}
+ {% if pagename == 'index' %}
+ <div class=indexwrapper>
+ {% endif %}
+{% endblock %}
+{% block footer %}
+ {% if pagename == 'index' %}
+ </div>
+ {% endif %}
+{% endblock %}
+{# do not display relbars #}
+{% block relbar1 %}{% endblock %}
+{% block relbar2 %}
+ {% if theme_github_fork %}
+ <a href="http://github.com/{{ theme_github_fork }}"><img style="position: fixed; top: 0; right: 0; border: 0;"
+ src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a>
+ {% endif %}
+{% endblock %}
+{% block sidebar1 %}{% endblock %}
+{% block sidebar2 %}{% endblock %}
diff --git a/docs/_themes/flask_small/static/flasky.css_t b/docs/_themes/flask_small/static/flasky.css_t
new file mode 100644
index 00000000..fe2141c5
--- /dev/null
+++ b/docs/_themes/flask_small/static/flasky.css_t
@@ -0,0 +1,287 @@
+/*
+ * flasky.css_t
+ * ~~~~~~~~~~~~
+ *
+ * Sphinx stylesheet -- flasky theme based on nature theme.
+ *
+ * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.
+ * :license: BSD, see LICENSE for details.
+ *
+ */
+
+@import url("basic.css");
+
+/* -- page layout ----------------------------------------------------------- */
+
+body {
+ font-family: 'Georgia', serif;
+ font-size: 17px;
+ color: #000;
+ background: white;
+ margin: 0;
+ padding: 0;
+}
+
+div.documentwrapper {
+ float: left;
+ width: 100%;
+}
+
+div.bodywrapper {
+ margin: 40px auto 0 auto;
+ width: 700px;
+}
+
+hr {
+ border: 1px solid #B1B4B6;
+}
+
+div.body {
+ background-color: #ffffff;
+ color: #3E4349;
+ padding: 0 30px 30px 30px;
+}
+
+img.floatingflask {
+ padding: 0 0 10px 10px;
+ float: right;
+}
+
+div.footer {
+ text-align: right;
+ color: #888;
+ padding: 10px;
+ font-size: 14px;
+ width: 650px;
+ margin: 0 auto 40px auto;
+}
+
+div.footer a {
+ color: #888;
+ text-decoration: underline;
+}
+
+div.related {
+ line-height: 32px;
+ color: #888;
+}
+
+div.related ul {
+ padding: 0 0 0 10px;
+}
+
+div.related a {
+ color: #444;
+}
+
+/* -- body styles ----------------------------------------------------------- */
+
+a {
+ color: #004B6B;
+ text-decoration: underline;
+}
+
+a:hover {
+ color: #6D4100;
+ text-decoration: underline;
+}
+
+div.body {
+ padding-bottom: 40px; /* saved for footer */
+}
+
+div.body h1,
+div.body h2,
+div.body h3,
+div.body h4,
+div.body h5,
+div.body h6 {
+ font-family: 'Garamond', 'Georgia', serif;
+ font-weight: normal;
+ margin: 30px 0px 10px 0px;
+ padding: 0;
+}
+
+{% if theme_index_logo %}
+div.indexwrapper h1 {
+ text-indent: -999999px;
+ background: url({{ theme_index_logo }}) no-repeat center center;
+ height: {{ theme_index_logo_height }};
+}
+{% endif %}
+
+div.body h2 { font-size: 180%; }
+div.body h3 { font-size: 150%; }
+div.body h4 { font-size: 130%; }
+div.body h5 { font-size: 100%; }
+div.body h6 { font-size: 100%; }
+
+a.headerlink {
+ color: white;
+ padding: 0 4px;
+ text-decoration: none;
+}
+
+a.headerlink:hover {
+ color: #444;
+ background: #eaeaea;
+}
+
+div.body p, div.body dd, div.body li {
+ line-height: 1.4em;
+}
+
+div.admonition {
+ background: #fafafa;
+ margin: 20px -30px;
+ padding: 10px 30px;
+ border-top: 1px solid #ccc;
+ border-bottom: 1px solid #ccc;
+}
+
+div.admonition p.admonition-title {
+ font-family: 'Garamond', 'Georgia', serif;
+ font-weight: normal;
+ font-size: 24px;
+ margin: 0 0 10px 0;
+ padding: 0;
+ line-height: 1;
+}
+
+div.admonition p.last {
+ margin-bottom: 0;
+}
+
+div.highlight{
+ background-color: white;
+}
+
+dt:target, .highlight {
+ background: #FAF3E8;
+}
+
+div.note {
+ background-color: #eee;
+ border: 1px solid #ccc;
+}
+
+div.seealso {
+ background-color: #ffc;
+ border: 1px solid #ff6;
+}
+
+div.topic {
+ background-color: #eee;
+}
+
+div.warning {
+ background-color: #ffe4e4;
+ border: 1px solid #f66;
+}
+
+p.admonition-title {
+ display: inline;
+}
+
+p.admonition-title:after {
+ content: ":";
+}
+
+pre, tt {
+ font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;
+ font-size: 0.85em;
+}
+
+img.screenshot {
+}
+
+tt.descname, tt.descclassname {
+ font-size: 0.95em;
+}
+
+tt.descname {
+ padding-right: 0.08em;
+}
+
+img.screenshot {
+ -moz-box-shadow: 2px 2px 4px #eee;
+ -webkit-box-shadow: 2px 2px 4px #eee;
+ box-shadow: 2px 2px 4px #eee;
+}
+
+table.docutils {
+ border: 1px solid #888;
+ -moz-box-shadow: 2px 2px 4px #eee;
+ -webkit-box-shadow: 2px 2px 4px #eee;
+ box-shadow: 2px 2px 4px #eee;
+}
+
+table.docutils td, table.docutils th {
+ border: 1px solid #888;
+ padding: 0.25em 0.7em;
+}
+
+table.field-list, table.footnote {
+ border: none;
+ -moz-box-shadow: none;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+}
+
+table.footnote {
+ margin: 15px 0;
+ width: 100%;
+ border: 1px solid #eee;
+}
+
+table.field-list th {
+ padding: 0 0.8em 0 0;
+}
+
+table.field-list td {
+ padding: 0;
+}
+
+table.footnote td {
+ padding: 0.5em;
+}
+
+dl {
+ margin: 0;
+ padding: 0;
+}
+
+dl dd {
+ margin-left: 30px;
+}
+
+pre {
+ padding: 0;
+ margin: 15px -30px;
+ padding: 8px;
+ line-height: 1.3em;
+ padding: 7px 30px;
+ background: #eee;
+ border-radius: 2px;
+ -moz-border-radius: 2px;
+ -webkit-border-radius: 2px;
+}
+
+dl pre {
+ margin-left: -60px;
+ padding-left: 60px;
+}
+
+tt {
+ background-color: #ecf0f3;
+ color: #222;
+ /* padding: 1px 2px; */
+}
+
+tt.xref, a tt {
+ background-color: #FBFBFB;
+}
+
+a:hover tt {
+ background: #EEE;
+}
diff --git a/docs/_themes/flask_small/theme.conf b/docs/_themes/flask_small/theme.conf
new file mode 100644
index 00000000..542b4625
--- /dev/null
+++ b/docs/_themes/flask_small/theme.conf
@@ -0,0 +1,10 @@
+[theme]
+inherit = basic
+stylesheet = flasky.css
+nosidebar = true
+pygments_style = flask_theme_support.FlaskyStyle
+
+[options]
+index_logo = ''
+index_logo_height = 120px
+github_fork = ''
diff --git a/docs/_themes/flask_theme_support.py b/docs/_themes/flask_theme_support.py
new file mode 100644
index 00000000..33f47449
--- /dev/null
+++ b/docs/_themes/flask_theme_support.py
@@ -0,0 +1,86 @@
+# flasky extensions. flasky pygments style based on tango style
+from pygments.style import Style
+from pygments.token import Keyword, Name, Comment, String, Error, \
+ Number, Operator, Generic, Whitespace, Punctuation, Other, Literal
+
+
+class FlaskyStyle(Style):
+ background_color = "#f8f8f8"
+ default_style = ""
+
+ styles = {
+ # No corresponding class for the following:
+ #Text: "", # class: ''
+ Whitespace: "underline #f8f8f8", # class: 'w'
+ Error: "#a40000 border:#ef2929", # class: 'err'
+ Other: "#000000", # class 'x'
+
+ Comment: "italic #8f5902", # class: 'c'
+ Comment.Preproc: "noitalic", # class: 'cp'
+
+ Keyword: "bold #004461", # class: 'k'
+ Keyword.Constant: "bold #004461", # class: 'kc'
+ Keyword.Declaration: "bold #004461", # class: 'kd'
+ Keyword.Namespace: "bold #004461", # class: 'kn'
+ Keyword.Pseudo: "bold #004461", # class: 'kp'
+ Keyword.Reserved: "bold #004461", # class: 'kr'
+ Keyword.Type: "bold #004461", # class: 'kt'
+
+ Operator: "#582800", # class: 'o'
+ Operator.Word: "bold #004461", # class: 'ow' - like keywords
+
+ Punctuation: "bold #000000", # class: 'p'
+
+ # because special names such as Name.Class, Name.Function, etc.
+ # are not recognized as such later in the parsing, we choose them
+ # to look the same as ordinary variables.
+ Name: "#000000", # class: 'n'
+ Name.Attribute: "#c4a000", # class: 'na' - to be revised
+ Name.Builtin: "#004461", # class: 'nb'
+ Name.Builtin.Pseudo: "#3465a4", # class: 'bp'
+ Name.Class: "#000000", # class: 'nc' - to be revised
+ Name.Constant: "#000000", # class: 'no' - to be revised
+ Name.Decorator: "#888", # class: 'nd' - to be revised
+ Name.Entity: "#ce5c00", # class: 'ni'
+ Name.Exception: "bold #cc0000", # class: 'ne'
+ Name.Function: "#000000", # class: 'nf'
+ Name.Property: "#000000", # class: 'py'
+ Name.Label: "#f57900", # class: 'nl'
+ Name.Namespace: "#000000", # class: 'nn' - to be revised
+ Name.Other: "#000000", # class: 'nx'
+ Name.Tag: "bold #004461", # class: 'nt' - like a keyword
+ Name.Variable: "#000000", # class: 'nv' - to be revised
+ Name.Variable.Class: "#000000", # class: 'vc' - to be revised
+ Name.Variable.Global: "#000000", # class: 'vg' - to be revised
+ Name.Variable.Instance: "#000000", # class: 'vi' - to be revised
+
+ Number: "#990000", # class: 'm'
+
+ Literal: "#000000", # class: 'l'
+ Literal.Date: "#000000", # class: 'ld'
+
+ String: "#4e9a06", # class: 's'
+ String.Backtick: "#4e9a06", # class: 'sb'
+ String.Char: "#4e9a06", # class: 'sc'
+ String.Doc: "italic #8f5902", # class: 'sd' - like a comment
+ String.Double: "#4e9a06", # class: 's2'
+ String.Escape: "#4e9a06", # class: 'se'
+ String.Heredoc: "#4e9a06", # class: 'sh'
+ String.Interpol: "#4e9a06", # class: 'si'
+ String.Other: "#4e9a06", # class: 'sx'
+ String.Regex: "#4e9a06", # class: 'sr'
+ String.Single: "#4e9a06", # class: 's1'
+ String.Symbol: "#4e9a06", # class: 'ss'
+
+ Generic: "#000000", # class: 'g'
+ Generic.Deleted: "#a40000", # class: 'gd'
+ Generic.Emph: "italic #000000", # class: 'ge'
+ Generic.Error: "#ef2929", # class: 'gr'
+ Generic.Heading: "bold #000080", # class: 'gh'
+ Generic.Inserted: "#00A000", # class: 'gi'
+ Generic.Output: "#888", # class: 'go'
+ Generic.Prompt: "#745334", # class: 'gp'
+ Generic.Strong: "bold #000000", # class: 'gs'
+ Generic.Subheading: "bold #800080", # class: 'gu'
+ Generic.Traceback: "bold #a40000", # class: 'gt'
+ }
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 00000000..ec11bcb2
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,311 @@
+# -*- coding: utf-8 -*-
+#
+# MoviePy documentation build configuration file, created by
+# sphinx-quickstart on Sat Jul 13 14:47:48 2013.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys, os
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#sys.path.insert(0, os.path.abspath('.'))
+
+# -- General configuration -----------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.pngmath', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode']
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'MoviePy'
+copyright = u'2013, Zulko'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = '0.1'
+# The full version, including alpha/beta/rc tags.
+release = '0.1'
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ['_build']
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+# If true, keep warnings as "system message" paragraphs in the built documents.
+#keep_warnings = False
+
+
+# -- Options for HTML output ---------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+sys.path.append(os.path.abspath('_themes'))
+sys.path.append("../moviepy")
+html_theme_path = ['_themes']
+html_theme = 'flask'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+#html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'MoviePydoc'
+
+
+# -- Options for LaTeX output --------------------------------------------------
+
+latex_elements = {
+# The paper size ('letterpaper' or 'a4paper').
+#'papersize': 'letterpaper',
+
+# The font size ('10pt', '11pt' or '12pt').
+#'pointsize': '10pt',
+
+# Additional stuff for the LaTeX preamble.
+#'preamble': '',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass [howto/manual]).
+latex_documents = [
+ ('index', 'MoviePy.tex', u'MoviePy Documentation',
+ u'Zulko', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output --------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ ('index', 'moviepy', u'MoviePy Documentation',
+ [u'Zulko'], 1)
+]
+
+# If true, show URL addresses after external links.
+#man_show_urls = False
+
+
+# -- Options for Texinfo output ------------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+# dir menu entry, description, category)
+texinfo_documents = [
+ ('index', 'MoviePy', u'MoviePy Documentation',
+ u'Zulko', 'MoviePy', 'One line description of project.',
+ 'Miscellaneous'),
+]
+
+# Documents to append as an appendix to all manuals.
+#texinfo_appendices = []
+
+# If false, no module index is generated.
+#texinfo_domain_indices = True
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+#texinfo_show_urls = 'footnote'
+
+# If true, do not generate a @detailmenu in the "Top" node's menu.
+#texinfo_no_detailmenu = False
+
+
+# -- Options for Epub output ---------------------------------------------------
+
+# Bibliographic Dublin Core info.
+epub_title = u'MoviePy'
+epub_author = u'Zulko'
+epub_publisher = u'Zulko'
+epub_copyright = u'2013, Zulko'
+
+# The language of the text. It defaults to the language option
+# or en if the language is not set.
+#epub_language = ''
+
+# The scheme of the identifier. Typical schemes are ISBN or URL.
+#epub_scheme = ''
+
+# The unique identifier of the text. This can be a ISBN number
+# or the project homepage.
+#epub_identifier = ''
+
+# A unique identification for the text.
+#epub_uid = ''
+
+# A tuple containing the cover image and cover page html template filenames.
+#epub_cover = ()
+
+# A sequence of (type, uri, title) tuples for the guide element of content.opf.
+#epub_guide = ()
+
+# HTML files that should be inserted before the pages created by sphinx.
+# The format is a list of tuples containing the path and title.
+#epub_pre_files = []
+
+# HTML files shat should be inserted after the pages created by sphinx.
+# The format is a list of tuples containing the path and title.
+#epub_post_files = []
+
+# A list of files that should not be packed into the epub file.
+#epub_exclude_files = []
+
+# The depth of the table of contents in toc.ncx.
+#epub_tocdepth = 3
+
+# Allow duplicate toc entries.
+#epub_tocdup = True
+
+# Fix unsupported image types using the PIL.
+#epub_fix_images = False
+
+# Scale large images.
+#epub_max_image_width = 0
+
+# If 'no', URL addresses will not be shown.
+#epub_show_urls = 'inline'
+
+# If false, no index is generated.
+#epub_use_index = True
+
+#autodoc_member_order = 'bysource'
diff --git a/docs/cookbook.rst b/docs/cookbook.rst
new file mode 100644
index 00000000..53d896b4
--- /dev/null
+++ b/docs/cookbook.rst
@@ -0,0 +1,22 @@
+.. _cookbook:
+
+Cookbook
+========
+The current policy of MoviePy is that most advanced features should not
+be included in the core program, but should rather be provided by
+individual coders as code snippets, by means of blogs, gits, etc.
+Then one can make a customized ``moviepytools.py`` module containing
+the advanced methods that one uses most.
+
+In this cookbook you will find a few scripts for useful tasks
+such as tracking an object, generating end credits, etc...
+For more artistic and less general functionalities, see the :ref:`examples` .
+
+
+.. toctree::
+ :maxdepth: 2
+
+ cookbook/gradientEffect
+ cookbook/credits
+ cookbook/compoFromImage
+ cookbook/blurred_face
diff --git a/docs/cookbook/blurred_face.rst b/docs/cookbook/blurred_face.rst
new file mode 100644
index 00000000..50aa3bce
--- /dev/null
+++ b/docs/cookbook/blurred_face.rst
@@ -0,0 +1,122 @@
+========================================
+Tracking and blurring someone's face
+========================================
+
+
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/FWCKYTRCrBI&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/FWCKYTRCrBI&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+First we will need to track the face, i.e. to get two functions ``fx`` and ``fy`` such that ``(fx(t),fy(t))`` gives the position of the center of the head at time ``t``. This will be easily done with
+:ref:`VideoClip.manual_tracking`. Then we will need to blur the area of the video around the center of the head.
+
+To track an object in a video you write: ::
+
+ txy = myClip.manual_tracking(0,5,fps=5)
+
+This will display the frames of ``myClip`` between t=0s and t=5s and on each frame it will wait for you to click on the face. It then returns a list ``[(t1,x1,y1),(t2,x2,y2)]`` of the positions that you have clicked.
+
+The next snippet uses these data to make the two functions ``(fx(t),fy(t))`` discussed above: ::
+
+ from scipy.interpolate import interp1d
+
+ def txy2functions(txyList):
+ """
+ Takes the output of VideoClip.manual_tracking and returns
+ 2 functions (fx,fy) where fx : t -> x(t) and fy : t -> y(t)
+ """
+ tt,xx,yy = zip(*txyList)
+ fx = interp1d(tt,xx,bounds_error=False, fill_value=xx[0])
+ fy = interp1d(tt,yy,bounds_error=False, fill_value=yy[0])
+ return fx,fy
+
+And the coming function makes a filter that blurs the regions around ``(fx(t),fy(t))``: ::
+
+ import cv2
+
+ def blur_filter(fx,fy,r_zone,r_blur=None):
+ """
+ Returns a filter that will blurr a moving part of
+ the frames. The position of the blur at time t is
+ defined by (fx(t), fy(t)), the radius of the blurring
+ by r_zone and the intensity of the blurring by r_blur.
+ """
+
+ if r_blur==None: r_blur = 2*r_zone/3
+
+ def fl(gf,t):
+ im = gf(t)
+ h,w,d = im.shape
+ x,y = int(fx(t)),int(fy(t))
+ x1,x2 = max(0,x-r_zone),min(x+r_zone,w)
+ y1,y2 = max(0,y-r_zone),min(y+r_zone,h)
+ reg_res = y2-y1,x2-x1
+ mask = cv2.circle(np.zeros(reg_res),
+ (r_zone,r_zone),r_zone,1,-1, lineType=cv2.LINE_AA)
+ mask = np.dstack(3*[mask])
+ orig = im[y1:y2,x1:x2]
+ blurred = cv2.blur(orig,(r_blur,r_blur))
+ im[y1:y2,x1:x2] = mask*blurred + (1-mask)*orig
+ return im
+
+ return fl
+
+Finally, here is the script: ::
+
+ # Because we will work with sound and we do not want to carry around
+ # the sound of the whole original movie, we first extract the
+ # interesting part of the movie (run this line only once):
+
+ ffmpeg.extract_subclip("./videos/chaplin.mp4",411.7,421.7+3,
+ "charlotSub.mp4")
+
+ # Now we have a shorter movie that we can load
+ chaplin = MovieClip("charlotSub.mp4", audio=True)
+ clip = chaplin.subclip(0, chaplin.duration-3)
+
+
+ # THE THREE NEXT LINES ARE FOR THE MANUAL TRACKING AND
+ # MUST BE COMMENTED ONCE THE TRACKING HAS BEEN DONE
+ # (AT FIRST RUN OF THE SCRIPT)
+ txyList = clip.manual_tracking(fps=6)
+ with open("chaplin_txy.dat",'w+') as f:
+ pickle.dump(txyList,f)
+
+ # Load the tracking data (see comment above)
+ with open("chaplin_txy.dat",'r') as f:
+ fx,fy = txy2functions(pickle.load(f))
+
+
+ # blur the head in the clip
+ clip_blurred = clip.fl(blur_filter(fx,fy,25))
+
+ # Generate the text
+ txt = TextClip("Hey you ! \n You're blurry!", color='grey',
+ font = "Century-Schoolbook-Italic", fontsize=40)
+
+ # Put the text on a grey background
+ txt = txt.on_color(chaplin.size,(25,25,25),("center","center"))
+
+ # Concatenate the clip with the blur and the clip with text
+ # Set the audio of concat so that there will also be music
+ # when the text is playing.
+
+ final = concat([clip_blurred,txt.set_duration(3)])
+ final = final.set_audio(chaplin.audio)
+
+ # write to a file. Here we use the 'XVID' codec because
+ # 'raw' is too heavy and 'DIVX' is too ugly.
+
+ final.to_movie('blurredChaplin.avi',fps=24, codec='XVID')
+
+ # This 13s movie with sound and special effects was generated
+ # in six seconds.
diff --git a/docs/cookbook/compoFromImage.rst b/docs/cookbook/compoFromImage.rst
new file mode 100644
index 00000000..60d1b569
--- /dev/null
+++ b/docs/cookbook/compoFromImage.rst
@@ -0,0 +1,112 @@
+======================================
+Placing clips according to a picture
+======================================
+
+So how do you do some complex compositing like this ?
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/1hdgNxX-tas&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/1hdgNxX-tas&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+It takes a lot of bad taste and... the right tools !
+
+So we first make a picture that indicates the regions where the clips will be. This picture (that I made with Inkscape) is a *.png* that looks like this:
+
+.. figure:: motif.jpeg
+
+The next function finds the regions in the picture. For each region found it returns a mask that defines the region, and a tuple ``(x1,y1,x2,y2)`` defining a bounding rectangle giving the position of the region in the picture. ::
+
+ import scipy.ndimage as spim
+ from pylab import *
+
+ def pic2regions(pic,render=True, crop=True):
+ """
+ Finds the different regions contained in a delimited by
+ picture as a list of elements (maskClip,(x1,y1,x2,y2)).
+ maskClip is a clip ready to be used as a mask delimiting
+ the region. The resolution of maskClip is that of 'pic'
+ if crop=True, else, it is the size of the region.
+ render=True pops a picture rendering which region has
+ which number
+ """
+
+ if len(pic.shape)>2:
+ pic = pic[:,:,0]
+ objects, num = spim.label(pic)
+ num = num+1
+ masks = [(objects==i).astype(float) for i in range(num)]
+ mamasks = [np.ma.masked_values(m,0) for m in masks]
+ h,w = pic.shape
+ XX,YY = [a for a in np.meshgrid(range(w),range(h))]
+ XXc = [ XX*c for c in mamasks]
+ YYc = [ YY*c for c in mamasks]
+ boxes = [ map(int,(xxc.min(),yyc.min(),xxc.max(),yyc.max()))
+ for xxc, yyc in zip(XXc, YYc)]
+
+ if crop:
+ masks = [ m[y1:y2,x1:x2]
+ for m,(x1,y1,x2,y2) in zip (masks,boxes)]
+ print [m.shape for m in masks]
+
+ maskClips = [ImageClip(m) for m in masks]
+
+ if render:
+ print "found %d objects"%(num)
+ fig,ax = subplots(2)
+ ax[0].axis('off')
+ ax[0].imshow(objects)
+ ax[1].imshow([range(num)],interpolation='nearest')
+ ax[1].set_yticks([])
+
+ return zip(maskClips,boxes)
+
+This function returns a list of the regions found. To help visualize which element of the list corresponds to which region in the picture, ``pic2regions`` splashes a Matplotlib figure giving the index of each region. For our picture, it returned this: ::
+
+ im = imread("./ultracompositing/motif.png")
+ regs = pic2regions(im)
+
+.. figure:: matplotlibCompo.jpeg
+
+Finally, we load 8 different video clips that we assign to the different regions. In our video, this implied for each of these clips
+
+- Resizing the clip so that it will fill the region.
+- Placing each clip at its position on the picture
+- Giving to each clip a mask that will shape it like the region.
+
+So here is the final script: ::
+
+ # We load height clips from the US National Parks.
+ # These are public domain. :D
+ clips = [MovieClip(n).subclip(20,25) for n in
+ [ "./videos/romo_0004.mov",
+ "./videos/apis-0001.mov",
+ "./videos/romo_0001.mov",
+ "./videos/elma_s0003.mov",
+ "./videos/elma_s0002.mov",
+ "./videos/calo-0007.mov",
+ "./videos/grsm_0005.mov",
+ "./videos/grsm_0002.mov"]]
+
+ im = imread("./ultracompositing/motif.png")
+ size = w,h = im.shape[:2][::-1]
+ regs = pic2regions(im,crop=True)
+ # eliminate the first region found (it is the border)
+ regs = regs[1:]
+ masks = [r[0] for r in regs]
+ poss = [(x1,y1) for m,(x1,y1,x2,y2) in regs]
+ comp_clips = [c.resize(m.size).set_mask(m).set_pos(p)
+ for c,m,p in zip(clips,masks,poss)]
+
+ cc = CompositeVideoClip(size,comp_clips)
+ cc.resize(0.5).preview()
+
+Nice and short ! And you can get very creative with this kind of tricks.
+
diff --git a/docs/cookbook/credits.jpeg b/docs/cookbook/credits.jpeg
new file mode 100644
index 00000000..234a8b1f
Binary files /dev/null and b/docs/cookbook/credits.jpeg differ
diff --git a/docs/cookbook/credits.rst b/docs/cookbook/credits.rst
new file mode 100644
index 00000000..c856773b
--- /dev/null
+++ b/docs/cookbook/credits.rst
@@ -0,0 +1,102 @@
+.. _autocredits:
+
+==========================
+Making Credits
+==========================
+
+Another advantage of scripting : we will see how to generate and animate some neat end credits. So here is a file ``EndCredits.txt``, which describes end credits in some weird yet understandable syntax (``.blank 4`` means "leave for blank lines"). ::
+
+ .blank 4
+
+ ..Executive Story Editor
+ MARCEL DURAND
+
+ ..Associate Producers
+ MARTIN MARCEL
+ DIDIER MARTIN
+
+ ..Music Supervisor
+ JEAN DIDIER
+
+ ..First Assistant Director
+ THOMAS JEAN
+
+ ..Second Assistant Director
+ MARIE THOMAS
+
+ ..Guest Starring
+ EDMOND MARIE
+ MARIE JACQUES
+ JACQUES MARIVON
+ MARIVONNE ANDRE
+
+ .blank 4
+
+And here is a function that can parse this file to produce some neat credits: ::
+
+ def make_credits(creditfile,width,stretch=30,color='white',
+ stroke_color='black', stroke_width=2,
+ font='Impact-Normal',fontsize=60):
+ """ Makes a nice credits picture from a text file"""
+
+
+ # PARSE THE TXT FILE
+
+ with open(creditfile) as f:
+ lines = f.readlines()
+
+ lines = filter(lambda x:not x.startswith('\n'),lines)
+ texts = []
+ oneline=True
+ for l in lines:
+ if l.startswith('.blank'):
+ for i in range(int(l.split(' ')[1])):
+ texts.append(['\n','\n'])
+ elif l.startswith('..'):
+ texts.append([l[2:],''])
+ oneline=True
+ else:
+ if oneline:
+ texts.append(['',l])
+ oneline=False
+ else:
+ texts.append(['\n',l])
+
+ left,right = [ "".join(l) for l in zip(*texts)]
+
+ # MAKE TWO COLUMNS FOR THE CREDITS
+
+ left,right = [TextClip(txt,color=color,stroke_color=stroke_color,
+ stroke_width=stroke_width,font=font,
+ fontsize=fontsize,align=al)
+ for txt,al in [(left,'East'),(right,'West')]]
+
+
+ cc = CompositeVideoClip((left.w+right.w+stretch,right.h),
+ [left, right.set_pos((left.w+stretch,0))],
+ transparent=True)
+
+ # SCALE TO THE REQUIRED SIZE
+
+ scaled = cc.resize(width=width)
+
+ # TRANSFORM THE WHOLE CREDIT CLIP INTO AN ImageCLip
+
+ imclip = ImageClip(scaled.get_frame(0))
+ amask = ImageClip(scaled.mask.get_frame(0),ismask=True)
+
+ return imclip.set_mask(amask)
+
+Applied on the previous text file, this function returns something like this:
+
+.. figure:: credits.jpeg
+
+Now, you can make this picture move with something like ::
+
+ CompositeVideoClip(myVideo.res,
+ [credits.set_pos(lambda t:('center',-speed*t))])
+
+You can also do much more ! See for instance :ref:`mountainMask`.
+
+
+
diff --git a/docs/cookbook/gradient.jpeg b/docs/cookbook/gradient.jpeg
new file mode 100644
index 00000000..2c609b70
Binary files /dev/null and b/docs/cookbook/gradient.jpeg differ
diff --git a/docs/cookbook/gradientEffect.rst b/docs/cookbook/gradientEffect.rst
new file mode 100644
index 00000000..522d8bdf
--- /dev/null
+++ b/docs/cookbook/gradientEffect.rst
@@ -0,0 +1,46 @@
+.. _gradients:
+
+=================================
+Gradient Effects
+=================================
+
+Gradients effects are extremely useful, for instance to make custom masks.
+In most graphical softwares, if you point two positions ``x1`` and ``x2``
+on the screen and choose two colors, you obtain a nice
+color gradient like this:
+
+.. figure:: gradient.jpeg
+
+Here is an efficient implementation of the gradient ::
+
+ def gradient(size,c1,c2,col1=0,col2=1.0):
+ """
+ size : size of the final picture
+ c1 : (x,y) of the border point of col1
+ c2 : (x,y) of the border point of col2
+ col1, col2: can be floats to create gradient masks, or
+ RGB arrays to create gradient images.
+ """
+
+ c1, c2, col1, col2 = map(np.array,
+ [c1[::-1], c2[::-1], col1, col2])
+ vector = c2 - c1
+ norm = np.linalg.norm(vector)
+ n_vec = vector/norm**2
+ M = np.meshgrid(range(size[1]),range(size[0]))
+ arr = (dstack(M)-c1).dot(n_vec)
+ arr = np.minimum(1,np.maximum(0,arr))
+ return (col2*arr + col1- col1*arr).T
+
+And while we are at it, here is the code for a bilateral gradient: ::
+
+ def biGradient(size,c1,vector,col1=0,col2=1.0):
+ """ Returns a picture of size `res` where the pixel
+ at position `center` is of color `col1` and the color
+ is fading is fading to `col2` in the direction of
+ `vector` AND the opposite direction """
+ c1, vector = map(np.array,[c1,vector])
+ l1 = gradient(size,c1,c1+vector,col1,col2)
+ l2 = gradient(size,c1,c1-vector,col1,col2)
+ return np.minimum(l1,l2)
+
diff --git a/docs/cookbook/matplotlibCompo.jpeg b/docs/cookbook/matplotlibCompo.jpeg
new file mode 100644
index 00000000..fdc8bd99
Binary files /dev/null and b/docs/cookbook/matplotlibCompo.jpeg differ
diff --git a/docs/cookbook/motif.jpeg b/docs/cookbook/motif.jpeg
new file mode 100644
index 00000000..bb55873a
Binary files /dev/null and b/docs/cookbook/motif.jpeg differ
diff --git a/docs/examples.rst b/docs/examples.rst
new file mode 100644
index 00000000..7c68931d
--- /dev/null
+++ b/docs/examples.rst
@@ -0,0 +1,24 @@
+.. _examples:
+
+Example Scripts
+===============
+
+Here are a few example scripts to get you started, including, as promised,
+the scripts used for all the clips of the demonstration video. This section
+may soon be replaced by a list of links to internet resources.
+
+
+.. toctree::
+ :maxdepth: 1
+
+ examples/textmovingletters
+ examples/musicVideo
+ examples/soundExample
+ examples/starwarslike
+ examples/mountainMask
+ examples/the_end
+ examples/freezepainting
+ examples/logo
+
+
+
diff --git a/docs/examples/freezepainting.rst b/docs/examples/freezepainting.rst
new file mode 100644
index 00000000..b5eb5651
--- /dev/null
+++ b/docs/examples/freezepainting.rst
@@ -0,0 +1,86 @@
+=============================================
+Freezing a movie frame with a painting effect
+=============================================
+
+That's an effect that we have seen a lot in westerns and such.
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/aC5CifkacSI&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/aC5CifkacSI&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+Before
+starting let us see how to make a photo look more like a painting. It
+can be done easy as follows:
+
+- Find the edges of the image with the Sobel algorithm. What you obtain
+ is what looks like a hand-drawing of the photo.
+- Multiply the image to make the colors flashier, and add the contours
+ obtained at the previous step.
+
+Which is implemented in just a few lines of code: ::
+
+ from moviepy import *
+ from skimage.filter import sobel
+
+ def to_painting(image,saturation = 1.4,black = 0.006):
+ """ transforms any photo into some kind of painting """
+ edges = sobel(image.mean(axis=2))
+ darkening = black*(255*np.dstack(3*[edges]))
+ painting = saturation*image-darkening
+ return np.maximum(0,np.minimum(255,painting)).astype('uint8')
+
+Now let us see the actual script. We work on an Audrey Hepburn clip taken
+from *Charade*, a movie which is not copyrighted due to a copyright
+omission (good for us).
+
+The final clip will be the concatenation of three part: the part before
+the effect, the part with the effect, and the part after the effect.
+The part with the effect is obtained as follows:
+
+- Take the frame to freeze and make a "painted image" of it. Make it a clip.
+- Add a text clip saying "Audrey" to the "painted image" clip.
+- Overlay the painted clip over the original frame, but make it appear and
+ disappear with a fading effect.
+
+Here you are for the code: ::
+
+ charade = MovieClip("./videos/charade.mp4", audio=False)
+ tf = 19*60+21.0 # Time of the freeze, 19'21
+
+ # WE TAKE THE SUBCLIPS WHICH ARE 2 SECONDS BEFORE & AFTER THE FREEZE
+
+ clip_before = charade.subclip(tf -2,tf )
+ clip_after = charade.subclip(tf ,tf +2)
+
+
+ # THE FRAME TO FREEZE
+
+ im_freeze = charade.get_frame(tf)
+ painting = ImageClip(to_painting(im_freeze))
+ txt = TextClip('Audrey',font='Amiri-regular',fontsize=35)
+ painting_txt = CompositeVideoClip(charade.size,
+ [painting,txt.set_pos((10,180))])
+
+ # FADEIN/FADEOUT EFFECT ON THE PAINTED IMAGE
+
+ painting_fading = CompositeVideoClip(charade.size,
+ [ImageClip(im_freeze),
+ painting_txt.with_mask().fadein(0.3).
+ set_duration(3).
+ fadeout(0.3)])
+
+ # FINAL CLIP AND RENDERING
+
+ final_clip = concat([ clip_before,
+ painting_fading.set_duration(3.6),
+ clip_after])
+
+ final_clip.to_movie('audrey.avi',fps=charade.fps)
diff --git a/docs/examples/logo.rst b/docs/examples/logo.rst
new file mode 100644
index 00000000..1233c38b
--- /dev/null
+++ b/docs/examples/logo.rst
@@ -0,0 +1,33 @@
+=================================
+MoviePy logo with a moving shadow
+=================================
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/TG86KzL18NA&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/TG86KzL18NA&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+Here the logo is a picture, while the shadow is actually a black rectangle taking the whole screen, overlaid over the logo, but with a moving mask composed of a bi-gradient, such that only one (moving) part of the rectangle is visible. See :ref:`gradients` for the code of the function `biGradient`: ::
+
+ def f(t,size,duration, a = np.pi/3, thickness = 20):
+ w,h = size
+ v = thickness* np.array([np.cos(a),np.sin(a)])[::-1]
+ center = [int(t*w/duration),h/2]
+ return biGradientScreen(size,center,v,0.6,0.0)
+
+ w,h = moviesize = (720,380)
+ im = ImageClip("./logo_descr.png", transparent=True)
+ im = im.resize(width=w/2)
+
+ duration = 1
+ shade = ColorClip(moviesize,col=(0,0,0)).with_mask()
+ shade.mask.get_frame = lambda t : f(t,moviesize,duration)
+ cc = CompositeVideoClip(moviesize,[im.set_pos(2*["center"]),shade])
+
+ cc.subclip(0,duration).to_movie("moviepy_logo.avi",fps=24)
diff --git a/docs/examples/mountainMask.rst b/docs/examples/mountainMask.rst
new file mode 100644
index 00000000..3445d20d
--- /dev/null
+++ b/docs/examples/mountainMask.rst
@@ -0,0 +1,60 @@
+.. _mountainMask:
+
+Partially Hidden credits
+-----------------------------------
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/NsTgBah6Ebk&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/NsTgBah6Ebk&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+First, see in :ref:`autocredits` how to make credits automatically with MoviePy. Before seeing the code for this video, here is a tutorial video that explains the different steps (also made with MoviePy):
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/7tKABfc0Yzw&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/7tKABfc0Yzw&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+
+
+
+
+And here is the code: ::
+
+ from moviepy import *
+
+ # Load the mountains clip, cut it, slow it down, make it look darker
+ clip = MovieClip('./mountain.mov',audio=False).subclip(37,46).speedx(0.4)
+ clip = clip.fl_image(lambda pic: (0.7*pic).astype('uint8'))
+
+ # Save the first frame to later make a mask with GIMP (only once)
+ # clip.save_frame('mountain.png')
+
+ # Load the mountain mask made with GIMP
+ mountainmask = ImageClip('./credits/mountainMask2.png',ismask=True)
+
+ # Generate the credits from a text file
+ credits = make_credits('./credits/credits.txt',3*clip.w/4)
+
+ # Make the credits scroll. Here, 10 pixels per second
+ mov_credits= CompositeVideoClip(clip.size,[
+ clip,
+ credits.set_pos(lambda t:('center',-10*t)),
+ clip.set_mask(mountainmask)])
+
+ final = CompositeVideoClip(clip.size,[clip,mov_credits.set_end(25)])
+ final.subclip(8,15).to_movie("credits_mount.avi",fps=24,codec='DIVX')
diff --git a/docs/examples/musicVideo.rst b/docs/examples/musicVideo.rst
new file mode 100644
index 00000000..1c37e968
--- /dev/null
+++ b/docs/examples/musicVideo.rst
@@ -0,0 +1,61 @@
+======================
+A simple music video
+======================
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/AqGZ4JFkQTU&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/AqGZ4JFkQTU&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+
+This is an example, with no sound (lame for a music video), soon to be
+replaced with a real music video example (the code will be 99% the same).
+The philosophy of MoviePy is that for each new music video I will make,
+I will just have to copy/paste this code, and modify a few lines. ::
+
+ from moviepy import *
+
+
+ # UKULELE CLIP, OBTAINED BY CUTTING AND CROPPING
+ # RAW FOOTAGE
+
+ ukulele = (MovieClip("./videos/moi_ukulele.MOV",audio=False).
+ subclip(60+33,60+50).
+ crop(486,180,1196,570))
+
+ w,h = moviesize = ukulele.size
+
+ # THE PIANO FOOTAGE IS DOWNSIZED, HAS A WHITE MARGIN, IS
+ # IN THE BOTTOM LEFT CORNER
+
+ piano = (MovieClip("./videos/douceamb.mp4",audio=False).
+ subclip(30,50).
+ resize((w/3,h/3)).
+ margin(6,color=(255,255,255)). #white margin
+ margin(bottom=20,right=20, opacity=0). # transparent
+ set_pos(('right','bottom')) )
+
+
+ # A CLIP WITH A TEXT AND A BLACK SEMI-OPAQUE BACKGROUND
+
+
+ txt = TextClip("V. Zulkoninov - Ukulele Sonata",
+ color='white',fontsize=24)
+ txt_col = txt.on_color(size=(ukulele.w + txt.w,txt.h+6), color=(0,0,0),
+ pos=(6,'center'), col_opacity=0.6)
+
+ # THE TEXT CLIP IS ANIMATED.
+ # I am *NOT* explaining the formula, understands who can/want.
+ txt_mov = txt_col.set_pos( lambda t: (max(w/30,int(w-0.5*w*t)),
+ max(5*h/6,int(100*t))) )
+
+ # FINAL ASSEMBLY
+ final = CompositeVideoClip(moviesize,[ukulele,txt_mov,piano])
+ final.subclip(0,5).to_movie("ukulele.avi",fps=24,codec='DIVX')
diff --git a/docs/examples/severalCharacters.rst b/docs/examples/severalCharacters.rst
new file mode 100644
index 00000000..29044345
--- /dev/null
+++ b/docs/examples/severalCharacters.rst
@@ -0,0 +1,20 @@
+.. charDuplication:
+
+Character duplication in a video
+-----------------------------------
+
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/sZMyzzGlsc0&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/sZMyzzGlsc0&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+
+So blabla
diff --git a/docs/examples/soundExample.rst b/docs/examples/soundExample.rst
new file mode 100644
index 00000000..cea3cc47
--- /dev/null
+++ b/docs/examples/soundExample.rst
@@ -0,0 +1,86 @@
+.. soundexample:
+
+An example with sound
+------------------------
+
+An example of using MoviePy to assemble movie clips with sounds. Here are two scenes of Charade put together:
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/gtyFuIoH7W0&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/gtyFuIoH7W0&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+Here is the code: ::
+
+ from moviepy import *
+ import numpy as np
+
+ # LOAD MOVIE
+
+ charade = MovieClip("./charadePhone.mp4",audio=True)
+ w,h = charade.size
+ duration=6
+
+
+
+ # MAKE THE LEFT CLIP
+
+ # cut and crop the clip
+ xleft = 60
+ clip_left = charade.subclip(0,duration)
+ clip_left = clip_left.crop(x1=xleft,x2=xleft+2*w/3)
+
+ # make the mask. Yeah it's complicated, there must be a simpler way.
+ # It is just a mask that is black on the right bottom corner.
+ c1a = np.array((2*w/3,0))
+ v1 = np.array([h,w/3])
+ v1 = 2*v1/np.linalg.norm(v1)
+ c1b = c1a- v1
+ g1 = gradient(clip_left.size,c1a,c1b,col1=0,col2=1.0)
+ clip_left.mask = ImageClip(g1,ismask=True)
+
+
+
+ # MAKE THE RIGHT CLIP
+
+ # cut and crop the clip
+ xright = 70
+ clip_right = charade.subclip(21,21+duration)
+ clip_right = clip_right.crop(x1=xright,x2=xright+2*w/3)
+
+ # make the mask
+ c2a = np.array((w/3,0))
+ c2b = c2a+v1
+ g2 = gradient(clip_right.size,c2a,c2b,col1=0,col2=1.0)
+ clip_right.mask = ImageClip(g2,ismask=True)
+
+
+ # ASSEMBLE AND WRITE THE MOVIE
+
+ cc = CompositeVideoClip(charade.size,
+ [clip_right.set_pos(('right',0)),
+ clip_left.set_pos(('left',0))])
+
+ cc.to_movie("biphone.avi")
+
+
+A few remarks:
+
+- In this script we never explicitly consider the sound. MoviePy does all the cutting and the mixing automatically.
+- We do not load the whole movie but just a part of it (never load a 2h00 movie when you are going to use its sound, see the remark in :ref:`goodPractices`). Rather, we first extract the part of interest with ::
+
+ import moviepy.ffmpeg as ff
+ t1 = 3050 #seconds
+ t2 = 3095
+ ff.extract_subclip("charade.mp4",t1,t2,"charadePhone.mp4")
+
+- We use a nerdy and complicated way of cutting the clips with the ``gradient`` function (defined in :ref:`gradients`) but you could have done it with masks from images for instance.
+
+
diff --git a/docs/examples/starwarslike.rst b/docs/examples/starwarslike.rst
new file mode 100644
index 00000000..3c0b5d70
--- /dev/null
+++ b/docs/examples/starwarslike.rst
@@ -0,0 +1,192 @@
+A Star-Wars like opening title
+-------------------------------
+
+This is an approximate effect (the perspective would require some more complex transformations) but it is a nice exercice. Achtung: clip with sound.
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/5euLdo8L0o0&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/5euLdo8L0o0&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+Before seeing the code, let us have a look at this tutorial which shows the different steps:
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/dGrP7GhzWEE&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/dGrP7GhzWEE&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+And here you are for the code (it uses the ``gradient`` function, see :ref:`gradients`): ::
+
+ from moviepy import *
+ from skimage import transform as tf
+
+ def trapzWarp(pic,cx,cy,ismask=False):
+ """" Warps the given picture into a trapezoid.
+ Warning: slow function. """
+ Y,X = pic.shape[:2]
+ src = np.array([[0,0],[X,0],[X,Y],[0,Y]])
+ dst = np.array([[cx*X,cy*Y],[(1-cx)*X,cy*Y],[X,Y],[0,Y]])
+ tform = tf.ProjectiveTransform()
+ tform.estimate(src,dst)
+ im = tf.warp(pic, tform.inverse, output_shape=(Y,X))
+ return im if ismask else (im*255).astype('uint8')
+
+ # RESOLUTION 16 / 9
+ w = 720
+ h = w*9/16
+ moviesize = w,h
+
+
+
+ # THE RAW TEXT
+ txt = "\n".join([
+ "A long time ago, in a faraway galaxy,",
+ "there lived a prince and a princess",
+ "who had never seen the stars, for they",
+ "lived deep underground.",
+ "",
+ "Many years before, the prince's",
+ "grandfather had ventured out to the",
+ "surface and had been burnt to ashes by",
+ "solar winds.",
+ "",
+ "One day, as the princess was coding",
+ "and the prince was shopping online, a",
+ "meteor landed just a few megameters",
+ "from the couple's flat."
+ ])
+
+
+ # Add blanks
+ txt = 10*"\n" +txt + 10*"\n"
+
+
+ # CREATE THE TEXT IMAGE
+
+
+ clip_txt = TextClip(txt,color='white',
+ align='West',fontsize=25,font='Xolonium-Bold',
+ method='label',remove_temp=False)
+
+
+
+ # SCROLL THE TEXT IMAGE BY CROPPING A MOVING AREA
+
+ txt_speed = 27
+ fl = lambda gf,t : gf(t)[int(txt_speed*t):int(txt_speed*t)+h,:]
+ moving_txt= clip_txt.fl(fl, applyto=['mask'])
+
+
+ # ADD VANISHING EFFECT ON THE TEXT
+
+ grad = gradient(moving_txt.size,c1=(0,2*h/3),
+ c2=(0,h/4),col1=1.0,col2=0.0)
+ gradmask = ImageClip(grad,ismask=True)
+ fl = lambda pic : np.minimum(pic,gradmask.img)
+ moving_txt.mask = moving_txt.mask.fl_image(fl)
+
+
+ # WARP THE TEXT (PERSPECTIVE EFFECT)
+
+ fl_im = lambda pic : trapzWarp(pic,0.2,0.3)
+ fl_mask = lambda pic : trapzWarp(pic,0.2,0.3, ismask=True)
+ warped_txt= moving_txt.fl_image(fl_im)
+ warped_txt.mask = warped_txt.mask.fl_image(fl_mask)
+
+
+ # BACKGROUND IMAGE, DARKENED AT 60%
+
+ stars = ImageClip('./starworms/stars.jpg')
+ stars_darkened = stars.fl_image(lambda pic: (0.6*pic).astype('int16'))
+
+
+ # COMPOSE THE MOVIE
+
+
+ txt_duration = 2*clip_txt.size[1]/txt_speed
+ movie_duration = txt_duration+5
+
+ cc = CompositeVideoClip(moviesize,[
+ stars.set_duration(movie_duration),
+ warped_txt.set_duration(txt_duration)
+ .set_pos(('center','bottom'))])
+
+
+ cc.subclip(0,3).preview()
+
+
+Code for the tutorial
+~~~~~~~~~~~~~~~~~~~~~~
+
+Here is the code I used to make the tutorial. When you think about it, it is a code for a video explaining how to make another video using some code (this is so meta !). This code uses the variables of the previous code (it should be placed after that previous code to work). Once again, scripting is very useful to make such videos. ::
+
+ def annotate(clip,txt,txt_color='white',bg_color=(0,0,255)):
+ """ Writes a text at the bottom of the clip. """
+
+ txtclip = TextClip(txt, fontsize=20, font='Ubuntu-bold',
+ color=txt_color)
+
+ cvc = CompositeVideoClip(clip.size,
+ [clip , txtclip.on_color((clip.w,txtclip.h+6),
+ color=(0,0,255),pos=(6,'center')).
+ set_pos((0,'bottom'))])
+
+ return cvc.set_duration(clip.duration)
+
+ # A few functions to resize/center clips that have different sizes.
+
+ def resizeCenter(clip):
+ return clip.resize(height=h).set_pos(('center','center'))
+
+ def composeCenter(clip):
+ return CompositeVideoClip(moviesize,
+ [clip.set_pos(('center','center'))])
+
+ # Annotations
+
+ annotations = [
+
+ annotate(composeCenter(resizeCenter(stars)).subclip(0,3),
+ "This is a public domain picture of stars"),
+
+ annotate(CompositeVideoClip(moviesize,[stars]).subclip(0,3),
+ "We only keep one part."),
+
+ annotate(CompositeVideoClip(moviesize,[stars_darkened]).subclip(0,3),
+ "We darken it a little."),
+
+ annotate(composeCenter(resizeCenter(clip_txt)).subclip(0,3),
+ "We generate a text image."),
+
+ annotate(composeCenter(moving_txt.set_mask(None)).subclip(6,9),
+ "We scroll the text by cropping a moving region of it."),
+
+ annotate(composeCenter(gradmask.toRGB()).subclip(0,2),
+ "We add this mask to the clip."),
+
+ annotate(composeCenter(moving_txt).subclip(6,9),
+ "Here is the result"),
+
+ annotate(composeCenter(warped_txt).subclip(6,9),
+ "We now warp this clip in a trapezoid."),
+
+ annotate(cc.subclip(6,9),
+ "We finally superimpose with the stars.")
+ ]
+
+ annotations_video = concat(annotations)
+ annotations_video.to_movie('tutorial.avi')
diff --git a/docs/examples/textmovingletters.rst b/docs/examples/textmovingletters.rst
new file mode 100644
index 00000000..1544986d
--- /dev/null
+++ b/docs/examples/textmovingletters.rst
@@ -0,0 +1,134 @@
+=============================
+Text with moving letters
+=============================
+
+I think this example illustrates well the interest of script-based editing (imagine doing that by hand).
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/jj5qrHl5ZS0&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/jj5qrHl5ZS0&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+
+Here is the code I used to generate the video above: we first define four ways of moving the letters, with four functions, then we make a clip for each of these movements, and concatenate everything. ::
+
+ from moviepy import *
+ import numpy as np
+
+ # A nerdy tool for rotations.
+ rotMatrix = lambda a: np.array( [[np.cos(a),np.sin(a)],
+ [-np.sin(a),np.cos(a)]])
+
+
+ # The letters appear from all directions
+ def vortex(fpos,i,nletters):
+ d = lambda t : 1.0/(0.3+t**8) #damping
+ a = i*np.pi/ nletters # angle of the movement
+ v = rotMatrix(a).dot([-1,0])
+ if i%2 : v[1] = -v[1]
+ return lambda t: fpos+400*d(t)*rotMatrix(0.5*d(t)*a).dot(v)
+
+
+ # The letters appear from above
+ def cascade(fpos,i,nletters):
+ v = np.array([0,-1])
+ d = lambda t : 1 if t<0 else abs(np.sinc(t)/(1+t**4))
+ return lambda t: fpos+v*400*d(t-0.15*i)
+
+
+ # The letters arrive from the right
+ def arrive(fpos,i,nletters):
+ v = np.array([-1,0])
+ d = lambda t : max(0, 3-3*t)
+ return lambda t: fpos-400*v*d(t-0.2*i)
+
+
+ # The letters 'explode'
+ def vortexout(fpos,i,nletters):
+ d = lambda t : max(0,t) #damping
+ a = i*np.pi/ nletters # angle of the movement
+ v = rotMatrix(a).dot([-1,0])
+ if i%2 : v[1] = -v[1]
+ return lambda t: fpos+400*d(t-0.1*i)*rotMatrix(-0.2*d(t)*a).dot(v)
+
+
+ screensize = (720,460)
+ txtClip = TextClip('Cool effect',color='white', font="Amiri-Bold",
+ kerning = 5, fontsize=100)
+
+ clips = [ CompositeVideoClip(screensize,
+ moveLetters(txtClip,screensize,funcpos)).
+ subclip(0,5)
+ for funcpos in [vortex, cascade, arrive, vortexout] ]
+
+ concat(clips).to_movie('coolTextEffects.avi')
+
+
+
+
+Ok, maybe you saw it, the central function in the script above is a function called ``moveLetters``. This is the function that recognizes the letters in the text clip and make them move, which is far from trivial. So here is the code for ``moveLetters``: ::
+
+ from skimage.morphology import label
+ import scipy.ndimage as ndi
+
+ def moveLetters(txtClip,screensize, funcpos,rem_thr=500):
+ """
+ Takes the textclip,centers it, separates the letters,
+ sets the position of each letter according to funcpos
+
+ funcpos : funcpos(fpos,i,nletters) where
+ - fpos : final position of the letter
+ - i : index of the letter
+ - nletters : total number of letters
+ Returns: a position function t-> (x(t),y(t))
+
+ rem_thr : all 'letters' with size < rem_Thr will be
+ considered false positives and will be removed
+
+
+ >>> letters = vortexLetters(txtClip,screensize,funcpos)
+ >>> CompositeVideoClip(screensize,letters,transparent=True)
+
+ """
+
+ # First place the text at the center of the clip
+ # This will only be useful to get the position of
+ # the letters in the clip
+ cvc = CompositeVideoClip(screensize,
+ [txtClip.set_pos(['center','center'])],
+ transparent=True)
+ image = cvc.get_frame(0)
+ mask = cvc.mask.get_frame(0)
+
+ # segment/label the image with scikit-image's function
+ mat = label(image[:,:,0])
+ #find the positions of the objects in the image
+ slices = ndi.find_objects(mat)
+ #cool trick to remove letter holes (in 'o','e','a', etc.)
+ slices = [e for e in slices if mask[e[0],e[1]].mean() >0.2]
+ # remove very small slices
+ slices = [e for e in slices if image[e[0],e[1]].size > rem_thr]
+ # Sort the slices from left to right
+ slices = sorted(slices, key = lambda s : s[1].start)
+
+
+ letters = []
+ for i,(sy,sx) in enumerate(slices):
+ """ crop each letter separately and set position """
+ sy = slice(sy.start-1,sy.stop+1)
+ sx = slice(sx.start-1,sx.stop+1)
+ letter = ImageClip(image[sy,sx])
+ letter.mask = ImageClip(mask[sy,sx],ismask=True)
+ finalpos = np.array((sx.start,sy.start)) # final position
+ letter.pos = funcpos(finalpos,i,len(slices))
+ letters.append(letter)
+
+ return letters
+
diff --git a/docs/examples/the_end.rst b/docs/examples/the_end.rst
new file mode 100644
index 00000000..2d082a73
--- /dev/null
+++ b/docs/examples/the_end.rst
@@ -0,0 +1,43 @@
+======================
+"The End" effect
+======================
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/sZMyzzGlsc0&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/sZMyzzGlsc0&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+So let's explain this one: there is a clip with "The End" written in the middle, and *above* this
+clip there is the actual movie. The actual movie has a mask which represents
+a white (=opaque) circle on a black (=transparent) background. At the begining,
+that circle is so large that you see all the actual movie and you don't see
+the "The End" clip. Then the circle becomes progressively smaller and as a
+consequence you see less of the actual movie and more of the "The End" clip. ::
+
+ from moviepy import *
+ from scipy.interpolate import interp1d
+
+
+ movie = MovieClip("./videos/badl-0006.mov", audio=False)
+ clip = movie.subclip(26,31).with_mask()
+ w,h = movie.size
+
+ # The mask is a circle with vanishing radius r(t) = 800-200*t
+ mask = lambda t: cv2.circle(np.zeros((h,w)),(w/2,h/4),
+ max(0, int(800-200*t)), 1,-1, lineType=cv2.LINE_AA)
+
+ clip.mask.get_frame = mask
+
+ the_end = TextClip("The End",font="Amiri-bold",
+ color="white",fontsize=70).set_pos(('center','center'))
+
+ final = CompositeVideoClip(movie.size,[the_end,clip])
+ final.duration = clip.duration
+ final.to_movie("theEnd.avi")
diff --git a/docs/first_steps.rst b/docs/first_steps.rst
new file mode 100644
index 00000000..ed6d4e02
--- /dev/null
+++ b/docs/first_steps.rst
@@ -0,0 +1,13 @@
+First steps with MoviePy
+========================
+
+This section will get you started in a few minutes. You will learn more by browsing the reference manual, the cookbook, and the sourcecode (try it, it's very simple).
+
+.. toctree::
+ :maxdepth: 1
+
+ first_steps/example_code
+ first_steps/crash_course
+ first_steps/good_practice
+
+
diff --git a/docs/first_steps/crash_course.rst b/docs/first_steps/crash_course.rst
new file mode 100644
index 00000000..bb2a9166
--- /dev/null
+++ b/docs/first_steps/crash_course.rst
@@ -0,0 +1,205 @@
+A MoviePy crash-course
+-----------------------
+
+In this section we will give you the basics to start editing your videos.
+
+The central objects of MoviePy are video clips. To compose movies, you start by loading video clips, then you may modify some of these, put them all together, and write the result to a file.
+
+What is a video clip ?
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+A video clip is basically an object with a ``get_frame`` attribute. ``get_frame`` is a function which for a given time ``t`` returns a picture of the clip at time ``t`` (more precisely, an array of numbers representing a picture). As an example, to play a clip frame by frame, you can (but you won't have to) write something like that: ::
+
+ while t< clip.duration:
+ display( clip.get_frame(t) )
+ t = t + 1.0/24 # for 24 frames/second
+
+A video clip has some fundamental attributes:
+
+- **The size** (width,height), ``clip.size``, indicates the dimensions in pixels of the clip. You can also access the clips's width and height with ``clip.w`` and ``clip.h`` respectively.
+- **The duration**, ``clip.duration``, is the time after which the clip stops playing
+- **The soundtrack**, ``clip.sound``, which contains the sound data (an array actually) of the clip. See :ref:`CCaudioClips`
+
+When you mix several clips together (see :ref:`CompositeVideoClips`), you may have to worry about some other attributes:
+
+- **The position** indicates where the clip will appear if you display it as part of a bigger screen.
+- **The mask**, ``clip.mask``, is an array of numbers between 0 and 1, a 0 at some position meaning that the pixel at the same position in the picture should not be displayed. If you are not going to do anything complicated, you shouldn't worry about the mask (by default, all video clips have a mask with only ones, meaning that the picture should be completely visible). Just know that ``clip.mask`` is actually... a clip ! More precisely, its method ``clip.mask.get_frame`` returns, for a given time, the mask that should be used when blitting the clip's frame over another picture.
+
+
+Classes of video clips
+~~~~~~~~~~~~~~~~~~~~~~
+
+Video clips can be created using one of the following commands:
+
+- **MovieClips** created with ``MovieClip('myHolidays.mp4')`` are clips read from a movie file.
+- **Image clips** created with ``ImageClip('myPic.png')`` are clips displaying a picture, for an *a priori* infinite duration.
+- **Color clips** created with ``ColorClip((height,width),color=(R,G,B))`` are special ImageClips of a single color.
+- **Text clips** created with ``TextClip('Hello public',font='Impact-Regular')`` are special ImageClips representing a text. They are automatically generated using ImageMagick.
+
+To that list we should add the ``CompositeVideoClips`` that are obtained by mixing several clips together (see :ref:`renderingAClip`).
+
+Finally, a clip can be of the base class :class:`VideoClip`, and have any arbitrary ``get_frame`` method. For instance the following clip represents a 460x320
+screen, that will go from black (color ``[1,1,1]``) to white (color ``[255,255,255]``) in 255 seconds. ::
+
+ import numpy
+ from moviepy import *
+ dark_picture = np.ones((320,460,3))
+ def custom_get_frame(t):
+ return min(int(t),255) * dark_picture
+ clip = VideoClip().set_get_frame(custom_get_frame)
+
+
+Modifying a clip
+~~~~~~~~~~~~~~~~
+
+You will find many pre-implemented methods to modify a clip ( see :class:`VideoClip`). For instance ``clip.subclip(15,20)`` returns the part of ``clip`` that is between 20 seconds and 50 seconds, ``clip.resize((heigth,width))`` will change the resolution of the clip, while ``clip.crop`` will enable you to keep only a region of the clip and ``clip.speedx(0.5)`` will make your clip play two times slower. When it is relevant, these methods are also applied to the sound and the mask of the clip, so that you don't have to worry about modifying these.
+
+
+In MoviePy **no modification of a clip occurs inplace**, which means that the result of ``clip.resize``, ``clip.speedx`` etc. will be a new clip and the original clip will be untouched. ::
+
+ clip = MovieClip('myHolidays.mp4')
+ clip.resize((460,320)) # ``clip`` is NOT modified
+ clip = clip.resize((460,320)) # ``clip`` is modified
+
+Another important aspect is that modified clips are just *special views* of the original clip, they do not carry all the video data with them. Actually, the *real* modifications are only performed when you are rendering the clip (see :ref:`renderingAClip`). The good news is, all the clip objects that you will create through modifications of other clips take virtually no place in the memory and are created instantly.
+
+Apart from the pre-implemented modifications, you can modify a clip as you want using filters. You can change the timeline of the clip like this: ::
+
+ modifiedClip1 = myClip.fl_time(lambda t: 3*t)
+ modifiedClip2 = myClip.fl_time(lambda t: 1+sin(t))
+
+Now the clip ``modifiedClip1`` plays the same as ``myClip``, only three times faster, while ``modifiedClip2`` will play `myClip`` by oscillating between the times t=0s and t=2s. Note that in the last case you have created a clip of infinite duration (which is not a problem for the moment).
+
+You can also modify the display of a clip. The following takes a clip and inverts the green and blue channels: ::
+
+ modified clip1 = myClip.fl_image(lambda im: im[:,:,[0,2,1]])
+
+Finally, you may want to process the clip by taking into account the time and the picture at the same time. This is possible with ``clip.fl``. The filter must be a function which takes two arguments and returns a picture. the fist argument is a ``get_frame`` method (i.e. a function which given a time returns a picture), and the second argument is the time. ::
+
+ modifiedClip = myClip.fl(lambda gf,t: np.minimum(int(t),gf(2*t))
+
+This one is a little complicated to grasp.
+
+
+
+
+.. _CompositeVideoClips:
+
+Composite video clips
+~~~~~~~~~~~~~~~~~~~~~
+
+Composite video clips are video clips which will display the contents of several other video clips. The simplest compositing is concatenation with :meth:`~VideoClip.concat`: ::
+
+ video = concat([clip1,clip2,clip3])
+
+Now ``myVideo`` is a clip that plays the clips 1, 2, and 3 one after the other. You can also play a transition clip between the clips with the option ``transition=myClip``.
+
+Next, you have the composite videoclip: ::
+
+ video = CompositeVideoClip(clip.res, [clip1,clip2,clip3])
+
+Now ``myVideo`` is a clip that has the size of ``clip1``, and plays ``clip1``, and ``clip2`` *on top of* ``clip1``, and ``clip3`` on top of
+``clip1``, and ``clip2``. Of course, if ``clip2`` and ``clip3`` have the same size as ``clip1``, then only ``clip3``, which is on top, will be
+visible in the video... unless ``clip3`` and ``clip2`` have masks which hide parts of them.
+
+You can set the starting time of each clip as follows: ::
+
+ video = CompositeVideoClip(clip.res, [clip1,clip2,clip3])
+
+Because the three clips overlap, we can make them appear with a fading-in effect. Here we go for fadein effects that last 1.5 seconds: ::
+
+ video = CompositeVideoClip(clip.res, [clip1, # starts at t=0
+ clip2.set_start(50).fadein(1.5),
+ clip3.set_start(90).fadein(1.5)])
+
+Finally, if ``clip2`` and ``clip3`` are smaller than ``clip1``, you can decide where they will appear: ::
+
+ video = CompositeVideoClip(clip.res,
+ [clip1,
+ clip2.set_pos((45,150)),
+ clip3.set_pos((90,100))])
+
+Note that there are many ways to specify the position: ::
+
+ clip2.set_pos((45,150)) # x=45, y=150
+
+ # clip2 is horizontally centered, and at the top of the picture
+ clip2.set_pos(("center","top"))
+
+ # clip2 is at 40% of the width, 70% of the height:
+ clip2.set_pos((0.4,0.7), relative=True)
+
+ # clip2's position is horizontally centered, and moving up !
+ clip2.set_pos(lambda t: ('center', 50+t) )
+
+Be careful when indicating the position that the ``y`` position has its
+zero at the top of the picture:
+
+.. figure:: videoWH.jpeg
+
+
+
+.. _renderingAClip:
+
+Rendering a video clip
+~~~~~~~~~~~~~~~~~~~~~~~
+
+The ``duration`` attribute must be set (with ``clip.set_duration``) to be able to preview or write the movie to a file (some clips, like clips displaying a picture, have *a priori* an infinite duration).
+
+To display one frame of the clip, you type one of these: ::
+
+ myClip.show() # shows the first frame of the clip
+ myClip.show(10.5) # shows the frame of the clip at t=10.5s
+ myClip.show(10.5,frontend="matplotlib") # show in a matplotlib window
+
+To preview the clip, you type::
+
+ myClip.preview() # preview with default fps=15
+ myClip.preview(fps=25)
+ myClip.preview(fps=15, audio=False) # Play the clip with no sound.
+
+It is important to note that the ``fps`` can be any number, independently of the ``fps`` of your different sources.
+
+To write a clip as a video file, use ::
+
+ myClip.to_movie("myEditedMovie.avi") # default codec: 'DIVX' fps: 24
+ myClip.to_movie("myEditedMovie.avi",fps=24, codec='raw') # raw movie
+ myClip.to_movie("myEditedMovie.avi",audio=False) # don't render the audio.
+
+The codec *DIVX* will produce very light yet good quality movies, while the *raw* codec will produce very large movies with perfect quality.
+
+
+.. _CCaudioClips:
+
+Audio clips
+~~~~~~~~~~~~~
+
+The second important objects of MoviePy are the audio clips. If ``myHolidays.mp4`` is a video with sound, then ::
+
+ clip = MovieClip('myHolidays.mp4', audio=True)
+
+will create a clip with a ``clip.sound`` attribute which is an audio clip. This is the sound that you will hear if you render the clip with ``clip.preview`` or ``clip.to_movie``. You can also create an audio clip from a sound file and then attach it to a video clip: ::
+
+ audio = SoundClip('mySong.wav')
+ video = MovieClip('myHolidays.mp4').set_audio(audio)
+
+Like video clips, audio clips can be cut (with ``clip.subclip``) modified (with for instance ``clip.volumex`` which multiplies the volume) and combined (with ``CompositeAudioClip``). But most of the time, MoviePy will do that for you:
+
+- When you cut a video clip with ``videoclip.subclip(20,25)`` then the sound will also be cut, i.e. the resulting clip will have an audio clip ``videoclip.audio.subclip(20,25)``.
+- When you put several clips together in a CompositeVideoClip, then the sound of the CompositeVideoClip will be the composition of the sounds of the different video clips.
+
+For an example, you can refer to :ref:`soundexample`. Like video clips, sound clips have a ``get_frame`` attribute, and creating new audio clips by modifying or putting together other audio clips does not take place in the memory. The actual sounds of the audio clips are only computed when we ask to play them or to write them to a file. You can do that as follows: ::
+
+ audioclip.preview() # default fps: 22050
+ audioclip.preview(fps=44100)
+ audioclip.to_soundfile('myclip.wav',fps=44100) #default fps: 22050
+
+Going further
+~~~~~~~~~~~~~~
+
+Now you should understand the scripts given in :ref:`examples`, and you should be able to write your own scripts. To go further and learn about all the available options and functionalities of MoviePy, see the :ref:`cookbook` and the reference manual.
+
+
+
+
+
diff --git a/docs/first_steps/example_code.rst b/docs/first_steps/example_code.rst
new file mode 100644
index 00000000..277d977d
--- /dev/null
+++ b/docs/first_steps/example_code.rst
@@ -0,0 +1,30 @@
+Example code
+------------
+
+We start with some code to show you the MoviePy syntax. In a typical script, you load or generate some clips, modify them, combine them, and write the result to a video file.
+
+We will now load a movie of my last holidays, lower the volume, add a title in the center of the video for the ten first seconds, and write the result in a file: ::
+
+ from moviepy import *
+
+ # Load myHolidays.mp4 and select the subclip 00:00:50 - 00:00:60
+ clip = MovieClip("myHolidays.mp4", audio=True).subclip(50,60)
+
+ # Reduce the sound volume (volume x 0.8)
+ clip.sound = clip.sound.volumex(0.8)
+
+ # Generate a text clip. You can customize the font, color, etc.
+ txt_clip = TextClip("My Holidays 2013",fontsize=70,color='white')
+
+
+ # Say that you want it to appear 10s at the center of the screen
+ txt_clip = txt_clip.set_pos(('center','center')).set_duration(10)
+
+ # Overlay the text clip on the first video clip
+ video = CompositeVideoClip(clip.size, [clip, txt_clip])
+
+ # Write the result to a file. The default encoding will be DIVX.
+ video.write("myHolidays_edited.avi",fps=24)
+
+See ? That was easy !
+
diff --git a/docs/first_steps/good_practice.rst b/docs/first_steps/good_practice.rst
new file mode 100644
index 00000000..21ef8ff4
--- /dev/null
+++ b/docs/first_steps/good_practice.rst
@@ -0,0 +1,25 @@
+.. _goodPractices:
+
+Good Practices
+---------------
+
+MoviePy works fine on my 1.5 petaflops supercomputer, but like for any other video software, the bottleneck is the heavy computations required to produce several pictures per second. If you write a very complex clip, the previews and the rendering to a file may be very slow. Here are a few tricks to ease things:
+
+
+- Use an interactive shell, like IPython or, better, the IPython notebook. If you don't know these, you don't know what you are missing !
+- Prefer the clip.show() option, and use it a lot. Only use clip.preview() when really necessary.
+- If some part of your video is particularly complex and long to render, save this part as either a raw video or in directory of pictures (better, because it enables to also save the mask), then use this video instead of this part's script.
+- If you are going to use extracts of big movies with sound, do NOT write ::
+
+ # "Charade" is a 2h00 long movie
+ myVideo = MovieClip("charade.mp4",sound=True).subclip(30,35)
+
+ The reason is that in the snippet above the whole sound of the movie will be converted into a .wav file and then loaded into the memory. Instead, extract the subclip between t=30s and t=35s as a new video file and use this one instead. Like this ::
+
+ import moviepy.ffmpeg as mf
+ mf.extract_subclip("charade.mp4",30,35, "charadeSUB30_35.mp4")
+ myVideo = MovieClip("charadeSUB30_35.mp4",sound=True)
+
+- Prototype: design your clips separately. If your composition involves a clip that is not finished yet, replace it temporarily with a basic color clip.
+- There are often several ways to produce a same effect with MoviePy, but some ways are faster. For instance don't apply effects to a whole screen video if you are only using one region of the screen afterwards: first crop the selected region, then apply your effects.
+- [wishful thinking] Check on the internet or in the examples of this documentation that what you do hasn't been done before. Code shared on the internet has more chances to be optimized.
diff --git a/docs/first_steps/videoWH.jpeg b/docs/first_steps/videoWH.jpeg
new file mode 100644
index 00000000..cf5c339e
Binary files /dev/null and b/docs/first_steps/videoWH.jpeg differ
diff --git a/docs/forDevelopers.rst b/docs/forDevelopers.rst
new file mode 100644
index 00000000..0d5ad0d6
--- /dev/null
+++ b/docs/forDevelopers.rst
@@ -0,0 +1,53 @@
+.. forDevs:
+
+===============================
+For developpers
+===============================
+
+
+TODO list
+------------
+
+Ideas of improvement (suggestions, help and commits are welcome !):
+
+- Find users.
+- Improve the ``set_pos`` functions, give it functionalities inspired from CSS/HTML, like margin-right, etc...
+- Improve readability/naming.
+- Make an installer for all the dependencies ?
+
+
+Discussion of the dependencies
+-------------------------------
+
+I have found that complicated dependencies are a main reason why people get
+discouraged by a software, so I take all the advices on the subject.
+
+
+Movie writing
+~~~~~~~~~~~~~~~~~~~~~~~
+
+To write a movie, I used to generate pictures of the frames and then put them together using ffmpeg, because this is what matplotlib does. But it can be up to fifty times slower than writing the movie directly with OpenCV, and it is less memory efficient.
+
+However, I like how you can tune the quality of the movie with ffmpeg, and I can't think of something else to merge sound and image. I know there is a war between ffmpeg/avconv/mencoder. I think ffmpeg is the most spread software. And no, it's not deprecated.
+
+Movie Rendering
+~~~~~~~~~~~~~~~~~~~~~~~
+
+For movie previews I am using Pygame instead of the original OpenCV frontend because Pygame
+can also generate sound.
+
+
+
+Movie and Image manimulation
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The python package SimpleCV is an attempt at making OpenCV easier to use. It is totally cool, but the OpenCV devs are also trying to make it easier so they always make a lot of changes which break SimpleCV. They use the Python Imaging Library for image processing.
+
+The package Wand (a Python binder for ImageMagick) is nice and is starting to accept numpy array images input/output.
+
+
+Sound
+~~~~~~~
+
+The python package Pydub is really good but working with numpy arrays gives more freedom so I stick with Scipy.
+
diff --git a/docs/index.rst b/docs/index.rst
new file mode 100644
index 00000000..de97a92a
--- /dev/null
+++ b/docs/index.rst
@@ -0,0 +1,59 @@
+MoviePy
+=======
+
+MoviePy is a Python module for script-based movie editing, which enables basic operations (cuts, concatenations, title insertions) to be done in a few lines. It can also be used for advanced compositing and special effects. Let me put together the clips in my demonstration folder: ::
+
+ import os
+ from moviepy import *
+ files = sorted( os.listdir("clips/") )
+ clips = [ MovieClip('clips/'+f,audio=False) for f in files]
+ video = concat(clips, transition = MovieClip("logo.avi"))
+ video.to_movie("demos.avi",fps=25, codec='DIVX')
+
+.. raw:: html
+
+ <center>
+ <object><param name="movie"
+ value="http://www.youtube.com/v/zGhoZ4UBxEQ&hl=en_US&fs=1&rel=0">
+ </param><param name="allowFullScreen" value="true"></param><param
+ name="allowscriptaccess" value="always"></param><embed
+ src="http://www.youtube.com/v/zGhoZ4UBxEQ&hl=en_US&fs=1&rel=0"
+ type="application/x-shockwave-flash" allowscriptaccess="always"
+ allowfullscreen="true" width="550" height="450"></embed></object>
+ </center>
+
+You will find the code for most clips in the :ref:`examples`.
+
+You can do pretty much any effect you want with MoviePy, but it is just a framework, and in most cases you will need to code a little (or find someone who will !) to come to your goal.
+
+
+User's Guide
+--------------
+
+.. toctree::
+ :maxdepth: 2
+
+ install
+ first_steps
+ examples
+ cookbook
+ ref
+ forDevelopers
+
+
+MoviePy is a (still experimental) open source software written by Zulko_ and released under the MIT liscence. Everyone is welcome to help improve the project, fork it, blog on it, share new effects, etc...
+
+For troubleshooting and bug reports, the best for now is to ask on Stackoverflow_ (it will advertize for the project :) ) or on the Github project page.
+
+Indices and tables
+------------------
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+
+
+
+.. _Zulko: https://github.com/Zulko/
+.. _Stackoverflow: http://stackoverflow.com/
+
diff --git a/docs/install.rst b/docs/install.rst
new file mode 100644
index 00000000..526e4676
--- /dev/null
+++ b/docs/install.rst
@@ -0,0 +1,33 @@
+Download And Installation
+--------------------------
+
+You can `download MoviePy`_ on Github. Just unzip everything in one folder, open a terminal and type ::
+
+ sudo python setup.py install
+
+MoviePy is a very small program but it relies on many existing Python libraries that you will need to install first:
+
+- `OpenCV 2.4.6`_ or more recent, to read and write movie files.
+- PyGame_ for video and sound previews
+- `Scipy and Numpy`_, for image and sound manipulation
+- `Scikit Image`_ for advanced image manipulation
+- The Decorator_ module for better code readability
+
+And it needs some external software:
+
+- ffmpeg_, for writing movies and many other useful operations.
+- imageMagick_ for text generation, GIF support, and much more in the future.
+
+All these are normally easy to install (on linux, they will certainly be in your repos).
+
+
+.. _`download MoviePy`: https://github.com/Zulko/moviepy
+.. _`OpenCV 2.4.6`: http://sourceforge.net/projects/opencvlibrary/files/
+.. _Pygame: http://www.pygame.org/download.shtml
+.. _`Scipy and Numpy`: http://www.scipy.org/install.html
+.. _`Scikit Image`: http://scikit-image.org/download.html
+.. _Decorator: https://pypi.python.org/pypi/decorator
+
+
+.. _ffmpeg: http://www.ffmpeg.org/download.html
+.. _imageMagick: http://www.imagemagick.org/script/index.php
diff --git a/docs/make.bat b/docs/make.bat
new file mode 100644
index 00000000..32523332
--- /dev/null
+++ b/docs/make.bat
@@ -0,0 +1,242 @@
+@ECHO OFF
+
+REM Command file for Sphinx documentation
+
+if "%SPHINXBUILD%" == "" (
+ set SPHINXBUILD=sphinx-build
+)
+set BUILDDIR=_build
+set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
+set I18NSPHINXOPTS=%SPHINXOPTS% .
+if NOT "%PAPER%" == "" (
+ set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
+ set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
+)
+
+if "%1" == "" goto help
+
+if "%1" == "help" (
+ :help
+ echo.Please use `make ^<target^>` where ^<target^> is one of
+ echo. html to make standalone HTML files
+ echo. dirhtml to make HTML files named index.html in directories
+ echo. singlehtml to make a single large HTML file
+ echo. pickle to make pickle files
+ echo. json to make JSON files
+ echo. htmlhelp to make HTML files and a HTML help project
+ echo. qthelp to make HTML files and a qthelp project
+ echo. devhelp to make HTML files and a Devhelp project
+ echo. epub to make an epub
+ echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
+ echo. text to make text files
+ echo. man to make manual pages
+ echo. texinfo to make Texinfo files
+ echo. gettext to make PO message catalogs
+ echo. changes to make an overview over all changed/added/deprecated items
+ echo. xml to make Docutils-native XML files
+ echo. pseudoxml to make pseudoxml-XML files for display purposes
+ echo. linkcheck to check all external links for integrity
+ echo. doctest to run all doctests embedded in the documentation if enabled
+ goto end
+)
+
+if "%1" == "clean" (
+ for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
+ del /q /s %BUILDDIR%\*
+ goto end
+)
+
+
+%SPHINXBUILD% 2> nul
+if errorlevel 9009 (
+ echo.
+ echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
+ echo.installed, then set the SPHINXBUILD environment variable to point
+ echo.to the full path of the 'sphinx-build' executable. Alternatively you
+ echo.may add the Sphinx directory to PATH.
+ echo.
+ echo.If you don't have Sphinx installed, grab it from
+ echo.http://sphinx-doc.org/
+ exit /b 1
+)
+
+if "%1" == "html" (
+ %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The HTML pages are in %BUILDDIR%/html.
+ goto end
+)
+
+if "%1" == "dirhtml" (
+ %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
+ goto end
+)
+
+if "%1" == "singlehtml" (
+ %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
+ goto end
+)
+
+if "%1" == "pickle" (
+ %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can process the pickle files.
+ goto end
+)
+
+if "%1" == "json" (
+ %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can process the JSON files.
+ goto end
+)
+
+if "%1" == "htmlhelp" (
+ %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can run HTML Help Workshop with the ^
+.hhp project file in %BUILDDIR%/htmlhelp.
+ goto end
+)
+
+if "%1" == "qthelp" (
+ %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can run "qcollectiongenerator" with the ^
+.qhcp project file in %BUILDDIR%/qthelp, like this:
+ echo.^> qcollectiongenerator %BUILDDIR%\qthelp\MoviePy.qhcp
+ echo.To view the help file:
+ echo.^> assistant -collectionFile %BUILDDIR%\qthelp\MoviePy.ghc
+ goto end
+)
+
+if "%1" == "devhelp" (
+ %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished.
+ goto end
+)
+
+if "%1" == "epub" (
+ %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The epub file is in %BUILDDIR%/epub.
+ goto end
+)
+
+if "%1" == "latex" (
+ %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
+ goto end
+)
+
+if "%1" == "latexpdf" (
+ %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
+ cd %BUILDDIR%/latex
+ make all-pdf
+ cd %BUILDDIR%/..
+ echo.
+ echo.Build finished; the PDF files are in %BUILDDIR%/latex.
+ goto end
+)
+
+if "%1" == "latexpdfja" (
+ %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
+ cd %BUILDDIR%/latex
+ make all-pdf-ja
+ cd %BUILDDIR%/..
+ echo.
+ echo.Build finished; the PDF files are in %BUILDDIR%/latex.
+ goto end
+)
+
+if "%1" == "text" (
+ %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The text files are in %BUILDDIR%/text.
+ goto end
+)
+
+if "%1" == "man" (
+ %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The manual pages are in %BUILDDIR%/man.
+ goto end
+)
+
+if "%1" == "texinfo" (
+ %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
+ goto end
+)
+
+if "%1" == "gettext" (
+ %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
+ goto end
+)
+
+if "%1" == "changes" (
+ %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.The overview file is in %BUILDDIR%/changes.
+ goto end
+)
+
+if "%1" == "linkcheck" (
+ %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Link check complete; look for any errors in the above output ^
+or in %BUILDDIR%/linkcheck/output.txt.
+ goto end
+)
+
+if "%1" == "doctest" (
+ %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Testing of doctests in the sources finished, look at the ^
+results in %BUILDDIR%/doctest/output.txt.
+ goto end
+)
+
+if "%1" == "xml" (
+ %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The XML files are in %BUILDDIR%/xml.
+ goto end
+)
+
+if "%1" == "pseudoxml" (
+ %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
+ goto end
+)
+
+:end
diff --git a/docs/makehtml.sh b/docs/makehtml.sh
new file mode 100755
index 00000000..040144c0
--- /dev/null
+++ b/docs/makehtml.sh
@@ -0,0 +1,2 @@
+make html
+firefox ../../docs/html/index.html
diff --git a/docs/readme.txt b/docs/readme.txt
new file mode 100644
index 00000000..a641b0f2
--- /dev/null
+++ b/docs/readme.txt
@@ -0,0 +1,27 @@
+Installation
+------------
+
+
+MoviePy is very light (~1000 lines of code) but it uses many Python libraries
+- `OpenCV 2.4.6`_ to read the movies
+- PyGame_ for video/sound previews
+- `Scipy and Numpy`_, for image/sound manipulation
+- `Scikit Image`_ for advanced image manipulation
+- The Decorator_ module for better code readability
+
+And needs some software:
+- avconv, the "new ffmpeg", for writing movies and many useful operations.
+- imageMagick for text generation (and much more in the future)
+
+All these are normally easy to install (on linux, most of these will be in your repos).
+
+Then you open a console in the moviepy source directory and type
+
+ sudo python setup.py install
+
+.. _`OpenCV 2.4.6`: http://sourceforge.net/projects/opencvlibrary/files/
+.. _Pygame: http://www.pygame.org/download.shtml
+.. _`Scipy and Numpy`: http://www.scipy.org/install.html
+.. _`Scikit Image`: http://scikit-image.org/download.html
+.. _Decorator: https://pypi.python.org/pypi/decorator
+
diff --git a/docs/ref.rst b/docs/ref.rst
new file mode 100644
index 00000000..7919288e
--- /dev/null
+++ b/docs/ref.rst
@@ -0,0 +1,10 @@
+Reference Manual
+================
+
+.. toctree::
+ :maxdepth: 2
+
+ ref/Clip_ref
+ ref/VideoClip_ref
+ ref/AudioClip_ref
+ ref/ffmpeg
diff --git a/docs/ref/AudioClip_ref.rst b/docs/ref/AudioClip_ref.rst
new file mode 100644
index 00000000..adeb23bb
--- /dev/null
+++ b/docs/ref/AudioClip_ref.rst
@@ -0,0 +1,28 @@
+.. ref_AudioClip:
+
+************
+AudioClip
+************
+
+:class:`AudioClip`
+==========================
+
+.. autoclass:: AudioClip.AudioClip
+ :members:
+ :show-inheritance:
+
+:class:`SoundClip`
+==========================
+
+.. autoclass:: AudioClip.SoundClip
+ :members:
+ :show-inheritance:
+
+
+:class:`CompositeAudioClip`
+================================
+
+.. autoclass:: AudioClip.CompositeAudioClip
+ :members:
+ :show-inheritance:
+
diff --git a/docs/ref/Clip_ref.rst b/docs/ref/Clip_ref.rst
new file mode 100644
index 00000000..db453cd7
--- /dev/null
+++ b/docs/ref/Clip_ref.rst
@@ -0,0 +1,10 @@
+************
+Clip
+************
+
+:class:`Clip`
+==========================
+
+.. autoclass:: Clip.Clip
+ :members:
+ :show-inheritance:
diff --git a/docs/ref/VideoClip_ref.rst b/docs/ref/VideoClip_ref.rst
new file mode 100644
index 00000000..2a781b56
--- /dev/null
+++ b/docs/ref/VideoClip_ref.rst
@@ -0,0 +1,53 @@
+.. ref_VideoClip:
+
+************
+VideoClip
+************
+
+:class:`VideoClip`
+==========================
+
+.. autoclass:: VideoClip.VideoClip
+ :members:
+ :show-inheritance:
+
+:class:`MovieClip`
+==========================
+
+.. autoclass:: VideoClip.MovieClip
+ :members:
+ :show-inheritance:
+
+:class:`ImageClip`
+==========================
+
+.. autoclass:: VideoClip.ImageClip
+ :members:
+ :show-inheritance:
+
+:class:`ColorClip`
+------------------
+
+.. autoclass:: VideoClip.ColorClip
+ :members:
+ :show-inheritance:
+
+
+:class:`TextClip`
+---------------------
+
+.. autoclass:: VideoClip.TextClip
+ :members:
+ :show-inheritance:
+
+:class:`CompositeVideoClip`
+============================
+
+.. autoclass:: VideoClip.CompositeVideoClip
+ :members:
+ :show-inheritance:
+
+Useful Methods
+--------------
+
+.. automethod:: moviepy.VideoClip.concat
diff --git a/docs/ref/ffmpeg.rst b/docs/ref/ffmpeg.rst
new file mode 100644
index 00000000..d1aae0d2
--- /dev/null
+++ b/docs/ref/ffmpeg.rst
@@ -0,0 +1,9 @@
+.. _ffmpegTools:
+
+FFMPEG-related functions
+----------------------------
+
+.. automodule:: ffmpeg
+ :members:
+ :undoc-members:
+ :show-inheritance:
diff --git a/moviepy/AudioClip.py b/moviepy/AudioClip.py
new file mode 100644
index 00000000..11810fca
--- /dev/null
+++ b/moviepy/AudioClip.py
@@ -0,0 +1,173 @@
+import time
+import os
+from copy import copy, deepcopy
+import shutil
+
+import numpy as np
+from scipy.io import wavfile
+
+import pygame as pg
+import ffmpeg
+
+from Clip import Clip, requires_duration
+
+
+class AudioClip(Clip):
+
+ """
+
+ Base class for audio clips. See ``SoundClip`` and ``CompositeSoundClip``
+ for usable classes.
+
+ :ivar get_frame: A function `t-> frame at time t`. the frame does not
+ mean much for a sound, it is just an integer.
+
+ :ivar nchannels: Number of channels (one or two for mono or stereo)
+ of the sound.
+
+ :ivar nbits: Number of bits per frame (the more the better).
+ """
+
+ def __init__(self):
+ Clip.__init__(self)
+
+ @requires_duration
+ def toSoundClip(self, fps=24000):
+ """ Transforms the clip into a soundclip by (audio clip with a
+ precomputed sound array """
+
+ tt = np.linspace(0, self.duration, self.duration * fps)[:-1]
+ arr = np.array(map(self.get_frame, tt)).astype('int16')
+ return SoundClip(arr, fps)
+
+ @requires_duration
+ def preview(self, fps=22050, sleep=True):
+ """ Plays the sound clip with pygame. If ``sleep=True`` the
+ program is freezed while the sound is playing (necessary
+ when the sound is playing alone without video)."""
+ pg.mixer.quit()
+ array = self.toSoundClip(fps).array
+ pg.mixer.init(fps, -8 * self.nbits, self.nchannels, 4096)
+ snd = pg.sndarray.make_sound(array)
+ snd.play()
+ if sleep:
+ time.sleep(self.duration)
+
+ @requires_duration
+ def to_soundfile(self, filename=None, fps=22050):
+ """ Writes the soundclip to a .wav file """
+ array = self.toSoundClip(fps).array
+ wavfile.write(filename, fps, array)
+
+ def volumex(self, factor):
+ """ Returns an audioclip playing the same sound but with a volume
+ multiplied by the ``factor``. """
+ return self.fl(lambda gf, t: factor * gf(t))
+
+ def fadein(self, duration):
+ """ Return a sound clip that is first mute, then the sound arrives
+ progressively over ``duration`` seconds. """
+ fading = lambda gf, t: min(1.0 * t / duration, 1) * gf(t)
+ return self.fl(fading)
+
+ @requires_duration
+ def fadeout(self, duration):
+ """ Return a sound clip where the sound fades out progressively
+ over ``duration`` seconds at the end of the clip. """
+ fading = lambda gf, t: min(
+ 1.0 * (self.duration - t) / duration, 1) * gf(t)
+ return self.fl(fading)
+
+ @property
+ def nchannels(self):
+ return len(list(self.get_frame(0)))
+
+ @property
+ def nbits(self):
+ return self.get_frame(0).itemsize
+
+
+class SoundClip(AudioClip):
+
+ """
+
+ An audio clip read from a sound file, or an array.
+
+ :param snd: Either a soundfile or an array representing a sound. If
+ the soundfile is not a .wav, it will be converted to .wav first,
+ using the ``fps`` and ``bitrate`` arguments.
+
+ :param fps: If ``snd`` is an array, this parameter is required.
+ :param bitrate: If ``snd`` is not a .wav, this prameter is required
+ for the conversion.
+
+ >>> snd = SoundClip("song.wav")
+ >>> snd = SoundClip("song.mp3", fps = 44100, bitrate=3000)
+ >>> snd = SoundClip(mySoundArray,fps=44100) # from a numeric array
+
+ """
+
+ def __init__(self, snd, fps=None, bitrate=3000):
+
+ Clip.__init__(self)
+
+ if isinstance(snd, str):
+ if not snd.endswith('.wav'):
+ temp = 'temp.wav'
+ ffmpeg.extract_sound(snd, temp, fps, bitrate)
+ fps, arr = wavfile.read(temp)
+ # os.remove(temp)
+ else:
+ fps, arr = wavfile.read(snd)
+
+ self.array = arr
+ self.fps = fps
+ else:
+ self.array = snd
+ self.fps = fps
+
+ self.duration = 1.0 * len(self.array) / self.fps
+
+ def gf(t):
+ i = int(self.fps * t)
+ if i < 0 or i >= len(self.array):
+ return 0
+ else:
+ return self.array[i]
+
+ self.get_frame = gf
+
+
+class CompositeAudioClip(AudioClip):
+
+ """
+
+ An audio clip made by putting together several audio clips.
+
+ :param clips: a list of audio clips, which may start playing at
+ different times or together. If all have their ``duration``
+ attribute set, the duration of the composite clip is computed
+ automatically.
+
+ """
+
+ def __init__(self, clips):
+
+ Clip.__init__(self)
+ self.clips = clips
+ self.compute_duration()
+
+ def gf(t):
+ return sum([0*self.clips[0].get_frame(0)]+
+ [c.get_frame(t - c.start)
+ for c in self.playing_clips(t)])
+
+ self.get_frame = gf
+
+ def compute_duration(self):
+ ends = [c.end for c in self.clips]
+ if not any([(e is None) for e in ends]):
+ self.duration = max(ends)
+
+ def playing_clips(self, t=0):
+ return [c for c in self.clips if c.is_playing(t)]
diff --git a/moviepy/Clip.py b/moviepy/Clip.py
new file mode 100644
index 00000000..5e04acd4
--- /dev/null
+++ b/moviepy/Clip.py
@@ -0,0 +1,264 @@
+import decorator
+from copy import copy, deepcopy
+
+
+def apply_to_mask(f, clip, *a, **k):
+ """ This decorator will apply the same function f to the mask of
+ the clip created with f """
+ newclip = f(clip, *a, **k)
+ if hasattr(newclip, 'mask') and (newclip.mask != None):
+ newclip.mask = f(newclip.mask, *a, **k)
+ return newclip
+
+
+def apply_to_audio(f, clip, *a, **k):
+ """ This decorator will apply the function f to the audio of
+ the clip created with f """
+ newclip = f(clip, *a, **k)
+ if hasattr(newclip, 'audio') and (newclip.audio != None):
+ newclip.audio = f(newclip.audio, *a, **k)
+ return newclip
+
+
+def requires_duration(f, clip, *a, **k):
+ """ will raise an error if the clip has no duration."""
+ if clip.duration is None:
+ raise ValueError("Attribute 'duration' not set")
+ else:
+ return f(clip, *a, **k)
+
+
+#
+#
+# C L I P
+#
+#
+
+
+class Clip:
+
+ """
+
+ Base class of all clips (VideoClips and AudioClips).
+
+
+
+ :ivar start: When the clip is included in a composition, time of the
+ composition at which the clip starts playing (in seconds).
+
+ :ivar end: When the clip is included in a composition, time of the
+ composition at which the clip starts playing (in seconds).
+
+ :ivar duration: duration of the clip (in seconds). Some clips
+ are infinite and do not have any duration.
+
+ """
+
+ def __init__(self):
+
+ self.start = 0
+ self.end = None
+ self.duration = None
+
+ def fl(self, fl, applyto=[], keep_duration=True):
+ """
+ Returns a clip whose frames are a transformation (through ``fl``)
+ of the frames of the current clip.
+
+ :param fl: a function with signature (gf,t -> frame) where:
+ - `gf` is a clip ``get_frame`` method, i.e. a function (t->image).
+ - `t` is a time in seconds
+ - `frame` is a picture (=Numpy array), and is the frame of the
+ returned clip at time ``t``.
+
+ :param applyto: can be either 'mask', or 'audio', or ['mask','audio'].
+ Specifies if the filter ``fl`` should also be applied to the
+ audio or the mask of the clip, if any.
+
+ :param keep_duration: Should the attributes ``duration`` and ``end``
+ of the clip be discarded.
+
+ >>> # ``newclip``, made from ``clip``, will be a 100 pixels-high
+ >>> # whose video content scrolls from the top to the bottom of
+ >>> # the frames of ``clip``.
+ >>> fl = lambda gf,t : gf(t)[int(t):int(t)+50,:]
+ >>> newclip = clip.fl(fl,applyto='mask')
+
+ """
+
+ gf = copy(self.get_frame)
+ newclip = self.set_get_frame(lambda t: fl(gf, t))
+
+ if not keep_duration:
+ newclip.duration = None
+ newclip.end = None
+
+ if isinstance(applyto, str):
+ applyto = [applyto]
+
+ for attr in applyto:
+ if hasattr(newclip, attr):
+ a = getattr(newclip, attr)
+ if a != None:
+ setattr(newclip, attr, a.fl(fl))
+
+ return newclip
+
+ def fl_time(self, t_func, applyto=['mask', 'sound'], keep_duration=False):
+ """
+ Returns a clip playing the content of the current clip but with a
+ modified timeline, time ``t`` being replaced by another
+ time `t_func(t)`. By default the attributes ``duration`` and ``end``
+ of the returned clip are discarded.
+
+ :param applyto: can be either 'mask', or 'audio', or ['mask','audio'].
+ Specifies if the filter ``fl`` should also be applied to the
+ audio or the mask of the clip, if any.
+
+ :param keep_duration: Should the attributes ``duration`` and ``end``
+ of the clip be discarded.
+
+ >>> # plays the clip (and its mask and sound) twice faster
+ >>> newclip = clip.fl_time(lambda: 2*t, applyto=['mask','audio'])
+ >>>
+ >>> # plays the clip starting at t=3, and backwards:
+ >>> newclip = clip.fl_time(lambda: 3-t)
+
+ """
+
+ return self.fl(lambda gf, t: gf(t_func(t)), applyto,
+ keep_duration=keep_duration)
+
+ @apply_to_mask
+ @apply_to_audio
+ def set_start(self, t):
+ """
+ Returns a copy of the clip, with the ``start`` attribute set to ``t``.
+ Also sets the duration of the returned clip's mask and audio, if any.
+ """
+ newclip = copy(self)
+ newclip.start = t
+ if newclip.end is None:
+ if newclip.duration != None:
+ newclip.end = t + newclip.duration
+ else:
+ newclip.duration = newclip.end - newclip.start
+
+ return newclip
+
+ @apply_to_mask
+ @apply_to_audio
+ def set_end(self, t):
+ """
+ Returns a copy of the clip, with the ``end`` attribute set to ``t``.
+ Also sets the duration of the returned clip's mask and audio, if any.
+ """
+ newclip = copy(self)
+ newclip.end = t
+ if newclip.start is None:
+ if newclip.duration != None:
+ newclip.start = max(0, t - newclip.duration)
+ else:
+ newclip.duration = newclip.end - newclip.start
+
+ return newclip
+
+ @apply_to_mask
+ @apply_to_audio
+ def set_duration(self, t):
+ """
+ Returns a copy of the clip, with the ``duration`` attribute set
+ to ``t``.
+ Also sets the duration of the returned clip's mask and audio, if any.
+ """
+ newclip = copy(self)
+ newclip.duration = t
+ if (newclip.start is None):
+ if newclip.end != None:
+ newclip.start = max(0, newclip.end - t)
+ else:
+ newclip.end = newclip.start + t
+
+ return newclip
+
+ def set_get_frame(self, gf):
+ newclip = copy(self)
+ newclip.get_frame = gf
+ return newclip
+
+ def is_playing(self, t):
+ """
+ Return true if t is between the start and the end of the clip """
+ return (((self.end is None) and (t >= self.start)) or
+ (self.start <= t <= self.end))
+
+ @apply_to_mask
+ @apply_to_audio
+ def subclip(self, ta=0, tb=None):
+ """
+ Returns a clip playing the content of the current clip
+ between times ``ta`` and ``tb`` (in seconds). If tb is not
+ provided, plays until the end of the clip, potentially forever.
+ If ``tb`` is provided, the duration of the returned clip is
+ set automatically.
+ The same effect is applied to the clip's audio and mask if any.
+ """
+ newclip = self.fl_time(lambda t: t + ta)
+ if (tb != None):
+ return newclip.set_duration(tb - ta)
+ else:
+ return newclip
+
+ @apply_to_mask
+ @apply_to_audio
+ def cutout(self, ta, tb):
+ """
+ Returns a clip playing the content of the current clip but
+ skips the extract between ``ta`` and ``tb`` (in seconds).
+ If the original clip clip has a ``duration`` attribute set,
+ the returned clip's duration is automatically computed.
+ The same effect is applied to the clip's audio and mask if any.
+ """
+ fl = lambda t: t + (0 if (t < ta) else tb - ta)
+ newclip = self.fl_time(fl)
+ if self.duration != None:
+ return newclip.set_duration(self.duration - (tb - ta))
+ else:
+ return newclip
+
+ @requires_duration
+ @apply_to_mask
+ @apply_to_audio
+ def time_mirror(self):
+ """
+ Returns a clip that plays the current clip backwards (who said
+ useless ???). The clip must have its ``duration`` attribute set.
+ The same effect is applied to the clip's audio and mask if any.
+ """
+ return self.fl_time(lambda t: self.duration - t)
+
+ @requires_duration
+ @apply_to_mask
+ @apply_to_audio
+ def loop(self):
+ """
+ Returns a clip that plays the current clip in an infinite loop.
+ """
+ return self.fl_time(lambda t: t % self.duration)
+
+ @apply_to_mask
+ @apply_to_audio
+ def speedx(self, factor):
+ """
+ Returns a clip playing the current clip but at a speed multiplied
+ by ``factor``.
+ The same effect is applied to the clip's audio and mask if any.
+ """
+ newclip = self.fl_time(lambda t: factor * t)
+ if self.duration != None:
+ return newclip.set_duration(1.0 * self.duration / factor)
+ else:
+ return newclip
diff --git a/moviepy/VideoClip.py b/moviepy/VideoClip.py
new file mode 100644
index 00000000..d5f1dca9
--- /dev/null
+++ b/moviepy/VideoClip.py
@@ -0,0 +1,1173 @@
+import time
+import os
+import shutil
+import subprocess
+from copy import copy
+
+import numpy as np
+from skimage.io import imread, imshow
+import cv2
+import pygame as pg
+import ffmpeg
+
+from Clip import Clip, apply_to_mask, requires_duration
+from AudioClip import SoundClip, CompositeAudioClip
+
+# Initiates a Pygame window
+pg.init()
+pg.display.set_caption('MoviePy')
+
+#
+#
+# TOOL FUNCTIONS
+#
+#
+
+
+def imdisplay(imarray, screen=None):
+ """ splashes the given image array on the given pygame screen """
+ a = pg.surfarray.make_surface(imarray.swapaxes(0, 1))
+ if screen == None:
+ screen = pg.display.set_mode(imarray.shape[:2][::-1])
+ screen.blit(a, (0, 0))
+ pg.display.flip()
+
+
+
+def blit(im1, im2, pos=[0, 0], mask=None, ismask=False):
+ """
+ Blits ``im1`` on ``im2`` as position ``pos=(x,y)``, using the
+ ``mask`` if provided. If ``im1`` and ``im2`` are mask pictures
+ (2D float arrays) then ``ismask`` must be ``True``
+ """
+
+ # xp1,yp1,xp2,yp2 = blit area on im2
+ # x1,y1,x2,y2 = area of im1 to blit on im2
+ xp, yp = pos
+ x1 = max(0, -xp)
+ y1 = max(0, -yp)
+ h1, w1 = im1.shape[:2]
+ h2, w2 = im2.shape[:2]
+ xp2 = min(w2, xp + w1)
+ yp2 = min(h2, yp + h1)
+ x2 = min(w1, w2 - xp)
+ y2 = min(h1, h2 - yp)
+ xp1 = max(0, xp)
+ yp1 = max(0, yp)
+
+ if (xp1 >= xp2) or (yp1 >= yp2):
+ return im2
+
+ blitted = im1[y1:y2, x1:x2]
+
+ new_im2 = +im2
+
+ if mask != None:
+ mask = mask[y1:y2, x1:x2]
+ if len(im1.shape) == 3:
+ mask = np.dstack(3 * [mask])
+ blit_region = new_im2[yp1:yp2, xp1:xp2]
+ new_im2[yp1:yp2, xp1:xp2] = (
+ 1.0 * mask * blitted + (1.0 - mask) * blit_region)
+ else:
+ new_im2[yp1:yp2, xp1:xp2] = blitted
+
+ return new_im2.astype('uint8') if (not ismask) else new_im2
+
+
+
+
+
+
+class VideoClip(Clip):
+
+ """
+
+ Base class for video clips. See ``MovieClip``, ``ImageClip`` etc. for
+ more user-friendly classes.
+
+ :param ismask: `True` if the clip is going to be used as a mask.
+
+ :ivar size: the size of the clip, (width,heigth), in pixels.
+ :ivar w: te width of the clip, in pixels.
+ :ivar h: te height of the clip, in pixels.
+
+
+ :ivar get_frame: A function `t-> frame at time t`
+
+ :ivar mask: VideoClip mask attached to this clip. If mask is ``None``,
+ The video clip is fully opaque.
+
+ :ivar audio: A :class:AudioClip attached to the video clip.
+
+ :ivar pos: a function ``t->(x,y)`` where ``x,y`` is the position
+ in pixels of the clip when it is composed with other clips.
+ See ``VideoClip.set_pos``
+
+ :ivar relative_pos: see variable ``pos``.
+
+ :ivar ismask: Boolean set to `True` if the clip is a mask.
+
+
+ """
+
+ def __init__(self, ismask=False):
+ Clip.__init__(self)
+ # self.mask = (None if ismask else
+ # VideoClip(ismask=True).set_get_frame(lambda t:None))
+ self.mask = None
+ self.audio = None
+ self.pos = lambda t: (0, 0)
+ self.relative_pos = False
+ self.ismask = ismask
+
+ @property
+ def w(self):
+ return self.size[0]
+
+ @property
+ def h(self):
+ return self.size[1]
+
+ @requires_duration
+ def preview(self, fps=15, audio=True, audiofps=22050):
+ """
+ Displays the clip in a window, at the given frames per second
+ (of movie) rate. It will avoid that the clip be played faster
+ than normal, but it cannot avoid the clip to be played slower
+ than normal if the computations are complex. In this case, try
+ reducing the ``fps``.
+
+ :param fps: Number of frames per second to be displayed.
+
+ :param audio: ``True`` (default) if you want the clip's audio
+ to be played in playback. The synchronization is not garanteed.
+
+ :param audiofps: The frames per second to use when generating the
+ audio sound. The lower, the cheaper the sound will be.
+
+ """
+
+ if self.ismask:
+ self = self.to_RGB()
+
+ screen = pg.display.set_mode(self.size)
+
+ if (audio == True) and (self.audio != None):
+ self.audio.preview(fps=audiofps, sleep=False)
+
+ img = self.get_frame(0)
+ for t in np.arange(0, self.duration, 1.0 / fps):
+ t1 = time.time()
+ imdisplay(img, screen)
+ img = self.get_frame(t)
+ t2 = time.time()
+ time.sleep(max(0, 1.0 / fps - (t2 - t1)))
+
+ def show(self, t=0, with_mask=True):
+ """
+ Splashes the frame of clip corresponding to time ``t``.
+
+ :param t: time in seconds of the frame to display.
+
+ :param with_mask: ``False`` if the clip has a mask but you
+ want to see the clip without the mask.
+
+ """
+
+ if self.ismask:
+ self = self.to_RGB()
+ if with_mask and (self.mask != None):
+ self = CompositeVideoClip(self.size, [self])
+ imdisplay(self.get_frame(t))
+
+ def save_frame(self, filename, t=0, savemask=False):
+ """
+ Saves the frame of clip corresponding to time ``t`` in
+ 'filename'. If ``savemask`` is ``True`` the mask is saved in the
+ alpha layer of the picture.
+ """
+ im = self.get_frame(t)
+ if savemask:
+ mask = 255 * self.mask.get_frame(t)
+ im = np.dstack([im, mask]).astype('uint8')
+
+ cv2.imwrite(filename,im)
+
+ def with_mask(self, constant_size=True):
+ """
+ Returns a copy of the clip with a completely opaque mask
+ (made of ones). This makes computations slow compared to having
+ a None mask but can be useful in many cases. Choose
+
+ :param constant_size: `False` for clips with moving image size.
+ """
+
+ if constant_size:
+ return self.set_mask(ColorClip(self.size, 1.0, ismask=True))
+ else:
+ mask = VideoClip(ismask=True).set_get_frame(
+ lambda t: np.ones(self.get_frame(t).shape))
+ return self.set_mask(mask)
+
+ @requires_duration
+ def to_directory(self, foldername, fps, transparent=True,
+ overwrite=True, startFrame=0):
+ """
+ Writes the frames of the clip into a folder as png format,
+ and returns the :class:DirectoryClip associated with this
+ folder
+
+ :param foldername: name of the folder (what did you expect ?)
+
+ :param fps: Number of frames per second of movie.
+
+ :param transparent: If `True`, the png images generated will
+ possess an alpha layer representing the mask of the clip.
+
+ :param overwrite: If `True`, will overwrite the content of
+ `folder` if already existing.
+
+ :param startFrame: Useless for the moment, but may come in handy
+ once parallelization is implemented.
+
+ """
+ print "writing frames in [%s]" % foldername,
+
+ try:
+ os.mkdir(foldername)
+ except:
+ if not overwrite:
+ print "Error: Maybe set overwrite =true "
+
+ tt = np.arange(0, self.duration, 1.0 / fps)
+ tt_feedback = tt[::len(tt) / 10]
+
+ for i, t in list(enumerate(tt))[startFrame:]:
+
+ picname = "%s/%s%06d.png" % (foldername, foldername, i)
+ pic = self.get_frame(t)
+ if transparent and (self.mask is not None):
+ fmask = self.mask.get_frame(t)
+ pic = np.dstack([pic, 255 * fmask]).astype('uint8')
+ imsave(picname, pic)
+ if t in tt_feedback:
+ print "%d" % (int(100 * t / tt[-1])) + "%",
+
+ print "done."
+ return DirectoryClip(foldername, fps=fps)
+
+ def to_movie(self, filename, fps=24, codec='DIVX',
+ audio=True, audiofps=44100, temp_wav='temp.wav',
+ remove_temp = True):
+ """
+ Makes a video file out of the clip.
+ First the clip is transformed into a directory clip, which means
+ that the frames of the future movie are computed and stored in a
+ folder as png files.
+ Then a ``DirectoryClip`` is made out of this folder and
+ transformed into a movie using ffmpeg (see DirectoryClip.to_movie)
+
+ Returns the directory clip.
+
+ :param filename: name of the video file. Whatever the codec used,
+ it is best to write the movie name as .avi
+
+ :param fps: Frames per second in the final movie.
+
+ :param codec: Codec to use for image encoding. Can be
+ - 'raw' : will produce a raw video, of perfect quality, but
+ possibly very huge size.
+ - 'DIVX' : For nice quality, very well compressed videos.
+ - 'XVID' : A little better than 'DVIX', a little heavier.
+ - Any of the (many) other codec supported by OpenCV, written
+ as a string of four characters. See here for a list:
+ http://remisoft.ath.cx/article14/fourcc
+
+ :param audio: Either ``True``, ``False``, or a file name.
+ If ``True`` and the clip has an audio clip attached, this
+ audio clip will be incorporated as a soundtrack in the movie.
+ If ``audio`` is the name of a .wav file, this wav file will
+ be incorporated as a soundtrack in the movie.
+
+ :param audiofps: frame rate to use when writing the sound.
+
+ :param temp_wav: the name of the temporary audiofile to be
+ generated and incorporated in the the movie, if any.
+
+ """
+
+ print "Making file %s ..."%filename
+ # Prepare audio
+
+ if isinstance(audio, str): # audio is a file
+ temp_wav = audio
+ elif self.audio is None: # if audio not a file and no clip.audio
+ audio = False
+ elif audio: # audio=True and clip.audio exists.
+ print "Rendering audio.",
+ self.audio.to_soundfile(temp_wav, audiofps)
+
+ # If there is any audio we will need to first write a mute
+ # temporary video file
+
+ if audio:
+ name, ext = os.path.splitext(filename)
+ videofile = name + 'TEMP' + ext
+ else:
+ videofile = filename
+
+ # Write the movie
+ print "Rendering video :",
+
+ codec = 0 if (codec=='raw') else cv2.VideoWriter_fourcc(*codec)
+
+ writer = cv2.VideoWriter(videofile, codec, fps, self.size)
+ tt = np.arange(0, self.duration, 1.0/fps)
+ lentt = len(tt)
+ for i,t in enumerate(tt):
+ writer.write(self.get_frame(t)[:,:,::-1].astype('uint8'))
+ if i % (len(tt)/10) == 0:
+ print "%d"%(100 * i / len(tt)) + "% ",
+ writer.release()
+ print "done !"
+
+ # Merge with audio if any and trash temporary files.
+
+ if audio:
+ print "Now merging video and audio...",
+ ffmpeg.merge_video_audio(videofile,temp_wav,filename)
+ if remove_temp:
+ os.remove(videofile)
+ if not isinstance(audio,str):
+ os.remove(temp_wav)
+ print "done !"
+
+
+ def blit_on(self, picture, t):
+ """ Returns the result of the blit of the clip's frame at time `t`
+ on the given `picture` """
+
+ hf, wf = sizef = picture.shape[:2]
+
+ if self.ismask and picture.max() != 0:
+ return np.maximum(picture, self.blit_on(np.zeros(sizef), t))
+
+ ct = t - self.start # clip time
+ mask = (None if (self.mask is None) else self.mask.get_frame(ct))
+
+ # Set position
+ pos = list(self.pos(ct))
+ img = self.get_frame(ct)
+
+ hi, wi = img.shape[:2]
+
+ # see set_pos doc for details
+ if self.relative_pos:
+ for i, dim in enumerate(wf, hf):
+ if not isinstance(pos[i], str):
+ pos[i] = dim * pos[i]
+
+ if isinstance(pos[0], str):
+ D = {'left': 0, 'center': (wf - wi) / 2, 'right': wf - wi}
+ pos[0] = D[pos[0]]
+
+ if isinstance(pos[1], str):
+
+ D = {'top': 0, 'center': (hf - hi) / 2, 'bottom': hf - hi}
+ pos[1] = D[pos[1]]
+
+ pos = map(int, pos)
+
+ return blit(img, picture, pos, mask=mask, ismask=self.ismask)
+
+ #-----------------------------------------------------------------
+ # F I L T E R I N G
+
+
+ def subapply(self, fun, ta=0, tb=None):
+ """
+ Returns a new clip in which the function ``fun`` (clip->clip) has
+ been applied to the subclip between times `ta` and `tb` (in
+ seconds).
+
+ >>> # The scene between times t=3s and t=6s in ``clip`` will be
+ >>> # be played twice slower in ``newclip``
+ >>> newclip = clip.subapply(lambda c:c.speedx(0.5) , 3,6)
+
+ """
+ left = None if (ta == 0) else self.subclip(0, tb=ta)
+ center = fun(self.subclip(ta, tb))
+ right = None if (tb is None) else self.subclip(ta=tb)
+
+ clips = [c for c in left, center, right if c != None]
+ cc = VideoClip.concat(clips)
+
+ if self.start != None:
+ cc = cc.set_start(self.start)
+
+ return cc
+
+ # IMAGE FILTERS
+ def fl_image(self, image_func, applyto=[]):
+ """ Modifies the images of a clip by replacing the frame
+ `get_frame(t)` by another frame, `image_func(get_frame(t))`
+ """
+ return self.fl(lambda gf, t: image_func(gf(t)), applyto)
+
+ @apply_to_mask
+ def resize(self, newsize=None, height=None, width=None):
+ """
+ Returns a video clip that is a resized version of the clip.
+
+ :param newsize: can be either ``(height,width)`` in pixels or
+ a float representing a scaling factor.
+
+ :param width: width of the new clip in pixel. The height is
+ then computed so that the width/height ratio is conserved.
+
+ :param height: height of the new clip in pixel. The width is
+ then computed so that the width/height ratio is conserved.
+
+ >>> myClip.resize( (460,720) ) # New resolution: (460,720)
+ >>> myClip.resize(0.6) # width and heigth multiplied by 0.6
+ >>> myClip.resize(width=800) # height computed automatically.
+
+
+ """
+ w, h = self.size
+
+ if newsize != None:
+ if isinstance(newsize, (int, float)):
+ newsize = [newsize * w, newsize * h]
+ elif height != None:
+ newsize = [w * height / h, height]
+ elif width != None:
+ newsize = [width, h * width / w]
+
+ newsize = map(int, newsize)[::-1]
+
+ if self.ismask:
+ fl = lambda pic: 1.0*cv2.resize((255 * pic).astype('uint8'),
+ tuple(newsize[::-1]), interpolation=cv2.INTER_AREA)/255
+ else:
+ fl = lambda pic: cv2.resize(pic.astype('uint8'),
+ tuple(newsize[::-1]), interpolation=cv2.INTER_AREA)
+
+ return self.fl_image(fl)
+
+ def on_color(self, size=None, color=(0, 0, 0), pos=None, col_opacity=None):
+ """ Returns a clip made of the current clip overlaid on a color
+ clip of bigger size.
+
+ :param size: size of the final clip. By default it will be the
+ size of the current clip.
+ :param bg_color: the background color of the final clip
+ :param pos: the position of the clip in the final clip.
+ :param col_opacity: should the added zones be transparent ?
+ """
+
+ if size is None:
+ size = self.size
+ if pos is None:
+ pos = ('center', 'center')
+ colorclip = ColorClip(size, color)
+ if col_opacity:
+ colorclip = colorclip.with_mask().set_opacity(col_opacity)
+
+ return CompositeVideoClip(size, [colorclip, self.set_pos(pos)],
+ transparent=(col_opacity != None))
+
+ @apply_to_mask
+ def margin(self, mar=None, left=0, right=0, top=0,
+ bottom=0, color=(0, 0, 0), opacity = 1.0):
+ """
+ Draws an external margin all around the frame.
+
+ :param mar: if not ``None``, then the new clip has a margin of
+ size ``mar`` in pixels on the left, right, top, and bottom.
+
+ :param left, right, top, bottom: width of the margin in pixel
+ in these directions.
+
+ :param color: color of the margin.
+
+ :param mask_margin: value of the mask on the margin. Setting
+ this value to 0 yields transparent margins.
+
+ """
+
+ if (opacity != 1.0) and (self.mask is None) and not (self.ismask):
+ self = self.with_mask()
+
+ if mar != None:
+ left = right = top = bottom = mar
+
+ new_w, new_h = self.w + left + right, self.h + top + bottom
+
+ if self.ismask:
+ shape = (new_h, new_w)
+ bg = np.tile(opacity, (new_h, new_w)).reshape(shape)
+ else:
+ shape = (new_h, new_w, 3)
+ bg = np.tile(color, (new_h, new_w)).reshape(shape)
+
+ def fl(pic):
+ im = +bg
+ im[top:top + self.h, left:left + self.w] = pic
+ return im
+
+ return self.fl_image(fl)
+
+ def padded(self, size, color=(0, 0, 0)):
+ """ internal margin by shrinking the frame """
+ w, h = self.size
+ return self.resize((x - 2 * size, y - 2 * size)).margin(size, color)
+
+ def crop(self, x1=0, y1=0, x2=None, y2=None):
+ if x2 is None:
+ x2 = self.size[0]
+ if y2 is None:
+ y2 = self.size[1]
+ return self.fl_image(lambda pic: pic[y1:y2, x1:x2],
+ applyto=['mask'])
+
+ #--------------------------------------------------------------
+ # C O M P O S I T I N G
+ def set_get_frame(self, gf):
+ newclip = Clip.set_get_frame(self, gf)
+ newclip.size = newclip.get_frame(0).shape[:2][::-1]
+ return newclip
+
+ def set_audio(self, audioclip):
+ """ mask must be a greyscale (0-1) Clip"""
+ newclip = copy(self)
+ newclip.audio = audioclip
+ return newclip
+
+ def set_mask(self, mask):
+ """ mask must be a greyscale (0-1) Clip"""
+ newclip = copy(self)
+ newclip.mask = mask
+ return newclip
+
+ def set_opacity(self, op):
+ """op is any float (normaly between 0 and 1) by which the
+ clip's mask will be multiplied """
+ newclip = copy(self)
+ newclip.mask = self.mask.fl_image(lambda pic: op * pic)
+ return newclip
+
+ @apply_to_mask
+ def set_pos(self, pos, relative=False):
+ """
+ Sets the position that the clip will have when included
+ in compositions. The argument ``pos`` can be either a couple
+ ``(x,y)`` or a function ``t-> (x,y)``. `x` and `y` mark the
+ location of the top left corner of the clip, and can be
+ of several types:
+
+ >>> clip.set_pos((45,150)) # x=45, y=150
+ >>>
+ >>> # clip horizontally centered, at the top of the picture
+ >>> clip.set_pos(("center","top"))
+ >>>
+ >>> # clip is at 40% of the width, 70% of the height:
+ >>> clip.set_pos((0.4,0.7), relative=True)
+ >>>
+ >>> # clip's position is horizontally centered, and moving up !
+ >>> clip.set_pos(lambda t: ('center', 50+t) )
+
+ """
+
+ newclip = copy(self)
+ newclip.relative_pos = relative
+ if hasattr(pos, '__call__'):
+ newclip.pos = pos
+ else:
+ newclip.pos = lambda t: pos
+
+ return newclip
+
+ def fadein(self, duration):
+ """
+ Makes the clip appear progressively, over ``duration`` seconds.
+ Only works when the clip is include in a CompositeVideoClip.
+ """
+ newclip = copy(self)
+ fading = lambda t: min(1.0 * t / duration, 1)
+ fl = lambda gf, t: fading(t) * gf(t)
+ newclip.mask = self.mask.fl(fl)
+ return newclip
+
+ @requires_duration
+ def fadeout(self, duration):
+ """
+ Makes the clip disappear progressively, over ``duration`` seconds.
+ Only works when the clip is include in a CompositeVideoClip.
+ """
+ newclip = copy(self)
+ fading = lambda t: min(1.0 * (self.duration - t) / duration, 1)
+ fl = lambda gf, t: fading(t) * gf(t)
+ newclip.mask = self.mask.fl(fl)
+ return newclip
+
+ #--------------------------------------------------------------
+ # CONVERSIONS
+ def to_ImageClip(self):
+ """ Return an ImageClip made out of the clip's first frame """
+ return ImageClip(self.get_frame(0))
+
+ def to_mask(self, canal=0):
+ """ Returns a mask a video clip made from the clip. """
+ if self.ismask:
+ return self
+ else:
+ newclip = self.fl_image(lambda pic: 1.0 * pic[:, :, canal] / 255)
+ newclip.ismask = True
+ return newclip
+
+ def to_RGB(self):
+ """ Returns a non-mask video clip made from the mask video clip. """
+ if self.ismask:
+ newclip = self.fl_image(
+ lambda pic: np.dstack(3 * [255 * pic]).astype('int'))
+ newclip.ismask = False
+ return newclip
+ else:
+ return self
+
+ #----------------------------------------------------------------
+ # Miscellaneous
+ def manual_tracking(self, t1=None, t2=None, fps=5):
+ """
+ Allows manual tracking of an object in the video clip between
+ times `t1` and `t2`. This displays the clip frame by frame
+ and you must click on the object in each frame. If ``t2=None``
+ only the frame at ``t1`` is taken into account.
+
+ Returns a list [(t1,x1,y1),(t2,x2,y2) etc... ]
+
+ >>> print myClip.manTrack(10, 13,fps=7)
+ >>>
+ >>> # To print 5 points coordinates at t=5 :
+ >>> for i in range(5):
+ >>> print myClip.manTrack(5)
+
+ Tip: To avoid redoing the tracking each time you run your script,
+ better save the result the first time and then load it at each run.
+
+ >>> # First time:
+ >>> import pickle
+ >>> txy = myClip.manTrack(20, 10,fps=10)
+ >>> with open("chaplin_txy.dat",'w+') as f:
+ >>> pickle.dump(txy,f)
+ >>>
+ >>> # Next times:
+ >>> import pickle
+ >>> with open("chaplin_txy.dat",'r') as f:
+ >>> txy = pickle.load(txy,f)
+
+ """
+
+ screen = pg.display.set_mode(self.size)
+ step = 1.0 / fps
+ if (t1 is None) and (t2 is None):
+ t1,t2 = 0, self.duration
+ elif (t2 is None):
+ t2 = t1 + step / 2
+ t = t1
+ txyList = []
+
+ while t < t2:
+
+ imdisplay(self.get_frame(t), screen)
+ doContinue = True
+
+ while doContinue:
+
+ for event in pg.event.get():
+
+ if event.type == pg.KEYDOWN:
+ if (event.key == pg.K_BACKSLASH):
+ t -= step
+ txyList.pop()
+ doContinue = False
+
+ elif event.type == pg.MOUSEBUTTONDOWN:
+ x, y = pg.mouse.get_pos()
+ txyList.append((t, x, y))
+ doContinue = False
+ t += step
+
+ return txyList
+
+
+class MovieClip(VideoClip):
+
+ """
+
+ A video clip originating from a movie file. For instance:
+
+ >>> clip = MovieClip("myHolidays.mp4")
+ >>> clip2 = MovieClip("myMaskVideo.avi",ismask = True)
+
+ :param source: Any video file: .ogv, .mp4, .mpeg, .avi, .mov etc.
+ :param ismask: `True` if the clip is a mask.
+ :param audio: If `True`, then the audio is extracted from the video
+ file, in wav format, and it attributed to the clip.
+
+ :ivar source: Name of the original video file
+ :ivar fps: Frames per second in the original file.
+ :ivar nframes: Total number of frames in the original file.
+
+ """
+
+ def __init__(self, source, ismask=False, audio=False):
+
+ VideoClip.__init__(self, ismask)
+
+ self.cap = cv2.VideoCapture(source)
+
+ self.source = source
+
+ self.fps = self.cap.get(cv2.CAP_PROP_FPS)
+
+ self.nframes = self.cap.get(cv2.CAP_PROP_FRAME_COUNT)
+
+ duration = 1.0 * (self.nframes) / self.fps
+ self.duration = duration
+
+ self.size = self.cap.read()[1].shape[:2][::-1]
+ self.last_frame_read = 0
+
+ def get_frame(t):
+ """
+ Gets the frame of the video at time t. Note for coders:
+ getting an arbitrary frame in the video with opencv can be
+ painfully slow if some decoding has to be made. This
+ function tries to avoid fectching arbitrary frames whenever
+ possible, by moving between adjacent frames.
+ """
+
+ nframe = int(self.fps * t)
+
+ if nframe == self.last_frame_read:
+ return self.cap.retrieve()[1][:, :, ::-1]
+ elif (self.last_frame_read < nframe < (self.last_frame_read + 5)):
+ for i in range(nframe - self.last_frame_read - 1):
+ self.cap.read()
+
+ else:
+ self.cap.set(cv2.CAP_PROP_POS_FRAMES, nframe - 1)
+
+ frame = self.cap.read()[1]
+ if frame is None:
+ return self.last_frame
+ else:
+ self.last_frame_read = nframe
+ frame = frame[:, :, ::-1]
+ self.last_frame = frame
+ return frame
+
+ self.get_frame = get_frame
+
+ if audio:
+ temp = 'temp.wav'
+ # try:
+ ffmpeg.extract_audio(source, temp)
+ self.audio = SoundClip(temp)
+ os.remove(temp)
+ # except:
+ # print "No audio detected in %s."%source
+
+
+class DirectoryClip(VideoClip):
+
+ """
+
+ A VideoClip from a directory containing pictures
+
+ """
+
+ def __init__(self, source, fps, transparent=True, repeat=False, ismask=False):
+
+ VideoClip.__init__(self, ismask=ismask)
+
+ self.directory = source
+ self.fps = fps
+ self.pics = sorted(["%s/%s" % (source, f) for f in os.listdir(source)
+ if not f.endswith('.txt')])
+
+ self.size = imread(self.pics[0]).shape[:2][::-1]
+
+ if imread(self.pics[0]).shape[2] == 4: # transparent png
+
+ if ismask:
+ def get_frame(t):
+ return 1.0 * imread(self.pics[int(self.fps * t)])[:, :, 3] / 255
+ else:
+ def get_frame(t):
+ return imread(self.pics[int(self.fps * t)])[:, :, :2]
+
+ if transparent:
+ self.mask = DirectoryClip(source, fps, ismask=True)
+
+ else:
+
+ def get_frame(t):
+ return imread(self.pics[int(self.fps * t)])
+
+ self.get_frame = get_frame
+ self.duration = 1.0 * len(self.pics) / self.fps
+
+ def to_movie(self, filename, bitrate=3000, audio=None):
+ """
+ Transforms the directory clip into a movie using ffmpeg.
+ Uses the framerate specified by ``clip.fps``.
+
+ :param filename: name of the video file to write in, like
+ 'myMovie.ogv' or 'myFilm.mp4'.
+ :param bitrate: final bitrate of the video file (in kilobytes/s).
+ 3000-6000 gives generally light files and an acceptable quality.
+ :param audio: the name of an audiofile to be incorporated in the
+ the movie.
+ """
+
+ if audio != None:
+ name, ext = os.path.splitext(filename)
+ videofile = name + 'TEMP' + ext
+ else:
+ videofile = filename
+
+ cmd = ("ffmpeg -y -f image2 -r %d -i %s/%s" % (
+ self.fps, self.directory, self.directory) + "%06d.png" +
+ " -b %dk -r %d %s" % (bitrate, self.fps, videofile))
+
+ print "\nrunning: %s" % cmd
+ os.system(cmd)
+
+ if audio != None:
+ cmd = (" ffmpeg -y -i %s" % audio +
+ " -i %s -strict experimental %s" % (videofile, filename))
+ print "running: %s" % cmd
+ os.system(cmd)
+ os.remove(videofile)
+
+class ImageClip(VideoClip):
+
+ """
+
+ A video clip originating from a picture. For instance:
+
+ >>> clip = ImageClip("myHouse.jpeg")
+ >>> clip = ImageClip( someNumpyArray )
+
+ :param img: Any picture file (png, tif, jpeg, etc.) or any array
+ representing an image, for instance a frame from a VideoClip
+ or a picture read with scipy of skimage's imread method.
+
+ :param ismask: `True` if the clip is a mask.
+ :param transparent: `True` (default) if you want the alpha layer
+ of the picture (if it exists) to be used as a mask.
+
+ :ivar img: array representing the image of the clip.
+
+ """
+
+ def __init__(self, img, ismask=False, transparent=True, fromalpha=False):
+
+ VideoClip.__init__(self, ismask=ismask)
+
+ if isinstance(img, str):
+ img = imread(img)
+
+ if len(img.shape) == 3:
+ if img.shape[2] == 4:
+ if fromalpha:
+ img = 1.0 * img[:, :, 3] / 255
+ elif ismask:
+ img = 1.0 * img[:, :, 0] / 255
+ elif transparent:
+ self.mask = ImageClip(
+ 1.0 * img[:, :, 3] / 255, ismask=True)
+ img = img[:, :, :3]
+ elif ismask:
+ img = 1.0 * img[:, :, 0] / 255
+
+ self.img = img
+ self.size = img.shape[:2][::-1]
+ self.get_frame = lambda t: self.img
+
+
+class ColorClip(VideoClip):
+
+ """
+
+ To be written
+
+ """
+
+ def __init__(self, size, col=(0, 0, 0), ismask=False):
+ VideoClip.__init__(self, ismask=ismask)
+ self.size = size
+ w, h = size
+ shape = (h, w) if isinstance(col, (int, float)) else (h, w, len(col))
+ self.img = np.tile(col, w * h).reshape(shape)
+ self.get_frame = lambda t: self.img
+
+
+class TextClip(ImageClip):
+
+ """
+
+ A VideoClip originating from a script-generated text image.
+ Makes a text PNG using ImageMagick.
+
+ :param txt: either a string, or a filename. If txt is in a file and
+ whose name is ``mytext.txt`` for instance, then txt must be
+ equal to ``@mytext.txt`` .
+
+ :param size: Size of the picture in pixels. Can be auto-set if
+ method='label', but mandatory if method='caption'.
+ the height can be None, it will then be auto-determined.
+
+ :param bg_color: Color of the background. See ``TextClip.list('color')``
+ for a list of acceptable names.
+
+ :param color: Color of the background. See ``TextClip.list('color')``
+ for a list of acceptable names.
+
+ :param font: Name of the font to use. See ``TextClip.list('font')`` for
+ the list of fonts you can use on your computer.
+
+ :param stroke_color: Color of the stroke (=contour line) of the text.
+ if ``None``, there will be no stroke.
+
+ :param stroke_width: Width of the strocke, in pixels. Can be a float,
+ like 1.5.
+
+ :param method: 'label' (autosized) or 'caption' (presized, wrapped)
+
+ :param align: center | East | West | South | North
+
+ :param transparent: ``True`` (default) if you want to take into account
+ the transparency in the image.
+
+ """
+
+ def __init__(self, txt, size=None, color='black', bg_color='transparent',
+ fontsize=None, font='Times-New-Roman-Regular',
+ stroke_color=None, stroke_width=1, method='label',
+ kerning=None, align='center', interline=None,
+ tempfile='temp.png',
+ temptxt='temp.txt', transparent=True, remove_temp=True,
+ print_cmd=False):
+
+ if not txt.startswith('@'):
+ temptxt = 'temp.txt'
+ with open(temptxt, 'w+') as f:
+ f.write(txt)
+ txt = '@temp.txt'
+
+ if size != None:
+ size = ('' if size[0] is None else str(size[0]),
+ '' if size[1] is None else str(size[1]))
+
+ cmd = ("convert "
+ + "-background transparent "
+ + "-fill %s " % (color)
+ + "-font %s " % font
+ + ("" if (fontsize is None)
+ else "-pointsize %d " % fontsize)
+ + ("" if (kerning is None)
+ else "-kerning %0.1f" % kerning)
+ + ("" if (stroke_color is None)
+ else "-stroke %s -strokewidth %d " % (
+ stroke_color, stroke_width))
+ + ("" if (size is None)
+ else "-size %sx%s " % (size[0], size[1]))
+ + "-gravity %s " % align
+ + ("" if (interline is None)
+ else "-interline-spacing %d " % interline)
+ + "%s:'%s' " % (method, txt)
+ + tempfile)
+
+ if print_cmd:
+ print cmd
+
+ os.system(cmd)
+ ImageClip.__init__(self, tempfile, transparent=transparent)
+ self.txt = txt
+ self.color = color
+ self.stroke_color = stroke_color
+
+ if remove_temp:
+ os.remove(tempfile)
+ try:
+ os.remove(temptxt)
+ except:
+ pass
+
+ @staticmethod
+ def list(arg):
+ """ Returns the list of all valid entries for the argument given
+ (can be ``font``, ``color``, etc...)
+ argument of ``TextClip`` """
+ process = subprocess.Popen(['convert', '-list', 'font'],
+ stdout=subprocess.PIPE)
+ result = process.communicate()[0]
+ lines = result.splitlines()
+
+ if arg == 'font':
+ return [l[8:] for l in lines if l.startswith(" Font:")]
+ elif arg == 'color':
+ return [l.split(" ")[1] for l in lines[2:]]
+
+
+class CompositeVideoClip(VideoClip):
+
+ """
+
+ A VideoClip made of other videoclips displayed together.
+
+ :param size: The size (height x width) of the final clip.
+
+ :param clips: A list of videoclips. Each clip of the list will
+ be displayed below the clips appearing after it in the list.
+ For each clip:
+
+ - The attribute ``pos`` determines where the clip is placed.
+ See ``VideoClip.set_pos``
+ - The mask of the clip determines which parts are visible.
+
+ Finally, if all the clips in the list have their ``duration``
+ attribute set, then the duration of the composite video clip
+ is computed automatically
+
+ :param transparent: if False, the clips are overlaid on a surface
+ of the color `bg_color`. If True, the clips are overlaid on
+ a transparent surface, so that all pixels that are transparent
+ for all clips will be transparent in the composite clip. More
+ precisely, the mask of the composite clip is then the composite
+ of the masks of the different clips. Only use `transparent=True`
+ when you intend to use your composite clip as part of another
+ composite clip and you care about its transparency.
+
+ """
+
+ def __init__(self, size, clips, bg_color=None, transparent=False,
+ ismask=False):
+
+ VideoClip.__init__(self)
+ self.size = size
+ self.ismask = ismask
+ self.clips = clips
+ self.transparent = transparent
+ if bg_color is None:
+ bg_color = 0.0 if self.ismask else (0, 0, 0)
+ self.bg_color = bg_color
+ self.bg = ColorClip(size, col=self.bg_color).get_frame(0)
+
+ # compute duration
+ ends = [c.end for c in self.clips]
+ if not any([(e is None) for e in ends]):
+ self.duration = max(ends)
+
+ # compute audio
+ audioclips = [v.audio for v in self.clips if v.audio != None]
+ if len(audioclips) > 0:
+ self.audio = CompositeAudioClip(audioclips)
+
+ # compute mask
+ if transparent:
+ maskclips = [c.mask.set_pos(c.pos) for c in self.clips]
+ self.mask = CompositeVideoClip(self.size, maskclips,
+ transparent=False, ismask=True)
+
+ def gf(t):
+ """ The clips playing at time `t` are blitted over one
+ another. """
+
+ f = self.bg
+ for c in self.playing_clips(t):
+ f = c.blit_on(f, t)
+ return f
+
+ self.get_frame = gf
+
+ def playing_clips(self, t=0):
+ """ Returns a list of the clips in the composite clips that are
+ actually playing at the given time `t`. """
+ return [c for c in self.clips if c.is_playing(t)]
+
+
+def concat(cliplist, transition=None, bg_color=(0, 0, 0), transparent=False,
+ ismask=False):
+ """
+
+ Makes one video clip by concatenating several clips of a list.
+ (Concatenated means that they will be played one after another).
+ if the clips do not have the same resolution, the final
+ resolution will be such that no clip has to be resized. As
+ a consequence the final clip has the height of the highest
+ clip and the width of the widest clip of the list. All the
+ clips with smaller dimensions will appear centered. The border
+ will be transparent if mask=True, else it will be of the
+ color specified by ``bg_color``.
+
+ :param cliplist: a list of video clips which must all have
+ their ``duration`` attributes set.
+ :param transparent: if true, the resulting clip's mask will be the
+ concatenation of the masks of the clips in the list. If
+ the clips do not have the same resolution, the border around
+ the smaller clips will be transparent.
+ :param transition: a clip that will be played between each two
+ clips of the list.
+
+ """
+
+ if transition:
+ l = [[v, transition] for v in cliplist[:-1]]
+ cliplist = reduce(lambda x, y: x + y, l) + [cliplist[-1]]
+
+ sizes = [v.size for v in cliplist]
+ tt = np.cumsum([0] + [c.duration for c in cliplist])
+
+ if len(set(sizes)) == 1: # All clips have the same size
+ result = VideoClip()
+ result.size = cliplist[0].size
+ result.cliplist = cliplist
+ result.tt = tt
+ result.duration = tt[-1]
+
+ def gf(t):
+ i = max([i for i, e in enumerate(tt) if e <= t])
+ return result.cliplist[i].get_frame(t - tt[i])
+ result.get_frame = gf
+
+ else:
+
+ w = max([r[0] for r in sizes])
+ h = max([r[1] for r in sizes])
+ result = CompositeVideoClip((w, h),
+ [c.set_start(t).set_pos(('center', 'center'))
+ for (c, t) in zip(cliplist, tt)],
+ bg_color=bg_color,
+ ismask=ismask, transparent=transparent)
+
+ # Compute the mask if any
+
+ if transparent and (not ismask):
+ result.mask = concat([c.mask for c in cliplist], transparent=False,
+ ismask=True)
+
+
+ # Compute the audio if any
+
+ audios = [c.audio for c in cliplist if c.audio!=None]
+ if len(audios)>1:
+ result.audio = CompositeAudioClip([a.set_start(t)
+ for a,t in zip(audios,tt)])
+
+ return result
diff --git a/moviepy/__init__.py b/moviepy/__init__.py
new file mode 100644
index 00000000..6d764d1b
--- /dev/null
+++ b/moviepy/__init__.py
@@ -0,0 +1,4 @@
+#__all__ = ['Clip','VideoClip','AudioClip']
+from Clip import *
+from VideoClip import *
+from AudioClip import *
diff --git a/moviepy/ffmpeg.py b/moviepy/ffmpeg.py
new file mode 100644
index 00000000..b3689d0d
--- /dev/null
+++ b/moviepy/ffmpeg.py
@@ -0,0 +1,80 @@
+""" Very experimental 'bindings' to ffmpeg and ImageMagick."""
+
+import os
+
+def movie_from_frames(filename, folder, fps, digits=6):
+ """ Writes a movie out of the frames (picture files) in a folder """
+ s = "%" + "%02d" % digits + "d.png"
+ cmd = ("ffmpeg -y -f image2 -r %d -i %s/%s" % (fps, folder, folder) +
+ s + " -b %dk -r %d %s" % (bitrate, self.fps, filename))
+ os.system(cmd)
+ return cmd
+
+
+def extract_subclip(filename, t1, t2, targetname=None):
+ """ makes a new video file playing video file ``filename`` between
+ the times ``t1`` and ``t2``. """
+ name,ext = os.path.splitext(filename)
+ if not targetname:
+ T1, T2 = [int(1000*t) for t in [t1, t2]]
+ targetname = name+ "%sSUB%d_%d.%s"(name, T1, T2, ext)
+
+ cmd = ( "ffmpeg -y -ss %0.2f -t %0.2f"%(t1, t2-t1)+
+ " -i %s -vcodec copy -acodec copy %s"%(filename, targetname))
+ os.system(cmd)
+ return cmd
+
+
+
+def merge_video_audio(video,audio,output):
+ """ merges video file ``video`` and audio file ``audio`` into one
+ movie file ``output``. """
+ cmd = "ffmpeg -y -i %s -i %s -vcodec copy -acodec libvorbis %s"%(
+ audio, video, output)
+ print "running: %s" % cmd
+ os.system(cmd)
+ return cmd
+
+def gif_to_directory(gif_file,dirName=None):
+ """
+ Stores all the frames of the given .gif file
+ into the directory ``dirName``. If ``dirName``
+ is not provided, the directory has the same name
+ as the .gif file. Supports transparency.
+ Returns the directory name.
+
+ Example:
+
+ >>> d = gif_to_directory("animated-earth.gif")
+ >>> clip = DirectoryClip(d,fps=3)
+
+ """
+
+ if dirName is None:
+ name, ext = os.path.splitext(gif_file)
+ dirName = name
+
+ try:
+ os.mkdir(dirName)
+ except:
+ pass
+
+ cmd = "convert -coalesce %s %s" %(
+ gif_file, os.path.join(dirName,"%04d.png"))
+ os.system(cmd)
+ return dirName
+
+
+def extract_audio(inputfile,output,bitrate=3000,fps=44100):
+ """ extract the sound from a video file and save it in ``output`` """
+ cmd = "ffmpeg -y -i %s -ab %dk -ar %d %s"%(inputfile,bitrate,fps,output)
+ os.system(cmd)
+ return cmd
+
+
+def resize(video,output,size):
+ """ resizes ``video`` to new size ``size`` and write the result
+ in file ``output``. """
+ cmd = "ffmpeg -i %s -vf scale=%d:%d %s"%(video,res[0],res[1],output)
+ os.system(cmd)
+ return cmd
diff --git a/setup.py b/setup.py
new file mode 100644
index 00000000..4276a981
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,13 @@
+#!/usr/bin/env python
+
+from distutils.core import setup
+setup(name='moviepy',
+ version='0.1',
+ author='Zulko 2013',
+ description='Module for script-based video editing',
+ long_description=open('README.txt').read(),
+ license='LICENSE.txt',
+ keywords="movie editing film mixing script-based",
+ packages=['moviepy'],
+ requires = ['scipy','numpy','matplotlib','pygame',
+ 'cv2 >=2.4.6','decorator'])