Skip to content

Instantly share code, notes, and snippets.

@BertrandBordage
Last active September 22, 2016 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BertrandBordage/4c84b6c27c9fbc139c8f to your computer and use it in GitHub Desktop.
Save BertrandBordage/4c84b6c27c9fbc139c8f to your computer and use it in GitHub Desktop.
Converts most videos to the same quality HTML5-compatible MP4+OGV
# coding: utf-8
"""
Converts videos inside the current directory to two complementary
HTML5 video formats while keeping the same quality.
The converted videos are placed in a subfolder.
You need avconv to be installed with some codecs
(packages libav-tools & libavcodecs-extra under Ubuntu)
"""
__author__ = 'Bertrand Bordage'
__copyright__ = 'Copyright © 2015 Bertrand Bordage'
__license__ = 'MIT'
import json
import os
from subprocess import check_output, PIPE, CalledProcessError
SUBFOLDER = 'Recompressed'
if not os.path.exists(SUBFOLDER):
os.mkdir(SUBFOLDER)
def convert_to(extension, video_codec, audio_codec,
video_bitrate, audio_bitrate):
new_filename = os.path.join(SUBFOLDER,
os.path.splitext(filename)[0] + extension)
print('Creating `%s`...' % new_filename)
check_output([
'avconv', '-i', filename, '-threads', '16',
'-vcodec', video_codec, '-acodec', audio_codec,
'-b:v', video_bitrate, '-b:a', audio_bitrate, '-y',
new_filename], stderr=PIPE)
for filename in os.listdir('.'):
try:
output = check_output(['avprobe', '-of', 'json', '-show_streams',
filename], stderr=PIPE)
except CalledProcessError:
continue
streams = json.loads(output.decode())['streams']
video_streams = [s for s in streams if s['codec_type'] == 'video']
audio_streams = [s for s in streams if s['codec_type'] == 'audio']
if len(video_streams) != 1 and len(audio_streams) != 1:
print('Skipping `%s` as it has %d video streams and %d audio streams'
% (filename, len(video_streams), len(audio_streams)))
continue
video, audio = video_streams[0], audio_streams[0]
convert_to('.ogv', 'libtheora', 'libvorbis',
video['bit_rate'], audio['bit_rate'])
convert_to('.mp4', 'libx264', 'libvo_aacenc',
video['bit_rate'], audio['bit_rate'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment