-
Notifications
You must be signed in to change notification settings - Fork 3
/
transcode.py
62 lines (51 loc) · 2.13 KB
/
transcode.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import re
from flask import Response, redirect
from subprocess import PIPE, Popen
from wsgi_utils import PipeWrapper
TRANSCODABLE_FORMATS = ['mp3', 'ogg', 'flac', 'm4a', 'wav']
def _format_of_file(filename):
return re.search('\.([^.]+)$', filename).group(1)
class Transcoder(object):
def __init__(self, music_dir, cache_dir):
self.music_dir = music_dir
self.cache_dir = cache_dir
def needs_transcode(self, filename, wanted_formats):
return _format_of_file(filename) not in wanted_formats
def can_transcode(self, filename, wanted_formats):
return (
_format_of_file(filename) in TRANSCODABLE_FORMATS and
'ogg' in wanted_formats
)
def path_for_cache_key(self, cache_key):
return os.path.join(self.cache_dir, 'tx' + cache_key + '.ogg')
def transcode_and_stream(self, filename, cache_key=None):
full_filename = os.path.join(self.music_dir, filename)
cache_filename = None
if cache_key:
cache_filename = self.path_for_cache_key(cache_key)
# See if the transcode is already cached.
try:
os.stat(cache_filename)
return redirect(os.path.join('/', cache_filename))
except OSError:
pass
# TODO: maintain a set of tasks for currently ongoing transcodes
# to avoid transcoding a track twice at the same time. Then try
# sending Accept-Ranges: bytes and honoring range requests, while
# not providing a Content-Length. See if this makes Firefox's
# media file fetching happy.
# Transcode to ogg.
# The filename should come out of the DB and *not* be user-specified
# (through the web interface), so it can be trusted.
command = [
'ffmpeg', '-v', 'quiet',
'-i', full_filename,
'-f', 'ogg', '-acodec', 'libvorbis', '-aq', '5', '-'
]
pipe = Popen(command, stdout=PIPE)
return Response(
PipeWrapper(pipe, copy_to_filename=cache_filename),
mimetype='audio/ogg',
direct_passthrough=True
)