-
Notifications
You must be signed in to change notification settings - Fork 189
/
__init__.py
207 lines (182 loc) · 7.96 KB
/
__init__.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#!/usr/bin/python3
import subprocess
import re
import os
import time
MimeTypes = {
'mp3' : 'audio/mpeg',
'ogg' : 'audio/ogg',
'flac' : 'audio/flac',
'aac' : 'audio/aac',
'm4a' : 'audio/m4a',
'wav' : 'audio/wav',
'wma' : 'audio/x-ms-wma',
}
class Transcoder(object):
devnull = open(os.devnull,'w')
def __init__(self):
self.command = ['']
def available(self):
try:
subprocess.Popen([self.command[0]],stdout=Transcoder.devnull, stderr=Transcoder.devnull)
return True
except OSError:
return False
class Encoder(Transcoder):
def __init__(self,filetype,command):
self.filetype = filetype
self.mimetype = MimeTypes[filetype]
self.command = command
def encode(self, decoder_process, bitrate):
cmd = self.command[:]
if 'BITRATE' in cmd:
cmd[cmd.index('BITRATE')] = '%dk' % bitrate
return subprocess.Popen(cmd,
stdin=decoder_process.stdout,
stdout=subprocess.PIPE,
stderr=Transcoder.devnull
)
def __str__(self):
return "<Encoder type='%s' cmd='%s'>"%(self.filetype,str(' '.join(self.command)))
class Decoder(Transcoder):
def __init__(self,filetype,command):
self.filetype = filetype
self.mimetype = MimeTypes[filetype]
self.command = command
def decode(self, filepath, starttime=0):
cmd = self.command[:]
if 'INPUT' in cmd:
cmd[cmd.index('INPUT')] = filepath
if 'STARTTIME' in cmd:
hours, minutes, seconds = starttime//3600, starttime//60%60, starttime%60
cmd[cmd.index('STARTTIME')] = '%d:%d:%d' % (hours, minutes, seconds)
return subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=Transcoder.devnull
)
def __str__(self):
return "<Decoder type='%s' cmd='%s'>"%(self.filetype,str(' '.join(self.command)))
class TranscodeError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class EncodeError(TranscodeError):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class DecodeError(TranscodeError):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class AudioTranscode:
READ_BUFFER = 1024
Encoders = [
#encoders take input from stdin and write output to stout
Encoder('ogg', ['oggenc', '-b','BITRATE','-']),
Encoder('ogg', ['ffmpeg', '-i', '-', '-f', 'ogg', '-acodec', 'libvorbis', '-ab', 'BITRATE', '-']),
Encoder('mp3', ['lame','-b','BITRATE','-','-']),
Encoder('mp3', ['ffmpeg', '-i', '-', '-f', 'mp3', '-acodec', 'libmp3lame', '-ab', 'BITRATE', '-']),
Encoder('aac', ['faac','-b','BITRATE','-P','-X','-o','-','-']),
Encoder('m4a', ['faac','-b','BITRATE','-P','-X','-o','-','-']),
Encoder('flac', ['flac', '--force-raw-format', '--endian=little', '--channels=2', '--bps=16', '--sample-rate=44100', '--sign=signed', '-o', '-', '-']),
Encoder('wav', ['cat']),
]
Decoders = [
#filepath must be appendable!
Decoder('mp3' , ['mpg123', '-w', '-', 'INPUT']),
Decoder('mp3' , ['ffmpeg', '-ss', 'STARTTIME', '-i', 'INPUT', '-f', 'wav', '-acodec', 'pcm_s16le', '-']),
Decoder('wma' , ['ffmpeg', '-ss', 'STARTTIME', '-i', 'INPUT', '-f', 'wav', '-acodec', 'pcm_s16le', '-']),
Decoder('ogg' , ['oggdec', '-Q','-b', '16', '-o', '-', 'INPUT']),
Decoder('ogg' , ['ffmpeg', '-ss', 'STARTTIME', '-i', 'INPUT', '-f', 'wav', '-acodec', 'pcm_s16le', '-']),
Decoder('flac' , ['flac', '-F','-d', '-c', 'INPUT']),
Decoder('aac' , ['faad', '-w', 'INPUT']),
Decoder('m4a' , ['faad', '-w', 'INPUT']),
Decoder('wav' , ['cat', 'INPUT']),
]
def __init__(self,debug=False):
self.debug = debug
self.availableEncoders = list(filter(lambda x:x.available(),AudioTranscode.Encoders))
self.availableDecoders = list(filter(lambda x:x.available(),AudioTranscode.Decoders))
self.bitrate = {'mp3':160, 'ogg': 128, 'aac': 128}
def availableEncoderFormats(self):
return list(set(map(lambda x:x.filetype, self.availableEncoders)))
def availableDecoderFormats(self):
return list(set(map(lambda x:x.filetype, self.availableDecoders)))
def _filetype(self, filepath):
if '.' in filepath:
return filepath.lower()[filepath.rindex('.')+1:]
def _decode(self, filepath, decoder=None, starttime=0):
if not os.path.exists(filepath):
filepath = os.path.abspath(filepath)
raise DecodeError('File not Found! Cannot decode "file" %s'%filepath)
filetype = self._filetype(filepath)
if not filetype in self.availableDecoderFormats():
raise DecodeError('No decoder available to handle filetype %s'%filetype)
elif not decoder:
for d in self.availableDecoders:
if d.filetype == filetype:
decoder = d
break
if self.debug:
print(decoder)
return decoder.decode(filepath, starttime=starttime)
def _encode(self, audio_format, decoder_process, bitrate=None,encoder=None):
if not audio_format in self.availableEncoderFormats():
raise EncodeError('No encoder available to handle audio format %s'%audio_format)
if not bitrate:
bitrate = self.bitrate.get(audio_format)
if not bitrate:
bitrate = 128
if not encoder:
for e in self.availableEncoders:
if e.filetype == audio_format:
encoder = e
break
if self.debug:
print(encoder)
return encoder.encode(decoder_process, bitrate)
def transcode(self, in_file, out_file, bitrate=None):
print(out_file)
audioformat = self._filetype(out_file)
with open(out_file, 'wb') as fh:
for data in self.transcodeStream(in_file,audioformat,bitrate):
fh.write(data)
fh.close()
def transcodeStream(self, filepath, newformat, bitrate=None,
encoder=None, decoder=None, starttime=0):
decoder_process = None
encoder_process = None
try:
decoder_process = self._decode(filepath, decoder, starttime=starttime)
encoder_process = self._encode(newformat, decoder_process,bitrate=bitrate,encoder=encoder)
while encoder_process.poll() == None:
data = encoder_process.stdout.read(AudioTranscode.READ_BUFFER)
if data == None:
time.sleep(0.1) #wait for new data...
break
yield data
except Exception as e:
#pass on exception, but clean up
raise e
finally:
if decoder_process and decoder_process.poll() == None:
if decoder_process.stderr:
decoder_process.stderr.close()
if decoder_process.stdout:
decoder_process.stdout.close()
if decoder_process.stdin:
decoder_process.stdin.close()
decoder_process.terminate()
if encoder_process:
encoder_process.stdout.read()
encoder_process.stdout.close()
if encoder_process.stdin:
encoder_process.stdin.close()
if encoder_process.stderr:
encoder_process.stderr.close()
encoder_process.wait()
def mimeType(self, fileExtension):
return MimeTypes.get(fileExtension)