Extensions: Various fixes and clean-ups from review
[gpodder.git] / share / gpodder / extensions / normalize_audio.py
blob58eb41ee97cdd8bce319bdb96964b337a8490fd1
1 # -*- coding: utf-8 -*-
2 # This extension adjusts the volume of audio files to a standard level
3 # Supported file formats are mp3 and ogg
5 # Requires: normalize-audio, mpg123
7 # (c) 2011-11-06 Bernd Schlapsi <brot@gmx.info>
8 # Released under the same license terms as gPodder itself.
10 import os
11 import subprocess
13 import gpodder
14 from gpodder import util
16 import logging
17 logger = logging.getLogger(__name__)
19 _ = gpodder.gettext
21 __title__ = _('Normalize audio with re-encoding')
22 __description__ = _('Normalize the volume of audio files with normalize-audio')
23 __author__ = 'Bernd Schlapsi <brot@gmx.info>'
26 DefaultConfig = {
27 'context_menu': True, # Show action in the episode list context menu
30 # a tuple of (extension, command)
31 CONVERT_COMMANDS = {
32 'ogg': 'normalize-ogg',
33 'mp3': 'normalize-mp3',
36 class gPodderExtension:
37 def __init__(self, container):
38 self.container = container
40 # Dependency check
41 self.container.require_command('normalize-ogg')
42 self.container.require_command('normalize-mp3')
43 self.container.require_command('normalize-audio')
45 def on_load(self):
46 logger.info('Extension "%s" is being loaded.' % __title__)
48 def on_unload(self):
49 logger.info('Extension "%s" is being unloaded.' % __title__)
51 def on_episode_downloaded(self, episode):
52 self._convert_episode(episode)
54 def on_episodes_context_menu(self, episodes):
55 if not self.container.config.context_menu:
56 return None
58 mimetypes = [e.mime_type for e in episodes
59 if e.mime_type is not None and e.file_exists()]
60 if 'audio/ogg' not in mimetypes and 'audio/mpeg' not in mimetypes:
61 return None
63 return [(self.container.metadata.title, self._convert_episodes)]
65 def _convert_episode(self, episode):
66 if episode.file_type() != 'audio':
67 return
69 filename = episode.local_filename(create=False)
70 if filename is None:
71 return
73 basename, extension = os.path.splitext(filename)
75 cmd = [CONVERT_COMMANDS.get(extension, 'normalize-audio'), filename]
77 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
78 stderr=subprocess.PIPE)
79 stdout, stderr = p.communicate()
81 if p.returncode == 0:
82 logger.info('normalize-audio processing successful.')
83 gpodder.user_extensions.on_notification_show(_('File normalized'),
84 episode)
85 else:
86 logger.warn('normalize-audio failed: %s / %s', stdout, stderr)
88 def _convert_episodes(self, episodes):
89 for episode in episodes:
90 self._convert_episode(episode)