added audio reprocessing transcoder
[mediagoblin.git] / mediagoblin / media_types / audio / processing.py
CommitLineData
5a34a80d
JW
1# GNU MediaGoblin -- federated, autonomous media hosting
2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Affero General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Affero General Public License for more details.
13#
14# You should have received a copy of the GNU Affero General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
5ac1fe80 17import argparse
5a34a80d 18import logging
5a34a80d
JW
19import os
20
21from mediagoblin import mg_globals as mgg
5ac1fe80 22from mediagoblin.processing import (
440e33aa 23 BadMediaFail, FilenameBuilder,
5ac1fe80
RE
24 ProgressCallback, MediaProcessor, ProcessingManager,
25 request_from_args, get_orig_filename,
26 store_public, copy_original)
5a34a80d 27
5ac1fe80 28from mediagoblin.media_types.audio.transcoders import (
440e33aa 29 AudioTranscoder, AudioThumbnailer)
5a34a80d 30
10085b77 31_log = logging.getLogger(__name__)
5a34a80d 32
df68438a
RE
33MEDIA_TYPE = 'mediagoblin.media_types.audio'
34
64712915 35
ec4261a4 36def sniff_handler(media_file, **kw):
df68438a 37 _log.info('Sniffing {0}'.format(MEDIA_TYPE))
196a5181 38 try:
4f4f2531 39 transcoder = AudioTranscoder()
ec4261a4 40 data = transcoder.discover(media_file.name)
4f4f2531
JW
41 except BadMediaFail:
42 _log.debug('Audio discovery raised BadMediaFail')
df68438a 43 return None
ec4261a4 44
440e33aa 45 if data.is_audio is True and data.is_video is False:
df68438a 46 return MEDIA_TYPE
10085b77 47
df68438a 48 return None
5a34a80d 49
64712915 50
5ac1fe80
RE
51class CommonAudioProcessor(MediaProcessor):
52 """
53 Provides a base for various audio processing steps
54 """
55
56 def common_setup(self):
57 """
440e33aa
RE
58 Setup the workbench directory and pull down the original file, add
59 the audio_config, transcoder, thumbnailer and spectrogram_tmp path
5ac1fe80
RE
60 """
61 self.audio_config = mgg \
62 .global_config['media_type:mediagoblin.media_types.audio']
63
64 # Pull down and set up the original file
65 self.orig_filename = get_orig_filename(
66 self.entry, self.workbench)
67 self.name_builder = FilenameBuilder(self.orig_filename)
68
5ac1fe80
RE
69 self.transcoder = AudioTranscoder()
70 self.thumbnailer = AudioThumbnailer()
71
72 def copy_original(self):
73 if self.audio_config['keep_original']:
74 copy_original(
75 self.entry, self.orig_filename,
76 self.name_builder.fill('{basename}{ext}'))
77
78 def transcode(self, quality=None):
79 if not quality:
80 quality = self.audio_config['quality']
81
82 progress_callback = ProgressCallback(self.entry)
83 webm_audio_tmp = os.path.join(self.workbench.dir,
84 self.name_builder.fill(
85 '{basename}{ext}'))
86
5ac1fe80
RE
87 self.transcoder.transcode(
88 self.orig_filename,
89 webm_audio_tmp,
90 quality=quality,
91 progress_callback=progress_callback)
92
93 self.transcoder.discover(webm_audio_tmp)
94
95 _log.debug('Saving medium...')
9448a98e
RE
96 store_public(self.entry, 'webm_audio', webm_audio_tmp,
97 self.name_builder.fill('{basename}.medium.webm'))
5ac1fe80 98
ad80fc8a 99 def create_spectrogram(self, max_width=None, fft_size=None):
5ac1fe80
RE
100 if not max_width:
101 max_width = mgg.global_config['media:medium']['max_width']
102 if not fft_size:
103 fft_size = self.audio_config['spectrogram_fft_size']
104
5ac1fe80
RE
105 wav_tmp = os.path.join(self.workbench.dir, self.name_builder.fill(
106 '{basename}.ogg'))
107
108 _log.info('Creating OGG source for spectrogram')
109 self.transcoder.transcode(
110 self.orig_filename,
111 wav_tmp,
ad80fc8a
RE
112 mux_string='vorbisenc quality={0} ! oggmux'.format(
113 self.audio_config['quality']))
5ac1fe80 114
d8f886dc
RE
115 spectrogram_tmp = os.path.join(self.workbench.dir,
116 self.name_builder.fill(
117 '{basename}-spectrogram.jpg'))
118
5ac1fe80
RE
119 self.thumbnailer.spectrogram(
120 wav_tmp,
d8f886dc 121 spectrogram_tmp,
5ac1fe80
RE
122 width=max_width,
123 fft_size=fft_size)
124
125 _log.debug('Saving spectrogram...')
d8f886dc 126 store_public(self.entry, 'spectrogram', spectrogram_tmp,
c6eaa555 127 self.name_builder.fill('{basename}.spectrogram.jpg'))
5ac1fe80
RE
128
129 def generate_thumb(self, size=None):
130 if not size:
776e4d7a
RE
131 max_width = mgg.global_config['media:thumb']['max_width']
132 max_height = mgg.global_config['media:thumb']['max_height']
5ac1fe80
RE
133 size = (max_width, max_height)
134
135 thumb_tmp = os.path.join(self.workbench.dir, self.name_builder.fill(
136 '{basename}-thumbnail.jpg'))
137
d8f886dc
RE
138 # We need the spectrogram to create a thumbnail
139 spectrogram = self.entry.media_files.get('spectrogram')
140 if not spectrogram:
141 _log.info('No spectrogram found, we will create one.')
142 self.create_spectrogram()
143 spectrogram = self.entry.media_files['spectrogram']
144
145 spectrogram_filepath = mgg.public_store.get_local_path(spectrogram)
146
5ac1fe80 147 self.thumbnailer.thumbnail_spectrogram(
d8f886dc 148 spectrogram_filepath,
5ac1fe80
RE
149 thumb_tmp,
150 size)
151
c6eaa555
RE
152 store_public(self.entry, 'thumb', thumb_tmp,
153 self.name_builder.fill('{basename}.thumbnail.jpg'))
5ac1fe80
RE
154
155
156class InitialProcessor(CommonAudioProcessor):
157 """
158 Initial processing steps for new audio
159 """
160 name = "initial"
161 description = "Initial processing"
162
163 @classmethod
164 def media_is_eligible(cls, entry=None, state=None):
165 """
166 Determine if this media type is eligible for processing
167 """
168 if not state:
169 state = entry.state
170 return state in (
171 "unprocessed", "failed")
172
173 @classmethod
174 def generate_parser(cls):
175 parser = argparse.ArgumentParser(
176 description=cls.description,
177 prog=cls.name)
178
179 parser.add_argument(
180 '--quality',
d8f886dc 181 help='vorbisenc quality. Range: -0.1..1')
5ac1fe80
RE
182
183 parser.add_argument(
184 '--fft_size',
185 type=int,
186 help='spectrogram fft size')
187
188 parser.add_argument(
189 '--thumb_size',
757376e3 190 nargs=2,
5ac1fe80
RE
191 metavar=('max_width', 'max_height'),
192 type=int)
193
194 parser.add_argument(
195 '--medium_width',
196 type=int,
197 help='The width of the spectogram')
198
199 parser.add_argument(
200 '--create_spectrogram',
201 action='store_true',
202 help='Create spectogram and thumbnail')
203
204 return parser
205
206 @classmethod
207 def args_to_request(cls, args):
208 return request_from_args(
209 args, ['create_spectrogram', 'quality', 'fft_size',
210 'thumb_size', 'medium_width'])
211
212 def process(self, quality=None, fft_size=None, thumb_size=None,
213 create_spectrogram=None, medium_width=None):
550af89f
RE
214 self.common_setup()
215
5ac1fe80
RE
216 if not create_spectrogram:
217 create_spectrogram = self.audio_config['create_spectrogram']
218
5ac1fe80
RE
219 self.transcode(quality=quality)
220 self.copy_original()
221
222 if create_spectrogram:
ad80fc8a 223 self.create_spectrogram(max_width=medium_width, fft_size=fft_size)
5ac1fe80
RE
224 self.generate_thumb(size=thumb_size)
225 self.delete_queue_file()
226
227
2e50e4b5
RE
228class Resizer(CommonAudioProcessor):
229 """
230 Thumbnail and spectogram resizing process steps for processed audio
231 """
232 name = 'resize'
ad80fc8a 233 description = 'Resize thumbnail or spectogram'
2e50e4b5
RE
234
235 @classmethod
236 def media_is_eligible(cls, entry=None, state=None):
237 """
238 Determine if this media entry is eligible for processing
239 """
240 if not state:
241 state = entry.state
242 return state in 'processed'
243
244 @classmethod
245 def generate_parser(cls):
246 parser = argparse.ArgumentParser(
247 description=cls.description,
248 prog=cls.name)
249
2e50e4b5
RE
250 parser.add_argument(
251 '--fft_size',
252 type=int,
253 help='spectrogram fft size')
254
255 parser.add_argument(
256 '--thumb_size',
257 nargs=2,
258 metavar=('max_width', 'max_height'),
259 type=int)
260
261 parser.add_argument(
262 '--medium_width',
263 type=int,
264 help='The width of the spectogram')
265
266 parser.add_argument(
267 'file',
268 choices=['thumb', 'spectrogram'])
269
270 return parser
271
272 @classmethod
273 def args_to_request(cls, args):
274 return request_from_args(
ad80fc8a 275 args, ['thumb_size', 'file', 'fft_size', 'medium_width'])
2e50e4b5 276
0c509b1b 277 def process(self, file, thumb_size=None, fft_size=None,
2e50e4b5
RE
278 medium_width=None):
279 self.common_setup()
ad80fc8a 280
2e50e4b5
RE
281 if file == 'thumb':
282 self.generate_thumb(size=thumb_size)
283 elif file == 'spectrogram':
ad80fc8a 284 self.create_spectrogram(max_width=medium_width, fft_size=fft_size)
2e50e4b5
RE
285
286
0c509b1b
RE
287class Transcoder(CommonAudioProcessor):
288 """
289 Transcoding processing steps for processed audio
290 """
291 name = 'transcode'
292 description = 'Re-transcode audio'
293
294 @classmethod
295 def media_is_eligible(cls, entry=None, state=None):
296 if not state:
297 state = entry.state
298 return state in 'processed'
299
300 @classmethod
301 def generate_parser(cls):
302 parser = argparse.ArgumentParser(
303 description=cls.description,
304 prog=cls.name)
305
306 parser.add_argument(
307 '--quality',
308 help='vorbisenc quality. Range: -0.1..1')
309
310 return parser
311
312 @classmethod
313 def args_to_request(cls, args):
314 return request_from_args(
315 args, ['quality'])
316
317 def process(self, quality=None):
318 self.common_setup()
319 self.transcode(quality=quality)
320
321
5ac1fe80
RE
322class AudioProcessingManager(ProcessingManager):
323 def __init__(self):
324 super(self.__class__, self).__init__()
325 self.add_processor(InitialProcessor)
2e50e4b5 326 self.add_processor(Resizer)
0c509b1b 327 self.add_processor(Transcoder)